target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void isMatchingKey() throws KeyAddress.IllegalAddressException { testMatch(true); testMatch(false); } | @Override public boolean isMatchingKey(AbstractKey key) { KeyAddress other = new KeyAddress(key, 0, _isLong); if (other.keyMask != keyMask) return false; if (!Arrays.equals(keyDigest, other.keyDigest)) return false; return true; } | KeyAddress implements KeyMatcher { @Override public boolean isMatchingKey(AbstractKey key) { KeyAddress other = new KeyAddress(key, 0, _isLong); if (other.keyMask != keyMask) return false; if (!Arrays.equals(keyDigest, other.keyDigest)) return false; return true; } } | KeyAddress implements KeyMatcher { @Override public boolean isMatchingKey(AbstractKey key) { KeyAddress other = new KeyAddress(key, 0, _isLong); if (other.keyMask != keyMask) return false; if (!Arrays.equals(keyDigest, other.keyDigest)) return false; return true; } KeyAddress(); KeyAddress(AbstractKey key, int typeMark, boolean useSha3_384); KeyAddress(byte[] packedSource); KeyAddress(String packedString); KeyAddress(Binder binder); } | KeyAddress implements KeyMatcher { @Override public boolean isMatchingKey(AbstractKey key) { KeyAddress other = new KeyAddress(key, 0, _isLong); if (other.keyMask != keyMask) return false; if (!Arrays.equals(keyDigest, other.keyDigest)) return false; return true; } KeyAddress(); KeyAddress(AbstractKey key, int typeMark, boolean useSha3_384); KeyAddress(byte[] packedSource); KeyAddress(String packedString); KeyAddress(Binder binder); @Override boolean isMatchingKey(AbstractKey key); @Override boolean isMatchingKeyAddress(KeyAddress other); final boolean isLong(); final byte[] getPacked(); final int getTypeMark(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static BiAdapter getBiAdapter(); } | KeyAddress implements KeyMatcher { @Override public boolean isMatchingKey(AbstractKey key) { KeyAddress other = new KeyAddress(key, 0, _isLong); if (other.keyMask != keyMask) return false; if (!Arrays.equals(keyDigest, other.keyDigest)) return false; return true; } KeyAddress(); KeyAddress(AbstractKey key, int typeMark, boolean useSha3_384); KeyAddress(byte[] packedSource); KeyAddress(String packedString); KeyAddress(Binder binder); @Override boolean isMatchingKey(AbstractKey key); @Override boolean isMatchingKeyAddress(KeyAddress other); final boolean isLong(); final byte[] getPacked(); final int getTypeMark(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static BiAdapter getBiAdapter(); } |
@Test public void decode() { byte[] ok = Safe58.decode("Helloworld"); assertArrayEquals(ok,Safe58.decode("HellOwOr1d")); assertArrayEquals(ok,Safe58.decode("He1IOw0r1d")); assertArrayEquals(ok,Safe58.decode("He!|Ow0r|d")); } | public static byte[] decode(String input) { return decode(input,false); } | Safe58 { public static byte[] decode(String input) { return decode(input,false); } } | Safe58 { public static byte[] decode(String input) { return decode(input,false); } } | Safe58 { public static byte[] decode(String input) { return decode(input,false); } static String encode(byte[] input); static byte[] decode(String input); static byte[] decode(String input, boolean strict); } | Safe58 { public static byte[] decode(String input) { return decode(input,false); } static String encode(byte[] input); static byte[] decode(String input); static byte[] decode(String input, boolean strict); } |
@Test public void checkTransactionPack() throws Exception { Contract r = new Contract(ownerKey1); r.seal(); Contract c = r.createRevision(ownerKey1); Contract n = c.split(1)[0]; n.seal(); c.seal(); c.addNewItems(n); String path = rootPath + "/testtranspack.unicon"; c.seal(); Files.deleteIfExists(Paths.get(path)); CLIMain.saveContract(c, path, true, true); callMain("--check", path, "-v"); System.out.println(output); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void exportPublicKeys() throws Exception { String role = "owner"; callMain( "-e", basePath + "contract_to_export.unicon", "--extract-key", role); System.out.println(output); assertTrue (output.indexOf(role + " export public keys ok") >= 0); assertEquals(0, errors.size()); } | private static void exportPublicKeys(Contract contract, String roleName, String fileName, boolean base64) throws IOException { if (fileName == null) { if (testMode && testRootPath != null) { fileName = testRootPath + "Universa_" + roleName + "_public_key"; } else { fileName = "Universa_" + roleName + "_public_key.pub"; } } Role role = contract.getRole(roleName); if (role != null) { Set<PublicKey> keys = role.getKeys(); int index = 0; byte[] data; for (PublicKey key : keys) { index++; data = key.pack(); String name = fileName.replaceAll("\\.(pub)$", "_key_" + roleName + "_" + index + ".public.unikey"); if (base64) { name += ".txt"; } try (FileOutputStream fs = new FileOutputStream(name)) { if (base64) fs.write(Base64.encodeLines(data).getBytes()); else fs.write(data); fs.close(); } } report(roleName + " export public keys ok"); } else { addError(Errors.NOT_FOUND.name(), roleName, "role doesn't exist"); } } | CLIMain { private static void exportPublicKeys(Contract contract, String roleName, String fileName, boolean base64) throws IOException { if (fileName == null) { if (testMode && testRootPath != null) { fileName = testRootPath + "Universa_" + roleName + "_public_key"; } else { fileName = "Universa_" + roleName + "_public_key.pub"; } } Role role = contract.getRole(roleName); if (role != null) { Set<PublicKey> keys = role.getKeys(); int index = 0; byte[] data; for (PublicKey key : keys) { index++; data = key.pack(); String name = fileName.replaceAll("\\.(pub)$", "_key_" + roleName + "_" + index + ".public.unikey"); if (base64) { name += ".txt"; } try (FileOutputStream fs = new FileOutputStream(name)) { if (base64) fs.write(Base64.encodeLines(data).getBytes()); else fs.write(data); fs.close(); } } report(roleName + " export public keys ok"); } else { addError(Errors.NOT_FOUND.name(), roleName, "role doesn't exist"); } } } | CLIMain { private static void exportPublicKeys(Contract contract, String roleName, String fileName, boolean base64) throws IOException { if (fileName == null) { if (testMode && testRootPath != null) { fileName = testRootPath + "Universa_" + roleName + "_public_key"; } else { fileName = "Universa_" + roleName + "_public_key.pub"; } } Role role = contract.getRole(roleName); if (role != null) { Set<PublicKey> keys = role.getKeys(); int index = 0; byte[] data; for (PublicKey key : keys) { index++; data = key.pack(); String name = fileName.replaceAll("\\.(pub)$", "_key_" + roleName + "_" + index + ".public.unikey"); if (base64) { name += ".txt"; } try (FileOutputStream fs = new FileOutputStream(name)) { if (base64) fs.write(Base64.encodeLines(data).getBytes()); else fs.write(data); fs.close(); } } report(roleName + " export public keys ok"); } else { addError(Errors.NOT_FOUND.name(), roleName, "role doesn't exist"); } } } | CLIMain { private static void exportPublicKeys(Contract contract, String roleName, String fileName, boolean base64) throws IOException { if (fileName == null) { if (testMode && testRootPath != null) { fileName = testRootPath + "Universa_" + roleName + "_public_key"; } else { fileName = "Universa_" + roleName + "_public_key.pub"; } } Role role = contract.getRole(roleName); if (role != null) { Set<PublicKey> keys = role.getKeys(); int index = 0; byte[] data; for (PublicKey key : keys) { index++; data = key.pack(); String name = fileName.replaceAll("\\.(pub)$", "_key_" + roleName + "_" + index + ".public.unikey"); if (base64) { name += ".txt"; } try (FileOutputStream fs = new FileOutputStream(name)) { if (base64) fs.write(Base64.encodeLines(data).getBytes()); else fs.write(data); fs.close(); } } report(roleName + " export public keys ok"); } else { addError(Errors.NOT_FOUND.name(), roleName, "role doesn't exist"); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { private static void exportPublicKeys(Contract contract, String roleName, String fileName, boolean base64) throws IOException { if (fileName == null) { if (testMode && testRootPath != null) { fileName = testRootPath + "Universa_" + roleName + "_public_key"; } else { fileName = "Universa_" + roleName + "_public_key.pub"; } } Role role = contract.getRole(roleName); if (role != null) { Set<PublicKey> keys = role.getKeys(); int index = 0; byte[] data; for (PublicKey key : keys) { index++; data = key.pack(); String name = fileName.replaceAll("\\.(pub)$", "_key_" + roleName + "_" + index + ".public.unikey"); if (base64) { name += ".txt"; } try (FileOutputStream fs = new FileOutputStream(name)) { if (base64) fs.write(Base64.encodeLines(data).getBytes()); else fs.write(data); fs.close(); } } report(roleName + " export public keys ok"); } else { addError(Errors.NOT_FOUND.name(), roleName, "role doesn't exist"); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void parsingAndExportRefsTest() throws Exception { Contract refContract = Contract.fromDslFile(rootPath + "ref_conditions_root_contract.yml"); Binder conditions = refContract.getReferences().get("test_ref4").getConditions(); List<Object> condList = conditions.getList(all_of.name(), null); condList.add("\"string\"!=this.state.data.string3"); condList.add("\"==INFORMATION==\"==this.state.data.string2"); condList.add("\"string\"==this.state.data.string4"); refContract.getReferences().get("test_ref4").setConditions(conditions); conditions = refContract.getReferences().get("test_ref3").getConditions(); condList = conditions.getList(all_of.name(), null); Binder parsed = ((Binder)condList.get(0)); assertEquals(parsed.getString("leftOperand", ""), "this.definition.issuer"); assertEquals(parsed.getString("rightOperand", ""), "this.state.issuer"); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 0); assertEquals(parsed.getIntOrThrow("leftConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 0); assertEquals(parsed.getIntOrThrow("operator"), 7); parsed = ((Binder)condList.get(9)); assertEquals(parsed.getString("leftOperand", ""), "this.state.data.bigdecimal_val"); assertEquals(parsed.getString("rightOperand", ""), "123980111893281903812098390128320192830219821321321321123910849732682917138291"); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 0); assertEquals(parsed.getIntOrThrow("leftConversion"), 1); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 1); assertEquals(parsed.getIntOrThrow("operator"), 3); conditions = refContract.getReferences().get("test_ref4").getConditions(); condList = conditions.getList(all_of.name(), null); parsed = ((Binder)condList.get(4)); assertEquals(parsed.getString("leftOperand", ""), "==INFORMATION=="); assertEquals(parsed.getString("rightOperand", ""), "this.state.data.string2"); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 1); assertEquals(parsed.getIntOrThrow("leftConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 0); assertEquals(parsed.getIntOrThrow("operator"), 7); conditions = refContract.getReferences().get("test_ref_arithmetic").getConditions(); condList = conditions.getList(any_of.name(), null); parsed = ((Binder)condList.get(0)); Binder left = parsed.getBinder("left", null); Binder right = parsed.getBinder("right", null); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 3); assertEquals(parsed.getIntOrThrow("leftConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 3); assertEquals(parsed.getIntOrThrow("operator"), 2); assertEquals(left.getString("leftOperand", ""), "this.state.data.double_val"); assertEquals(left.getString("rightOperand", ""), "this.state.data.int_val"); assertEquals(left.getIntOrThrow("rightConversion"), 0); assertEquals(left.getIntOrThrow("typeOfLeftOperand"), 0); assertEquals(left.getIntOrThrow("leftConversion"), 0); assertEquals(left.getIntOrThrow("typeOfRightOperand"), 0); assertEquals(left.getIntOrThrow("operation"), 2); assertEquals(right.getString("leftOperand", ""), "this.state.data.bigdecimal_val"); assertEquals(right.getString("rightOperand", ""), "734291738921738179832719873921873920100219.83912839289189189"); assertEquals(right.getIntOrThrow("rightConversion"), 0); assertEquals(right.getIntOrThrow("typeOfLeftOperand"), 0); assertEquals(right.getIntOrThrow("leftConversion"), 1); assertEquals(right.getIntOrThrow("typeOfRightOperand"), 2); assertEquals(right.getIntOrThrow("operation"), 1); conditions = ((Binder)condList.get(3)); condList = conditions.getList(all_of.name(), null); parsed = ((Binder)condList.get(0)); left = parsed.getBinder("left", null); assertEquals(parsed.getString("rightOperand", ""), "72"); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 3); assertEquals(parsed.getIntOrThrow("leftConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 2); assertEquals(parsed.getIntOrThrow("operator"), 7); assertFalse(parsed.containsKey("leftParentheses")); assertFalse(parsed.containsKey("rightParentheses")); assertEquals(left.getString("leftOperand", ""), "12"); right = left.getBinder("right", null); assertEquals(left.getIntOrThrow("rightConversion"), 0); assertEquals(left.getIntOrThrow("typeOfLeftOperand"), 2); assertEquals(left.getIntOrThrow("leftConversion"), 0); assertEquals(left.getIntOrThrow("typeOfRightOperand"), 3); assertEquals(left.getIntOrThrow("operation"), 0); assertFalse(left.containsKey("leftParentheses")); assertFalse(left.containsKey("rightParentheses")); assertEquals(right.getString("leftOperand", ""), "4"); assertEquals(right.getIntOrThrow("rightConversion"), 0); assertEquals(right.getIntOrThrow("typeOfLeftOperand"), 2); assertEquals(right.getIntOrThrow("leftConversion"), 0); assertEquals(right.getIntOrThrow("typeOfRightOperand"), 3); assertEquals(right.getIntOrThrow("operation"), 2); assertFalse(right.containsKey("leftParentheses")); assertTrue(right.containsKey("rightParentheses")); right = right.getBinder("right", null); assertEquals(right.getString("leftOperand", ""), "10"); assertEquals(right.getString("rightOperand", ""), "5"); assertEquals(right.getIntOrThrow("rightConversion"), 0); assertEquals(right.getIntOrThrow("typeOfLeftOperand"), 2); assertEquals(right.getIntOrThrow("leftConversion"), 0); assertEquals(right.getIntOrThrow("typeOfRightOperand"), 2); assertEquals(right.getIntOrThrow("operation"), 0); assertFalse(right.containsKey("leftParentheses")); assertFalse(right.containsKey("rightParentheses")); parsed = ((Binder)condList.get(5)); left = parsed.getBinder("left", null); assertEquals(parsed.getString("rightOperand", ""), "450.59"); assertEquals(parsed.getIntOrThrow("operator"), 7); assertEquals(parsed.getIntOrThrow("rightConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfLeftOperand"), 3); assertEquals(parsed.getIntOrThrow("leftConversion"), 0); assertEquals(parsed.getIntOrThrow("typeOfRightOperand"), 2); assertFalse(parsed.containsKey("leftParentheses")); assertFalse(parsed.containsKey("rightParentheses")); assertEquals(left.getString("leftOperand", ""), "450.59012"); assertEquals(left.getString("rightOperand", ""), "3"); assertEquals(left.getIntOrThrow("rightConversion"), 0); assertEquals(left.getIntOrThrow("typeOfLeftOperand"), 2); assertEquals(left.getIntOrThrow("leftConversion"), 0); assertEquals(left.getIntOrThrow("typeOfRightOperand"), 2); assertEquals(left.getIntOrThrow("operation"), 100); assertFalse(left.containsKey("leftParentheses")); assertFalse(left.containsKey("rightParentheses")); refContract.addSignerKeyFromFile(rootPath + "_xer0yfe2nn1xthc.private.unikey"); refContract.seal(); refContract.check(); refContract.traceErrors(); CLIMain.saveContract(refContract, basePath + "ref_conditions_root_contract.unicon"); callMain( "-e", basePath + "ref_conditions_root_contract.unicon", "-as", "yaml"); System.out.println(output); assertTrue (output.indexOf("export as yaml ok") >= 0); assertEquals(0, errors.size()); File file = new File( basePath + "ref_conditions_root_contract.yaml"); Scanner scanner = new Scanner(file); List<String> list=new ArrayList<>(); while(scanner.hasNextLine()){ list.add(scanner.nextLine()); } assertTrue((list.contains(" - this.definition.issuer==this.state.issuer"))); assertTrue((list.contains(" - this.owner defined"))); assertTrue((list.contains(" - this.state.data.int_val>37"))); assertTrue((list.contains(" - this.state.data.string_val==\"==DATA==\""))); assertTrue((list.contains(" - false!=this.state.data.boolean_val"))); assertTrue((list.contains(" - this.state.data.long_val<=1540809613457836"))); assertTrue((list.contains(" - -67029039209309103.09204932<=this.state.data.double_val"))); assertTrue((list.contains(" - this.state.data.string_val!=\"jkdsjdksjakjl12901ndasds_ksdokaoss\""))); assertTrue((list.contains(" - 3242905403309310398882034989390309091424678928328433888839898041300111129094320492094029007845298372939==this.state.data.bigdecimal_val::number"))); assertTrue((list.contains(" - this.state.data.bigdecimal_val::number>=\"123980111893281903812098390128320192830219821321321321123910849732682917138291\""))); assertTrue((list.contains(" - this.definition.issuer defined"))); assertTrue((list.contains(" - inherits this.state.references.test_ref1"))); assertTrue((list.contains(" - this.state.data.int_val>37"))); assertTrue((list.contains(" - this.state.data.string_val==\"==DATA==\""))); assertTrue((list.contains(" - false!=this.state.data.boolean_val"))); assertTrue((list.contains(" - this.state.data.long_val<=1540809613457836"))); assertTrue((list.contains(" - -67029039209309103.09204932>this.state.data.double_val"))); assertTrue((list.contains(" - jkdsjdksjakjl12901ndasds_ksdokaoss!=this.state.data.string_val"))); assertTrue((list.contains(" - 3242905403309310398882034989390309091424678928328433888839898041300111129094320492094029007845298372939==this.state.data.bigdecimal_val::number"))); assertTrue((list.contains(" - this.state.data.bigdecimal_val::number>=\"123980111893281903812098390128320192830219821321321321123910849732682917138291\""))); assertTrue((list.contains(" - this.state.data.long_val<=1540809613457836"))); assertTrue((list.contains(" - -67029039209309103.09204932>this.state.data.double_val"))); assertTrue((list.contains(" - jkdsjdksjakjl12901ndasds_ksdokaoss!=this.state.data.string_val"))); assertTrue((list.contains(" - 3242905403309310398882034989390309091424678928328433888839898041300111129094320492094029007845298372939==this.state.data.bigdecimal_val::number"))); assertTrue((list.contains(" - this.state.data.bigdecimal_val::number>=\"123980111893281903812098390128320192830219821321321321123910849732682917138291\""))); assertTrue((list.contains(" - this.definition.issuer==this.state.issuer"))); assertTrue((list.contains(" - this.owner defined"))); assertTrue((list.contains(" - this.state.data.int_val>37"))); assertTrue((list.contains(" - this.state.data.string_val==\"==DATA==\""))); assertTrue((list.contains(" - false!=this.state.data.boolean_val"))); assertTrue((list.contains(" - this.state.data.long_val<=1540809613457836"))); assertTrue((list.contains(" - -67029039209309103.09204932<=this.state.data.double_val"))); assertTrue((list.contains(" - this.state.data.string_val!=\"jkdsjdksjakjl12901ndasds_ksdokaoss\""))); assertTrue((list.contains(" - 3242905403309310398882034989390309091424678928328433888839898041300111129094320492094029007845298372939==this.state.data.bigdecimal_val::number"))); assertTrue((list.contains(" - this.state.data.bigdecimal_val::number>=\"123980111893281903812098390128320192830219821321321321123910849732682917138291\""))); assertTrue((list.contains(" - this.state.references.test_ref2 is_a this.state.references.test_ref1"))); assertTrue((list.contains(" - this.definition.created_at>this.state.data.time3"))); assertTrue((list.contains(" - this.definition.expires_at<\"2908-04-18 23:58:00\""))); assertTrue((list.contains(" - this.state.data.time5<=this.definition.created_at"))); assertTrue((list.contains(" - '\"string\"!=this.state.data.string3'"))); assertTrue((list.contains(" - '\"==INFORMATION==\"==this.state.data.string2'"))); assertTrue((list.contains(" - '\"string\"==this.state.data.string4'"))); assertTrue((list.contains(" - this.state.data.double_val*this.state.data.int_val<=this.state.data.bigdecimal_val::number-734291738921738179832719873921873920100219.83912839289189189"))); assertTrue((list.contains(" - -67029039209309103.09204932<this.state.data.double_val/382138291832182819.391291092190901"))); assertTrue((list.contains(" - this.state.data.int_val<this.state.data.long_val+37"))); assertTrue((list.contains(" - this.state.data.int_val==1*this.state.data.int_val"))); assertTrue((list.contains(" - this.state.data.long_val==this.state.data.long_val/1+78-78"))); assertTrue((list.contains(" - this.state.data.long_val<=154*7836"))); assertTrue((list.contains(" - -67029039209309103.09204932>this.state.data.double_val-231892.293207"))); assertTrue((list.contains(" - 3242905403309310398882034989390309091424678928328433888839898041300111129094320492094029007845298300000+72939==this.state.data.bigdecimal_val::number"))); assertTrue((list.contains(" - this.state.data.bigdecimal_val::number>=1239801118932819038120*1123910849732682917138291-8938291839218928/382"))); assertTrue((list.contains(" - 12+4*(10+5)==72"))); assertTrue((list.contains(" - 12+(4)*(10+5)==72"))); assertTrue((list.contains(" - 12+(4*(10+5))==72"))); assertTrue((list.contains(" - (-5)+2<0"))); assertTrue((list.contains(" - (this.state.data.int_val-5)/(43+7)*20==((this.state.data.int_val-5)/10-5)+20"))); assertTrue((list.contains(" - round(450.59012,3)==450.59"))); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void updateFields() throws Exception { ZonedDateTime zdt = ZonedDateTime.now().plusHours(1); String field1 = "definition.issuer"; String value1 = "<definition.issuer>\n" + " <SimpleRole>\n" + " <keys isArray=\"true\">\n" + " <item>\n" + " <KeyRecord>\n" + " <name>Universa</name>\n" + " <key>\n" + " <RSAPublicKey>\n" + " <packed>\n" + " <binary>\n" + " <base64>HggcAQABxAACzHE9ibWlnK4RzpgFIB4jIg3WcXZSKXNAqOTYUtGXY03xJSwpqE+y/HbqqE0W\n" + "smcAt5a0F5H7bz87Uy8Me1UdIDcOJgP8HMF2M0I/kkT6d59ZhYH/TlpDcpLvnJWElZAfOyta\n" + "ICE01bkOkf6Mz5egpToDEEPZH/RXigj9wkSXkk43WZSxVY5f2zaVmibUZ9VLoJlmjNTZ+utJ\n" + "UZi66iu9e0SXupOr/+BJL1Gm595w32Fd0141kBvAHYDHz2K3x4m1oFAcElJ83ahSl1u85/na\n" + "Iaf2yuxiQNz3uFMTn0IpULCMvLMvmE+L9io7+KWXld2usujMXI1ycDRw85h6IJlPcKHVQKnJ\n" + "/4wNBUveBDLFLlOcMpCzWlO/D7M2IyNa8XEvwPaFJlN1UN/9eVpaRUBEfDq6zi+RC8MaVWzF\n" + "bNi913suY0Q8F7ejKR6aQvQPuNN6bK6iRYZchxe/FwWIXOr0C0yA3NFgxKLiKZjkd5eJ84GL\n" + "y+iD00Rzjom+GG4FDQKr2HxYZDdDuLE4PEpYSzEB/8LyIqeM7dSyaHFTBII/sLuFru6ffoKx\n" + "BNk/cwAGZqOwD3fkJjNq1R3h6QylWXI/cSO9yRnRMmMBJwalMexOc3/kPEEdfjH/GcJU0Mw6\n" + "DgoY8QgfaNwXcFbBUvf3TwZ5Mysf21OLHH13g8gzREm+h8c=</base64>\n" + " </binary>\n" + " </packed>\n" + " </RSAPublicKey>\n" + " </key>\n" + " </KeyRecord>\n" + " </item>\n" + " </keys>\n" + " <name>issuer</name>\n" + " </SimpleRole>\n" + " </definition.issuer>"; String field2 = "definition.expires_at"; String value2 = "<definition.expires__at>\n" + " <unixtime>" + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss [XXX]").format(zdt) + "</unixtime>\n" + "</definition.expires__at>"; callMain( "-e", basePath + "contract_to_export.unicon", "-set", field1, "-value", value1, "-set", field2, "-value", value2); System.out.println(output); assertTrue (output.indexOf("update field " + field2 + " ok") >= 0); assertTrue (output.indexOf("contract expires at " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(zdt)) >= 0); assertEquals(0, errors.size()); } | private static void updateFields(Contract contract, HashMap<String, String> fields) throws IOException { for (String fieldName : fields.keySet()) { report("update field: " + fieldName + " -> " + fields.get(fieldName)); Binder data = null; Object obj = null; try { XStream xstream = new XStream(new DomDriver()); xstream.registerConverter(new MapEntryConverter()); xstream.alias(fieldName, Binder.class); data = Binder.convertAllMapsToBinders(xstream.fromXML(fields.get(fieldName))); } catch (Exception xmlEx) { try { Gson gson = new GsonBuilder().create(); data = Binder.convertAllMapsToBinders(gson.fromJson(fields.get(fieldName), Binder.class)); if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } catch (Exception jsonEx) { try { Yaml yaml = new Yaml(); Object loaded = Binder.convertAllMapsToBinders(yaml.load(fields.get(fieldName))); if (loaded.getClass().equals(Binder.class)) { data = (Binder) loaded; if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } else obj = loaded; } catch (Exception yamlEx) { try { obj = fields.get(fieldName); } catch (Exception ex) { ex.printStackTrace(); xmlEx.printStackTrace(); jsonEx.printStackTrace(); yamlEx.printStackTrace(); } } } } if ((data != null) || (obj != null)) { Binder binder = new Binder(); if (data != null) { BiDeserializer bm = DefaultBiMapper.getInstance().newDeserializer(); binder.put("data", bm.deserialize(data)); } else binder.put("data", obj); contract.set(fieldName, binder); report("update field " + fieldName + " ok"); } else { report("update field " + fieldName + " error: no valid data"); } } report("contract expires at " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(contract.getExpiresAt())); } | CLIMain { private static void updateFields(Contract contract, HashMap<String, String> fields) throws IOException { for (String fieldName : fields.keySet()) { report("update field: " + fieldName + " -> " + fields.get(fieldName)); Binder data = null; Object obj = null; try { XStream xstream = new XStream(new DomDriver()); xstream.registerConverter(new MapEntryConverter()); xstream.alias(fieldName, Binder.class); data = Binder.convertAllMapsToBinders(xstream.fromXML(fields.get(fieldName))); } catch (Exception xmlEx) { try { Gson gson = new GsonBuilder().create(); data = Binder.convertAllMapsToBinders(gson.fromJson(fields.get(fieldName), Binder.class)); if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } catch (Exception jsonEx) { try { Yaml yaml = new Yaml(); Object loaded = Binder.convertAllMapsToBinders(yaml.load(fields.get(fieldName))); if (loaded.getClass().equals(Binder.class)) { data = (Binder) loaded; if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } else obj = loaded; } catch (Exception yamlEx) { try { obj = fields.get(fieldName); } catch (Exception ex) { ex.printStackTrace(); xmlEx.printStackTrace(); jsonEx.printStackTrace(); yamlEx.printStackTrace(); } } } } if ((data != null) || (obj != null)) { Binder binder = new Binder(); if (data != null) { BiDeserializer bm = DefaultBiMapper.getInstance().newDeserializer(); binder.put("data", bm.deserialize(data)); } else binder.put("data", obj); contract.set(fieldName, binder); report("update field " + fieldName + " ok"); } else { report("update field " + fieldName + " error: no valid data"); } } report("contract expires at " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(contract.getExpiresAt())); } } | CLIMain { private static void updateFields(Contract contract, HashMap<String, String> fields) throws IOException { for (String fieldName : fields.keySet()) { report("update field: " + fieldName + " -> " + fields.get(fieldName)); Binder data = null; Object obj = null; try { XStream xstream = new XStream(new DomDriver()); xstream.registerConverter(new MapEntryConverter()); xstream.alias(fieldName, Binder.class); data = Binder.convertAllMapsToBinders(xstream.fromXML(fields.get(fieldName))); } catch (Exception xmlEx) { try { Gson gson = new GsonBuilder().create(); data = Binder.convertAllMapsToBinders(gson.fromJson(fields.get(fieldName), Binder.class)); if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } catch (Exception jsonEx) { try { Yaml yaml = new Yaml(); Object loaded = Binder.convertAllMapsToBinders(yaml.load(fields.get(fieldName))); if (loaded.getClass().equals(Binder.class)) { data = (Binder) loaded; if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } else obj = loaded; } catch (Exception yamlEx) { try { obj = fields.get(fieldName); } catch (Exception ex) { ex.printStackTrace(); xmlEx.printStackTrace(); jsonEx.printStackTrace(); yamlEx.printStackTrace(); } } } } if ((data != null) || (obj != null)) { Binder binder = new Binder(); if (data != null) { BiDeserializer bm = DefaultBiMapper.getInstance().newDeserializer(); binder.put("data", bm.deserialize(data)); } else binder.put("data", obj); contract.set(fieldName, binder); report("update field " + fieldName + " ok"); } else { report("update field " + fieldName + " error: no valid data"); } } report("contract expires at " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(contract.getExpiresAt())); } } | CLIMain { private static void updateFields(Contract contract, HashMap<String, String> fields) throws IOException { for (String fieldName : fields.keySet()) { report("update field: " + fieldName + " -> " + fields.get(fieldName)); Binder data = null; Object obj = null; try { XStream xstream = new XStream(new DomDriver()); xstream.registerConverter(new MapEntryConverter()); xstream.alias(fieldName, Binder.class); data = Binder.convertAllMapsToBinders(xstream.fromXML(fields.get(fieldName))); } catch (Exception xmlEx) { try { Gson gson = new GsonBuilder().create(); data = Binder.convertAllMapsToBinders(gson.fromJson(fields.get(fieldName), Binder.class)); if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } catch (Exception jsonEx) { try { Yaml yaml = new Yaml(); Object loaded = Binder.convertAllMapsToBinders(yaml.load(fields.get(fieldName))); if (loaded.getClass().equals(Binder.class)) { data = (Binder) loaded; if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } else obj = loaded; } catch (Exception yamlEx) { try { obj = fields.get(fieldName); } catch (Exception ex) { ex.printStackTrace(); xmlEx.printStackTrace(); jsonEx.printStackTrace(); yamlEx.printStackTrace(); } } } } if ((data != null) || (obj != null)) { Binder binder = new Binder(); if (data != null) { BiDeserializer bm = DefaultBiMapper.getInstance().newDeserializer(); binder.put("data", bm.deserialize(data)); } else binder.put("data", obj); contract.set(fieldName, binder); report("update field " + fieldName + " ok"); } else { report("update field " + fieldName + " error: no valid data"); } } report("contract expires at " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(contract.getExpiresAt())); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { private static void updateFields(Contract contract, HashMap<String, String> fields) throws IOException { for (String fieldName : fields.keySet()) { report("update field: " + fieldName + " -> " + fields.get(fieldName)); Binder data = null; Object obj = null; try { XStream xstream = new XStream(new DomDriver()); xstream.registerConverter(new MapEntryConverter()); xstream.alias(fieldName, Binder.class); data = Binder.convertAllMapsToBinders(xstream.fromXML(fields.get(fieldName))); } catch (Exception xmlEx) { try { Gson gson = new GsonBuilder().create(); data = Binder.convertAllMapsToBinders(gson.fromJson(fields.get(fieldName), Binder.class)); if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } catch (Exception jsonEx) { try { Yaml yaml = new Yaml(); Object loaded = Binder.convertAllMapsToBinders(yaml.load(fields.get(fieldName))); if (loaded.getClass().equals(Binder.class)) { data = (Binder) loaded; if (data.containsKey(fieldName)) data = (Binder) data.get(fieldName); } else obj = loaded; } catch (Exception yamlEx) { try { obj = fields.get(fieldName); } catch (Exception ex) { ex.printStackTrace(); xmlEx.printStackTrace(); jsonEx.printStackTrace(); yamlEx.printStackTrace(); } } } } if ((data != null) || (obj != null)) { Binder binder = new Binder(); if (data != null) { BiDeserializer bm = DefaultBiMapper.getInstance().newDeserializer(); binder.put("data", bm.deserialize(data)); } else binder.put("data", obj); contract.set(fieldName, binder); report("update field " + fieldName + " ok"); } else { report("update field " + fieldName + " error: no valid data"); } } report("contract expires at " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(contract.getExpiresAt())); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void findContractsInPath() throws Exception { File dirFile = new File(rootPath + "contract_subfolder/"); if (!dirFile.exists()) dirFile.mkdir(); dirFile = new File(rootPath + "contract_subfolder/contract_subfolder_level2/"); if (!dirFile.exists()) dirFile.mkdir(); List<String> coinValues = Arrays.asList("5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "0.3"); List<Contract> listOfCoinsWithAmount = createListOfCoinsWithAmount(coinValues); for (Contract coin : listOfCoinsWithAmount) { int rnd = new Random().nextInt(2); String dir = ""; switch (rnd) { case 0: dir += "contract_subfolder/"; break; case 1: dir += "contract_subfolder/contract_subfolder_level2/"; break; } CLIMain.saveContract(coin, rootPath + dir + "Coin_" + coin.getStateData().getStringOrThrow(FIELD_NAME) + ".unicon"); } Contract nonCoin = Contract.fromDslFile("./src/test_files/simple_root_contract_v2.yml"); nonCoin.seal(); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/NonCoin.unicon"); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/contract_subfolder_level2/NonCoin.unicon"); callMain("-f", rootPath + "contract_subfolder/", "-v", "-r"); System.out.println(output); File[] filesToRemove = new File(rootPath + "contract_subfolder/").listFiles(); for (File file : filesToRemove) { file.delete(); } filesToRemove = new File(rootPath + "contract_subfolder/contract_subfolder_level2/").listFiles(); for (File file : filesToRemove) { file.delete(); } Decimal total = new Decimal(0); for (String i : coinValues) { total = total.add(new Decimal(i)); } System.out.println(output); assertTrue (output.indexOf(total + " (TUNC)") >= 0); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void findMintContractsInPath() throws Exception { File dirFile = new File(rootPath + "contract_subfolder/"); if (!dirFile.exists()) dirFile.mkdir(); dirFile = new File(rootPath + "contract_subfolder/contract_subfolder_level2/"); if (!dirFile.exists()) dirFile.mkdir(); List<String> mintContractsHexes = new ArrayList<>(); mintContractsHexes.add("27 33 5F 5F 74 79 70 65 7B 54 72 61 6E 73 61 63 74 69 6F 6E 50 61 63 6B 43 63 6F 6E 74 72 61 63 74 C4 70 05 27 3B 76 65 72 73 69 6F 6E 18 23 74 79 70 65 53 75 6E 69 63 61 70 73 75 6C 65 53 73 69 67 6E 61 74 75 72 65 73 0E C4 A8 02 17 23 65 78 74 73 C4 97 01 27 1B 6B 65 79 BC 21 07 66 EF 93 DB A7 78 84 0B 7C CF 64 DB 9E 07 24 4F F3 6E 48 C7 80 01 EE 46 E4 52 40 A7 3B 90 A8 61 33 73 68 61 35 31 32 BC 40 4D B2 60 99 0D C1 71 E2 1A 2C EF 0D E1 2E 2F 8D AB 2B 89 2B BC 86 13 6C 3F EE 62 CF F5 72 A8 5C 9B 06 A4 54 66 D9 E9 2F 43 66 B0 7E 99 A2 1B 7B 62 40 44 F0 B6 54 B8 39 8E C4 37 68 D9 F9 00 FB 53 63 72 65 61 74 65 64 5F 61 74 79 38 22 70 58 85 3B 70 75 62 5F 6B 65 79 C4 0A 01 1E 08 1C 01 00 01 C4 01 01 00 AB 3A 2E D8 2A 22 AF E2 30 89 85 73 14 37 BC 7B D7 6D 04 2F 44 35 EF DF 98 0B 79 0C EA 88 D1 6A F0 CD 9A 79 C6 C8 70 9A DC 71 21 E9 36 62 9B 6F DB 75 6B 02 25 E5 37 93 B7 65 0A DD 3D 13 AE 36 D4 0A 72 4D 2B 7E 58 37 BB C4 5C 92 BB FA D5 42 85 46 B9 73 B2 C3 DE CE 89 AA BA FC D7 DB CD 48 AC 98 D3 13 AC 38 16 62 D1 97 08 62 CF E1 1A F0 1B BC 2E 95 BE DF 83 07 AF BA E3 60 4D 7B 67 E2 9D 35 9A 5A D6 7C 66 8F 47 C1 3E 91 2F 57 39 72 CF 0F 1D CE 51 73 58 07 26 07 5F 91 8A 3A F7 45 35 F3 A8 15 89 6C 7F FC 44 33 81 2A 6B 51 AC 4E 2C 44 70 9E FE 39 90 A7 DA 5A 15 10 CC 67 6B 50 F1 B4 3E EB A2 BC 7C B5 24 D6 7E 9E A1 E2 AC 1C 99 C8 17 63 54 4A BE C6 63 D2 BA DF E0 FC 2A 52 16 30 92 9E 5C 7D B1 3D 76 A1 EF E7 6E 5A A0 73 B9 93 71 1D 0D E4 6E AA 87 5C 64 E8 76 40 4B BD 23 73 69 67 6E C4 00 01 02 3C 70 A1 49 5E 6B A4 BF BF DB 77 82 D3 3C 4C C9 9C 25 E5 F3 CC 7A AD 48 A7 7E 05 6B 32 C0 50 E7 61 43 C1 47 3B 9F 51 92 85 06 75 4E C8 9E 2E B9 33 13 5F A0 6F 6C 70 86 F7 10 CF 6E D5 A6 9E 0B 0D 12 6E F5 09 2D 62 FC 7C B0 54 6F A9 CA 24 8B AB 15 B7 CC 5E 44 95 9A CA 32 FE 57 97 77 AC 0B 15 17 66 0B 3C 4B A3 F3 E3 5E 8D C3 14 F1 E0 AC EB D1 E1 65 2F B4 0C 11 49 9A BD 2E AD 6F AA ED DB EB 54 B6 1F 54 67 02 95 E3 C6 41 2F 03 6B 0F B2 39 DB B9 FE B8 03 13 21 E9 6A F3 9E 35 04 2A 67 6B C5 DD 3A 08 52 BB 15 08 FC 34 E5 05 C2 AB E6 B0 29 A2 22 8D 83 2C 32 A2 6D 39 23 75 EC C3 D3 3F 93 8D 2B 5D 0C BC D2 0F 62 2A EF C2 C5 FB E6 C9 29 8E 72 0A BD DB AE 97 86 5E 08 0F 99 14 B9 7E 05 86 C7 0E 4D F8 11 9A BB 7B 8F 7E 29 0B B3 BF 09 11 FC B2 2A 27 C2 DA 89 FB DA A0 BD 23 64 61 74 61 C4 97 02 1F 43 72 65 76 6F 6B 69 6E 67 06 43 63 6F 6E 74 72 61 63 74 27 33 5F 5F 74 79 70 65 83 55 6E 69 76 65 72 73 61 43 6F 6E 74 72 61 63 74 4B 61 70 69 5F 6C 65 76 65 6C 18 53 64 65 66 69 6E 69 74 69 6F 6E 2F 53 63 72 65 61 74 65 64 5F 61 74 79 22 06 70 58 85 23 64 61 74 61 1F 23 6E 61 6D 65 23 6D 65 77 31 43 63 75 72 72 65 6E 63 79 7D 73 73 68 6F 72 74 5F 63 75 72 72 65 6E 63 79 7D 33 69 73 73 75 65 72 1F 35 53 53 69 6D 70 6C 65 52 6F 6C 65 75 95 4B 61 64 64 72 65 73 73 65 73 0E 17 35 53 4B 65 79 41 64 64 72 65 73 73 43 75 61 64 64 72 65 73 73 BC 25 10 AE 02 80 D9 08 99 1A E5 E4 78 6A 71 D7 48 8F 65 4F 97 8C 89 78 23 D2 D0 9F 9C FE C2 11 F4 2E A6 CB A0 42 33 5B 70 65 72 6D 69 73 73 69 6F 6E 73 1F 33 64 6C 75 79 78 69 1F 35 83 52 65 76 6F 6B 65 50 65 72 6D 69 73 73 69 6F 6E 23 72 6F 6C 65 1F 35 43 52 6F 6C 65 4C 69 6E 6B 75 3B 40 72 65 76 6F 6B 65 5B 74 61 72 67 65 74 5F 6E 61 6D 65 2B 6F 77 6E 65 72 75 33 72 65 76 6F 6B 65 33 76 36 57 57 43 33 3F 53 66 69 65 6C 64 5F 6E 61 6D 65 33 61 6D 6F 75 6E 74 4B 6D 69 6E 5F 76 61 6C 75 65 08 43 6D 69 6E 5F 75 6E 69 74 08 8B 6A 6F 69 6E 5F 6D 61 74 63 68 5F 66 69 65 6C 64 73 16 BB 18 64 65 66 69 6E 69 74 69 6F 6E 2E 64 61 74 61 2E 63 75 72 72 65 6E 63 79 8B 64 65 66 69 6E 69 74 69 6F 6E 2E 69 73 73 75 65 72 35 9B 53 70 6C 69 74 4A 6F 69 6E 50 65 72 6D 69 73 73 69 6F 6E BD 20 1F 35 BD 22 75 5B 40 73 70 6C 69 74 5F 6A 6F 69 6E BD 24 BD 25 75 53 73 70 6C 69 74 5F 6A 6F 69 6E 33 49 73 61 49 36 64 1F 35 AB 43 68 61 6E 67 65 4F 77 6E 65 72 50 65 72 6D 69 73 73 69 6F 6E BD 20 1F 35 BD 22 75 6B 40 63 68 61 6E 67 65 5F 6F 77 6E 65 72 BD 24 BD 25 75 63 63 68 61 6E 67 65 5F 6F 77 6E 65 72 2B 72 6F 6C 65 73 1D 2B 73 74 61 74 65 4F 5D 79 22 06 70 58 85 53 65 78 70 69 72 65 73 5F 61 74 79 12 7E 54 5C 85 53 63 72 65 61 74 65 64 5F 62 79 1F 35 A5 75 3B 63 72 65 61 74 6F 72 AD B5 65 0F BD 2A C0 E8 03 BD 25 1F 35 BD 22 75 BD 25 BD 24 95 43 72 65 76 69 73 69 6F 6E 08 BD 3B 1D 33 70 61 72 65 6E 74 05 33 6F 72 69 67 69 6E 05 1B 6E 65 77 1D 43 73 75 62 49 74 65 6D 73 06 23 6B 65 79 73 0E C4 0A 01 1E 08 1C 01 00 01 C4 01 01 00 AB 3A 2E D8 2A 22 AF E2 30 89 85 73 14 37 BC 7B D7 6D 04 2F 44 35 EF DF 98 0B 79 0C EA 88 D1 6A F0 CD 9A 79 C6 C8 70 9A DC 71 21 E9 36 62 9B 6F DB 75 6B 02 25 E5 37 93 B7 65 0A DD 3D 13 AE 36 D4 0A 72 4D 2B 7E 58 37 BB C4 5C 92 BB FA D5 42 85 46 B9 73 B2 C3 DE CE 89 AA BA FC D7 DB CD 48 AC 98 D3 13 AC 38 16 62 D1 97 08 62 CF E1 1A F0 1B BC 2E 95 BE DF 83 07 AF BA E3 60 4D 7B 67 E2 9D 35 9A 5A D6 7C 66 8F 47 C1 3E 91 2F 57 39 72 CF 0F 1D CE 51 73 58 07 26 07 5F 91 8A 3A F7 45 35 F3 A8 15 89 6C 7F FC 44 33 81 2A 6B 51 AC 4E 2C 44 70 9E FE 39 90 A7 DA 5A 15 10 CC 67 6B 50 F1 B4 3E EB A2 BC 7C B5 24 D6 7E 9E A1 E2 AC 1C 99 C8 17 63 54 4A BE C6 63 D2 BA DF E0 FC 2A 52 16 30 92 9E 5C 7D B1 3D 76 A1 EF E7 6E 5A A0 73 B9 93 71 1D 0D E4 6E AA 87 5C 64 E8 76 40 4B BD"); mintContractsHexes.add("27 33 5F 5F 74 79 70 65 7B 54 72 61 6E 73 61 63 74 69 6F 6E 50 61 63 6B 43 63 6F 6E 74 72 61 63 74 C4 6E 06 27 3B 76 65 72 73 69 6F 6E 18 23 74 79 70 65 53 75 6E 69 63 61 70 73 75 6C 65 53 73 69 67 6E 61 74 75 72 65 73 0E C4 A8 02 17 23 65 78 74 73 C4 97 01 27 1B 6B 65 79 BC 21 07 66 EF 93 DB A7 78 84 0B 7C CF 64 DB 9E 07 24 4F F3 6E 48 C7 80 01 EE 46 E4 52 40 A7 3B 90 A8 61 33 73 68 61 35 31 32 BC 40 5D 24 63 80 51 96 37 55 B4 21 88 5A F3 D7 CA FA D0 4A 30 F0 23 0D 39 90 7B 2F 1D 30 42 DC F3 15 99 6F F1 4F 6B 7C EE D4 F2 B2 AD F8 12 52 69 91 C4 9E F3 B4 10 CA 0C 96 AA 16 EB 31 11 42 84 16 53 63 72 65 61 74 65 64 5F 61 74 79 0C 24 70 58 85 3B 70 75 62 5F 6B 65 79 C4 0A 01 1E 08 1C 01 00 01 C4 01 01 00 AB 3A 2E D8 2A 22 AF E2 30 89 85 73 14 37 BC 7B D7 6D 04 2F 44 35 EF DF 98 0B 79 0C EA 88 D1 6A F0 CD 9A 79 C6 C8 70 9A DC 71 21 E9 36 62 9B 6F DB 75 6B 02 25 E5 37 93 B7 65 0A DD 3D 13 AE 36 D4 0A 72 4D 2B 7E 58 37 BB C4 5C 92 BB FA D5 42 85 46 B9 73 B2 C3 DE CE 89 AA BA FC D7 DB CD 48 AC 98 D3 13 AC 38 16 62 D1 97 08 62 CF E1 1A F0 1B BC 2E 95 BE DF 83 07 AF BA E3 60 4D 7B 67 E2 9D 35 9A 5A D6 7C 66 8F 47 C1 3E 91 2F 57 39 72 CF 0F 1D CE 51 73 58 07 26 07 5F 91 8A 3A F7 45 35 F3 A8 15 89 6C 7F FC 44 33 81 2A 6B 51 AC 4E 2C 44 70 9E FE 39 90 A7 DA 5A 15 10 CC 67 6B 50 F1 B4 3E EB A2 BC 7C B5 24 D6 7E 9E A1 E2 AC 1C 99 C8 17 63 54 4A BE C6 63 D2 BA DF E0 FC 2A 52 16 30 92 9E 5C 7D B1 3D 76 A1 EF E7 6E 5A A0 73 B9 93 71 1D 0D E4 6E AA 87 5C 64 E8 76 40 4B BD 23 73 69 67 6E C4 00 01 8B 59 27 EB 2C 32 37 A3 F6 D4 B3 09 B2 B3 CE 32 14 FA 55 C6 95 02 0F 78 1D 18 5C AE BA DE FD BF B2 E1 A3 A3 F0 BE 0B F3 7F CC DD EA 8A 1E 47 61 FD 43 F5 39 13 EB 69 76 DC AE 73 9D B7 08 EE 2C 2A C6 16 EF 77 CE 59 28 EA 37 E9 9E FF C8 74 59 48 79 E1 21 07 1F D8 88 F0 AE D5 BE B3 61 25 04 BD 65 6A 31 A4 12 93 EB FE 42 FE 60 5F 36 3C 1B 5E 5C B3 43 08 75 4D 94 5F C3 F1 35 C8 E2 C8 54 BE 67 42 9C 21 E9 F9 19 D3 0C 2D 42 F7 C2 E1 48 B9 21 1F DF D2 1C 06 3C C1 C4 5B 15 E6 42 68 A0 37 7F 15 96 10 63 48 EC D1 DC 9E 79 EB BE 90 5C 9C BC C8 49 35 EF C7 11 53 0E A7 51 E2 3F 9B F1 48 47 D4 19 27 C0 FF E9 AD C9 68 07 73 52 DA 74 A2 DC 53 D7 02 81 26 F6 BE 1C 0C 9A A4 F3 C2 08 42 B0 3C 66 24 9E 81 1D F4 31 7E 9D 22 FB 69 5F 24 C9 DC 30 D0 B3 AE 29 E7 D4 41 89 46 CD 47 99 23 64 61 74 61 C4 95 03 1F 43 72 65 76 6F 6B 69 6E 67 0E 17 33 5F 5F 74 79 70 65 33 48 61 73 68 49 64 53 63 6F 6D 70 6F 73 69 74 65 33 BC 60 9E A0 99 F2 14 85 9B 79 53 88 17 55 78 B8 9B 27 AB 0B E7 85 25 E8 EE 79 8B 7A 6C 34 D0 6F 68 53 E5 3F 6B 19 F8 49 FA 2F 96 4E D2 B6 B9 3D CB 57 27 7C AF 95 27 8F 33 E5 85 8D 74 F6 41 00 65 AA 66 B5 F9 CD 5F 81 6F 42 44 8B CB 59 BA ED C9 6B 38 C1 6B F2 66 86 93 5B CA 9C 63 45 B8 63 7D 48 43 63 6F 6E 74 72 61 63 74 2F 2D 83 55 6E 69 76 65 72 73 61 43 6F 6E 74 72 61 63 74 4B 61 70 69 5F 6C 65 76 65 6C 18 53 64 65 66 69 6E 69 74 69 6F 6E 2F 53 63 72 65 61 74 65 64 5F 61 74 79 62 06 70 58 85 23 64 61 74 61 1F 23 6E 61 6D 65 23 6D 65 77 31 43 63 75 72 72 65 6E 63 79 9D 73 73 68 6F 72 74 5F 63 75 72 72 65 6E 63 79 9D 33 69 73 73 75 65 72 1F 2D 53 53 69 6D 70 6C 65 52 6F 6C 65 95 B5 4B 61 64 64 72 65 73 73 65 73 0E 17 2D 53 4B 65 79 41 64 64 72 65 73 73 43 75 61 64 64 72 65 73 73 BC 25 10 AE 02 80 D9 08 99 1A E5 E4 78 6A 71 D7 48 8F 65 4F 97 8C 89 78 23 D2 D0 9F 9C FE C2 11 F4 2E A6 CB A0 42 33 5B 70 65 72 6D 69 73 73 69 6F 6E 73 1F 33 6B 55 6F 45 4F 44 1F 2D 83 52 65 76 6F 6B 65 50 65 72 6D 69 73 73 69 6F 6E 23 72 6F 6C 65 1F 2D 43 52 6F 6C 65 4C 69 6E 6B 95 3B 40 72 65 76 6F 6B 65 5B 74 61 72 67 65 74 5F 6E 61 6D 65 2B 6F 77 6E 65 72 95 33 72 65 76 6F 6B 65 33 35 38 75 50 4B 77 3F 53 66 69 65 6C 64 5F 6E 61 6D 65 33 61 6D 6F 75 6E 74 4B 6D 69 6E 5F 76 61 6C 75 65 08 43 6D 69 6E 5F 75 6E 69 74 08 8B 6A 6F 69 6E 5F 6D 61 74 63 68 5F 66 69 65 6C 64 73 16 BB 18 64 65 66 69 6E 69 74 69 6F 6E 2E 64 61 74 61 2E 63 75 72 72 65 6E 63 79 8B 64 65 66 69 6E 69 74 69 6F 6E 2E 69 73 73 75 65 72 2D 9B 53 70 6C 69 74 4A 6F 69 6E 50 65 72 6D 69 73 73 69 6F 6E BD 24 1F 2D BD 26 95 5B 40 73 70 6C 69 74 5F 6A 6F 69 6E BD 28 BD 29 95 53 73 70 6C 69 74 5F 6A 6F 69 6E 33 4F 68 48 52 57 57 1F 2D AB 43 68 61 6E 67 65 4F 77 6E 65 72 50 65 72 6D 69 73 73 69 6F 6E BD 24 1F 2D BD 26 95 6B 40 63 68 61 6E 67 65 5F 6F 77 6E 65 72 BD 28 BD 29 95 63 63 68 61 6E 67 65 5F 6F 77 6E 65 72 2B 72 6F 6C 65 73 06 2B 73 74 61 74 65 57 7D 79 0C 24 70 58 85 53 65 78 70 69 72 65 73 5F 61 74 79 52 7E 54 5C 85 53 63 72 65 61 74 65 64 5F 62 79 1F 2D BD 18 95 3B 63 72 65 61 74 6F 72 BD 19 BD 1A 85 0F BD 2E 1B 39 36 37 BD 29 1F 2D BD 26 95 BD 29 BD 28 B5 43 72 65 76 69 73 69 6F 6E 10 BD 3F BD 40 33 70 61 72 65 6E 74 25 33 6F 72 69 67 69 6E 25 4B 62 72 61 6E 63 68 5F 69 64 1B 31 3A 30 6B 74 72 61 6E 73 61 63 74 69 6F 6E 61 6C 05 1B 6E 65 77 0E 17 2D 35 3D BC 60 09 1B EB A6 43 D9 46 06 57 6A 54 81 D2 67 B0 03 7B 8B 2F FF E2 2E BD BD A5 CE E3 0D 69 CF E2 DE 30 0D A8 5B 26 77 28 14 92 B1 1B ED 1D 31 D8 AA 39 AA 46 58 DA 2F E5 74 E6 62 0E B4 60 D7 4A 0F D5 C7 F5 E5 B8 37 CD 30 C8 47 F1 D1 6D 99 45 F4 86 59 35 3E 43 3A 3C 2B AA B6 66 93 26 93 F3 58 43 73 75 62 49 74 65 6D 73 06 23 6B 65 79 73 0E C4 0A 01 1E 08 1C 01 00 01 C4 01 01 00 AB 3A 2E D8 2A 22 AF E2 30 89 85 73 14 37 BC 7B D7 6D 04 2F 44 35 EF DF 98 0B 79 0C EA 88 D1 6A F0 CD 9A 79 C6 C8 70 9A DC 71 21 E9 36 62 9B 6F DB 75 6B 02 25 E5 37 93 B7 65 0A DD 3D 13 AE 36 D4 0A 72 4D 2B 7E 58 37 BB C4 5C 92 BB FA D5 42 85 46 B9 73 B2 C3 DE CE 89 AA BA FC D7 DB CD 48 AC 98 D3 13 AC 38 16 62 D1 97 08 62 CF E1 1A F0 1B BC 2E 95 BE DF 83 07 AF BA E3 60 4D 7B 67 E2 9D 35 9A 5A D6 7C 66 8F 47 C1 3E 91 2F 57 39 72 CF 0F 1D CE 51 73 58 07 26 07 5F 91 8A 3A F7 45 35 F3 A8 15 89 6C 7F FC 44 33 81 2A 6B 51 AC 4E 2C 44 70 9E FE 39 90 A7 DA 5A 15 10 CC 67 6B 50 F1 B4 3E EB A2 BC 7C B5 24 D6 7E 9E A1 E2 AC 1C 99 C8 17 63 54 4A BE C6 63 D2 BA DF E0 FC 2A 52 16 30 92 9E 5C 7D B1 3D 76 A1 EF E7 6E 5A A0 73 B9 93 71 1D 0D E4 6E AA 87 5C 64 E8 76 40 4B BD"); for (String hex : mintContractsHexes) { Contract coin = Contract.fromPackedTransaction(Bytes.fromHex(hex).getData()); int rnd = new Random().nextInt(2); String dir = ""; switch (rnd) { case 0: dir += "contract_subfolder/"; break; case 1: dir += "contract_subfolder/contract_subfolder_level2/"; break; } CLIMain.saveContract(coin, rootPath + dir + "Coin_" + coin.getStateData().getStringOrThrow(FIELD_NAME) + ".unicon"); } Contract nonCoin = Contract.fromDslFile("./src/test_files/simple_root_contract_v2.yml"); nonCoin.seal(); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/NonCoin.unicon"); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/contract_subfolder_level2/NonCoin.unicon"); callMain("-f", rootPath + "contract_subfolder/", "-v", "-r"); System.out.println(output); File[] filesToRemove = new File(rootPath + "contract_subfolder/").listFiles(); for (File file : filesToRemove) { file.delete(); } filesToRemove = new File(rootPath + "contract_subfolder/contract_subfolder_level2/").listFiles(); for (File file : filesToRemove) { file.delete(); } Decimal total = new Decimal(1967); System.out.println(output); assertTrue (output.indexOf(total + " (mew1)") >= 0); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void downloadContract() throws Exception { callMain("-d", "www.mainnetwork.io"); System.out.println(output); assertTrue (output.indexOf("downloading from www.mainnetwork.io") >= 0); assertEquals(0, errors.size()); } | public static Contract downloadContract(String url) { report("downloading from " + url); return null; } | CLIMain { public static Contract downloadContract(String url) { report("downloading from " + url); return null; } } | CLIMain { public static Contract downloadContract(String url) { report("downloading from " + url); return null; } } | CLIMain { public static Contract downloadContract(String url) { report("downloading from " + url); return null; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Contract downloadContract(String url) { report("downloading from " + url); return null; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void checkContract() throws Exception { callMain("-ch", basePath + "contract1.unicon"); System.out.println(output); assertEquals(0, errors.size()); } | private static void checkContract(Contract contract) { 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"); } } | CLIMain { private static void checkContract(Contract contract) { 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"); } } } | CLIMain { private static void checkContract(Contract contract) { 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"); } } } | CLIMain { private static void checkContract(Contract contract) { 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"); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { private static void checkContract(Contract contract) { 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"); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void checkContractInPathRecursively() throws Exception { File dirFile = new File(rootPath + "contract_subfolder/"); if (!dirFile.exists()) dirFile.mkdir(); dirFile = new File(rootPath + "contract_subfolder/contract_subfolder_level2/"); if (!dirFile.exists()) dirFile.mkdir(); List<String> coinValues = Arrays.asList("5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60"); List<Contract> listOfCoinsWithAmount = createListOfCoinsWithAmount(coinValues); for (Contract coin : listOfCoinsWithAmount) { int rnd = new Random().nextInt(2); String dir = ""; switch (rnd) { case 0: dir += "contract_subfolder/"; break; case 1: dir += "contract_subfolder/contract_subfolder_level2/"; break; } CLIMain.saveContract(coin, rootPath + dir + "Coin_" + coin.getStateData().getStringOrThrow(FIELD_NAME) + ".unicon"); } Contract nonCoin = Contract.fromDslFile("./src/test_files/simple_root_contract_v2.yml"); nonCoin.seal(); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/NonCoin.unicon"); CLIMain.saveContract(nonCoin, rootPath + "contract_subfolder/contract_subfolder_level2/NonCoin.unicon"); callMain("-ch", rootPath, "-v", "-r"); System.out.println(output); File[] filesToRemove = new File(rootPath + "contract_subfolder/").listFiles(); for (File file : filesToRemove) { file.delete(); } filesToRemove = new File(rootPath + "contract_subfolder/contract_subfolder_level2/").listFiles(); for (File file : filesToRemove) { file.delete(); } } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void unpackKey() throws Exception { AbstractKey k1 = TestKeys.privateKey(3).getPublicKey(); AbstractKey kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); k1 = SymmetricKey.fromPassword("helluva", 4096); kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); k1 = TestKeys.privateKey(2); kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); } | public AbstractKey unpackKey(byte[] data) throws EncryptionError { switch (algorythm) { case RSAPublic: return new PublicKey(data, this); case RSAPrivate: return new PrivateKey(data, this); case AES256: return new SymmetricKey(data, this); } throw new EncryptionError("can't unpack key: " + this); } | KeyInfo { public AbstractKey unpackKey(byte[] data) throws EncryptionError { switch (algorythm) { case RSAPublic: return new PublicKey(data, this); case RSAPrivate: return new PrivateKey(data, this); case AES256: return new SymmetricKey(data, this); } throw new EncryptionError("can't unpack key: " + this); } } | KeyInfo { public AbstractKey unpackKey(byte[] data) throws EncryptionError { switch (algorythm) { case RSAPublic: return new PublicKey(data, this); case RSAPrivate: return new PrivateKey(data, this); case AES256: return new SymmetricKey(data, this); } throw new EncryptionError("can't unpack key: " + this); } KeyInfo(Algorythm algorythm, byte[] tag, int keyLength); KeyInfo(Algorythm algorythm, byte[] tag); KeyInfo(PRF PRF, int rounds, byte[] salt, byte[] tag); KeyInfo(byte[] packedInfo); } | KeyInfo { public AbstractKey unpackKey(byte[] data) throws EncryptionError { switch (algorythm) { case RSAPublic: return new PublicKey(data, this); case RSAPrivate: return new PrivateKey(data, this); case AES256: return new SymmetricKey(data, this); } throw new EncryptionError("can't unpack key: " + this); } KeyInfo(Algorythm algorythm, byte[] tag, int keyLength); KeyInfo(Algorythm algorythm, byte[] tag); KeyInfo(PRF PRF, int rounds, byte[] salt, byte[] tag); KeyInfo(byte[] packedInfo); byte[] getSalt(); boolean matchType(KeyInfo otherInfo); boolean matchType(AbstractKey otherKey); boolean matchTag(KeyInfo keyInfo); void setTag(byte[] tag); String getBase64Tag(); boolean isPassword(); byte[] getTag(); int getRounds(); Algorythm getAlgorythm(); PRF getPRF(); int getKeyLength(); byte[] pack(); SymmetricKey derivePassword(String password); AbstractKey unpackKey(byte[] data); @Override String toString(); } | KeyInfo { public AbstractKey unpackKey(byte[] data) throws EncryptionError { switch (algorythm) { case RSAPublic: return new PublicKey(data, this); case RSAPrivate: return new PrivateKey(data, this); case AES256: return new SymmetricKey(data, this); } throw new EncryptionError("can't unpack key: " + this); } KeyInfo(Algorythm algorythm, byte[] tag, int keyLength); KeyInfo(Algorythm algorythm, byte[] tag); KeyInfo(PRF PRF, int rounds, byte[] salt, byte[] tag); KeyInfo(byte[] packedInfo); byte[] getSalt(); boolean matchType(KeyInfo otherInfo); boolean matchType(AbstractKey otherKey); boolean matchTag(KeyInfo keyInfo); void setTag(byte[] tag); String getBase64Tag(); boolean isPassword(); byte[] getTag(); int getRounds(); Algorythm getAlgorythm(); PRF getPRF(); int getKeyLength(); byte[] pack(); SymmetricKey derivePassword(String password); AbstractKey unpackKey(byte[] data); @Override String toString(); } |
@Test public void revokeContractVirtual() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(rootPath+"_xer0yfe2nn1xthc.private.unikey"); c.addSignerKeyFromFile(rootPath + "keys/u_key.private.unikey"); PrivateKey goodKey = c.getKeysToSignWith().iterator().next(); c.setOwnerKeys(goodKey); c.seal(); System.out.println("---"); System.out.println("register contract"); System.out.println("---"); CLIMain.registerContract(c); Thread.sleep(1500); System.out.println("---"); System.out.println("check contract"); System.out.println("---"); callMain("--probe", c.getId().toBase64String()); System.out.println(output); assertTrue (output.indexOf(ItemState.APPROVED.name()) >= 0); PrivateKey issuer1 = TestKeys.privateKey(1 ); Contract tc = ContractsService.createRevocation(c, issuer1, goodKey); assertTrue(tc.check()); System.out.println("---"); System.out.println("register revoking contract"); System.out.println("---"); CLIMain.registerContract(tc); Thread.sleep(1500); System.out.println("---"); System.out.println("check revoking contract"); System.out.println("---"); callMain("--probe", tc.getId().toBase64String()); System.out.println(output); assertTrue (output.indexOf(ItemState.APPROVED.name()) >= 1); Thread.sleep(1500); System.out.println("---"); System.out.println("check contract"); System.out.println("---"); callMain("--probe", c.getId().toBase64String()); System.out.println(output); assertTrue (output.indexOf(ItemState.REVOKED.name()) >= 0); } | @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contract.getId().toBase64String()); addErrors(errors); } else { ItemResult r; if (fromPackedTransaction) { r = getClientNetwork().register(contract.getPackedTransaction(), waitTime); } else { r = getClientNetwork().register(contract.getLastSealedBinary(), waitTime); } report("submitted with result:"); report(r.toString()); } } | CLIMain { @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contract.getId().toBase64String()); addErrors(errors); } else { ItemResult r; if (fromPackedTransaction) { r = getClientNetwork().register(contract.getPackedTransaction(), waitTime); } else { r = getClientNetwork().register(contract.getLastSealedBinary(), waitTime); } report("submitted with result:"); report(r.toString()); } } } | CLIMain { @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contract.getId().toBase64String()); addErrors(errors); } else { ItemResult r; if (fromPackedTransaction) { r = getClientNetwork().register(contract.getPackedTransaction(), waitTime); } else { r = getClientNetwork().register(contract.getLastSealedBinary(), waitTime); } report("submitted with result:"); report(r.toString()); } } } | CLIMain { @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contract.getId().toBase64String()); addErrors(errors); } else { ItemResult r; if (fromPackedTransaction) { r = getClientNetwork().register(contract.getPackedTransaction(), waitTime); } else { r = getClientNetwork().register(contract.getLastSealedBinary(), waitTime); } report("submitted with result:"); report(r.toString()); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contract.getId().toBase64String()); addErrors(errors); } else { ItemResult r; if (fromPackedTransaction) { r = getClientNetwork().register(contract.getPackedTransaction(), waitTime); } else { r = getClientNetwork().register(contract.getLastSealedBinary(), waitTime); } report("submitted with result:"); report(r.toString()); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void revokeCreatedContractWithRole() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(PRIVATE_KEY_PATH); PrivateKey goodKey = c.getKeysToSignWith().iterator().next(); c.setOwnerKeys(goodKey); c.seal(); String contractFileName = basePath + "with_role_for_revoke.unicon"; CLIMain.saveContract(c, contractFileName); System.out.println("---"); System.out.println("register contract"); System.out.println("---"); String uContract = getApprovedUContract(); callMain2("--register", contractFileName, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); Thread.sleep(1500); System.out.println("---"); System.out.println("check contract"); System.out.println("---"); callMain("--probe", c.getId().toBase64String()); System.out.println(output); assertTrue (output.indexOf(ItemState.APPROVED.name()) >= 0); uContract = getApprovedUContract(); callMain2("-revoke", contractFileName, "-k", PRIVATE_KEY_PATH, "-v", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); Thread.sleep(1500); System.out.println("---"); System.out.println("check contract after revoke"); System.out.println("---"); callMain("--probe", c.getId().toBase64String()); System.out.println(output); assertTrue (output.indexOf(ItemState.REVOKED.name()) >= 0); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void revokeContract() throws Exception { String contractFileName = basePath + "contract_for_revoke3.unicon"; String uContract = getApprovedUContract(); callMain2("--register", contractFileName, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); Contract c = CLIMain.loadContract(contractFileName); System.out.println("contract: " + c.getId().toBase64String()); Thread.sleep(1500); System.out.println("probe before revoke"); callMain2("--probe", c.getId().toBase64String(), "--verbose"); Thread.sleep(500); uContract = getApprovedUContract(); callMain2("-revoke", contractFileName, "-k", PRIVATE_KEY_PATH, "-v", "--u", uContract, "-k", rootPath + "keys/stepan_mamontov.private.unikey"); Thread.sleep(2500); System.out.println("probe after revoke"); callMain("--probe", c.getId().toBase64String(), "--verbose"); System.out.println(output); assertEquals(0, errors.size()); assertTrue (output.indexOf(ItemState.REVOKED.name()) >= 0); } | public static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key) throws IOException { report("keys num: " + key.length); Contract tc = ContractsService.createRevocation(contract, key); Parcel parcel = prepareForRegisterContract(tc, u, amount, uKeys, withTestPayment); if (parcel != null) registerParcel(parcel, 0); return parcel; } | CLIMain { public static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key) throws IOException { report("keys num: " + key.length); Contract tc = ContractsService.createRevocation(contract, key); Parcel parcel = prepareForRegisterContract(tc, u, amount, uKeys, withTestPayment); if (parcel != null) registerParcel(parcel, 0); return parcel; } } | CLIMain { public static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key) throws IOException { report("keys num: " + key.length); Contract tc = ContractsService.createRevocation(contract, key); Parcel parcel = prepareForRegisterContract(tc, u, amount, uKeys, withTestPayment); if (parcel != null) registerParcel(parcel, 0); return parcel; } } | CLIMain { public static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key) throws IOException { report("keys num: " + key.length); Contract tc = ContractsService.createRevocation(contract, key); Parcel parcel = prepareForRegisterContract(tc, u, amount, uKeys, withTestPayment); if (parcel != null) registerParcel(parcel, 0); return parcel; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key) throws IOException { report("keys num: " + key.length); Contract tc = ContractsService.createRevocation(contract, key); Parcel parcel = prepareForRegisterContract(tc, u, amount, uKeys, withTestPayment); if (parcel != null) registerParcel(parcel, 0); return parcel; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void revokeContractWithoutKey() throws Exception { String contractFileName = basePath + "contract_for_revoke1.unicon"; String uContract = getApprovedUContract(); callMain2("--register", contractFileName, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); callMain2("-revoke", contractFileName, "-v"); Thread.sleep(1500); System.out.println("probe after revoke"); Contract c = CLIMain.loadContract(contractFileName); callMain("--probe", c.getId().toBase64String(), "--verbose"); System.out.println(output); assertEquals(0, errors.size()); assertTrue (output.indexOf(ItemState.REVOKED.name()) < 0); } | public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void revokeTwoContracts() throws Exception { String contractFileName1 = basePath + "contract_for_revoke1.unicon"; String contractFileName2 = basePath + "contract_for_revoke2.unicon"; System.out.println("---"); System.out.println("register contracts"); System.out.println("---"); String uContract = getApprovedUContract(); callMain2("--register", contractFileName1, contractFileName2, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); Thread.sleep(1500); System.out.println("---"); System.out.println("check u"); System.out.println("---"); uContract = getApprovedUContract(); Contract u = CLIMain.loadContract(uContract); System.out.println("check u " + u.getId().toBase64String()); callMain2("--probe", u.getId().toBase64String(), "--verbose"); System.out.println("---"); System.out.println("revoke contracts"); System.out.println("---"); callMain2("-revoke", contractFileName1, contractFileName2, "-v", "--u", uContract, "-k", rootPath + "keys/stepan_mamontov.private.unikey", "-k", PRIVATE_KEY_PATH); Thread.sleep(1500); System.out.println("---"); System.out.println("check contracts after revoke"); System.out.println("---"); Contract c1 = CLIMain.loadContract(contractFileName1); callMain2("--probe", c1.getId().toBase64String(), "--verbose"); Contract c2 = CLIMain.loadContract(contractFileName2); callMain("--probe", c2.getId().toBase64String(), "--verbose"); Contract u2 = CLIMain.loadContract(uContract); System.out.println("check u " + u2.getId().toBase64String()); callMain2("--probe", u2.getId().toBase64String(), "--verbose"); System.out.println(output); assertEquals(0, errors.size()); assertTrue (output.indexOf(ItemState.REVOKED.name()) >= 1); } | public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void packContractWithCounterParts() throws Exception { String contractFileName = basePath + "coin1000.unicon"; Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(1000)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, contractFileName); callMain2("--check", contractFileName, "-v"); callMain2("-pack-with", contractFileName, "-add-sibling", basePath + "packedContract_new_item.unicon", "-add-revoke", basePath + "packedContract_revoke.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey", "-v"); callMain("--check", contractFileName, "-v"); System.out.println(output); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void packContractWithCounterPartsWithName() throws Exception { String contractFileName = basePath + "coin100.unicon"; String savingFileName = basePath + "packed.unicon"; Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, contractFileName); callMain2("--check", contractFileName, "-v"); callMain2("-pack-with", contractFileName, "-add-sibling", basePath + "contract2.unicon", "-add-revoke", basePath + "contract_for_revoke1.unicon", "--output", savingFileName, "-v"); callMain("--check", savingFileName, "-v"); System.out.println(output); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void calculateContractProcessingCostFromBinary() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_cost.unicon"); System.out.println("--- cost checking ---"); int costShouldBe = (int) Math.ceil((double)28 / Quantiser.quantaPerU); callMain("--cost", basePath + "contract_for_cost.unicon"); System.out.println(output); assertTrue (output.indexOf("Contract processing cost is " + costShouldBe + " U") >= 0); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void calculateContractProcessingCostFromManySources() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_cost1.unicon"); CLIMain.saveContract(contract, basePath + "contract_for_cost2.unicon"); System.out.println("--- cost checking ---"); int costShouldBe = (int) Math.ceil((double)28 / Quantiser.quantaPerU); callMain("--cost", basePath + "contract_for_cost1.unicon", basePath + "contract_for_cost2.unicon"); System.out.println(output); assertTrue (output.indexOf("Contract processing cost is " + costShouldBe + " U") >= 2); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void registerContractAndPrintProcessingCost() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost.unicon"); System.out.println("--- registering contract (with processing cost print) ---"); int costShouldBe = (int) Math.ceil((double) 28 / Quantiser.quantaPerU); callMain("--register", basePath + "contract_for_register_and_cost.unicon", "--cost"); System.out.println(output); assertTrue (output.indexOf("Contract processing cost is " + costShouldBe + " U") >= 0); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void testBasics() throws Exception { Syntex1 s = new Syntex1(); s.update("Hello world"); byte[] d1 = s.digest(); assertEquals(36, s.getLength()); byte[] d2 = new Syntex1().digest("Fello world"); assertEquals(36, d2.length); byte[] d3 = new Syntex1().digest("Hello world"); assertArrayEquals(d1, d3); assertThat( d3, equalTo(d1)); assertThat( d2, not(equalTo(d1))); InputStream in = new ByteArrayInputStream("Hello world".getBytes()); assertThat(d1, equalTo( new Syntex1().digest(in))); } | @Override public int getLength() { return 36; } | Syntex1 extends Digest { @Override public int getLength() { return 36; } } | Syntex1 extends Digest { @Override public int getLength() { return 36; } } | Syntex1 extends Digest { @Override public int getLength() { return 36; } @Override int getLength(); } | Syntex1 extends Digest { @Override public int getLength() { return 36; } @Override int getLength(); } |
@Test public void registerContractWithPayment() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); Files.deleteIfExists(Paths.get(basePath + "contract_for_register_and_cost.unicon")); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost.unicon"); System.out.println("--- get u ---"); String uContract = getApprovedUContract(); System.out.println("--- registering contract (with processing cost print) ---"); LogPrinter.showDebug(true); callMain("--register", basePath + "contract_for_register_and_cost.unicon", "--u", uContract, "-k", rootPath + "keys/stepan_mamontov.private.unikey", "-amount", "2", "-wait", "5000"); System.out.println(output); assertTrue (output.indexOf("registering the paid contract " + contract.getId() + " from " + basePath + "contract_for_register_and_cost.unicon" + " for 2 U") >= 0); assertTrue (output.indexOf("paid contract " + contract.getId() + " submitted with result: ItemResult<APPROVED") >= 0); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void registerContractWithPaymentForStorage() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); Files.deleteIfExists(Paths.get(basePath + "contract_for_register_and_cost.unicon")); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost.unicon"); System.out.println("--- get u ---"); String uContract = getApprovedUContract(); System.out.println("--- registering contract with paying parcel (with processing cost print) ---"); LogPrinter.showDebug(true); callMain("--register", basePath + "contract_for_register_and_cost.unicon", "-k-contract", PRIVATE_KEY_PATH, "--u", uContract, "-k", rootPath + "keys/stepan_mamontov.private.unikey", "-amount", "2", "-amount-storage", "100", "-wait", "10000"); System.out.println(output); assertTrue (output.indexOf("registering the paid contract " + contract.getId() + " from " + basePath + "contract_for_register_and_cost.unicon" + " for 2 U (and 100 U for storage)") >= 0); assertTrue (output.indexOf("submitted with result: ItemResult<APPROVED") >= 0); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void registerContractAndPrintProcessingCostBreak() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost.unicon"); System.out.println("--- registering contract (with processing cost print) ---"); int costShouldBe = 28; Contract.setTestQuantaLimit(15); callMain("--register", basePath + "contract_for_register_and_cost.unicon", "--cost"); System.out.println(output); assertTrue (output.indexOf("ERROR: QUANTIZER_COST_LIMIT") >= 0); Contract.setTestQuantaLimit(-1); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void registerContractAndPrintProcessingCostBreakWhileUnpacking() throws Exception { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost.unicon"); System.out.println("--- registering contract (with processing cost print) ---"); int costShouldBe = 28; Contract.setTestQuantaLimit(1); callMain("--register", basePath + "contract_for_register_and_cost.unicon", "--cost"); System.out.println(output); assertTrue (output.indexOf("ERROR: QUANTIZER_COST_LIMIT") >= 0); Contract.setTestQuantaLimit(-1); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void registerManyContractAndPrintProcessingCost() throws Exception { for (int i = 0; i < 2; i++) { Contract contract = createCoin(); contract.getStateData().set(FIELD_NAME, new Decimal(100)); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); contract.seal(); CLIMain.saveContract(contract, basePath + "contract_for_register_and_cost" + i + ".unicon"); } System.out.println("--- registering contract (with processing cost print) ---"); int costShouldBe = (int) Math.ceil((double)28 / Quantiser.quantaPerU); callMain("--register", basePath + "contract_for_register_and_cost0.unicon", basePath + "contract_for_register_and_cost1.unicon", "--cost"); System.out.println(output); assertTrue (output.indexOf("Contract processing cost is " + costShouldBe + " U") >= 1); } | public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Ignore @Test public void printWallets() throws Exception { System.out.println("\n\n"); callMain("-f", "/home/flint/w/uniclient-test", "--verbose"); System.out.println(output); System.out.println("\n\n"); } | 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(""); HashSet<WalletValueModel> balance = new HashSet<>(); for (Contract contract : wallet.getContracts()) { try { Decimal numcoins = new Decimal(contract.getStateData().getStringOrThrow(AMOUNT_FIELD_NAME)); SplitJoinPermission sjp = (SplitJoinPermission)contract.getPermissions().get("split_join").iterator().next(); WalletValueModel walletValueModel = null; for (WalletValueModel wvm : balance) { if (sjp.validateMergeFields(contract, wvm.contract)) walletValueModel = wvm; } if (walletValueModel == null) walletValueModel = new WalletValueModel(); walletValueModel.value = walletValueModel.value.add(numcoins); String currencyTag = contract.getDefinition().getData().getString("currency_code", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_short_name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("short_currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_name", null); if (currencyTag == null) currencyTag = contract.getOrigin().toString(); walletValueModel.tag = currencyTag; walletValueModel.contract = contract; balance.add(walletValueModel); reporter.verbose("found coins: " + contract.getOrigin().toString() + " -> " + numcoins + " (" + currencyTag + ") "); } catch (Exception e) { e.printStackTrace(); } } reporter.verbose(""); reporter.message("total in the wallet: "); for (WalletValueModel w : balance) { reporter.message(w.value + " (" + w.tag + ") "); } } } | CLIMain { 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(""); HashSet<WalletValueModel> balance = new HashSet<>(); for (Contract contract : wallet.getContracts()) { try { Decimal numcoins = new Decimal(contract.getStateData().getStringOrThrow(AMOUNT_FIELD_NAME)); SplitJoinPermission sjp = (SplitJoinPermission)contract.getPermissions().get("split_join").iterator().next(); WalletValueModel walletValueModel = null; for (WalletValueModel wvm : balance) { if (sjp.validateMergeFields(contract, wvm.contract)) walletValueModel = wvm; } if (walletValueModel == null) walletValueModel = new WalletValueModel(); walletValueModel.value = walletValueModel.value.add(numcoins); String currencyTag = contract.getDefinition().getData().getString("currency_code", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_short_name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("short_currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_name", null); if (currencyTag == null) currencyTag = contract.getOrigin().toString(); walletValueModel.tag = currencyTag; walletValueModel.contract = contract; balance.add(walletValueModel); reporter.verbose("found coins: " + contract.getOrigin().toString() + " -> " + numcoins + " (" + currencyTag + ") "); } catch (Exception e) { e.printStackTrace(); } } reporter.verbose(""); reporter.message("total in the wallet: "); for (WalletValueModel w : balance) { reporter.message(w.value + " (" + w.tag + ") "); } } } } | CLIMain { 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(""); HashSet<WalletValueModel> balance = new HashSet<>(); for (Contract contract : wallet.getContracts()) { try { Decimal numcoins = new Decimal(contract.getStateData().getStringOrThrow(AMOUNT_FIELD_NAME)); SplitJoinPermission sjp = (SplitJoinPermission)contract.getPermissions().get("split_join").iterator().next(); WalletValueModel walletValueModel = null; for (WalletValueModel wvm : balance) { if (sjp.validateMergeFields(contract, wvm.contract)) walletValueModel = wvm; } if (walletValueModel == null) walletValueModel = new WalletValueModel(); walletValueModel.value = walletValueModel.value.add(numcoins); String currencyTag = contract.getDefinition().getData().getString("currency_code", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_short_name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("short_currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_name", null); if (currencyTag == null) currencyTag = contract.getOrigin().toString(); walletValueModel.tag = currencyTag; walletValueModel.contract = contract; balance.add(walletValueModel); reporter.verbose("found coins: " + contract.getOrigin().toString() + " -> " + numcoins + " (" + currencyTag + ") "); } catch (Exception e) { e.printStackTrace(); } } reporter.verbose(""); reporter.message("total in the wallet: "); for (WalletValueModel w : balance) { reporter.message(w.value + " (" + w.tag + ") "); } } } } | CLIMain { 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(""); HashSet<WalletValueModel> balance = new HashSet<>(); for (Contract contract : wallet.getContracts()) { try { Decimal numcoins = new Decimal(contract.getStateData().getStringOrThrow(AMOUNT_FIELD_NAME)); SplitJoinPermission sjp = (SplitJoinPermission)contract.getPermissions().get("split_join").iterator().next(); WalletValueModel walletValueModel = null; for (WalletValueModel wvm : balance) { if (sjp.validateMergeFields(contract, wvm.contract)) walletValueModel = wvm; } if (walletValueModel == null) walletValueModel = new WalletValueModel(); walletValueModel.value = walletValueModel.value.add(numcoins); String currencyTag = contract.getDefinition().getData().getString("currency_code", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_short_name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("short_currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_name", null); if (currencyTag == null) currencyTag = contract.getOrigin().toString(); walletValueModel.tag = currencyTag; walletValueModel.contract = contract; balance.add(walletValueModel); reporter.verbose("found coins: " + contract.getOrigin().toString() + " -> " + numcoins + " (" + currencyTag + ") "); } catch (Exception e) { e.printStackTrace(); } } reporter.verbose(""); reporter.message("total in the wallet: "); for (WalletValueModel w : balance) { reporter.message(w.value + " (" + w.tag + ") "); } } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { 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(""); HashSet<WalletValueModel> balance = new HashSet<>(); for (Contract contract : wallet.getContracts()) { try { Decimal numcoins = new Decimal(contract.getStateData().getStringOrThrow(AMOUNT_FIELD_NAME)); SplitJoinPermission sjp = (SplitJoinPermission)contract.getPermissions().get("split_join").iterator().next(); WalletValueModel walletValueModel = null; for (WalletValueModel wvm : balance) { if (sjp.validateMergeFields(contract, wvm.contract)) walletValueModel = wvm; } if (walletValueModel == null) walletValueModel = new WalletValueModel(); walletValueModel.value = walletValueModel.value.add(numcoins); String currencyTag = contract.getDefinition().getData().getString("currency_code", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_short_name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("short_currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("currency", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("name", null); if (currencyTag == null) currencyTag = contract.getDefinition().getData().getString("unit_name", null); if (currencyTag == null) currencyTag = contract.getOrigin().toString(); walletValueModel.tag = currencyTag; walletValueModel.contract = contract; balance.add(walletValueModel); reporter.verbose("found coins: " + contract.getOrigin().toString() + " -> " + numcoins + " (" + currencyTag + ") "); } catch (Exception e) { e.printStackTrace(); } } reporter.verbose(""); reporter.message("total in the wallet: "); for (WalletValueModel w : balance) { reporter.message(w.value + " (" + w.tag + ") "); } } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void anonymizeRole() throws Exception { callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing.unicon").exists()); callMain("-anonymize", basePath + "forRoleAnonymizing.unicon", "-role", "issuer"); assertTrue (new File(basePath + "forRoleAnonymizing_anonymized.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); Contract contract = CLIMain.loadContract(basePath + "forRoleAnonymizing_anonymized.unicon", true); assertFalse(contract.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract = new Contract(contract.getLastSealedBinary()); assertFalse(anonPublishedContract.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract.getSealedByKeys().contains(key.getPublicKey())); } | public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void anonymizeAllRoles() throws Exception { callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing.unicon").exists()); callMain("-anonymize", basePath + "forRoleAnonymizing.unicon"); assertTrue (new File(basePath + "forRoleAnonymizing_anonymized.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); PrivateKey ownerKey = new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey")); Contract contract = CLIMain.loadContract(basePath + "forRoleAnonymizing_anonymized.unicon", true); assertFalse(contract.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(contract.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(contract.getCreator().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract = new Contract(contract.getLastSealedBinary()); assertFalse(anonPublishedContract.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(anonPublishedContract.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract.getCreator().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract.getSealedByKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract.getSealedByKeys().contains(ownerKey.getPublicKey())); } | public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void anonymizeRoleAndSaveWithName() throws Exception { callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing.unicon").exists()); callMain("-anonymize", basePath + "forRoleAnonymizing.unicon", "-role", "issuer", "--output", basePath + "myAnon.unicon"); assertTrue (new File(basePath + "myAnon.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); Contract contract = CLIMain.loadContract(basePath + "myAnon.unicon", true); assertFalse(contract.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract = new Contract(contract.getLastSealedBinary()); assertFalse(anonPublishedContract.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract.getSealedByKeys().contains(key.getPublicKey())); } | public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void anonymizeRoleForTwoContracts() throws Exception { callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing1.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing2.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing1.unicon").exists()); assertTrue (new File(basePath + "forRoleAnonymizing2.unicon").exists()); callMain("-anonymize", basePath + "forRoleAnonymizing1.unicon", basePath + "forRoleAnonymizing2.unicon", "-role", "issuer"); assertTrue (new File(basePath + "forRoleAnonymizing1_anonymized.unicon").exists()); assertTrue (new File(basePath + "forRoleAnonymizing2_anonymized.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); Contract contract1 = CLIMain.loadContract(basePath + "forRoleAnonymizing1_anonymized.unicon", true); assertFalse(contract1.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract1 = new Contract(contract1.getLastSealedBinary()); assertFalse(anonPublishedContract1.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract1.getSealedByKeys().contains(key.getPublicKey())); Contract contract2 = CLIMain.loadContract(basePath + "forRoleAnonymizing2_anonymized.unicon", true); assertFalse(contract2.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract2 = new Contract(contract2.getLastSealedBinary()); assertFalse(anonPublishedContract2.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract2.getSealedByKeys().contains(key.getPublicKey())); } | public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void serializationTest() throws Exception { byte[] packedPublicKey = Do.decodeBase64(publicKey64); PublicKey publicKey = new PublicKey(packedPublicKey); byte[] packedPublicKey2 = publicKey.pack(); assertArrayEquals(packedPublicKey, packedPublicKey2); byte[] packedPrivateKey = Do.decodeBase64(TestKeys.binaryKeys[3]); PrivateKey privateKey = new PrivateKey(packedPrivateKey); byte[] packedPrivateKey2 = privateKey.pack(); assertArrayEquals(packedPrivateKey, packedPrivateKey2); } | public byte[] pack() { @NonNull final Map<String, Object> params = privateKey.toHash(); return Boss.dumpToArray(new Object[]{ TYPE_PRIVATE, params.get("e"), params.get("p"), params.get("q") }); } | PrivateKey extends AbstractKey { public byte[] pack() { @NonNull final Map<String, Object> params = privateKey.toHash(); return Boss.dumpToArray(new Object[]{ TYPE_PRIVATE, params.get("e"), params.get("p"), params.get("q") }); } } | PrivateKey extends AbstractKey { public byte[] pack() { @NonNull final Map<String, Object> params = privateKey.toHash(); return Boss.dumpToArray(new Object[]{ TYPE_PRIVATE, params.get("e"), params.get("p"), params.get("q") }); } PrivateKey(byte[] packedBinaryKey, KeyInfo info); PrivateKey(byte[] packedBinaryKey); PrivateKey(int bitStrength); PrivateKey(); } | PrivateKey extends AbstractKey { public byte[] pack() { @NonNull final Map<String, Object> params = privateKey.toHash(); return Boss.dumpToArray(new Object[]{ TYPE_PRIVATE, params.get("e"), params.get("p"), params.get("q") }); } PrivateKey(byte[] packedBinaryKey, KeyInfo info); PrivateKey(byte[] packedBinaryKey); PrivateKey(int bitStrength); PrivateKey(); @Override boolean canSign(); @Override boolean isPrivate(); @Override byte[] decrypt(final byte[] encrypted); PublicKey getPublicKey(); byte[] pack(); @Override byte[] sign(InputStream input, HashType hashType); @Override KeyInfo info(); @Override boolean equals(Object obj); @Override int hashCode(); @Override byte[] fingerprint(); static PrivateKey fromPath(Path path); @Override Digest updateDigestWithKeyComponents(Digest digest); byte[] packWithPassword(String password); byte[] packWithPassword(String password, int rounds); static PrivateKey unpackWithPassword(byte[] packedBinary, String password); } | PrivateKey extends AbstractKey { public byte[] pack() { @NonNull final Map<String, Object> params = privateKey.toHash(); return Boss.dumpToArray(new Object[]{ TYPE_PRIVATE, params.get("e"), params.get("p"), params.get("q") }); } PrivateKey(byte[] packedBinaryKey, KeyInfo info); PrivateKey(byte[] packedBinaryKey); PrivateKey(int bitStrength); PrivateKey(); @Override boolean canSign(); @Override boolean isPrivate(); @Override byte[] decrypt(final byte[] encrypted); PublicKey getPublicKey(); byte[] pack(); @Override byte[] sign(InputStream input, HashType hashType); @Override KeyInfo info(); @Override boolean equals(Object obj); @Override int hashCode(); @Override byte[] fingerprint(); static PrivateKey fromPath(Path path); @Override Digest updateDigestWithKeyComponents(Digest digest); byte[] packWithPassword(String password); byte[] packWithPassword(String password, int rounds); static PrivateKey unpackWithPassword(byte[] packedBinary, String password); } |
@Test public void decrypt() throws Exception { AbstractPrivateKey rsaPrivateKey = oaepSpec.getPrivateKey(); AbstractPublicKey rsaPublicKey = rsaPrivateKey.getPublicKey(); ((RSAOAEPPrivateKey) rsaPrivateKey).resetDecryptor(); assertArrayEquals(rsaPrivateKey.decrypt(oaepSpec.C), oaepSpec.M); ((RSAOAEPPublicKey) rsaPublicKey).resetEncryptor(); assertArrayEquals(rsaPublicKey.encrypt(oaepSpec.M), oaepSpec.C); AbstractPrivateKey randomPrivateKey = randomPrivateKey4096; AbstractPublicKey randomPublicKey = randomPrivateKey.getPublicKey(); SecureRandom rng = new SecureRandom(); int maxMessageSize = ((RSAOAEPPrivateKey) randomPrivateKey).getMaxBlockSize(), minMessageSize = maxMessageSize, messageSize = (maxMessageSize >= minMessageSize) ? rng.nextInt(maxMessageSize - minMessageSize + 1) + minMessageSize : 0; for (int i = 0; i < NUMBER_OF_RANDOM_ENCRYPTION_DECRYPTION_CYCLES; i++) { ((RSAOAEPPrivateKey) randomPrivateKey).resetDecryptor(); ((RSAOAEPPublicKey) randomPublicKey).resetEncryptor(); byte[] message = new byte[messageSize]; rng.nextBytes(message); byte[] encrypted = randomPublicKey.encrypt(message), decrypted = randomPrivateKey.decrypt(encrypted); assertArrayEquals(decrypted, message); } } | @Override public byte[] decrypt(byte[] ciphertext) throws EncryptionError { if (state == null) { throw new IllegalStateException(); } else { try { return state.decryptor.processBlock(ciphertext, 0, ciphertext.length); } catch (InvalidCipherTextException e) { throw new EncryptionError("decrypt failed", e); } } } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] decrypt(byte[] ciphertext) throws EncryptionError { if (state == null) { throw new IllegalStateException(); } else { try { return state.decryptor.processBlock(ciphertext, 0, ciphertext.length); } catch (InvalidCipherTextException e) { throw new EncryptionError("decrypt failed", e); } } } } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] decrypt(byte[] ciphertext) throws EncryptionError { if (state == null) { throw new IllegalStateException(); } else { try { return state.decryptor.processBlock(ciphertext, 0, ciphertext.length); } catch (InvalidCipherTextException e) { throw new EncryptionError("decrypt failed", e); } } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] decrypt(byte[] ciphertext) throws EncryptionError { if (state == null) { throw new IllegalStateException(); } else { try { return state.decryptor.processBlock(ciphertext, 0, ciphertext.length); } catch (InvalidCipherTextException e) { throw new EncryptionError("decrypt failed", e); } } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] decrypt(byte[] ciphertext) throws EncryptionError { if (state == null) { throw new IllegalStateException(); } else { try { return state.decryptor.processBlock(ciphertext, 0, ciphertext.length); } catch (InvalidCipherTextException e) { throw new EncryptionError("decrypt failed", e); } } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; } |
@Test public void anonymizeRoleForTwoContractsWithNames() throws Exception { callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing1.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing2.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing1.unicon").exists()); assertTrue (new File(basePath + "forRoleAnonymizing2.unicon").exists()); callMain("-anonymize", basePath + "forRoleAnonymizing1.unicon", basePath + "forRoleAnonymizing2.unicon", "-role", "issuer", "--output", basePath + "myAnon1.unicon", "--output", basePath + "myAnon2.unicon"); assertTrue (new File(basePath + "myAnon1.unicon").exists()); assertTrue (new File(basePath + "myAnon2.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); Contract contract1 = CLIMain.loadContract(basePath + "myAnon1.unicon", true); assertFalse(contract1.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract1 = new Contract(contract1.getLastSealedBinary()); assertFalse(anonPublishedContract1.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract1.getSealedByKeys().contains(key.getPublicKey())); Contract contract2 = CLIMain.loadContract(basePath + "myAnon2.unicon", true); assertFalse(contract2.getIssuer().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract2 = new Contract(contract2.getLastSealedBinary()); assertFalse(anonPublishedContract2.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract2.getSealedByKeys().contains(key.getPublicKey())); } | public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void anonymizeAllRolesForTwoContracts() throws Exception { Files.deleteIfExists(Paths.get(basePath + "forRoleAnonymizing1.unicon")); Files.deleteIfExists(Paths.get(basePath + "forRoleAnonymizing2.unicon")); callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing1.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); callMain2("-create", rootPath + "TokenDSLTemplate.yml", "--output", basePath + "forRoleAnonymizing2.unicon", "-k", rootPath + "_xer0yfe2nn1xthc.private.unikey"); assertTrue (new File(basePath + "forRoleAnonymizing1.unicon").exists()); assertTrue (new File(basePath + "forRoleAnonymizing2.unicon").exists()); Files.deleteIfExists(Paths.get(basePath + "forRoleAnonymizing1_anonymized.unicon")); Files.deleteIfExists(Paths.get(basePath + "forRoleAnonymizing2_anonymized.unicon")); callMain("-anonymize", basePath + "forRoleAnonymizing1.unicon", basePath + "forRoleAnonymizing2.unicon"); assertTrue (new File(basePath + "forRoleAnonymizing1_anonymized.unicon").exists()); assertTrue (new File(basePath + "forRoleAnonymizing2_anonymized.unicon").exists()); System.out.println(output); PrivateKey key = new PrivateKey(Do.read(rootPath + "_xer0yfe2nn1xthc.private.unikey")); PrivateKey ownerKey = new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey")); Contract contract1 = CLIMain.loadContract(basePath + "forRoleAnonymizing1_anonymized.unicon", true); assertFalse(contract1.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(contract1.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(contract1.getCreator().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract1 = new Contract(contract1.getLastSealedBinary()); assertFalse(anonPublishedContract1.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(anonPublishedContract1.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract1.getCreator().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract1.getSealedByKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract1.getSealedByKeys().contains(ownerKey.getPublicKey())); Contract contract2 = CLIMain.loadContract(basePath + "forRoleAnonymizing1_anonymized.unicon", true); assertFalse(contract2.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(contract2.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(contract2.getCreator().getKeys().contains(key.getPublicKey())); Contract anonPublishedContract2 = new Contract(contract2.getLastSealedBinary()); assertFalse(anonPublishedContract2.getOwner().getKeys().contains(ownerKey.getPublicKey())); assertFalse(anonPublishedContract2.getIssuer().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract2.getCreator().getKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract2.getSealedByKeys().contains(key.getPublicKey())); assertFalse(anonPublishedContract2.getSealedByKeys().contains(ownerKey.getPublicKey())); } | public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void sign() throws Exception { PrivateKey key1 = new PrivateKey(2048); PrivateKey key2 = new PrivateKey(2048); Files.write(Paths.get(basePath + "signKey1.privateKey.unikey"),key1.pack(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); Files.write(Paths.get(basePath + "signKey2.privateKey.unikey"),key2.pack(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); HashSet<PrivateKey> issuers = new HashSet<>(); issuers.add(key1); HashSet<PublicKey> owners = new HashSet<>(); owners.add(key1.getPublicKey()); Contract contract = ContractsService.createTokenContract(issuers, owners, new BigDecimal("10000.50"), new BigDecimal("0.01")); SimpleRole issuer1 = new SimpleRole("issuer1",contract,new KeyRecord(key1.getPublicKey())); SimpleRole issuer2 = new SimpleRole("issuer2",contract,new KeyRecord(key2.getPublicKey())); ListRole issuer = new ListRole("issuer",contract,ListRole.Mode.ALL,Do.listOf(issuer1,issuer2)); contract.addRole(issuer); contract.seal(); contract.check(); assertFalse(contract.isOk()); Files.write(Paths.get(basePath + "sign.unicon"),contract.getPackedTransaction(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); assertFalse(CLIMain.loadContract(basePath + "sign.unicon").check()); callMain("--sign",basePath + "sign.unicon","--keys",basePath + "signKey2.privateKey.unikey"); callMain("--sign",basePath + "sign.unicon","--keys",basePath + "signKey2.privateKey.unikey","--output", basePath + "sign_2.unicon"); assertTrue(CLIMain.loadContract(basePath + "sign_2.unicon").check()); } | public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void probeFile() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(rootPath+"_xer0yfe2nn1xthc.private.unikey"); c.addSignerKeyFromFile(rootPath + "keys/u_key.private.unikey"); PrivateKey goodKey = c.getKeysToSignWith().iterator().next(); ((SimpleRole)c.getRole("owner")).addKeyRecord(new KeyRecord(goodKey.getPublicKey())); c.seal(); Files.write(Paths.get(basePath + "probeFile.unicon"),c.getPackedTransaction(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); System.out.println("---"); System.out.println("register contract"); System.out.println("---"); CLIMain.registerContract(c); Thread.sleep(1500); System.out.println("---"); System.out.println("check contract"); System.out.println("---"); callMain("--probe-file", basePath + "probeFile.unicon"); System.out.println(output); assertTrue (output.indexOf(ItemState.APPROVED.name()) >= 0); } | @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contract.getId().toBase64String()); addErrors(errors); } else { ItemResult r; if (fromPackedTransaction) { r = getClientNetwork().register(contract.getPackedTransaction(), waitTime); } else { r = getClientNetwork().register(contract.getLastSealedBinary(), waitTime); } report("submitted with result:"); report(r.toString()); } } | CLIMain { @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contract.getId().toBase64String()); addErrors(errors); } else { ItemResult r; if (fromPackedTransaction) { r = getClientNetwork().register(contract.getPackedTransaction(), waitTime); } else { r = getClientNetwork().register(contract.getLastSealedBinary(), waitTime); } report("submitted with result:"); report(r.toString()); } } } | CLIMain { @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contract.getId().toBase64String()); addErrors(errors); } else { ItemResult r; if (fromPackedTransaction) { r = getClientNetwork().register(contract.getPackedTransaction(), waitTime); } else { r = getClientNetwork().register(contract.getLastSealedBinary(), waitTime); } report("submitted with result:"); report(r.toString()); } } } | CLIMain { @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contract.getId().toBase64String()); addErrors(errors); } else { ItemResult r; if (fromPackedTransaction) { r = getClientNetwork().register(contract.getPackedTransaction(), waitTime); } else { r = getClientNetwork().register(contract.getLastSealedBinary(), waitTime); } report("submitted with result:"); report(r.toString()); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contract.getId().toBase64String()); addErrors(errors); } else { ItemResult r; if (fromPackedTransaction) { r = getClientNetwork().register(contract.getPackedTransaction(), waitTime); } else { r = getClientNetwork().register(contract.getLastSealedBinary(), waitTime); } report("submitted with result:"); report(r.toString()); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void createRegisterParcel() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.seal(); String contractFileName = basePath + "createRegisterParcel.unicon"; new FileOutputStream(contractFileName).write(contract.getPackedTransaction()); String uContract = getApprovedUContract(); callMain("--create-parcel", contractFileName, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); callMain("--register-parcel", new FilenameTool(contractFileName).setExtension("uniparcel").toString()); Thread.sleep(1500); System.out.println("probe after register"); Contract c = CLIMain.loadContract(contractFileName); callMain("--probe", c.getId().toBase64String(), "--verbose"); System.out.println(output); assertEquals(0, errors.size()); assertTrue (output.indexOf(ItemState.APPROVED.name()) > 0); } | public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); } | CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data); } } catch (Quantiser.QuantiserException e) { addError("QUANTIZER_COST_LIMIT", fileName, e.toString()); } } else { addError(Errors.NOT_FOUND.name(), fileName, "Path " + fileName + " does not exist"); } return contract; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; } |
@Test public void passwordProtectedJsCompatibilityTest() throws Exception { byte[] encrypted = Base64.decodeCompactString("NhDIoIYBvB1jb20uaWNvZGljaS5jcnlwdG8uUHJpdmF0ZUtleVtITUFDX1NIQTI1NsQaAe01NLf/Ffcye5nVmAOsYV5uy/Q/OXqbVfH4baSo5rgdtYl3xmTrkwfHEerHVjyB/raQcJ6b96k3oVIHu6I/wDtZ3TMkQ8gpjzlEnzOs6LQ+0OzObrjxFfpiXZdPMLzu4XPMSJINSZtkPkSOeBEqItCf2C2CfPgdI1MniiDAN9qmuWMuGkD4o6UgaGfCjy0WGv8vY0rgkkQUanf8ctcIEgbLCcpu2irJY+OUhh1qC+Dwm3uSDFarXC/94i/YWpSbo2Apyxjq6ynpXVyc2aQiOmOf13iHulq5t9eyoqP4uSXL4xHff23onQRnvvc4OC+vbQvHType64zPTxVCFDpw6rlUhT/bEJ6IOh8XhX+LHZeTEuaTy0LXE055xiT1P375"); byte[] packed = Base64.decodeCompactString("JgAcAQABvIEA96FWTEq/Wjmd7kYbx04I/Ax3OQV+6e4YWu7xBr8k/SexvYvFEE3c9dRsZSsEj7KzYrNpIXezCsxO+j1sHADmeojwuveDdQQM6M6fbvygHq/mxKGllDoJTpzX/CnkuXDwC+lpRkkMTIF48GaYDM525951HYW1pAIYaVr+V5ctVQW8gQDGM71OC1yBLv6n23dEuu9Vqna2lvDpEWNO7MgKY0Ri9vUPwp+F+dUiKsRTbjnukDFqiYiNj+jkcWgiXqnjqdAGf9LUWHfF80W1PwUhkFw7torLJfaAr6bZ6FRzGcxTMad0x7Rz+5lkBjliKqOt8AUAIvMVe45G0c0StJSoqdqc4Q=="); PrivateKey pk1 = PrivateKey.unpackWithPassword(encrypted,"some-password"); PrivateKey pk2 = new PrivateKey(packed); assertEquals(pk1,pk2); try { PrivateKey.unpackWithPassword(encrypted,"some-password1"); fail("should throw"); } catch (PrivateKey.PasswordProtectedException e) { } } | public static PrivateKey unpackWithPassword(byte[] packedBinary, String password) throws EncryptionError { List params = Boss.load(packedBinary); if ((Integer) params.get(0) == TYPE_PRIVATE) { return new PrivateKey(packedBinary); } else if ((Integer) params.get(0) == TYPE_PUBLIC) { throw new EncryptionError("the key is public, not private"); } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD) { try { int rounds = (int) params.get(1); Bytes salt = (Bytes) params.get(2); String function = (String) params.get(3); Bytes packedEncryptedKey = (Bytes) params.get(4); Bytes digest = (Bytes) params.get(5); SymmetricKey key = new KeyInfo(KeyInfo.PRF.valueOf(function), rounds, salt.getData(), null) .derivePassword(password); byte[] packedKey = key.decrypt(packedEncryptedKey.getData()); byte[] resDigest = new Crc32().update(packedKey).digest(); if (!digest.equals(new Bytes(resDigest))) { throw new PasswordProtectedException("wrong password"); } return new PrivateKey(packedKey); } catch (Exception e) { if (e instanceof PasswordProtectedException) throw e; throw new EncryptionError("failed to parse password protected private key", e); } } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD_V2) { try { KeyInfo keyInfo = new KeyInfo(((Bytes)params.get(1)).getData()); SymmetricKey key = keyInfo .derivePassword(password); byte[] packedKey = key.etaDecrypt(((Bytes) params.get(2)).getData()); return new PrivateKey(packedKey); } catch (SymmetricKey.AuthenticationFailed authenticationFailed) { throw new PasswordProtectedException("wrong password"); } catch (Exception e) { throw new EncryptionError("failed to parse password protected private key"); } } else { throw new EncryptionError("Bad or unknown private key type"); } } | PrivateKey extends AbstractKey { public static PrivateKey unpackWithPassword(byte[] packedBinary, String password) throws EncryptionError { List params = Boss.load(packedBinary); if ((Integer) params.get(0) == TYPE_PRIVATE) { return new PrivateKey(packedBinary); } else if ((Integer) params.get(0) == TYPE_PUBLIC) { throw new EncryptionError("the key is public, not private"); } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD) { try { int rounds = (int) params.get(1); Bytes salt = (Bytes) params.get(2); String function = (String) params.get(3); Bytes packedEncryptedKey = (Bytes) params.get(4); Bytes digest = (Bytes) params.get(5); SymmetricKey key = new KeyInfo(KeyInfo.PRF.valueOf(function), rounds, salt.getData(), null) .derivePassword(password); byte[] packedKey = key.decrypt(packedEncryptedKey.getData()); byte[] resDigest = new Crc32().update(packedKey).digest(); if (!digest.equals(new Bytes(resDigest))) { throw new PasswordProtectedException("wrong password"); } return new PrivateKey(packedKey); } catch (Exception e) { if (e instanceof PasswordProtectedException) throw e; throw new EncryptionError("failed to parse password protected private key", e); } } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD_V2) { try { KeyInfo keyInfo = new KeyInfo(((Bytes)params.get(1)).getData()); SymmetricKey key = keyInfo .derivePassword(password); byte[] packedKey = key.etaDecrypt(((Bytes) params.get(2)).getData()); return new PrivateKey(packedKey); } catch (SymmetricKey.AuthenticationFailed authenticationFailed) { throw new PasswordProtectedException("wrong password"); } catch (Exception e) { throw new EncryptionError("failed to parse password protected private key"); } } else { throw new EncryptionError("Bad or unknown private key type"); } } } | PrivateKey extends AbstractKey { public static PrivateKey unpackWithPassword(byte[] packedBinary, String password) throws EncryptionError { List params = Boss.load(packedBinary); if ((Integer) params.get(0) == TYPE_PRIVATE) { return new PrivateKey(packedBinary); } else if ((Integer) params.get(0) == TYPE_PUBLIC) { throw new EncryptionError("the key is public, not private"); } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD) { try { int rounds = (int) params.get(1); Bytes salt = (Bytes) params.get(2); String function = (String) params.get(3); Bytes packedEncryptedKey = (Bytes) params.get(4); Bytes digest = (Bytes) params.get(5); SymmetricKey key = new KeyInfo(KeyInfo.PRF.valueOf(function), rounds, salt.getData(), null) .derivePassword(password); byte[] packedKey = key.decrypt(packedEncryptedKey.getData()); byte[] resDigest = new Crc32().update(packedKey).digest(); if (!digest.equals(new Bytes(resDigest))) { throw new PasswordProtectedException("wrong password"); } return new PrivateKey(packedKey); } catch (Exception e) { if (e instanceof PasswordProtectedException) throw e; throw new EncryptionError("failed to parse password protected private key", e); } } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD_V2) { try { KeyInfo keyInfo = new KeyInfo(((Bytes)params.get(1)).getData()); SymmetricKey key = keyInfo .derivePassword(password); byte[] packedKey = key.etaDecrypt(((Bytes) params.get(2)).getData()); return new PrivateKey(packedKey); } catch (SymmetricKey.AuthenticationFailed authenticationFailed) { throw new PasswordProtectedException("wrong password"); } catch (Exception e) { throw new EncryptionError("failed to parse password protected private key"); } } else { throw new EncryptionError("Bad or unknown private key type"); } } PrivateKey(byte[] packedBinaryKey, KeyInfo info); PrivateKey(byte[] packedBinaryKey); PrivateKey(int bitStrength); PrivateKey(); } | PrivateKey extends AbstractKey { public static PrivateKey unpackWithPassword(byte[] packedBinary, String password) throws EncryptionError { List params = Boss.load(packedBinary); if ((Integer) params.get(0) == TYPE_PRIVATE) { return new PrivateKey(packedBinary); } else if ((Integer) params.get(0) == TYPE_PUBLIC) { throw new EncryptionError("the key is public, not private"); } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD) { try { int rounds = (int) params.get(1); Bytes salt = (Bytes) params.get(2); String function = (String) params.get(3); Bytes packedEncryptedKey = (Bytes) params.get(4); Bytes digest = (Bytes) params.get(5); SymmetricKey key = new KeyInfo(KeyInfo.PRF.valueOf(function), rounds, salt.getData(), null) .derivePassword(password); byte[] packedKey = key.decrypt(packedEncryptedKey.getData()); byte[] resDigest = new Crc32().update(packedKey).digest(); if (!digest.equals(new Bytes(resDigest))) { throw new PasswordProtectedException("wrong password"); } return new PrivateKey(packedKey); } catch (Exception e) { if (e instanceof PasswordProtectedException) throw e; throw new EncryptionError("failed to parse password protected private key", e); } } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD_V2) { try { KeyInfo keyInfo = new KeyInfo(((Bytes)params.get(1)).getData()); SymmetricKey key = keyInfo .derivePassword(password); byte[] packedKey = key.etaDecrypt(((Bytes) params.get(2)).getData()); return new PrivateKey(packedKey); } catch (SymmetricKey.AuthenticationFailed authenticationFailed) { throw new PasswordProtectedException("wrong password"); } catch (Exception e) { throw new EncryptionError("failed to parse password protected private key"); } } else { throw new EncryptionError("Bad or unknown private key type"); } } PrivateKey(byte[] packedBinaryKey, KeyInfo info); PrivateKey(byte[] packedBinaryKey); PrivateKey(int bitStrength); PrivateKey(); @Override boolean canSign(); @Override boolean isPrivate(); @Override byte[] decrypt(final byte[] encrypted); PublicKey getPublicKey(); byte[] pack(); @Override byte[] sign(InputStream input, HashType hashType); @Override KeyInfo info(); @Override boolean equals(Object obj); @Override int hashCode(); @Override byte[] fingerprint(); static PrivateKey fromPath(Path path); @Override Digest updateDigestWithKeyComponents(Digest digest); byte[] packWithPassword(String password); byte[] packWithPassword(String password, int rounds); static PrivateKey unpackWithPassword(byte[] packedBinary, String password); } | PrivateKey extends AbstractKey { public static PrivateKey unpackWithPassword(byte[] packedBinary, String password) throws EncryptionError { List params = Boss.load(packedBinary); if ((Integer) params.get(0) == TYPE_PRIVATE) { return new PrivateKey(packedBinary); } else if ((Integer) params.get(0) == TYPE_PUBLIC) { throw new EncryptionError("the key is public, not private"); } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD) { try { int rounds = (int) params.get(1); Bytes salt = (Bytes) params.get(2); String function = (String) params.get(3); Bytes packedEncryptedKey = (Bytes) params.get(4); Bytes digest = (Bytes) params.get(5); SymmetricKey key = new KeyInfo(KeyInfo.PRF.valueOf(function), rounds, salt.getData(), null) .derivePassword(password); byte[] packedKey = key.decrypt(packedEncryptedKey.getData()); byte[] resDigest = new Crc32().update(packedKey).digest(); if (!digest.equals(new Bytes(resDigest))) { throw new PasswordProtectedException("wrong password"); } return new PrivateKey(packedKey); } catch (Exception e) { if (e instanceof PasswordProtectedException) throw e; throw new EncryptionError("failed to parse password protected private key", e); } } else if ((Integer) params.get(0) == TYPE_PRIVATE_PASSWORD_V2) { try { KeyInfo keyInfo = new KeyInfo(((Bytes)params.get(1)).getData()); SymmetricKey key = keyInfo .derivePassword(password); byte[] packedKey = key.etaDecrypt(((Bytes) params.get(2)).getData()); return new PrivateKey(packedKey); } catch (SymmetricKey.AuthenticationFailed authenticationFailed) { throw new PasswordProtectedException("wrong password"); } catch (Exception e) { throw new EncryptionError("failed to parse password protected private key"); } } else { throw new EncryptionError("Bad or unknown private key type"); } } PrivateKey(byte[] packedBinaryKey, KeyInfo info); PrivateKey(byte[] packedBinaryKey); PrivateKey(int bitStrength); PrivateKey(); @Override boolean canSign(); @Override boolean isPrivate(); @Override byte[] decrypt(final byte[] encrypted); PublicKey getPublicKey(); byte[] pack(); @Override byte[] sign(InputStream input, HashType hashType); @Override KeyInfo info(); @Override boolean equals(Object obj); @Override int hashCode(); @Override byte[] fingerprint(); static PrivateKey fromPath(Path path); @Override Digest updateDigestWithKeyComponents(Digest digest); byte[] packWithPassword(String password); byte[] packWithPassword(String password, int rounds); static PrivateKey unpackWithPassword(byte[] packedBinary, String password); } |
@Test public void computeSha512() { String src = "test $pbkdf$pbkdf2-sha512$5000$26$KFuMDXmo$yPsu5qmQto99vDqAMWnldNuagfVl5OhPr6g="; String[] parts = src.split("\\$"); String password = parts[0].trim(); int c = Integer.valueOf(parts[3]); int dkLen = Integer.valueOf(parts[4]); byte[] salt = Do.decodeBase64(parts[5]); byte[] DK = Do.decodeBase64(parts[6]); assertArrayEquals(DK, PBKDF2.derive(Sha512.class, password, salt, c, dkLen)); } | public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } private PBKDF2(Class<? extends Digest> hashClass,
String password,
byte[] salt,
int c,
int dkLen); } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } private PBKDF2(Class<? extends Digest> hashClass,
String password,
byte[] salt,
int c,
int dkLen); static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen); } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } private PBKDF2(Class<? extends Digest> hashClass,
String password,
byte[] salt,
int c,
int dkLen); static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen); } |
@Test public void computeSha1() throws Exception { String P = "password"; byte[] S = "salt".getBytes(); int c = 1; int dkLen = 20; byte[] DK = Hex.decode("0c 60 c8 0f 96 1f 0e 71\n" + "f3 a9 b5 24 af 60 12 06\n" + "2f e0 37 a6"); final byte[] key = PBKDF2.derive(Sha1.class, P, S, c, dkLen); assertArrayEquals(DK, key); } | public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } private PBKDF2(Class<? extends Digest> hashClass,
String password,
byte[] salt,
int c,
int dkLen); } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } private PBKDF2(Class<? extends Digest> hashClass,
String password,
byte[] salt,
int c,
int dkLen); static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen); } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } private PBKDF2(Class<? extends Digest> hashClass,
String password,
byte[] salt,
int c,
int dkLen); static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen); } |
@Test public void computeSha256() throws Exception { String P = "password"; byte[] S = "salt".getBytes(); int c = 1; int dkLen = 32; byte [] DK = Hex.decode("12 0f b6 cf fc f8 b3 2c\n" + "43 e7 22 52 56 c4 f8 37\n" + "a8 65 48 c9 2c cc 35 48\n" + "08 05 98 7c b7 0b e1 7b"); byte[] key = PBKDF2.derive(Sha256.class, P, S, c, dkLen); assertArrayEquals(DK, key); c = 2; DK = Hex.decode("ae 4d 0c 95 af 6b 46 d3\n" + " 2d 0a df f9 28 f0 6d d0\n" + " 2a 30 3f 8e f3 c2 51 df\n" + " d6 e2 d8 5a 95 47 4c 43"); c = 4096; DK = Hex.decode("c5 e4 78 d5 92 88 c8 41\n" + " aa 53 0d b6 84 5c 4c 8d\n" + " 96 28 93 a0 01 ce 4e 11\n" + " a4 96 38 73 aa 98 13 4a"); key = PBKDF2.derive(Sha256.class, P, S, c, dkLen); assertArrayEquals(DK, key); } | public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } private PBKDF2(Class<? extends Digest> hashClass,
String password,
byte[] salt,
int c,
int dkLen); } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } private PBKDF2(Class<? extends Digest> hashClass,
String password,
byte[] salt,
int c,
int dkLen); static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen); } | PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } private PBKDF2(Class<? extends Digest> hashClass,
String password,
byte[] salt,
int c,
int dkLen); static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen); } |
@Test public void findKey() throws Exception { KeyInfo i1 = new KeyInfo(KeyInfo.PRF.HMAC_SHA256, 1024, null, null); AbstractKey pk1 = i1.derivePassword("helluva"); KeyInfo i2 = new KeyInfo(KeyInfo.PRF.HMAC_SHA256, 1025, null, "the tag".getBytes()); AbstractKey pk2 = i2.derivePassword("helluva"); assertEquals(i2.getTag(), pk2.info().getTag()); KeyRing kr = new KeyRing(); SymmetricKey sk1 = new SymmetricKey(); SymmetricKey sk2 = new SymmetricKey(); AbstractKey privateKey = TestKeys.privateKey(0); AbstractKey publicKey1 =TestKeys.privateKey(1).getPublicKey(); AbstractKey publicKey2 = privateKey.getPublicKey(); kr.addKeys( sk1, sk2, privateKey, publicKey1, publicKey2, pk1, pk2 ); kr.addKeys(pk1, pk2); Binder b = kr.toBinder(); KeyRing kr2 = KeyRing.fromBinder(b); assertTrue(kr.keySet().contains(pk1)); assertTrue(kr.keySet().contains(pk2)); assertEquals(pk2, kr.findKey(i2).toArray()[0]); assertEquals(pk2, kr2.findKey(i2).toArray()[0]); final Collection<AbstractKey> keys = kr.findKey(i1); assertTrue(keys.contains(pk1)); assertTrue(keys.contains(pk1)); assertTrue(keys.contains(sk1)); assertTrue(keys.contains(sk2)); assertEquals(4, kr2.findKey(i1).size()); } | @Override @NonNull public Collection<AbstractKey> findKey(KeyInfo keyInfo) { final ArrayList<AbstractKey> result = new ArrayList<>(); for( AbstractKey k: keys) { final KeyInfo ki = k.info(); if( ki.matchType(keyInfo) ) { if( ki.matchTag(keyInfo) ) result.add(0, k); else result.add(k); } } return result; } | KeyRing implements Capsule.KeySource, Bindable { @Override @NonNull public Collection<AbstractKey> findKey(KeyInfo keyInfo) { final ArrayList<AbstractKey> result = new ArrayList<>(); for( AbstractKey k: keys) { final KeyInfo ki = k.info(); if( ki.matchType(keyInfo) ) { if( ki.matchTag(keyInfo) ) result.add(0, k); else result.add(k); } } return result; } } | KeyRing implements Capsule.KeySource, Bindable { @Override @NonNull public Collection<AbstractKey> findKey(KeyInfo keyInfo) { final ArrayList<AbstractKey> result = new ArrayList<>(); for( AbstractKey k: keys) { final KeyInfo ki = k.info(); if( ki.matchType(keyInfo) ) { if( ki.matchTag(keyInfo) ) result.add(0, k); else result.add(k); } } return result; } } | KeyRing implements Capsule.KeySource, Bindable { @Override @NonNull public Collection<AbstractKey> findKey(KeyInfo keyInfo) { final ArrayList<AbstractKey> result = new ArrayList<>(); for( AbstractKey k: keys) { final KeyInfo ki = k.info(); if( ki.matchType(keyInfo) ) { if( ki.matchTag(keyInfo) ) result.add(0, k); else result.add(k); } } return result; } @Override Binder toBinder(); static KeyRing fromBinder(Binder source); @Override KeyRing updateFrom(Binder source); void clear(); void addKey(AbstractKey key); boolean removeKey(AbstractKey key); @Override @NonNull Collection<AbstractKey> findKey(KeyInfo keyInfo); void addKeys(AbstractKey... newKeys); @Override boolean equals(Object obj); @Override String toString(); boolean contains(AbstractKey k); } | KeyRing implements Capsule.KeySource, Bindable { @Override @NonNull public Collection<AbstractKey> findKey(KeyInfo keyInfo) { final ArrayList<AbstractKey> result = new ArrayList<>(); for( AbstractKey k: keys) { final KeyInfo ki = k.info(); if( ki.matchType(keyInfo) ) { if( ki.matchTag(keyInfo) ) result.add(0, k); else result.add(k); } } return result; } @Override Binder toBinder(); static KeyRing fromBinder(Binder source); @Override KeyRing updateFrom(Binder source); void clear(); void addKey(AbstractKey key); boolean removeKey(AbstractKey key); @Override @NonNull Collection<AbstractKey> findKey(KeyInfo keyInfo); void addKeys(AbstractKey... newKeys); @Override boolean equals(Object obj); @Override String toString(); boolean contains(AbstractKey k); } |
@Test public void etaEncrypt() throws Exception { SymmetricKey k = new SymmetricKey(); byte[] plainText = "Hello, world!".getBytes(); byte[] cipherText = k.etaEncrypt(plainText); assertEquals(16 + 32 + plainText.length, cipherText.length); byte[] decryptedText = k.etaDecrypt(cipherText); assertArrayEquals(plainText, decryptedText); exception.expect(SymmetricKey.AuthenticationFailed.class); cipherText[19] += 1; k.etaDecrypt(cipherText); } | public byte[] etaEncrypt(byte[] data) throws EncryptionError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { final EtaEncryptingStream s = etaEncryptStream(bos); s.write(data); s.end(); return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException("unexpected IOError", e); } } | SymmetricKey extends AbstractKey implements Serializable, Hashable { public byte[] etaEncrypt(byte[] data) throws EncryptionError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { final EtaEncryptingStream s = etaEncryptStream(bos); s.write(data); s.end(); return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException("unexpected IOError", e); } } } | SymmetricKey extends AbstractKey implements Serializable, Hashable { public byte[] etaEncrypt(byte[] data) throws EncryptionError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { final EtaEncryptingStream s = etaEncryptStream(bos); s.write(data); s.end(); return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException("unexpected IOError", e); } } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[] key, KeyInfo keyInfo); } | SymmetricKey extends AbstractKey implements Serializable, Hashable { public byte[] etaEncrypt(byte[] data) throws EncryptionError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { final EtaEncryptingStream s = etaEncryptStream(bos); s.write(data); s.end(); return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException("unexpected IOError", e); } } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[] key, KeyInfo keyInfo); static SymmetricKey fromPassword(String password, int rounds); static SymmetricKey fromPassword(String password, int rounds, byte[] salt); void setKey(byte[] key); byte[] getKey(); int getBitStrength(); int getSize(); @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); byte[] encrypt(byte[] plaintext); byte[] decrypt(byte[] ciphertext); OutputStream encryptStream(OutputStream outputStream); InputStream decryptStream(InputStream inputStream); EtaEncryptingStream etaEncryptStream(OutputStream out); EtaDecryptingStream etaDecryptStream(InputStream in); byte[] etaEncrypt(byte[] data); byte[] etaSign(byte[] data); byte[] etaDecrypt(byte[] data); static byte[] xor(byte[] src, int value); @Override byte[] pack(); @Override boolean equals(Object obj); @Override int hashCode(); } | SymmetricKey extends AbstractKey implements Serializable, Hashable { public byte[] etaEncrypt(byte[] data) throws EncryptionError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { final EtaEncryptingStream s = etaEncryptStream(bos); s.write(data); s.end(); return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException("unexpected IOError", e); } } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[] key, KeyInfo keyInfo); static SymmetricKey fromPassword(String password, int rounds); static SymmetricKey fromPassword(String password, int rounds, byte[] salt); void setKey(byte[] key); byte[] getKey(); int getBitStrength(); int getSize(); @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); byte[] encrypt(byte[] plaintext); byte[] decrypt(byte[] ciphertext); OutputStream encryptStream(OutputStream outputStream); InputStream decryptStream(InputStream inputStream); EtaEncryptingStream etaEncryptStream(OutputStream out); EtaDecryptingStream etaDecryptStream(InputStream in); byte[] etaEncrypt(byte[] data); byte[] etaSign(byte[] data); byte[] etaDecrypt(byte[] data); static byte[] xor(byte[] src, int value); @Override byte[] pack(); @Override boolean equals(Object obj); @Override int hashCode(); } |
@Test public void xor() throws Exception { byte[] test = new byte[]{0, 0x55, (byte) 0xFF}; byte[] src = new byte[]{0, 0x55, (byte) 0xFF}; test = SymmetricKey.xor(test, 0); assertArrayEquals(test, src); test = SymmetricKey.xor(test, 0xFF); assertArrayEquals(new byte[]{(byte) 0xFF, (byte) 0xAA, 0}, test); test = SymmetricKey.xor(src, 0x11); assertArrayEquals(new byte[]{0x11, (byte) 0x44, (byte) 0xEE}, test); } | public static byte[] xor(byte[] src, int value) { byte[] result = new byte[src.length]; for (int i = 0; i < src.length; i++) result[i] = (byte) ((src[i] ^ value) & 0xFF); return result; } | SymmetricKey extends AbstractKey implements Serializable, Hashable { public static byte[] xor(byte[] src, int value) { byte[] result = new byte[src.length]; for (int i = 0; i < src.length; i++) result[i] = (byte) ((src[i] ^ value) & 0xFF); return result; } } | SymmetricKey extends AbstractKey implements Serializable, Hashable { public static byte[] xor(byte[] src, int value) { byte[] result = new byte[src.length]; for (int i = 0; i < src.length; i++) result[i] = (byte) ((src[i] ^ value) & 0xFF); return result; } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[] key, KeyInfo keyInfo); } | SymmetricKey extends AbstractKey implements Serializable, Hashable { public static byte[] xor(byte[] src, int value) { byte[] result = new byte[src.length]; for (int i = 0; i < src.length; i++) result[i] = (byte) ((src[i] ^ value) & 0xFF); return result; } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[] key, KeyInfo keyInfo); static SymmetricKey fromPassword(String password, int rounds); static SymmetricKey fromPassword(String password, int rounds, byte[] salt); void setKey(byte[] key); byte[] getKey(); int getBitStrength(); int getSize(); @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); byte[] encrypt(byte[] plaintext); byte[] decrypt(byte[] ciphertext); OutputStream encryptStream(OutputStream outputStream); InputStream decryptStream(InputStream inputStream); EtaEncryptingStream etaEncryptStream(OutputStream out); EtaDecryptingStream etaDecryptStream(InputStream in); byte[] etaEncrypt(byte[] data); byte[] etaSign(byte[] data); byte[] etaDecrypt(byte[] data); static byte[] xor(byte[] src, int value); @Override byte[] pack(); @Override boolean equals(Object obj); @Override int hashCode(); } | SymmetricKey extends AbstractKey implements Serializable, Hashable { public static byte[] xor(byte[] src, int value) { byte[] result = new byte[src.length]; for (int i = 0; i < src.length; i++) result[i] = (byte) ((src[i] ^ value) & 0xFF); return result; } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[] key, KeyInfo keyInfo); static SymmetricKey fromPassword(String password, int rounds); static SymmetricKey fromPassword(String password, int rounds, byte[] salt); void setKey(byte[] key); byte[] getKey(); int getBitStrength(); int getSize(); @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); byte[] encrypt(byte[] plaintext); byte[] decrypt(byte[] ciphertext); OutputStream encryptStream(OutputStream outputStream); InputStream decryptStream(InputStream inputStream); EtaEncryptingStream etaEncryptStream(OutputStream out); EtaDecryptingStream etaDecryptStream(InputStream in); byte[] etaEncrypt(byte[] data); byte[] etaSign(byte[] data); byte[] etaDecrypt(byte[] data); static byte[] xor(byte[] src, int value); @Override byte[] pack(); @Override boolean equals(Object obj); @Override int hashCode(); } |
@Test public void divideAndRemainder() throws Exception { Decimal x = new Decimal("1000000000000"); Decimal[] dr = x.divideAndRemainder(new Decimal(3)); assertEquals("333333333333", dr[0].toString()); assertEquals(1, dr[1].intValue()); } | public Decimal[] divideAndRemainder(BigDecimal divisor) { BigDecimal[] result = value.divideAndRemainder(divisor); return new Decimal[]{new Decimal(result[0]), new Decimal(result[1])}; } | Decimal extends Number implements Comparable<Number> { public Decimal[] divideAndRemainder(BigDecimal divisor) { BigDecimal[] result = value.divideAndRemainder(divisor); return new Decimal[]{new Decimal(result[0]), new Decimal(result[1])}; } } | Decimal extends Number implements Comparable<Number> { public Decimal[] divideAndRemainder(BigDecimal divisor) { BigDecimal[] result = value.divideAndRemainder(divisor); return new Decimal[]{new Decimal(result[0]), new Decimal(result[1])}; } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(BigDecimal bigDecimalValue); } | Decimal extends Number implements Comparable<Number> { public Decimal[] divideAndRemainder(BigDecimal divisor) { BigDecimal[] result = value.divideAndRemainder(divisor); return new Decimal[]{new Decimal(result[0]), new Decimal(result[1])}; } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(BigDecimal bigDecimalValue); @Override int intValue(); @Override long longValue(); @Override float floatValue(); @Override double doubleValue(); Decimal divide(BigDecimal divisor); Decimal divide(Decimal divisor); Decimal getIntegral(); Decimal getFraction(); Decimal add(Decimal augend); Decimal subtract(Decimal subtrahend); Decimal multiply(Decimal muliplicand); Decimal remainder(Decimal divisor); Decimal add(BigDecimal augend); Decimal subtract(BigDecimal subtrahend); Decimal multiply(BigDecimal muliplicand); Decimal remainder(BigDecimal divisor); Decimal[] divideAndRemainder(BigDecimal divisor); Decimal[] divideAndRemainder(Decimal divisor); Decimal abs(); Decimal negate(); int signum(); int compareTo(Number val); @Override boolean equals(Object x); @Override int hashCode(); @Override String toString(); String toEngineeringString(); String toPlainString(); BigInteger toBigInteger(); Decimal ulp(); } | Decimal extends Number implements Comparable<Number> { public Decimal[] divideAndRemainder(BigDecimal divisor) { BigDecimal[] result = value.divideAndRemainder(divisor); return new Decimal[]{new Decimal(result[0]), new Decimal(result[1])}; } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(BigDecimal bigDecimalValue); @Override int intValue(); @Override long longValue(); @Override float floatValue(); @Override double doubleValue(); Decimal divide(BigDecimal divisor); Decimal divide(Decimal divisor); Decimal getIntegral(); Decimal getFraction(); Decimal add(Decimal augend); Decimal subtract(Decimal subtrahend); Decimal multiply(Decimal muliplicand); Decimal remainder(Decimal divisor); Decimal add(BigDecimal augend); Decimal subtract(BigDecimal subtrahend); Decimal multiply(BigDecimal muliplicand); Decimal remainder(BigDecimal divisor); Decimal[] divideAndRemainder(BigDecimal divisor); Decimal[] divideAndRemainder(Decimal divisor); Decimal abs(); Decimal negate(); int signum(); int compareTo(Number val); @Override boolean equals(Object x); @Override int hashCode(); @Override String toString(); String toEngineeringString(); String toPlainString(); BigInteger toBigInteger(); Decimal ulp(); static final int SCALE; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; } |
@Test public void ulp() throws Exception { Decimal x = new Decimal("1000000000000.0000000000000000001"); assertEquals( 1e-19,x.ulp().doubleValue(), 0); } | public Decimal ulp() { return new Decimal(value.ulp()); } | Decimal extends Number implements Comparable<Number> { public Decimal ulp() { return new Decimal(value.ulp()); } } | Decimal extends Number implements Comparable<Number> { public Decimal ulp() { return new Decimal(value.ulp()); } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(BigDecimal bigDecimalValue); } | Decimal extends Number implements Comparable<Number> { public Decimal ulp() { return new Decimal(value.ulp()); } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(BigDecimal bigDecimalValue); @Override int intValue(); @Override long longValue(); @Override float floatValue(); @Override double doubleValue(); Decimal divide(BigDecimal divisor); Decimal divide(Decimal divisor); Decimal getIntegral(); Decimal getFraction(); Decimal add(Decimal augend); Decimal subtract(Decimal subtrahend); Decimal multiply(Decimal muliplicand); Decimal remainder(Decimal divisor); Decimal add(BigDecimal augend); Decimal subtract(BigDecimal subtrahend); Decimal multiply(BigDecimal muliplicand); Decimal remainder(BigDecimal divisor); Decimal[] divideAndRemainder(BigDecimal divisor); Decimal[] divideAndRemainder(Decimal divisor); Decimal abs(); Decimal negate(); int signum(); int compareTo(Number val); @Override boolean equals(Object x); @Override int hashCode(); @Override String toString(); String toEngineeringString(); String toPlainString(); BigInteger toBigInteger(); Decimal ulp(); } | Decimal extends Number implements Comparable<Number> { public Decimal ulp() { return new Decimal(value.ulp()); } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(BigDecimal bigDecimalValue); @Override int intValue(); @Override long longValue(); @Override float floatValue(); @Override double doubleValue(); Decimal divide(BigDecimal divisor); Decimal divide(Decimal divisor); Decimal getIntegral(); Decimal getFraction(); Decimal add(Decimal augend); Decimal subtract(Decimal subtrahend); Decimal multiply(Decimal muliplicand); Decimal remainder(Decimal divisor); Decimal add(BigDecimal augend); Decimal subtract(BigDecimal subtrahend); Decimal multiply(BigDecimal muliplicand); Decimal remainder(BigDecimal divisor); Decimal[] divideAndRemainder(BigDecimal divisor); Decimal[] divideAndRemainder(Decimal divisor); Decimal abs(); Decimal negate(); int signum(); int compareTo(Number val); @Override boolean equals(Object x); @Override int hashCode(); @Override String toString(); String toEngineeringString(); String toPlainString(); BigInteger toBigInteger(); Decimal ulp(); static final int SCALE; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; } |
@Test public void testCloneAsAddressRole() throws Exception { Set<KeyAddress> keyAddresses = new HashSet<>(); keyAddresses.add(new KeyAddress(keys.get(0).getPublicKey(), 0, true)); SimpleRole sr = new SimpleRole("tr1",null, keyAddresses); SimpleRole r1 = sr.cloneAs("tr2",null); SimpleRole r2 = r1.cloneAs("tr1",null); assertEquals(sr, r2); } | public SimpleRole cloneAs(String name,Contract contract) { SimpleRole r = new SimpleRole(name,contract); keyRecords.values().forEach(kr -> r.addKeyRecord(kr)); anonymousIds.forEach(aid -> r.anonymousIds.add(aid)); keyAddresses.forEach(keyAddr -> r.keyAddresses.add(keyAddr)); return r; } | SimpleRole extends Role { public SimpleRole cloneAs(String name,Contract contract) { SimpleRole r = new SimpleRole(name,contract); keyRecords.values().forEach(kr -> r.addKeyRecord(kr)); anonymousIds.forEach(aid -> r.anonymousIds.add(aid)); keyAddresses.forEach(keyAddr -> r.keyAddresses.add(keyAddr)); return r; } } | SimpleRole extends Role { public SimpleRole cloneAs(String name,Contract contract) { SimpleRole r = new SimpleRole(name,contract); keyRecords.values().forEach(kr -> r.addKeyRecord(kr)); anonymousIds.forEach(aid -> r.anonymousIds.add(aid)); keyAddresses.forEach(keyAddr -> r.keyAddresses.add(keyAddr)); return r; } @Deprecated SimpleRole(String name, @NonNull KeyRecord keyRecord); SimpleRole(String name, Contract contract, @NonNull KeyRecord keyRecord); private SimpleRole(); @Deprecated SimpleRole(String name); SimpleRole(String name,Contract contract); @Deprecated SimpleRole(String name, @NonNull Collection records); SimpleRole(String name, Contract contract, @NonNull Collection records); } | SimpleRole extends Role { public SimpleRole cloneAs(String name,Contract contract) { SimpleRole r = new SimpleRole(name,contract); keyRecords.values().forEach(kr -> r.addKeyRecord(kr)); anonymousIds.forEach(aid -> r.anonymousIds.add(aid)); keyAddresses.forEach(keyAddr -> r.keyAddresses.add(keyAddr)); return r; } @Deprecated SimpleRole(String name, @NonNull KeyRecord keyRecord); SimpleRole(String name, Contract contract, @NonNull KeyRecord keyRecord); private SimpleRole(); @Deprecated SimpleRole(String name); SimpleRole(String name,Contract contract); @Deprecated SimpleRole(String name, @NonNull Collection records); SimpleRole(String name, Contract contract, @NonNull Collection records); void addKeyRecord(KeyRecord keyRecord); @Deprecated KeyRecord getKeyRecord(); @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Deprecated @Override Set<KeyAddress> getKeyAddresses(); Set<KeyRecord> getSimpleKeyRecords(); Set<PublicKey> getSimpleKeys(); Set<AnonymousId> getSimpleAnonymousIds(); Set<KeyAddress> getSimpleKeyAddresses(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); boolean isValid(); @Override void initWithDsl(Binder serializedRole); SimpleRole cloneAs(String name,Contract contract); @Deprecated SimpleRole cloneAs(String name); @Override String toString(); boolean isAllowedForKeys(SimpleRole anotherRole); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } | SimpleRole extends Role { public SimpleRole cloneAs(String name,Contract contract) { SimpleRole r = new SimpleRole(name,contract); keyRecords.values().forEach(kr -> r.addKeyRecord(kr)); anonymousIds.forEach(aid -> r.anonymousIds.add(aid)); keyAddresses.forEach(keyAddr -> r.keyAddresses.add(keyAddr)); return r; } @Deprecated SimpleRole(String name, @NonNull KeyRecord keyRecord); SimpleRole(String name, Contract contract, @NonNull KeyRecord keyRecord); private SimpleRole(); @Deprecated SimpleRole(String name); SimpleRole(String name,Contract contract); @Deprecated SimpleRole(String name, @NonNull Collection records); SimpleRole(String name, Contract contract, @NonNull Collection records); void addKeyRecord(KeyRecord keyRecord); @Deprecated KeyRecord getKeyRecord(); @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Deprecated @Override Set<KeyAddress> getKeyAddresses(); Set<KeyRecord> getSimpleKeyRecords(); Set<PublicKey> getSimpleKeys(); Set<AnonymousId> getSimpleAnonymousIds(); Set<KeyAddress> getSimpleKeyAddresses(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); boolean isValid(); @Override void initWithDsl(Binder serializedRole); SimpleRole cloneAs(String name,Contract contract); @Deprecated SimpleRole cloneAs(String name); @Override String toString(); boolean isAllowedForKeys(SimpleRole anotherRole); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } |
@Test public void getPublicKey() throws Exception { AbstractPublicKey randomPublicKey4096 = randomPrivateKey4096.getPublicKey(); assertTrue(randomPublicKey4096 instanceof RSAOAEPPublicKey); AbstractPrivateKey rsaPrivateKey = oaepSpec.getPrivateKey(); AbstractPublicKey rsaPublicKey = rsaPrivateKey.getPublicKey(); ((RSAOAEPPublicKey) rsaPublicKey).resetEncryptor(); assertArrayEquals(rsaPublicKey.encrypt(oaepSpec.M), oaepSpec.C); } | @Override public AbstractPublicKey getPublicKey() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return state.publicKey; } } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public AbstractPublicKey getPublicKey() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return state.publicKey; } } } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public AbstractPublicKey getPublicKey() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return state.publicKey; } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public AbstractPublicKey getPublicKey() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return state.publicKey; } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public AbstractPublicKey getPublicKey() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return state.publicKey; } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; } |
@Test public void testGetSimpleAddress() throws Exception { Set<Object> keyAddresses = new HashSet<>(); keyAddresses.add(keys.get(0).getPublicKey().getShortAddress()); SimpleRole sr = new SimpleRole("tr1",null, keyAddresses); assertEquals(sr.getSimpleAddress(),keyAddresses.iterator().next()); keyAddresses.add(keys.get(1).getPublicKey()); sr = new SimpleRole("tr1", null, keyAddresses); assertNull(sr.getSimpleAddress()); keyAddresses.remove(keys.get(0).getPublicKey().getShortAddress()); sr = new SimpleRole("tr1", null, keyAddresses); assertEquals(sr.getSimpleAddress(),keys.get(1).getPublicKey().getShortAddress()); sr.addRequiredReference("dummy", Role.RequiredMode.ALL_OF); assertNull(sr.getSimpleAddress()); assertEquals(RoleExtractor.extractSimpleAddress(sr),keys.get(1).getPublicKey().getShortAddress()); } | @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(anonymousIds.size() == 0 && keyRecords.size() + keyAddresses.size() == 1) { if(keyRecords.size() == 1) { return keyRecords.keySet().iterator().next().getShortAddress(); } else { return keyAddresses.iterator().next(); } } return null; } | SimpleRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(anonymousIds.size() == 0 && keyRecords.size() + keyAddresses.size() == 1) { if(keyRecords.size() == 1) { return keyRecords.keySet().iterator().next().getShortAddress(); } else { return keyAddresses.iterator().next(); } } return null; } } | SimpleRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(anonymousIds.size() == 0 && keyRecords.size() + keyAddresses.size() == 1) { if(keyRecords.size() == 1) { return keyRecords.keySet().iterator().next().getShortAddress(); } else { return keyAddresses.iterator().next(); } } return null; } @Deprecated SimpleRole(String name, @NonNull KeyRecord keyRecord); SimpleRole(String name, Contract contract, @NonNull KeyRecord keyRecord); private SimpleRole(); @Deprecated SimpleRole(String name); SimpleRole(String name,Contract contract); @Deprecated SimpleRole(String name, @NonNull Collection records); SimpleRole(String name, Contract contract, @NonNull Collection records); } | SimpleRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(anonymousIds.size() == 0 && keyRecords.size() + keyAddresses.size() == 1) { if(keyRecords.size() == 1) { return keyRecords.keySet().iterator().next().getShortAddress(); } else { return keyAddresses.iterator().next(); } } return null; } @Deprecated SimpleRole(String name, @NonNull KeyRecord keyRecord); SimpleRole(String name, Contract contract, @NonNull KeyRecord keyRecord); private SimpleRole(); @Deprecated SimpleRole(String name); SimpleRole(String name,Contract contract); @Deprecated SimpleRole(String name, @NonNull Collection records); SimpleRole(String name, Contract contract, @NonNull Collection records); void addKeyRecord(KeyRecord keyRecord); @Deprecated KeyRecord getKeyRecord(); @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Deprecated @Override Set<KeyAddress> getKeyAddresses(); Set<KeyRecord> getSimpleKeyRecords(); Set<PublicKey> getSimpleKeys(); Set<AnonymousId> getSimpleAnonymousIds(); Set<KeyAddress> getSimpleKeyAddresses(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); boolean isValid(); @Override void initWithDsl(Binder serializedRole); SimpleRole cloneAs(String name,Contract contract); @Deprecated SimpleRole cloneAs(String name); @Override String toString(); boolean isAllowedForKeys(SimpleRole anotherRole); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } | SimpleRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(anonymousIds.size() == 0 && keyRecords.size() + keyAddresses.size() == 1) { if(keyRecords.size() == 1) { return keyRecords.keySet().iterator().next().getShortAddress(); } else { return keyAddresses.iterator().next(); } } return null; } @Deprecated SimpleRole(String name, @NonNull KeyRecord keyRecord); SimpleRole(String name, Contract contract, @NonNull KeyRecord keyRecord); private SimpleRole(); @Deprecated SimpleRole(String name); SimpleRole(String name,Contract contract); @Deprecated SimpleRole(String name, @NonNull Collection records); SimpleRole(String name, Contract contract, @NonNull Collection records); void addKeyRecord(KeyRecord keyRecord); @Deprecated KeyRecord getKeyRecord(); @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Deprecated @Override Set<KeyAddress> getKeyAddresses(); Set<KeyRecord> getSimpleKeyRecords(); Set<PublicKey> getSimpleKeys(); Set<AnonymousId> getSimpleAnonymousIds(); Set<KeyAddress> getSimpleKeyAddresses(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); boolean isValid(); @Override void initWithDsl(Binder serializedRole); SimpleRole cloneAs(String name,Contract contract); @Deprecated SimpleRole cloneAs(String name); @Override String toString(); boolean isAllowedForKeys(SimpleRole anotherRole); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } |
@Test public void resolve() throws Exception { Contract c = new Contract(); SimpleRole s1 = new SimpleRole("owner",c); c.addRole(s1); RoleLink r1 = new RoleLink("lover",c, "owner"); c.addRole(r1); RoleLink r2 = r1.linkAs("mucker"); assertSame(s1, s1.resolve()); assertSame(s1, r1.resolve()); assertSame(s1, r2.resolve()); } | @Override public <T extends Role> T resolve() { return resolve(true); } | RoleLink extends Role { @Override public <T extends Role> T resolve() { return resolve(true); } } | RoleLink extends Role { @Override public <T extends Role> T resolve() { return resolve(true); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); } | RoleLink extends Role { @Override public <T extends Role> T resolve() { return resolve(true); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); } | RoleLink extends Role { @Override public <T extends Role> T resolve() { return resolve(true); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); } |
@Test public void detectsCirculars() throws Exception { Contract c = new Contract(); RoleLink r1 = new RoleLink("bar", "foo"); RoleLink r2 = new RoleLink("foo", "bar"); c.registerRole(r1); c.registerRole(r2); assertNull(r2.resolve()); } | @Override public <T extends Role> T resolve() { return resolve(true); } | RoleLink extends Role { @Override public <T extends Role> T resolve() { return resolve(true); } } | RoleLink extends Role { @Override public <T extends Role> T resolve() { return resolve(true); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); } | RoleLink extends Role { @Override public <T extends Role> T resolve() { return resolve(true); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); } | RoleLink extends Role { @Override public <T extends Role> T resolve() { return resolve(true); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); } |
@Test public void serialize() throws Exception { RoleLink r1 = new RoleLink("name", "target"); r1.addRequiredReference("ref", Role.RequiredMode.ALL_OF); Binder s = DefaultBiMapper.serialize(r1); RoleLink r2 = DefaultBiMapper.deserialize(s); assertEquals(r1, r2); assertEquals(r1.getName(), r2.getName()); } | @Override public Binder serialize(BiSerializer s) { return super.serialize(s).putAll( "name", getName(), "target_name", roleName ); } | RoleLink extends Role { @Override public Binder serialize(BiSerializer s) { return super.serialize(s).putAll( "name", getName(), "target_name", roleName ); } } | RoleLink extends Role { @Override public Binder serialize(BiSerializer s) { return super.serialize(s).putAll( "name", getName(), "target_name", roleName ); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); } | RoleLink extends Role { @Override public Binder serialize(BiSerializer s) { return super.serialize(s).putAll( "name", getName(), "target_name", roleName ); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); } | RoleLink extends Role { @Override public Binder serialize(BiSerializer s) { return super.serialize(s).putAll( "name", getName(), "target_name", roleName ); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); } |
@Test public void testGetSimpleAddress() throws Exception { Set<Object> keyAddresses = new HashSet<>(); keyAddresses.add(TestKeys.publicKey(0).getLongAddress()); Contract c = new Contract(); SimpleRole sr = new SimpleRole("sr",c, keyAddresses); c.addRole(sr); RoleLink rl = new RoleLink("rl",c,sr.getName()); c.addRole(rl); assertEquals(rl.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); rl.addRequiredReference("dummy", Role.RequiredMode.ALL_OF); assertNull(rl.getSimpleAddress()); assertEquals(RoleExtractor.extractSimpleAddress(rl),TestKeys.publicKey(0).getLongAddress()); } | @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { Role r = resolve(ignoreRefs); if (r != null && r != this) return r.getSimpleAddress(ignoreRefs); return null; } | RoleLink extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { Role r = resolve(ignoreRefs); if (r != null && r != this) return r.getSimpleAddress(ignoreRefs); return null; } } | RoleLink extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { Role r = resolve(ignoreRefs); if (r != null && r != this) return r.getSimpleAddress(ignoreRefs); return null; } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); } | RoleLink extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { Role r = resolve(ignoreRefs); if (r != null && r != this) return r.getSimpleAddress(ignoreRefs); return null; } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); } | RoleLink extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { Role r = resolve(ignoreRefs); if (r != null && r != this) return r.getSimpleAddress(ignoreRefs); return null; } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); } |
@Test public void shouldNotAllowToSetQuorum() { ListRole listRole = new ListRole("roles"); try { listRole.setMode(ListRole.Mode.QUORUM); fail("Expected exception to be thrown."); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().equalsIgnoreCase("Only ANY or ALL of the modes should be set.")); } } | public void setMode(Mode newMode) { if (newMode != Mode.QUORUM) this.mode = newMode; else throw new IllegalArgumentException("Only ANY or ALL of the modes should be set."); } | ListRole extends Role { public void setMode(Mode newMode) { if (newMode != Mode.QUORUM) this.mode = newMode; else throw new IllegalArgumentException("Only ANY or ALL of the modes should be set."); } } | ListRole extends Role { public void setMode(Mode newMode) { if (newMode != Mode.QUORUM) this.mode = newMode; else throw new IllegalArgumentException("Only ANY or ALL of the modes should be set."); } ListRole(); ListRole(String name,Contract contract); @Deprecated ListRole(String name); ListRole(String name, Contract contract, Mode mode, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, Mode mode, @NonNull Collection<Role> roles); ListRole(String name, Contract contract, int quorumSize, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, int quorumSize, @NonNull Collection<Role> roles); } | ListRole extends Role { public void setMode(Mode newMode) { if (newMode != Mode.QUORUM) this.mode = newMode; else throw new IllegalArgumentException("Only ANY or ALL of the modes should be set."); } ListRole(); ListRole(String name,Contract contract); @Deprecated ListRole(String name); ListRole(String name, Contract contract, Mode mode, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, Mode mode, @NonNull Collection<Role> roles); ListRole(String name, Contract contract, int quorumSize, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, int quorumSize, @NonNull Collection<Role> roles); void addAll(Collection<Role> roles); Set<Role> getRoles(); ListRole addRole(Role role); void setQuorum(int n); int getQuorum(); void setMode(Mode newMode); Mode getMode(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override void initWithDsl(Binder serializedRole); @Override void setContract(Contract contract); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override String toString(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } | ListRole extends Role { public void setMode(Mode newMode) { if (newMode != Mode.QUORUM) this.mode = newMode; else throw new IllegalArgumentException("Only ANY or ALL of the modes should be set."); } ListRole(); ListRole(String name,Contract contract); @Deprecated ListRole(String name); ListRole(String name, Contract contract, Mode mode, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, Mode mode, @NonNull Collection<Role> roles); ListRole(String name, Contract contract, int quorumSize, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, int quorumSize, @NonNull Collection<Role> roles); void addAll(Collection<Role> roles); Set<Role> getRoles(); ListRole addRole(Role role); void setQuorum(int n); int getQuorum(); void setMode(Mode newMode); Mode getMode(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override void initWithDsl(Binder serializedRole); @Override void setContract(Contract contract); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override String toString(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } |
@Test public void testGetSimpleAddress() throws Exception { Set<Object> keyAddresses = new HashSet<>(); keyAddresses.add(TestKeys.publicKey(0).getLongAddress()); SimpleRole sr = new SimpleRole("sr", keyAddresses); ListRole lr = new ListRole(); lr.addRole(sr); lr.setMode(ListRole.Mode.ALL); assertEquals(lr.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); lr.setMode(ListRole.Mode.ANY); assertEquals(lr.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); lr.setQuorum(2); assertNull(lr.getSimpleAddress()); lr.setQuorum(1); assertEquals(lr.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); lr.setMode(ListRole.Mode.ANY); SimpleRole sr2 = new SimpleRole("sr2", keyAddresses); lr.addRole(sr2); assertNull(lr.getSimpleAddress()); lr.getRoles().remove(sr2); lr.addRequiredReference("dummy", Role.RequiredMode.ALL_OF); assertNull(lr.getSimpleAddress()); assertEquals(RoleExtractor.extractSimpleAddress(lr),TestKeys.publicKey(0).getLongAddress()); } | @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(roles.size() == 1 && (mode != Mode.QUORUM || quorumSize == 1)) { return roles.iterator().next().getSimpleAddress(ignoreRefs); } return null; } | ListRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(roles.size() == 1 && (mode != Mode.QUORUM || quorumSize == 1)) { return roles.iterator().next().getSimpleAddress(ignoreRefs); } return null; } } | ListRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(roles.size() == 1 && (mode != Mode.QUORUM || quorumSize == 1)) { return roles.iterator().next().getSimpleAddress(ignoreRefs); } return null; } ListRole(); ListRole(String name,Contract contract); @Deprecated ListRole(String name); ListRole(String name, Contract contract, Mode mode, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, Mode mode, @NonNull Collection<Role> roles); ListRole(String name, Contract contract, int quorumSize, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, int quorumSize, @NonNull Collection<Role> roles); } | ListRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(roles.size() == 1 && (mode != Mode.QUORUM || quorumSize == 1)) { return roles.iterator().next().getSimpleAddress(ignoreRefs); } return null; } ListRole(); ListRole(String name,Contract contract); @Deprecated ListRole(String name); ListRole(String name, Contract contract, Mode mode, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, Mode mode, @NonNull Collection<Role> roles); ListRole(String name, Contract contract, int quorumSize, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, int quorumSize, @NonNull Collection<Role> roles); void addAll(Collection<Role> roles); Set<Role> getRoles(); ListRole addRole(Role role); void setQuorum(int n); int getQuorum(); void setMode(Mode newMode); Mode getMode(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override void initWithDsl(Binder serializedRole); @Override void setContract(Contract contract); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override String toString(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } | ListRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(roles.size() == 1 && (mode != Mode.QUORUM || quorumSize == 1)) { return roles.iterator().next().getSimpleAddress(ignoreRefs); } return null; } ListRole(); ListRole(String name,Contract contract); @Deprecated ListRole(String name); ListRole(String name, Contract contract, Mode mode, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, Mode mode, @NonNull Collection<Role> roles); ListRole(String name, Contract contract, int quorumSize, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, int quorumSize, @NonNull Collection<Role> roles); void addAll(Collection<Role> roles); Set<Role> getRoles(); ListRole addRole(Role role); void setQuorum(int n); int getQuorum(); void setMode(Mode newMode); Mode getMode(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override void initWithDsl(Binder serializedRole); @Override void setContract(Contract contract); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override String toString(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); } |
@Test public void deserializeOldContract() throws Exception { TransactionPack tp = TransactionPack.unpack(c.sealAsV2()); checkSimplePack(tp); } | public static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions) throws IOException { Object x = Boss.load(packOrContractBytes); if (x instanceof TransactionPack) { return (TransactionPack) x; } if (!allowNonTransactions) throw new IOException("expected transaction pack"); TransactionPack tp = new TransactionPack(); tp.reconstructed = true; tp.packedBinary = packOrContractBytes; tp.contract = Contract.fromSealedBinary(packOrContractBytes, tp); return tp; } | TransactionPack implements BiSerializable { public static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions) throws IOException { Object x = Boss.load(packOrContractBytes); if (x instanceof TransactionPack) { return (TransactionPack) x; } if (!allowNonTransactions) throw new IOException("expected transaction pack"); TransactionPack tp = new TransactionPack(); tp.reconstructed = true; tp.packedBinary = packOrContractBytes; tp.contract = Contract.fromSealedBinary(packOrContractBytes, tp); return tp; } } | TransactionPack implements BiSerializable { public static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions) throws IOException { Object x = Boss.load(packOrContractBytes); if (x instanceof TransactionPack) { return (TransactionPack) x; } if (!allowNonTransactions) throw new IOException("expected transaction pack"); TransactionPack tp = new TransactionPack(); tp.reconstructed = true; tp.packedBinary = packOrContractBytes; tp.contract = Contract.fromSealedBinary(packOrContractBytes, tp); return tp; } TransactionPack(Contract contract); TransactionPack(); } | TransactionPack implements BiSerializable { public static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions) throws IOException { Object x = Boss.load(packOrContractBytes); if (x instanceof TransactionPack) { return (TransactionPack) x; } if (!allowNonTransactions) throw new IOException("expected transaction pack"); TransactionPack tp = new TransactionPack(); tp.reconstructed = true; tp.packedBinary = packOrContractBytes; tp.contract = Contract.fromSealedBinary(packOrContractBytes, tp); return tp; } TransactionPack(Contract contract); TransactionPack(); Contract getContract(); Contract getSubItem(HashId id); Contract getSubItem(HashIdentifiable hid); Set<PublicKey> getKeysForPack(); void setContract(Contract c); void addSubItem(Contract subItem); void addReferencedItem(Contract referencedItem); void addTag(String tag, HashId itemId); void addKeys(PublicKey... keys); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer serializer); final boolean isReconstructed(); static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions); static TransactionPack unpack(byte[] packOrContractBytes); synchronized byte[] pack(); Map<HashId, Contract> getSubItems(); Map<HashId, Contract> getReferencedItems(); Map<String, Contract> getTags(); void trace(); void setReferenceContextKeys(Set<PublicKey> referenceEffectiveKeys); Contract findContract(Predicate<Contract> function); } | TransactionPack implements BiSerializable { public static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions) throws IOException { Object x = Boss.load(packOrContractBytes); if (x instanceof TransactionPack) { return (TransactionPack) x; } if (!allowNonTransactions) throw new IOException("expected transaction pack"); TransactionPack tp = new TransactionPack(); tp.reconstructed = true; tp.packedBinary = packOrContractBytes; tp.contract = Contract.fromSealedBinary(packOrContractBytes, tp); return tp; } TransactionPack(Contract contract); TransactionPack(); Contract getContract(); Contract getSubItem(HashId id); Contract getSubItem(HashIdentifiable hid); Set<PublicKey> getKeysForPack(); void setContract(Contract c); void addSubItem(Contract subItem); void addReferencedItem(Contract referencedItem); void addTag(String tag, HashId itemId); void addKeys(PublicKey... keys); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer serializer); final boolean isReconstructed(); static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions); static TransactionPack unpack(byte[] packOrContractBytes); synchronized byte[] pack(); Map<HashId, Contract> getSubItems(); Map<HashId, Contract> getReferencedItems(); Map<String, Contract> getTags(); void trace(); void setReferenceContextKeys(Set<PublicKey> referenceEffectiveKeys); Contract findContract(Predicate<Contract> function); static final String TAG_PREFIX_RESERVED; } |
@Test public void serializeNew() throws Exception { TransactionPack tp = new TransactionPack(); tp.setContract(c); checkSimplePack(tp); } | public void setContract(Contract c) { if (contract != null) throw new IllegalArgumentException("the contract is already added"); contract = c; packedBinary = null; extractAllSubItemsAndReferenced(c); c.setTransactionPack(this); for (PrivateKey key : c.getKeysToSignWith()) addKeys(key.getPublicKey()); } | TransactionPack implements BiSerializable { public void setContract(Contract c) { if (contract != null) throw new IllegalArgumentException("the contract is already added"); contract = c; packedBinary = null; extractAllSubItemsAndReferenced(c); c.setTransactionPack(this); for (PrivateKey key : c.getKeysToSignWith()) addKeys(key.getPublicKey()); } } | TransactionPack implements BiSerializable { public void setContract(Contract c) { if (contract != null) throw new IllegalArgumentException("the contract is already added"); contract = c; packedBinary = null; extractAllSubItemsAndReferenced(c); c.setTransactionPack(this); for (PrivateKey key : c.getKeysToSignWith()) addKeys(key.getPublicKey()); } TransactionPack(Contract contract); TransactionPack(); } | TransactionPack implements BiSerializable { public void setContract(Contract c) { if (contract != null) throw new IllegalArgumentException("the contract is already added"); contract = c; packedBinary = null; extractAllSubItemsAndReferenced(c); c.setTransactionPack(this); for (PrivateKey key : c.getKeysToSignWith()) addKeys(key.getPublicKey()); } TransactionPack(Contract contract); TransactionPack(); Contract getContract(); Contract getSubItem(HashId id); Contract getSubItem(HashIdentifiable hid); Set<PublicKey> getKeysForPack(); void setContract(Contract c); void addSubItem(Contract subItem); void addReferencedItem(Contract referencedItem); void addTag(String tag, HashId itemId); void addKeys(PublicKey... keys); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer serializer); final boolean isReconstructed(); static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions); static TransactionPack unpack(byte[] packOrContractBytes); synchronized byte[] pack(); Map<HashId, Contract> getSubItems(); Map<HashId, Contract> getReferencedItems(); Map<String, Contract> getTags(); void trace(); void setReferenceContextKeys(Set<PublicKey> referenceEffectiveKeys); Contract findContract(Predicate<Contract> function); } | TransactionPack implements BiSerializable { public void setContract(Contract c) { if (contract != null) throw new IllegalArgumentException("the contract is already added"); contract = c; packedBinary = null; extractAllSubItemsAndReferenced(c); c.setTransactionPack(this); for (PrivateKey key : c.getKeysToSignWith()) addKeys(key.getPublicKey()); } TransactionPack(Contract contract); TransactionPack(); Contract getContract(); Contract getSubItem(HashId id); Contract getSubItem(HashIdentifiable hid); Set<PublicKey> getKeysForPack(); void setContract(Contract c); void addSubItem(Contract subItem); void addReferencedItem(Contract referencedItem); void addTag(String tag, HashId itemId); void addKeys(PublicKey... keys); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer serializer); final boolean isReconstructed(); static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions); static TransactionPack unpack(byte[] packOrContractBytes); synchronized byte[] pack(); Map<HashId, Contract> getSubItems(); Map<HashId, Contract> getReferencedItems(); Map<String, Contract> getTags(); void trace(); void setReferenceContextKeys(Set<PublicKey> referenceEffectiveKeys); Contract findContract(Predicate<Contract> function); static final String TAG_PREFIX_RESERVED; } |
@Test public void badRevoke() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(rootPath+"_xer0yfe2nn1xthc.private.unikey"); c.seal(); PrivateKey issuer = TestKeys.privateKey(2); Contract tc = c.createRevocation(issuer); boolean result = tc.check(); assertFalse(result); assertEquals(1, tc.getErrors().size()); assertEquals(Errors.FORBIDDEN, tc.getErrors().get(0).getError()); } | public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); tc.addSignerKey(k); } tc.addRole(issuerRole); tc.addRole("owner", issuerRole); tc.addRole("creator", issuerRole); if (!tc.getRevokingItems().contains(c)) { Binder data = tc.getDefinition().getData(); List<Binder> actions = data.getOrCreateList("actions"); tc.getRevokingItems().add(c); actions.add(Binder.fromKeysValues("action", "remove", "id", c.getId())); } tc.seal(); return tc; } | ContractsService { public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); tc.addSignerKey(k); } tc.addRole(issuerRole); tc.addRole("owner", issuerRole); tc.addRole("creator", issuerRole); if (!tc.getRevokingItems().contains(c)) { Binder data = tc.getDefinition().getData(); List<Binder> actions = data.getOrCreateList("actions"); tc.getRevokingItems().add(c); actions.add(Binder.fromKeysValues("action", "remove", "id", c.getId())); } tc.seal(); return tc; } } | ContractsService { public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); tc.addSignerKey(k); } tc.addRole(issuerRole); tc.addRole("owner", issuerRole); tc.addRole("creator", issuerRole); if (!tc.getRevokingItems().contains(c)) { Binder data = tc.getDefinition().getData(); List<Binder> actions = data.getOrCreateList("actions"); tc.getRevokingItems().add(c); actions.add(Binder.fromKeysValues("action", "remove", "id", c.getId())); } tc.seal(); return tc; } } | ContractsService { public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); tc.addSignerKey(k); } tc.addRole(issuerRole); tc.addRole("owner", issuerRole); tc.addRole("creator", issuerRole); if (!tc.getRevokingItems().contains(c)) { Binder data = tc.getDefinition().getData(); List<Binder> actions = data.getOrCreateList("actions"); tc.getRevokingItems().add(c); actions.add(Binder.fromKeysValues("action", "remove", "id", c.getId())); } tc.seal(); return tc; } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } | ContractsService { public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); tc.addSignerKey(k); } tc.addRole(issuerRole); tc.addRole("owner", issuerRole); tc.addRole("creator", issuerRole); if (!tc.getRevokingItems().contains(c)) { Binder data = tc.getDefinition().getData(); List<Binder> actions = data.getOrCreateList("actions"); tc.getRevokingItems().add(c); actions.add(Binder.fromKeysValues("action", "remove", "id", c.getId())); } tc.seal(); return tc; } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } |
@Test public void sign() throws Exception { AbstractPrivateKey rsaPrivateKey = pssSpec.getPrivateKey(); assertArrayEquals(rsaPrivateKey.sign(pssSpec.M, HashType.SHA1, RSASSAPSSTestVectors.salt), pssSpec.S); } | @Override public byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt) throws IllegalStateException, IOException { if (state == null) { throw new IllegalStateException(); } else { final Digest primaryDigest = hashType.makeDigest(); final PSSSigner signer; if (salt == null) { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), getMaxSaltLength(getBitStrength(), primaryDigest.getDigestSize())); } else { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), salt); } signer.init(true, new ParametersWithRandom(state.keyParameters, state.rng)); boolean done = false; while (!done) { int availableBytes = input.available(); if (availableBytes <= 0) { done = true; } else { byte[] buffer = new byte[availableBytes]; int howManyBytesRead = input.read(buffer); if (howManyBytesRead <= 0) { done = true; } else { signer.update(buffer, 0, howManyBytesRead); } } } try { return signer.generateSignature(); } catch (CryptoException e) { throw new IOException(String.format("Cannot sign data: %s", e.toString())); } } } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt) throws IllegalStateException, IOException { if (state == null) { throw new IllegalStateException(); } else { final Digest primaryDigest = hashType.makeDigest(); final PSSSigner signer; if (salt == null) { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), getMaxSaltLength(getBitStrength(), primaryDigest.getDigestSize())); } else { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), salt); } signer.init(true, new ParametersWithRandom(state.keyParameters, state.rng)); boolean done = false; while (!done) { int availableBytes = input.available(); if (availableBytes <= 0) { done = true; } else { byte[] buffer = new byte[availableBytes]; int howManyBytesRead = input.read(buffer); if (howManyBytesRead <= 0) { done = true; } else { signer.update(buffer, 0, howManyBytesRead); } } } try { return signer.generateSignature(); } catch (CryptoException e) { throw new IOException(String.format("Cannot sign data: %s", e.toString())); } } } } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt) throws IllegalStateException, IOException { if (state == null) { throw new IllegalStateException(); } else { final Digest primaryDigest = hashType.makeDigest(); final PSSSigner signer; if (salt == null) { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), getMaxSaltLength(getBitStrength(), primaryDigest.getDigestSize())); } else { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), salt); } signer.init(true, new ParametersWithRandom(state.keyParameters, state.rng)); boolean done = false; while (!done) { int availableBytes = input.available(); if (availableBytes <= 0) { done = true; } else { byte[] buffer = new byte[availableBytes]; int howManyBytesRead = input.read(buffer); if (howManyBytesRead <= 0) { done = true; } else { signer.update(buffer, 0, howManyBytesRead); } } } try { return signer.generateSignature(); } catch (CryptoException e) { throw new IOException(String.format("Cannot sign data: %s", e.toString())); } } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt) throws IllegalStateException, IOException { if (state == null) { throw new IllegalStateException(); } else { final Digest primaryDigest = hashType.makeDigest(); final PSSSigner signer; if (salt == null) { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), getMaxSaltLength(getBitStrength(), primaryDigest.getDigestSize())); } else { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), salt); } signer.init(true, new ParametersWithRandom(state.keyParameters, state.rng)); boolean done = false; while (!done) { int availableBytes = input.available(); if (availableBytes <= 0) { done = true; } else { byte[] buffer = new byte[availableBytes]; int howManyBytesRead = input.read(buffer); if (howManyBytesRead <= 0) { done = true; } else { signer.update(buffer, 0, howManyBytesRead); } } } try { return signer.generateSignature(); } catch (CryptoException e) { throw new IOException(String.format("Cannot sign data: %s", e.toString())); } } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); } | RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt) throws IllegalStateException, IOException { if (state == null) { throw new IllegalStateException(); } else { final Digest primaryDigest = hashType.makeDigest(); final PSSSigner signer; if (salt == null) { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), getMaxSaltLength(getBitStrength(), primaryDigest.getDigestSize())); } else { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), salt); } signer.init(true, new ParametersWithRandom(state.keyParameters, state.rng)); boolean done = false; while (!done) { int availableBytes = input.available(); if (availableBytes <= 0) { done = true; } else { byte[] buffer = new byte[availableBytes]; int howManyBytesRead = input.read(buffer); if (howManyBytesRead <= 0) { done = true; } else { signer.update(buffer, 0, howManyBytesRead); } } } try { return signer.generateSignature(); } catch (CryptoException e) { throw new IOException(String.format("Cannot sign data: %s", e.toString())); } } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; } |
@Test public void goodRevoke() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(rootPath+"_xer0yfe2nn1xthc.private.unikey"); PrivateKey goodKey = c.getKeysToSignWith().iterator().next(); c.setOwnerKeys(new KeyRecord(goodKey.getPublicKey())); c.seal(); Contract revokeContract = c.createRevocation(goodKey); revokeContract.check(); assertTrue(revokeContract.isOk()); } | public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); tc.addSignerKey(k); } tc.addRole(issuerRole); tc.addRole("owner", issuerRole); tc.addRole("creator", issuerRole); if (!tc.getRevokingItems().contains(c)) { Binder data = tc.getDefinition().getData(); List<Binder> actions = data.getOrCreateList("actions"); tc.getRevokingItems().add(c); actions.add(Binder.fromKeysValues("action", "remove", "id", c.getId())); } tc.seal(); return tc; } | ContractsService { public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); tc.addSignerKey(k); } tc.addRole(issuerRole); tc.addRole("owner", issuerRole); tc.addRole("creator", issuerRole); if (!tc.getRevokingItems().contains(c)) { Binder data = tc.getDefinition().getData(); List<Binder> actions = data.getOrCreateList("actions"); tc.getRevokingItems().add(c); actions.add(Binder.fromKeysValues("action", "remove", "id", c.getId())); } tc.seal(); return tc; } } | ContractsService { public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); tc.addSignerKey(k); } tc.addRole(issuerRole); tc.addRole("owner", issuerRole); tc.addRole("creator", issuerRole); if (!tc.getRevokingItems().contains(c)) { Binder data = tc.getDefinition().getData(); List<Binder> actions = data.getOrCreateList("actions"); tc.getRevokingItems().add(c); actions.add(Binder.fromKeysValues("action", "remove", "id", c.getId())); } tc.seal(); return tc; } } | ContractsService { public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); tc.addSignerKey(k); } tc.addRole(issuerRole); tc.addRole("owner", issuerRole); tc.addRole("creator", issuerRole); if (!tc.getRevokingItems().contains(c)) { Binder data = tc.getDefinition().getData(); List<Binder> actions = data.getOrCreateList("actions"); tc.getRevokingItems().add(c); actions.add(Binder.fromKeysValues("action", "remove", "id", c.getId())); } tc.seal(); return tc; } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } | ContractsService { public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); tc.addSignerKey(k); } tc.addRole(issuerRole); tc.addRole("owner", issuerRole); tc.addRole("creator", issuerRole); if (!tc.getRevokingItems().contains(c)) { Binder data = tc.getDefinition().getData(); List<Binder> actions = data.getOrCreateList("actions"); tc.getRevokingItems().add(c); actions.add(Binder.fromKeysValues("action", "remove", "id", c.getId())); } tc.seal(); return tc; } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } |
@Test public void goodNotary() throws Exception { Set<PrivateKey> martyPrivateKeys = new HashSet<>(); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(); Set<PublicKey> martyPublicKeys = new HashSet<>(); Set<PublicKey> stepaPublicKeys = new HashSet<>(); martyPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/marty_mcfly.private.unikey"))); stepaPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey"))); for (PrivateKey pk : stepaPrivateKeys) stepaPublicKeys.add(pk.getPublicKey()); for (PrivateKey pk : martyPrivateKeys) martyPublicKeys.add(pk.getPublicKey()); Contract notaryContract = ContractsService.createNotaryContract(martyPrivateKeys, stepaPublicKeys); notaryContract.check(); notaryContract.traceErrors(); assertTrue(notaryContract.isOk()); assertTrue(notaryContract.getOwner().isAllowedForKeys(stepaPublicKeys)); assertTrue(notaryContract.getIssuer().isAllowedForKeys(martyPrivateKeys)); assertTrue(notaryContract.getCreator().isAllowedForKeys(martyPrivateKeys)); assertFalse(notaryContract.getOwner().isAllowedForKeys(martyPrivateKeys)); assertFalse(notaryContract.getIssuer().isAllowedForKeys(stepaPublicKeys)); assertFalse(notaryContract.getCreator().isAllowedForKeys(stepaPublicKeys)); assertTrue(notaryContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(notaryContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertTrue(notaryContract.isPermitted("revoke", stepaPublicKeys)); assertTrue(notaryContract.isPermitted("revoke", martyPublicKeys)); assertTrue(notaryContract.isPermitted("change_owner", stepaPublicKeys)); assertFalse(notaryContract.isPermitted("change_owner", martyPublicKeys)); } | public synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys) { Contract notaryContract = new Contract(); notaryContract.setApiLevel(3); Contract.Definition cd = notaryContract.getDefinition(); cd.setExpiresAt(notaryContract.getCreatedAt().plusMonths(60)); Binder data = new Binder(); data.set("name", "Default notary"); data.set("description", "Default notary description."); data.set("template_name", "NOTARY_CONTRACT"); data.set("holder_identifier", "default holder identifier"); cd.setData(data); SimpleRole issuerRole = new SimpleRole("issuer",notaryContract); for (PrivateKey k : issuerKeys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); } SimpleRole ownerRole = new SimpleRole("owner",notaryContract); for (PublicKey k : ownerKeys) { KeyRecord kr = new KeyRecord(k); ownerRole.addKeyRecord(kr); } notaryContract.addRole(issuerRole); notaryContract.addRole("issuer", issuerRole); notaryContract.addRole("creator", issuerRole); notaryContract.addRole(ownerRole); notaryContract.addRole("owner", ownerRole); ChangeOwnerPermission changeOwnerPerm = new ChangeOwnerPermission(ownerRole); notaryContract.addPermission(changeOwnerPerm); RevokePermission revokePerm1 = new RevokePermission(ownerRole); notaryContract.addPermission(revokePerm1); RevokePermission revokePerm2 = new RevokePermission(issuerRole); notaryContract.addPermission(revokePerm2); notaryContract.seal(); notaryContract.addSignatureToSeal(issuerKeys); return notaryContract; } | ContractsService { public synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys) { Contract notaryContract = new Contract(); notaryContract.setApiLevel(3); Contract.Definition cd = notaryContract.getDefinition(); cd.setExpiresAt(notaryContract.getCreatedAt().plusMonths(60)); Binder data = new Binder(); data.set("name", "Default notary"); data.set("description", "Default notary description."); data.set("template_name", "NOTARY_CONTRACT"); data.set("holder_identifier", "default holder identifier"); cd.setData(data); SimpleRole issuerRole = new SimpleRole("issuer",notaryContract); for (PrivateKey k : issuerKeys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); } SimpleRole ownerRole = new SimpleRole("owner",notaryContract); for (PublicKey k : ownerKeys) { KeyRecord kr = new KeyRecord(k); ownerRole.addKeyRecord(kr); } notaryContract.addRole(issuerRole); notaryContract.addRole("issuer", issuerRole); notaryContract.addRole("creator", issuerRole); notaryContract.addRole(ownerRole); notaryContract.addRole("owner", ownerRole); ChangeOwnerPermission changeOwnerPerm = new ChangeOwnerPermission(ownerRole); notaryContract.addPermission(changeOwnerPerm); RevokePermission revokePerm1 = new RevokePermission(ownerRole); notaryContract.addPermission(revokePerm1); RevokePermission revokePerm2 = new RevokePermission(issuerRole); notaryContract.addPermission(revokePerm2); notaryContract.seal(); notaryContract.addSignatureToSeal(issuerKeys); return notaryContract; } } | ContractsService { public synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys) { Contract notaryContract = new Contract(); notaryContract.setApiLevel(3); Contract.Definition cd = notaryContract.getDefinition(); cd.setExpiresAt(notaryContract.getCreatedAt().plusMonths(60)); Binder data = new Binder(); data.set("name", "Default notary"); data.set("description", "Default notary description."); data.set("template_name", "NOTARY_CONTRACT"); data.set("holder_identifier", "default holder identifier"); cd.setData(data); SimpleRole issuerRole = new SimpleRole("issuer",notaryContract); for (PrivateKey k : issuerKeys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); } SimpleRole ownerRole = new SimpleRole("owner",notaryContract); for (PublicKey k : ownerKeys) { KeyRecord kr = new KeyRecord(k); ownerRole.addKeyRecord(kr); } notaryContract.addRole(issuerRole); notaryContract.addRole("issuer", issuerRole); notaryContract.addRole("creator", issuerRole); notaryContract.addRole(ownerRole); notaryContract.addRole("owner", ownerRole); ChangeOwnerPermission changeOwnerPerm = new ChangeOwnerPermission(ownerRole); notaryContract.addPermission(changeOwnerPerm); RevokePermission revokePerm1 = new RevokePermission(ownerRole); notaryContract.addPermission(revokePerm1); RevokePermission revokePerm2 = new RevokePermission(issuerRole); notaryContract.addPermission(revokePerm2); notaryContract.seal(); notaryContract.addSignatureToSeal(issuerKeys); return notaryContract; } } | ContractsService { public synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys) { Contract notaryContract = new Contract(); notaryContract.setApiLevel(3); Contract.Definition cd = notaryContract.getDefinition(); cd.setExpiresAt(notaryContract.getCreatedAt().plusMonths(60)); Binder data = new Binder(); data.set("name", "Default notary"); data.set("description", "Default notary description."); data.set("template_name", "NOTARY_CONTRACT"); data.set("holder_identifier", "default holder identifier"); cd.setData(data); SimpleRole issuerRole = new SimpleRole("issuer",notaryContract); for (PrivateKey k : issuerKeys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); } SimpleRole ownerRole = new SimpleRole("owner",notaryContract); for (PublicKey k : ownerKeys) { KeyRecord kr = new KeyRecord(k); ownerRole.addKeyRecord(kr); } notaryContract.addRole(issuerRole); notaryContract.addRole("issuer", issuerRole); notaryContract.addRole("creator", issuerRole); notaryContract.addRole(ownerRole); notaryContract.addRole("owner", ownerRole); ChangeOwnerPermission changeOwnerPerm = new ChangeOwnerPermission(ownerRole); notaryContract.addPermission(changeOwnerPerm); RevokePermission revokePerm1 = new RevokePermission(ownerRole); notaryContract.addPermission(revokePerm1); RevokePermission revokePerm2 = new RevokePermission(issuerRole); notaryContract.addPermission(revokePerm2); notaryContract.seal(); notaryContract.addSignatureToSeal(issuerKeys); return notaryContract; } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } | ContractsService { public synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys) { Contract notaryContract = new Contract(); notaryContract.setApiLevel(3); Contract.Definition cd = notaryContract.getDefinition(); cd.setExpiresAt(notaryContract.getCreatedAt().plusMonths(60)); Binder data = new Binder(); data.set("name", "Default notary"); data.set("description", "Default notary description."); data.set("template_name", "NOTARY_CONTRACT"); data.set("holder_identifier", "default holder identifier"); cd.setData(data); SimpleRole issuerRole = new SimpleRole("issuer",notaryContract); for (PrivateKey k : issuerKeys) { KeyRecord kr = new KeyRecord(k.getPublicKey()); issuerRole.addKeyRecord(kr); } SimpleRole ownerRole = new SimpleRole("owner",notaryContract); for (PublicKey k : ownerKeys) { KeyRecord kr = new KeyRecord(k); ownerRole.addKeyRecord(kr); } notaryContract.addRole(issuerRole); notaryContract.addRole("issuer", issuerRole); notaryContract.addRole("creator", issuerRole); notaryContract.addRole(ownerRole); notaryContract.addRole("owner", ownerRole); ChangeOwnerPermission changeOwnerPerm = new ChangeOwnerPermission(ownerRole); notaryContract.addPermission(changeOwnerPerm); RevokePermission revokePerm1 = new RevokePermission(ownerRole); notaryContract.addPermission(revokePerm1); RevokePermission revokePerm2 = new RevokePermission(issuerRole); notaryContract.addPermission(revokePerm2); notaryContract.seal(); notaryContract.addSignatureToSeal(issuerKeys); return notaryContract; } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } |
@Test public void goodToken() throws Exception { Set<PrivateKey> martyPrivateKeys = new HashSet<>(); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(); Set<PublicKey> martyPublicKeys = new HashSet<>(); Set<PublicKey> stepaPublicKeys = new HashSet<>(); martyPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/marty_mcfly.private.unikey"))); stepaPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey"))); for (PrivateKey pk : stepaPrivateKeys) stepaPublicKeys.add(pk.getPublicKey()); for (PrivateKey pk : martyPrivateKeys) martyPublicKeys.add(pk.getPublicKey()); Contract tokenContract = ContractsService.createTokenContract(martyPrivateKeys, stepaPublicKeys, new BigDecimal("100")); tokenContract.check(); tokenContract.traceErrors(); assertTrue(tokenContract.isOk()); assertTrue(tokenContract.getOwner().isAllowedForKeys(stepaPublicKeys)); assertTrue(tokenContract.getIssuer().isAllowedForKeys(martyPrivateKeys)); assertTrue(tokenContract.getCreator().isAllowedForKeys(martyPrivateKeys)); assertFalse(tokenContract.getOwner().isAllowedForKeys(martyPrivateKeys)); assertFalse(tokenContract.getIssuer().isAllowedForKeys(stepaPublicKeys)); assertFalse(tokenContract.getCreator().isAllowedForKeys(stepaPublicKeys)); assertTrue(tokenContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(tokenContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertEquals(InnerContractsService.getDecimalField(tokenContract, "amount"), new Decimal(100)); assertEquals(tokenContract.getPermissions().get("split_join").size(), 1); Binder splitJoinParams = tokenContract.getPermissions().get("split_join").iterator().next().getParams(); assertEquals(splitJoinParams.get("min_value"), "0.01"); assertEquals(splitJoinParams.get("min_unit"), "0.01"); assertEquals(splitJoinParams.get("field_name"), "amount"); assertTrue(splitJoinParams.get("join_match_fields") instanceof List); assertEquals(((List)splitJoinParams.get("join_match_fields")).get(0), "state.origin"); assertTrue(tokenContract.isPermitted("revoke", stepaPublicKeys)); assertTrue(tokenContract.isPermitted("revoke", martyPublicKeys)); assertTrue(tokenContract.isPermitted("change_owner", stepaPublicKeys)); assertFalse(tokenContract.isPermitted("change_owner", martyPublicKeys)); assertTrue(tokenContract.isPermitted("split_join", stepaPublicKeys)); assertFalse(tokenContract.isPermitted("split_join", martyPublicKeys)); } | @Deprecated public synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description) { return createTokenContract(issuerKeys, ownerKeys, new BigDecimal(amount), new BigDecimal(minValue), currency, name, description); } | ContractsService { @Deprecated public synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description) { return createTokenContract(issuerKeys, ownerKeys, new BigDecimal(amount), new BigDecimal(minValue), currency, name, description); } } | ContractsService { @Deprecated public synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description) { return createTokenContract(issuerKeys, ownerKeys, new BigDecimal(amount), new BigDecimal(minValue), currency, name, description); } } | ContractsService { @Deprecated public synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description) { return createTokenContract(issuerKeys, ownerKeys, new BigDecimal(amount), new BigDecimal(minValue), currency, name, description); } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } | ContractsService { @Deprecated public synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description) { return createTokenContract(issuerKeys, ownerKeys, new BigDecimal(amount), new BigDecimal(minValue), currency, name, description); } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } |
@Test public void goodShare() throws Exception { Set<PrivateKey> martyPrivateKeys = new HashSet<>(); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(); Set<PublicKey> martyPublicKeys = new HashSet<>(); Set<PublicKey> stepaPublicKeys = new HashSet<>(); martyPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/marty_mcfly.private.unikey"))); stepaPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/stepan_mamontov.private.unikey"))); for (PrivateKey pk : stepaPrivateKeys) stepaPublicKeys.add(pk.getPublicKey()); for (PrivateKey pk : martyPrivateKeys) martyPublicKeys.add(pk.getPublicKey()); Contract shareContract = ContractsService.createShareContract(martyPrivateKeys, stepaPublicKeys, new BigDecimal("100")); shareContract.check(); shareContract.traceErrors(); assertTrue(shareContract.isOk()); assertTrue(shareContract.getOwner().isAllowedForKeys(stepaPublicKeys)); assertTrue(shareContract.getIssuer().isAllowedForKeys(martyPrivateKeys)); assertTrue(shareContract.getCreator().isAllowedForKeys(martyPrivateKeys)); assertFalse(shareContract.getOwner().isAllowedForKeys(martyPrivateKeys)); assertFalse(shareContract.getIssuer().isAllowedForKeys(stepaPublicKeys)); assertFalse(shareContract.getCreator().isAllowedForKeys(stepaPublicKeys)); assertTrue(shareContract.getExpiresAt().isAfter(ZonedDateTime.now().plusMonths(3))); assertTrue(shareContract.getCreatedAt().isBefore(ZonedDateTime.now())); assertEquals(InnerContractsService.getDecimalField(shareContract, "amount"), new Decimal(100)); assertEquals(shareContract.getPermissions().get("split_join").size(), 1); Binder splitJoinParams = shareContract.getPermissions().get("split_join").iterator().next().getParams(); assertEquals(splitJoinParams.get("min_value"), 1); assertEquals(splitJoinParams.get("min_unit"), 1); assertEquals(splitJoinParams.get("field_name"), "amount"); assertTrue(splitJoinParams.get("join_match_fields") instanceof List); assertEquals(((List)splitJoinParams.get("join_match_fields")).get(0), "state.origin"); assertTrue(shareContract.isPermitted("revoke", stepaPublicKeys)); assertTrue(shareContract.isPermitted("revoke", martyPublicKeys)); assertTrue(shareContract.isPermitted("change_owner", stepaPublicKeys)); assertFalse(shareContract.isPermitted("change_owner", martyPublicKeys)); assertTrue(shareContract.isPermitted("split_join", stepaPublicKeys)); assertFalse(shareContract.isPermitted("split_join", martyPublicKeys)); } | @Deprecated public synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount) { return createShareContract(issuerKeys, ownerKeys, new BigDecimal(amount)); } | ContractsService { @Deprecated public synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount) { return createShareContract(issuerKeys, ownerKeys, new BigDecimal(amount)); } } | ContractsService { @Deprecated public synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount) { return createShareContract(issuerKeys, ownerKeys, new BigDecimal(amount)); } } | ContractsService { @Deprecated public synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount) { return createShareContract(issuerKeys, ownerKeys, new BigDecimal(amount)); } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } | ContractsService { @Deprecated public synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount) { return createShareContract(issuerKeys, ownerKeys, new BigDecimal(amount)); } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys); @Deprecated synchronized static Contract createSplit(Contract c, String amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys); synchronized static Contract createSplit(Contract c, BigDecimal amount, String fieldName, Set<PrivateKey> keys, boolean andSetCreator); synchronized static Contract createJoin(Contract contract1, Contract contract2, String fieldName, Set<PrivateKey> keys); static List<Contract> createSplitJoin(Collection<Contract> contractsToJoin, List<String> amountsToSplit, List<KeyAddress> addressesToSplit,Set<PrivateKey> ownerKeys, String fieldName); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys); synchronized static Contract startSwap(Contract contract1, Contract contract2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); synchronized static Contract startSwap(List<Contract> contracts1, List<Contract> contracts2, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract signPresentedSwap(Contract swapContract, Set<PrivateKey> keys); @Deprecated synchronized static Contract finishSwap(Contract swapContract, Set<PrivateKey> keys); synchronized static Contract createTwoSignedContract(Contract baseContract, Set<PrivateKey> fromKeys, Set<PublicKey> toKeys, boolean createNewRevision); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description); @Deprecated synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue, String currency, String name, String description); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); synchronized static Contract createMintableTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, String amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount, BigDecimal minValue); @Deprecated synchronized static Contract createTokenContractWithEmission(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys, String fieldName); @Deprecated synchronized static Contract createTokenEmission(Contract tokenContract, BigDecimal amount, Set<PrivateKey> keys); @Deprecated synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount); synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, BigDecimal amount); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths); synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys,
List<String> filePaths, List<String> fileDescriptions); synchronized static boolean checkAttachNotaryContract(Contract notaryContract, String filePaths); synchronized static SlotContract createSlotContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static UnsContract createUnsContractForRegisterContractName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, Contract namedContract); synchronized static UnsContract createUnsContractForRegisterKeyName(
Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider,
String name, String description, String URL, AbstractKey namedKey); synchronized static FollowerContract createFollowerContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, NSmartContract.NodeInfoProvider nodeInfoProvider); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, Binder conditions); synchronized static Contract addReferenceToContract(
Contract baseContract, Contract refContract, String refName, int refType, List<String> listConditions, boolean isAllOfConditions); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(Contract payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys); synchronized static Parcel createParcel(TransactionPack payload, Contract payment, int amount, Set<PrivateKey> keys,
boolean withTestPayment); synchronized static Parcel createPayingParcel(TransactionPack payload, Contract payment, int amount, int amountSecond,
Set<PrivateKey> keys, boolean withTestPayment); static Contract createBatch(Collection<PrivateKey> keys, Contract... contracts); static Contract addConsent(Contract source, KeyAddress... consentKeyAddresses); static Contract createEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createInternalEscrowContract(
Collection<PrivateKey> issuerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys,
Collection<PublicKey> arbitratorKeys); static Contract createExternalEscrowContract(Contract internalEscrow, Collection<PrivateKey> issuerKeys); static Contract modifyPaymentForEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract modifyPaymentForEscrowContract(
String escrowOrigin,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static boolean addPaymentToEscrowContract(
Contract escrow,
Contract payment,
Collection<PrivateKey> paymentOwnerKeys,
Collection<PublicKey> customerKeys,
Collection<PublicKey> executorKeys); static Contract completeEscrowContract(Contract escrow); static Contract cancelEscrowContract(Contract escrow); static Contract takeEscrowPayment(Collection<PrivateKey> newOwnerKeys, Contract payment); synchronized static Contract createRateLimitDisablingContract(PublicKey key, Contract payment, int amount, Set<PrivateKey> keys); } |
@Test public void shouldNotSplitWithWrongDataAmountSerialize() throws Exception { Contract c = createCoin(); c.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(c, true); Contract c2 = c.split(1)[0]; sealCheckTrace(c2, true); Binder sd2 = DefaultBiMapper.serialize(c2); Binder state = (Binder) sd2.get("state"); assertNotNull(state); assertTrue(state.size() > 0); Binder data = (Binder) state.get("data"); assertNotNull(data); assertTrue(data.size() > 0); data.remove(FIELD_NAME); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); } | @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); boolean validateMergeFields(Contract changed, Contract c); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); boolean validateMergeFields(Contract changed, Contract c); } |
@Test public void shouldNotSplitWithWrongCreatedBySerialize() throws Exception { Contract c = createCoin(); c.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(c, true); Contract c2 = c.split(1)[0]; sealCheckTrace(c2, true); Binder sd2 = DefaultBiMapper.serialize(c2); Binder state = (Binder) sd2.get("state"); assertNotNull(state); assertTrue(state.size() > 0); state.set("createdBy", "other"); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); state.set("createdBy", "owner"); Contract dc3 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc3, false); state.remove("createdBy"); Contract dc4 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc4, false); } | @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); boolean validateMergeFields(Contract changed, Contract c); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); boolean validateMergeFields(Contract changed, Contract c); } |
@Test public void shouldNotSplitWithWrongOriginSerialize() throws Exception { Contract c = createCoin(); c.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(c, true); Contract c2 = c.split(1)[0]; sealCheckTrace(c2, true); Binder sd2 = DefaultBiMapper.serialize(c2); Binder state = (Binder) sd2.get("state"); assertNotNull(state); assertTrue(state.size() > 0); HashId origin = HashId.withDigest(Do.randomNegativeBytes(64)); Binder originB = DefaultBiMapper.serialize(origin); state.set("origin", originB); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); state.remove("origin"); Contract dc3 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc3, false); } | @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); boolean validateMergeFields(Contract changed, Contract c); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); boolean validateMergeFields(Contract changed, Contract c); } |
@Test public void shouldNotSplitWithWrongParentSerialize() throws Exception { Contract c = createCoin(); c.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(c, true); Contract c2 = c.split(1)[0]; sealCheckTrace(c2, true); Binder sd2 = DefaultBiMapper.serialize(c2); Binder state = (Binder) sd2.get("state"); assertNotNull(state); assertTrue(state.size() > 0); HashId parent = HashId.withDigest(Do.randomNegativeBytes(64)); Binder parentB = DefaultBiMapper.serialize(parent); state.set("parent", parentB); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); state.remove("parent"); Contract dc3 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc3, false); } | @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); boolean validateMergeFields(Contract changed, Contract c); } | SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); boolean validateMergeFields(Contract changed, Contract c); } |
@Test public void modifyDataAllowed() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.getStateData().put("field_to_be_changed", "value1"); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("field_to_be_changed", null); contract.addPermission(modifyDataPermission); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("field_to_be_changed", "value2"); changed.seal(); changed.check(); assertTrue(changed.isOk()); } | public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); static final String FIELD_NAME; } |
@Test public void modifyDataWhiteList() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.getStateData().put("field_to_be_changed", "value1"); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("field_to_be_changed", Do.listOf("value2", "value3")); contract.addPermission(modifyDataPermission); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("field_to_be_changed", "value2"); changed.seal(); changed.check(); assertTrue(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("field_to_be_changed", "value3"); changed.seal(); changed.check(); assertTrue(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("field_to_be_changed", "value4"); changed.seal(); changed.check(); assertTrue(!changed.isOk()); } | public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); static final String FIELD_NAME; } |
@Test public void toHash() throws Exception { AbstractPrivateKey rsaPrivateKey = oaepSpec.getPrivateKey(); Map mapRSA = rsaPrivateKey.toHash(); assertArrayEquals((byte[]) mapRSA.get("e"), oaepSpec.e); assertArrayEquals((byte[]) mapRSA.get("p"), oaepSpec.p); assertArrayEquals((byte[]) mapRSA.get("q"), oaepSpec.q); assertFalse(mapRSA.containsKey("mgf1Hash")); AbstractPublicKey randomPublicKey4096 = randomPrivateKey4096.getPublicKey(); Map mapPrivate4096 = randomPrivateKey4096.toHash(), mapPublic4096 = randomPublicKey4096.toHash(); RSAPrivateCrtKeyParameters privateKeyParameters4096 = ((RSAOAEPPrivateKey) randomPrivateKey4096).state.keyParameters; RSAKeyParameters publicKeyParameters4096 = ((RSAOAEPPublicKey) (randomPrivateKey4096.getPublicKey())).state.keyParameters; assertArrayEquals( (byte[]) mapPrivate4096.get("e"), BigIntegers.asUnsignedByteArray(privateKeyParameters4096.getPublicExponent())); assertArrayEquals( (byte[]) mapPrivate4096.get("p"), BigIntegers.asUnsignedByteArray(privateKeyParameters4096.getP())); assertArrayEquals( (byte[]) mapPrivate4096.get("q"), BigIntegers.asUnsignedByteArray(privateKeyParameters4096.getQ())); assertEquals(mapPrivate4096.get("mgf1Hash"), "SHA-512"); assertArrayEquals( (byte[]) mapPublic4096.get("n"), BigIntegers.asUnsignedByteArray(publicKeyParameters4096.getModulus())); assertArrayEquals( (byte[]) mapPublic4096.get("e"), BigIntegers.asUnsignedByteArray(publicKeyParameters4096.getExponent())); assertEquals(mapPublic4096.get("mgf1Hash"), "SHA-512"); } | @NonNull @Override public Map<String, Object> toHash() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return Collections.unmodifiableMap(new HashMap<String, Object>() {{ put("e", BigIntegers.asUnsignedByteArray(state.keyParameters.getPublicExponent())); put("p", BigIntegers.asUnsignedByteArray(state.keyParameters.getP())); put("q", BigIntegers.asUnsignedByteArray(state.keyParameters.getQ())); if (!state.mgf1HashType.equals(DEFAULT_MGF1_HASH)) { put("mgf1Hash", state.mgf1HashType.getAlgorithmName()); } }}); } } | RSAOAEPPrivateKey extends AbstractPrivateKey { @NonNull @Override public Map<String, Object> toHash() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return Collections.unmodifiableMap(new HashMap<String, Object>() {{ put("e", BigIntegers.asUnsignedByteArray(state.keyParameters.getPublicExponent())); put("p", BigIntegers.asUnsignedByteArray(state.keyParameters.getP())); put("q", BigIntegers.asUnsignedByteArray(state.keyParameters.getQ())); if (!state.mgf1HashType.equals(DEFAULT_MGF1_HASH)) { put("mgf1Hash", state.mgf1HashType.getAlgorithmName()); } }}); } } } | RSAOAEPPrivateKey extends AbstractPrivateKey { @NonNull @Override public Map<String, Object> toHash() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return Collections.unmodifiableMap(new HashMap<String, Object>() {{ put("e", BigIntegers.asUnsignedByteArray(state.keyParameters.getPublicExponent())); put("p", BigIntegers.asUnsignedByteArray(state.keyParameters.getP())); put("q", BigIntegers.asUnsignedByteArray(state.keyParameters.getQ())); if (!state.mgf1HashType.equals(DEFAULT_MGF1_HASH)) { put("mgf1Hash", state.mgf1HashType.getAlgorithmName()); } }}); } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); } | RSAOAEPPrivateKey extends AbstractPrivateKey { @NonNull @Override public Map<String, Object> toHash() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return Collections.unmodifiableMap(new HashMap<String, Object>() {{ put("e", BigIntegers.asUnsignedByteArray(state.keyParameters.getPublicExponent())); put("p", BigIntegers.asUnsignedByteArray(state.keyParameters.getP())); put("q", BigIntegers.asUnsignedByteArray(state.keyParameters.getQ())); if (!state.mgf1HashType.equals(DEFAULT_MGF1_HASH)) { put("mgf1Hash", state.mgf1HashType.getAlgorithmName()); } }}); } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); } | RSAOAEPPrivateKey extends AbstractPrivateKey { @NonNull @Override public Map<String, Object> toHash() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return Collections.unmodifiableMap(new HashMap<String, Object>() {{ put("e", BigIntegers.asUnsignedByteArray(state.keyParameters.getPublicExponent())); put("p", BigIntegers.asUnsignedByteArray(state.keyParameters.getP())); put("q", BigIntegers.asUnsignedByteArray(state.keyParameters.getQ())); if (!state.mgf1HashType.equals(DEFAULT_MGF1_HASH)) { put("mgf1Hash", state.mgf1HashType.getAlgorithmName()); } }}); } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; } |
@Test public void modifyExpiresAtAllowed() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.getStateData().put("field_to_be_changed", "value1"); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("/expires_at", null); contract.addPermission(modifyDataPermission); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.setExpiresAt(ZonedDateTime.now().plusDays(1)); changed.seal(); changed.check(); assertTrue(changed.isOk()); } | public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); static final String FIELD_NAME; } |
@Test public void modifyExpiresAtDeclined() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.getStateData().put("field_to_be_changed", "value1"); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("expires_at", null); contract.addPermission(modifyDataPermission); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.setExpiresAt(ZonedDateTime.now().plusDays(1)); changed.seal(); changed.check(); assertTrue(!changed.isOk()); } | public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); static final String FIELD_NAME; } |
@Test public void modifyExpiresAtWhiteList() throws Exception { ZonedDateTime now = ZonedDateTime.ofInstant(Instant.ofEpochSecond(ZonedDateTime.now().toEpochSecond()), ZoneId.systemDefault()); Contract contract = new Contract(TestKeys.privateKey(0)); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("/expires_at", Do.listOf(now.plusDays(1), now.plusDays(2))); contract.addPermission(modifyDataPermission); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.setExpiresAt(now.plusDays(1)); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.setExpiresAt(now.plusDays(2)); changed.seal(); changed.check(); assertTrue(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.setExpiresAt(now.plusDays(3)); changed.seal(); changed.check(); assertTrue(!changed.isOk()); } | public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); static final String FIELD_NAME; } |
@Test public void modifyReferencesAllowed() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"),new Binder()); modifyDataPermission.addField("/references", null); contract.addPermission(modifyDataPermission); contract.seal(); Contract referencedContract = new Contract(TestKeys.privateKey(1)); referencedContract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); Reference ref = new Reference(referencedContract); ref.type = Reference.TYPE_EXISTING_STATE; ref.addMatchingItem(referencedContract); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); } | public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); static final String FIELD_NAME; } |
@Test public void modifyReferencesDeclined() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"),new Binder()); modifyDataPermission.addField("references", null); contract.addPermission(modifyDataPermission); contract.seal(); Contract referencedContract = new Contract(TestKeys.privateKey(1)); referencedContract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); Reference ref = new Reference(referencedContract); ref.addMatchingItem(referencedContract); ref.type = Reference.TYPE_EXISTING_STATE; changed.addReference(ref); changed.seal(); changed.check(); assertTrue(!changed.isOk()); } | public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); static final String FIELD_NAME; } |
@Test public void modifyReferencesWhiteList() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.getDefinition().getData().put("type","Good Bank"); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"),new Binder()); Contract referencedContract = new Contract(TestKeys.privateKey(1)); referencedContract.seal(); List<String> listConditionsForDefinition = new ArrayList<>(); listConditionsForDefinition.add("ref.definition.data.type == \"Good Bank\""); Binder conditionsForDefinition = new Binder(); conditionsForDefinition.set("all_of", listConditionsForDefinition); Reference ref = new Reference(referencedContract); ref.name = "bank_certificate"; ref.type = Reference.TYPE_EXISTING_STATE; ref.setConditions(conditionsForDefinition); modifyDataPermission.addField("/references", Do.listOf(ref)); contract.addPermission(modifyDataPermission); contract.seal(); ref = Boss.load(Boss.dump(ref)); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); ref.name = "stepa_certificate"; changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); ref.name = "bank_certificate"; ref.type = Reference.TYPE_TRANSACTIONAL; changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); ref.type = Reference.TYPE_EXISTING_STATE; conditionsForDefinition = new Binder(); conditionsForDefinition.set("any_of", listConditionsForDefinition); ref.setConditions(conditionsForDefinition); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); listConditionsForDefinition = new ArrayList<>(); listConditionsForDefinition.add("ref.definition.data.type == \"Stepa Bank\""); conditionsForDefinition = new Binder(); conditionsForDefinition.set("all_of", listConditionsForDefinition); ref.setConditions(conditionsForDefinition); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); listConditionsForDefinition = new ArrayList<>(); listConditionsForDefinition.add("ref.definition.data.type == \"Good Bank\""); conditionsForDefinition = new Binder(); conditionsForDefinition.set("all_of", listConditionsForDefinition); ref.setConditions(conditionsForDefinition); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); ref.setContract(changed); changed.addReference(ref); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); } | public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); static final String FIELD_NAME; } |
@Test public void modifyStatDataAtWhiteList() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("value", Do.listOf("0", "1")); contract.addPermission(modifyDataPermission); contract.getStateData().set("value", null); contract.seal(); Contract changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("value", "2"); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("value", "1"); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); changed = contract.createRevision(); changed.addSignerKey(TestKeys.privateKey(0)); changed.getStateData().set("value", "2"); changed.seal(); changed.check(); changed.traceErrors(); assertFalse(changed.isOk()); changed.getErrors().clear(); changed.getStateData().set("value", "1"); changed.seal(); changed.check(); changed.traceErrors(); assertTrue(changed.isOk()); Contract trickContract = new Contract(TestKeys.privateKey(0)); trickContract.addPermission(modifyDataPermission); trickContract.getStateData().set("value", "2"); trickContract.seal(); trickContract.check(); trickContract.traceErrors(); assertTrue(trickContract.isOk()); } | public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); } | ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void addAllFields(Map<String, List<String>> fields); @Override void checkChangesQuantized(Contract contract, Contract changedContract, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); Map<String, List<String>> getFields(); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); static final String FIELD_NAME; } |
@Test public void contractGetPermission() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); Contract contract2 = new Contract(TestKeys.privateKey(0)); ChangeNumberPermission changeNumberPermission = new ChangeNumberPermission(new RoleLink("@owner", "owner"), Binder.of( "field_name", "field1", "min_value", 33, "max_value", 34, "min_step", 1, "max_step", 1 ) ); changeNumberPermission.setId("changenumber"); contract.addPermission(changeNumberPermission); contract2.addPermission(changeNumberPermission); contract.seal(); contract2.seal(); contract = Contract.fromPackedTransaction(contract.getPackedTransaction()); contract2 = Contract.fromPackedTransaction(contract2.getPackedTransaction()); assertNotNull(contract.get("definition.permissions.changenumber")); assertEquals((Permission)contract.get("definition.permissions.changenumber"),contract2.get("definition.permissions.changenumber")); } | public void setId(@NonNull String id) { if( this.id != null && !this.id.equals(id) ) throw new IllegalStateException("permission id is already set"); this.id = id; } | Permission implements BiSerializable, Comparable<Permission> { public void setId(@NonNull String id) { if( this.id != null && !this.id.equals(id) ) throw new IllegalStateException("permission id is already set"); this.id = id; } } | Permission implements BiSerializable, Comparable<Permission> { public void setId(@NonNull String id) { if( this.id != null && !this.id.equals(id) ) throw new IllegalStateException("permission id is already set"); this.id = id; } protected Permission(); protected Permission(String name, Role role); protected Permission(String name, Role role, Binder params); } | Permission implements BiSerializable, Comparable<Permission> { public void setId(@NonNull String id) { if( this.id != null && !this.id.equals(id) ) throw new IllegalStateException("permission id is already set"); this.id = id; } protected Permission(); protected Permission(String name, Role role); protected Permission(String name, Role role, Binder params); @Nullable String getId(); void setId(@NonNull String id); Binder getParams(); static Permission forName(String name, Role role, Binder params); @Deprecated boolean isAllowedForKeys(PublicKey... keys); @Deprecated boolean isAllowedForKeys(Collection<PublicKey> keys); @Deprecated boolean isAllowedFor(Collection<PublicKey> keys); boolean isAllowedForKeysQuantized(PublicKey... keys); boolean isAllowedForKeysQuantized(Collection<PublicKey> keys); boolean isAllowedForQuantized(Collection<PublicKey> keys); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); final void checkChanges(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); abstract void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); @Override String toString(); Role getRole(); String getName(); @Override boolean equals(Object obj); @Override int compareTo(Permission o); } | Permission implements BiSerializable, Comparable<Permission> { public void setId(@NonNull String id) { if( this.id != null && !this.id.equals(id) ) throw new IllegalStateException("permission id is already set"); this.id = id; } protected Permission(); protected Permission(String name, Role role); protected Permission(String name, Role role, Binder params); @Nullable String getId(); void setId(@NonNull String id); Binder getParams(); static Permission forName(String name, Role role, Binder params); @Deprecated boolean isAllowedForKeys(PublicKey... keys); @Deprecated boolean isAllowedForKeys(Collection<PublicKey> keys); @Deprecated boolean isAllowedFor(Collection<PublicKey> keys); boolean isAllowedForKeysQuantized(PublicKey... keys); boolean isAllowedForKeysQuantized(Collection<PublicKey> keys); boolean isAllowedForQuantized(Collection<PublicKey> keys); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); final void checkChanges(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); abstract void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); @Override String toString(); Role getRole(); String getName(); @Override boolean equals(Object obj); @Override int compareTo(Permission o); } |
@Test public void sign() throws Exception { byte[] data = "Hello world".getBytes(); PrivateKey k = TestKeys.privateKey(3); byte [] signature = ExtendedSignature.sign(k, data); PublicKey pubKey = k.getPublicKey(); ExtendedSignature es = ExtendedSignature.verify(pubKey, signature, data); assertNotNull(es); assertAlmostSame(es.getCreatedAt(), ZonedDateTime.now()); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.keyId(pubKey)); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.extractKeyId(signature)); } | static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } | ExtendedSignature { static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } } | ExtendedSignature { static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } } | ExtendedSignature { static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } Bytes getKeyId(); ZonedDateTime getCreatedAt(); PublicKey getPublicKey(); static byte[] sign(PrivateKey key, byte[] data); static byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey); static byte[] createTargetSignature(PublicKey publicKey, byte[] data, boolean savePublicKey); @Deprecated static byte[] of(byte[] targetSignature, byte[] sign, byte[] sign2); static byte[] ofSha512AndSha3_384(byte[] targetSignature, byte[] sign512, byte[] sign3_384); static Bytes keyId(AbstractKey key); static Bytes extractKeyId(byte[] signature); static PublicKey extractPublicKey(byte[] signature); byte[] getSignature(); static ExtendedSignature verify(PublicKey key, byte[] signature, byte[] data); } | ExtendedSignature { static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } Bytes getKeyId(); ZonedDateTime getCreatedAt(); PublicKey getPublicKey(); static byte[] sign(PrivateKey key, byte[] data); static byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey); static byte[] createTargetSignature(PublicKey publicKey, byte[] data, boolean savePublicKey); @Deprecated static byte[] of(byte[] targetSignature, byte[] sign, byte[] sign2); static byte[] ofSha512AndSha3_384(byte[] targetSignature, byte[] sign512, byte[] sign3_384); static Bytes keyId(AbstractKey key); static Bytes extractKeyId(byte[] signature); static PublicKey extractPublicKey(byte[] signature); byte[] getSignature(); static ExtendedSignature verify(PublicKey key, byte[] signature, byte[] data); } |
@Test public void parallelExecutionSign() throws Exception { ExecutorService single = Executors.newSingleThreadExecutor(); ExecutorService multiple = Executors.newCachedThreadPool(); byte[] data = "Hello world".getBytes(); PrivateKey k = new PrivateKey(2048); for(int i=0; i<200; i++) ExtendedSignature.sign(k, data); double t1 = parallelize(single, 1, ()-> { for(int i=0; i<100; i++) ExtendedSignature.sign(k, data); }); System.out.println(t1); double t2 = parallelize(multiple, 4, ()-> { for(int i=0; i<100; i++) ExtendedSignature.sign(k, data); }); System.out.println(t2); assertThat(Math.abs(t1-t2), is(lessThan(0.15))); } | static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } | ExtendedSignature { static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } } | ExtendedSignature { static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } } | ExtendedSignature { static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } Bytes getKeyId(); ZonedDateTime getCreatedAt(); PublicKey getPublicKey(); static byte[] sign(PrivateKey key, byte[] data); static byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey); static byte[] createTargetSignature(PublicKey publicKey, byte[] data, boolean savePublicKey); @Deprecated static byte[] of(byte[] targetSignature, byte[] sign, byte[] sign2); static byte[] ofSha512AndSha3_384(byte[] targetSignature, byte[] sign512, byte[] sign3_384); static Bytes keyId(AbstractKey key); static Bytes extractKeyId(byte[] signature); static PublicKey extractPublicKey(byte[] signature); byte[] getSignature(); static ExtendedSignature verify(PublicKey key, byte[] signature, byte[] data); } | ExtendedSignature { static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } Bytes getKeyId(); ZonedDateTime getCreatedAt(); PublicKey getPublicKey(); static byte[] sign(PrivateKey key, byte[] data); static byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey); static byte[] createTargetSignature(PublicKey publicKey, byte[] data, boolean savePublicKey); @Deprecated static byte[] of(byte[] targetSignature, byte[] sign, byte[] sign2); static byte[] ofSha512AndSha3_384(byte[] targetSignature, byte[] sign512, byte[] sign3_384); static Bytes keyId(AbstractKey key); static Bytes extractKeyId(byte[] signature); static PublicKey extractPublicKey(byte[] signature); byte[] getSignature(); static ExtendedSignature verify(PublicKey key, byte[] signature, byte[] data); } |
@Test public void testFromUnikeyRSAOAEP() throws Exception { final RSAOAEPPrivateKey pk1 = UnikeyFactory.rsaOaepPKFromUnikey(pk1Bytes); assertNotNull(pk1); assertArrayEquals( pk1E, BigIntegers.asUnsignedByteArray(pk1.state.keyParameters.getPublicExponent())); assertArrayEquals( pk1P, BigIntegers.asUnsignedByteArray(pk1.state.keyParameters.getP())); assertArrayEquals( pk1Q, BigIntegers.asUnsignedByteArray(pk1.state.keyParameters.getQ())); } | @Nullable static RSAOAEPPrivateKey rsaOaepPKFromUnikey(@NonNull byte[] bytes) { assert bytes != null; try { final ArrayList unpackedFromBoss = Boss.load(bytes); assert ((Integer) unpackedFromBoss.get(0)) == 0; final byte[] e = ((Bytes) unpackedFromBoss.get(1)).toArray(), p = ((Bytes) unpackedFromBoss.get(2)).toArray(), q = ((Bytes) unpackedFromBoss.get(3)).toArray(); return new RSAOAEPPrivateKey( e, p, q, RSAOAEPPrivateKey.DEFAULT_OAEP_HASH, RSAOAEPPrivateKey.DEFAULT_MGF1_HASH, new SecureRandom()); } catch (Throwable e) { return null; } } | UnikeyFactory { @Nullable static RSAOAEPPrivateKey rsaOaepPKFromUnikey(@NonNull byte[] bytes) { assert bytes != null; try { final ArrayList unpackedFromBoss = Boss.load(bytes); assert ((Integer) unpackedFromBoss.get(0)) == 0; final byte[] e = ((Bytes) unpackedFromBoss.get(1)).toArray(), p = ((Bytes) unpackedFromBoss.get(2)).toArray(), q = ((Bytes) unpackedFromBoss.get(3)).toArray(); return new RSAOAEPPrivateKey( e, p, q, RSAOAEPPrivateKey.DEFAULT_OAEP_HASH, RSAOAEPPrivateKey.DEFAULT_MGF1_HASH, new SecureRandom()); } catch (Throwable e) { return null; } } } | UnikeyFactory { @Nullable static RSAOAEPPrivateKey rsaOaepPKFromUnikey(@NonNull byte[] bytes) { assert bytes != null; try { final ArrayList unpackedFromBoss = Boss.load(bytes); assert ((Integer) unpackedFromBoss.get(0)) == 0; final byte[] e = ((Bytes) unpackedFromBoss.get(1)).toArray(), p = ((Bytes) unpackedFromBoss.get(2)).toArray(), q = ((Bytes) unpackedFromBoss.get(3)).toArray(); return new RSAOAEPPrivateKey( e, p, q, RSAOAEPPrivateKey.DEFAULT_OAEP_HASH, RSAOAEPPrivateKey.DEFAULT_MGF1_HASH, new SecureRandom()); } catch (Throwable e) { return null; } } } | UnikeyFactory { @Nullable static RSAOAEPPrivateKey rsaOaepPKFromUnikey(@NonNull byte[] bytes) { assert bytes != null; try { final ArrayList unpackedFromBoss = Boss.load(bytes); assert ((Integer) unpackedFromBoss.get(0)) == 0; final byte[] e = ((Bytes) unpackedFromBoss.get(1)).toArray(), p = ((Bytes) unpackedFromBoss.get(2)).toArray(), q = ((Bytes) unpackedFromBoss.get(3)).toArray(); return new RSAOAEPPrivateKey( e, p, q, RSAOAEPPrivateKey.DEFAULT_OAEP_HASH, RSAOAEPPrivateKey.DEFAULT_MGF1_HASH, new SecureRandom()); } catch (Throwable e) { return null; } } @Nullable static PrivateKey fromUnikey(@NonNull byte[] bytes); @NonNull static byte[] toUnikey(@NonNull PrivateKey privateKey); } | UnikeyFactory { @Nullable static RSAOAEPPrivateKey rsaOaepPKFromUnikey(@NonNull byte[] bytes) { assert bytes != null; try { final ArrayList unpackedFromBoss = Boss.load(bytes); assert ((Integer) unpackedFromBoss.get(0)) == 0; final byte[] e = ((Bytes) unpackedFromBoss.get(1)).toArray(), p = ((Bytes) unpackedFromBoss.get(2)).toArray(), q = ((Bytes) unpackedFromBoss.get(3)).toArray(); return new RSAOAEPPrivateKey( e, p, q, RSAOAEPPrivateKey.DEFAULT_OAEP_HASH, RSAOAEPPrivateKey.DEFAULT_MGF1_HASH, new SecureRandom()); } catch (Throwable e) { return null; } } @Nullable static PrivateKey fromUnikey(@NonNull byte[] bytes); @NonNull static byte[] toUnikey(@NonNull PrivateKey privateKey); } |
@Test public void extractPublicKey() throws Exception { byte[] data = "Hello world".getBytes(); PrivateKey k = TestKeys.privateKey(3); byte [] signature = ExtendedSignature.sign(k, data); PublicKey pubKey = k.getPublicKey(); ExtendedSignature es = ExtendedSignature.verify(pubKey, signature, data); assertNotNull(es); assertAlmostSame(es.getCreatedAt(), ZonedDateTime.now()); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.keyId(pubKey)); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.extractKeyId(signature)); assertNotNull(es.getPublicKey()); assertEquals(pubKey, es.getPublicKey()); } | public static PublicKey extractPublicKey(byte[] signature) { Binder src = Boss.unpack(signature); PublicKey publicKey = null; byte[] exts = src.getBinaryOrThrow("exts"); Binder b = Boss.unpack(exts); try { byte[] publicKeyBytes = b.getBinaryOrThrow("pub_key"); publicKey = new PublicKey(publicKeyBytes); } catch (EncryptionError e) { publicKey = null; } catch (IllegalArgumentException e) { publicKey = null; } return publicKey; } | ExtendedSignature { public static PublicKey extractPublicKey(byte[] signature) { Binder src = Boss.unpack(signature); PublicKey publicKey = null; byte[] exts = src.getBinaryOrThrow("exts"); Binder b = Boss.unpack(exts); try { byte[] publicKeyBytes = b.getBinaryOrThrow("pub_key"); publicKey = new PublicKey(publicKeyBytes); } catch (EncryptionError e) { publicKey = null; } catch (IllegalArgumentException e) { publicKey = null; } return publicKey; } } | ExtendedSignature { public static PublicKey extractPublicKey(byte[] signature) { Binder src = Boss.unpack(signature); PublicKey publicKey = null; byte[] exts = src.getBinaryOrThrow("exts"); Binder b = Boss.unpack(exts); try { byte[] publicKeyBytes = b.getBinaryOrThrow("pub_key"); publicKey = new PublicKey(publicKeyBytes); } catch (EncryptionError e) { publicKey = null; } catch (IllegalArgumentException e) { publicKey = null; } return publicKey; } } | ExtendedSignature { public static PublicKey extractPublicKey(byte[] signature) { Binder src = Boss.unpack(signature); PublicKey publicKey = null; byte[] exts = src.getBinaryOrThrow("exts"); Binder b = Boss.unpack(exts); try { byte[] publicKeyBytes = b.getBinaryOrThrow("pub_key"); publicKey = new PublicKey(publicKeyBytes); } catch (EncryptionError e) { publicKey = null; } catch (IllegalArgumentException e) { publicKey = null; } return publicKey; } Bytes getKeyId(); ZonedDateTime getCreatedAt(); PublicKey getPublicKey(); static byte[] sign(PrivateKey key, byte[] data); static byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey); static byte[] createTargetSignature(PublicKey publicKey, byte[] data, boolean savePublicKey); @Deprecated static byte[] of(byte[] targetSignature, byte[] sign, byte[] sign2); static byte[] ofSha512AndSha3_384(byte[] targetSignature, byte[] sign512, byte[] sign3_384); static Bytes keyId(AbstractKey key); static Bytes extractKeyId(byte[] signature); static PublicKey extractPublicKey(byte[] signature); byte[] getSignature(); static ExtendedSignature verify(PublicKey key, byte[] signature, byte[] data); } | ExtendedSignature { public static PublicKey extractPublicKey(byte[] signature) { Binder src = Boss.unpack(signature); PublicKey publicKey = null; byte[] exts = src.getBinaryOrThrow("exts"); Binder b = Boss.unpack(exts); try { byte[] publicKeyBytes = b.getBinaryOrThrow("pub_key"); publicKey = new PublicKey(publicKeyBytes); } catch (EncryptionError e) { publicKey = null; } catch (IllegalArgumentException e) { publicKey = null; } return publicKey; } Bytes getKeyId(); ZonedDateTime getCreatedAt(); PublicKey getPublicKey(); static byte[] sign(PrivateKey key, byte[] data); static byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey); static byte[] createTargetSignature(PublicKey publicKey, byte[] data, boolean savePublicKey); @Deprecated static byte[] of(byte[] targetSignature, byte[] sign, byte[] sign2); static byte[] ofSha512AndSha3_384(byte[] targetSignature, byte[] sign512, byte[] sign3_384); static Bytes keyId(AbstractKey key); static Bytes extractKeyId(byte[] signature); static PublicKey extractPublicKey(byte[] signature); byte[] getSignature(); static ExtendedSignature verify(PublicKey key, byte[] signature, byte[] data); } |
@Test public void fromYamlFile() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); assertProperSimpleRootContract(c); } | public static Contract fromDslFile(String fileName) throws IOException { Yaml yaml = new Yaml(); try (FileReader r = new FileReader(fileName)) { Binder binder = Binder.from(DefaultBiMapper.deserialize((Map) yaml.load(r))); return new Contract().initializeWithDsl(binder); } } | Contract implements Approvable, BiSerializable, Cloneable { public static Contract fromDslFile(String fileName) throws IOException { Yaml yaml = new Yaml(); try (FileReader r = new FileReader(fileName)) { Binder binder = Binder.from(DefaultBiMapper.deserialize((Map) yaml.load(r))); return new Contract().initializeWithDsl(binder); } } } | Contract implements Approvable, BiSerializable, Cloneable { public static Contract fromDslFile(String fileName) throws IOException { Yaml yaml = new Yaml(); try (FileReader r = new FileReader(fileName)) { Binder binder = Binder.from(DefaultBiMapper.deserialize((Map) yaml.load(r))); return new Contract().initializeWithDsl(binder); } } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); } | Contract implements Approvable, BiSerializable, Cloneable { public static Contract fromDslFile(String fileName) throws IOException { Yaml yaml = new Yaml(); try (FileReader r = new FileReader(fileName)) { Binder binder = Binder.from(DefaultBiMapper.deserialize((Map) yaml.load(r))); return new Contract().initializeWithDsl(binder); } } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); } | Contract implements Approvable, BiSerializable, Cloneable { public static Contract fromDslFile(String fileName) throws IOException { Yaml yaml = new Yaml(); try (FileReader r = new FileReader(fileName)) { Binder binder = Binder.from(DefaultBiMapper.deserialize((Map) yaml.load(r))); return new Contract().initializeWithDsl(binder); } } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); static String JSAPI_SCRIPT_FIELD; } |
@Test public void calculateProcessingCostSimpleBreak() throws Exception { Contract contract = createCoin100apiv3(); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(contract, true); int costShouldBe = 28; boolean exceptionThrown = false; try { processContractAsItWillBeOnTheNode(contract, 10); } catch (Quantiser.QuantiserException e) { System.out.println("Thrown correct exception: " + e.toString()); exceptionThrown = true; } assertEquals(true, exceptionThrown); } | public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } | Contract implements Approvable, BiSerializable, Cloneable { public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } } | Contract implements Approvable, BiSerializable, Cloneable { public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); } | Contract implements Approvable, BiSerializable, Cloneable { public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); } | Contract implements Approvable, BiSerializable, Cloneable { public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); static String JSAPI_SCRIPT_FIELD; } |
@Test public void calculateProcessingCostSimpleBreakWhileUnpacking() throws Exception { Contract contract = createCoin100apiv3(); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(contract, true); int costShouldBe = 28; boolean exceptionThrown = false; try { processContractAsItWillBeOnTheNode(contract, 1); } catch (Quantiser.QuantiserException e) { System.out.println("Thrown correct exception: " + e.getMessage()); exceptionThrown = true; } catch (BiSerializationException e) { System.out.println("Thrown correct exception: " + e.getMessage()); exceptionThrown = true; } assertEquals(true, exceptionThrown); } | public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } | Contract implements Approvable, BiSerializable, Cloneable { public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } } | Contract implements Approvable, BiSerializable, Cloneable { public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); } | Contract implements Approvable, BiSerializable, Cloneable { public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); } | Contract implements Approvable, BiSerializable, Cloneable { public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); static String JSAPI_SCRIPT_FIELD; } |
@Test public void calculateSplit7To2ProcessingCost_key2048() throws Exception { Contract processingContract = calculateSplit7To2ProcessingCost(PRIVATE_KEY2048_PATH, true); int costShouldBeForSplit = 188; assertEquals(costShouldBeForSplit, processingContract.getProcessedCost()); } | public int getProcessedCost() { return getQuantiser().getQuantaSum(); } | Contract implements Approvable, BiSerializable, Cloneable { public int getProcessedCost() { return getQuantiser().getQuantaSum(); } } | Contract implements Approvable, BiSerializable, Cloneable { public int getProcessedCost() { return getQuantiser().getQuantaSum(); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); } | Contract implements Approvable, BiSerializable, Cloneable { public int getProcessedCost() { return getQuantiser().getQuantaSum(); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); } | Contract implements Approvable, BiSerializable, Cloneable { public int getProcessedCost() { return getQuantiser().getQuantaSum(); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); static String JSAPI_SCRIPT_FIELD; } |
@Test public void calculateSplit7To2ProcessingCost_key4096() throws Exception { Contract processingContract = calculateSplit7To2ProcessingCost(PRIVATE_KEY_PATH, false); int costShouldBeForSplit = 209; assertEquals(costShouldBeForSplit, processingContract.getProcessedCost()); } | public int getProcessedCost() { return getQuantiser().getQuantaSum(); } | Contract implements Approvable, BiSerializable, Cloneable { public int getProcessedCost() { return getQuantiser().getQuantaSum(); } } | Contract implements Approvable, BiSerializable, Cloneable { public int getProcessedCost() { return getQuantiser().getQuantaSum(); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); } | Contract implements Approvable, BiSerializable, Cloneable { public int getProcessedCost() { return getQuantiser().getQuantaSum(); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); } | Contract implements Approvable, BiSerializable, Cloneable { public int getProcessedCost() { return getQuantiser().getQuantaSum(); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack pack); Contract(); Contract(PrivateKey key); void setVotedByKeys(Set<PublicKey> votedByKeys); void prepareForReferenceMatching(); Quantiser getQuantiser(); static int getTestQuantaLimit(); static void setTestQuantaLimit(int testQuantaLimit); List<ErrorRecord> getErrors(); static Contract fromDslFile(String fileName); static Contract fromDslString(String dslString); static Contract fromDslStream(InputStream dslStream); State getState(); Transactional getTransactional(); int getApiLevel(); void setApiLevel(int apiLevel); @Override HashMap<String, Reference> getReferences(); @Override Set<Approvable> getReferencedItems(); void removeReferencedItem(Contract removed); void removeAllReferencedItems(); @Override Set<Approvable> getRevokingItems(); @Override Set<Approvable> getNewItems(); List<Contract> getAllContractInTree(); boolean isUnlimitKeyContract(Config config); void verifySealedKeys(boolean isQuantise); @Override boolean check(String prefix); void setReferenceContextKeys(Set<PublicKey> effectiveKeys); Set<String> checkReferencedItems(Set<String> roleRefsToResolve); @Override boolean paymentCheck(Set<KeyAddress> issuerKeys); int getProcessedCost(); int getProcessedCostU(); @Deprecated int getProcessedCostTU(); String getRevisionId(); @Override void addError(Errors code, String field, String text); @Override void addError(ErrorRecord er); void addRevokingItems(Contract... toRevoke); @NonNull @Deprecated Role createRole(String roleName, Object roleObject); @NonNull Role addRole(String roleName, Object roleObject); Role createRole(String roleName, Object roleObject,boolean addToContract); Role getRole(String roleName); @Deprecated List<String> getRoleAddresses(String roleName); HashId getId(boolean sealAsNeed); @Override HashId getId(); Role getIssuer(); @Override ZonedDateTime getCreatedAt(); @Override ZonedDateTime getExpiresAt(); Map<String, Role> getRoles(); Map<String, Role> getPredefinedRoles(); Map<String, Role> getCustomRoles(); Definition getDefinition(); @Deprecated KeyRecord testGetOwner(); @Deprecated Role registerRole(Role role); Role addRole(Role role); void anonymizeRole(String roleName); boolean isPermitted(String permissionName, KeyRecord keyRecord); void addPermission(Permission perm); boolean isPermitted(String permissionName, PublicKey key); boolean isPermitted(String permissionName, Collection<PublicKey> keys); ChronoZonedDateTime<?> getEarliestCreationTime(); Set<PublicKey> getSealedByKeys(); Set<PrivateKey> getKeysToSignWith(); void setKeysToSignWith(Set<PrivateKey> keysToSignWith); void addSignerKeyFromFile(String fileName); void addSignerKey(PrivateKey privateKey); void addSignerKeys(Collection<PrivateKey> keys); void addReference(Reference reference); void removeReference(Reference reference); boolean isOk(); byte[] sealAsV2(); byte[] seal(); void addSignatureToSeal(PrivateKey privateKey); void addSignatureToSeal(Set<PrivateKey> privateKeys); void addSignatureToSeal(byte[] signature, PublicKey publicKey); byte[] getContractBytes(); void removeAllSignatures(); boolean findSignatureInSeal(PublicKey publicKey); byte[] extractTheContract(); byte[] getLastSealedBinary(); Contract createRevision(); synchronized Contract createRevision(Transactional transactional); int getRevision(); HashId getParent(); HashId getRawOrigin(); HashId getOrigin(); Contract createRevision(PrivateKey... keys); Contract createRevision(Transactional transactional, PrivateKey... keys); synchronized Contract createRevision(Collection<PrivateKey> keys); synchronized Contract createRevision(Collection<PrivateKey> keys, Transactional transactional); synchronized Contract createRevisionAnonymously(Collection<?> keys); synchronized Contract createRevisionAnonymously(Collection<?> keys, Transactional transactional); synchronized Contract createRevisionWithAddress(Collection<?> keys); synchronized Contract createRevisionWithAddress(Collection<?> keys, Transactional transactional); Role setCreator(Collection<KeyRecord> records); @Deprecated Role setCreator(Role role); @NonNull Role setCreatorKeys(Object... keys); @NonNull Role setCreatorKeys(Collection<?> keys); Role getOwner(); @NonNull Role setOwnerKey(Object keyOrRecord); @NonNull Role setOwnerKeys(Collection<?> keys); Role setRoleKeys(String roleName, Object... keys); Role setRoleKeys(String roleName, Collection<?> keys); @NonNull Role setOwnerKeys(Object... keys); Role getCreator(); Multimap<String, Permission> getPermissions(); Binder getStateData(); Role setIssuerKeys(Collection<?> keys); Role setIssuerKeys(Object... keys); void setExpiresAt(ZonedDateTime dateTime); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); Contract[] split(int count); Contract splitValue(String fieldName, Decimal valueToExtract); Set<Contract> getSiblings(); void addNewItems(Contract... newContracts); T get(String name); void set(String name, Binder value); static Contract fromSealedFile(String contractFileName); ZonedDateTime getIssuedAt(); byte[] getLastSealedBinary(boolean sealAsNeed); byte[] getPackedTransaction(); Binder getTransactionalData(); static Contract fromPackedTransaction(@NonNull byte[] packedItem); void setTransactionPack(TransactionPack transactionPack); synchronized TransactionPack getTransactionPack(); Contract createRevocation(PrivateKey... keys); List<Contract> getRevoking(); List<? extends Contract> getNew(); List<? extends Contract> getReferenced(); boolean canBeRevoked(Set<PublicKey> keys); Transactional createTransactionalSection(); void checkApplicablePermissionQuantized(Permission permission); Reference findReferenceByName(String name); Reference findReferenceByName(String name, String section); Set<String> getValidRoleReferences(); Set<PublicKey> getEffectiveKeys(); Set<PublicKey> getReferenceContextKeys(); Contract getContract(); void traceErrors(); String getErrorsString(); synchronized Contract copy(); @Override boolean isU(Set<KeyAddress> issuerKeys, String issuerName); @Override boolean shouldBeU(); void setShouldBeU(boolean shouldBeU); void setLimitedForTestnet(boolean limitedForTestnet); boolean isLimitedForTestnet(); boolean isSuitableForTestnet(); @Override boolean isInWhiteList(List<PublicKey> whiteList); static ZonedDateTime decodeDslTime(Object t); Object execJS(JSApiExecOptions execOptions, byte[] jsFileContent, String... params); Object execJS(byte[] jsFileContent, String... params); Object execJSByScriptHash(JSApiExecOptions execOptions, HashId scriptHash, String... params); Object execJSByScriptHash(HashId scriptHash, String... params); Object execJSByName(JSApiExecOptions execOptions, String jsFileName, String... params); Object execJSByName(String jsFileName, String... params); List<String> extractJSNames(); static Contract fromSealedBinary(byte[] sealedBinary); static Contract fromSealedBinary(byte[] sealedBinary, TransactionPack tp); void attachToNetwork(Client client); static String JSAPI_SCRIPT_FIELD; } |
@Ignore @Test public void checkMemoryLeaks() throws Exception { List<String> dbUrls = new ArrayList<>(); dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: List<Ledger> ledgers = new ArrayList<>(); for (int it = 0; it < 100; it++) { if (it % 10 == 0) System.out.println("Iteration " + it); dbUrls.stream().forEach(url -> { try { clearLedger(url); PostgresLedger ledger = new PostgresLedger(url); ledgers.add(ledger); } catch (Exception e) { e.printStackTrace(); } }); TestSpace ts = prepareTestSpace(); ts.node.config.getAddressesWhiteList().add(new KeyAddress(TestKeys.publicKey(3), 0, true)); Contract testContract = new Contract(ts.myKey); testContract.seal(); assertTrue(testContract.isOk()); Parcel parcel = createParcelWithFreshU(ts.client, testContract, Do.listOf(ts.myKey)); ts.client.registerParcelWithState(parcel.pack(), 18000); Contract testContract2 = new Contract(ts.myKey); testContract2.seal(); assertTrue(testContract2.isOk()); ts.client.register(testContract2.getPackedTransaction(), 18000); ts.nodes.forEach(x -> x.shutdown()); ts.myKey = null; ts.nodes.clear(); ts.node = null; ts.nodes = null; ts.client = null; ts = null; ledgers.stream().forEach(ledger -> ledger.close()); ledgers.clear(); System.gc(); Thread.sleep(2000); } } | public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; } |
@Test public void startNode() throws Exception { String path = new File("src/test_node_config_v2/node1").getAbsolutePath(); System.out.println(path); String[] args = new String[]{"--test", "--config", path, "--nolog"}; Main main = new Main(args); main.waitReady(); BufferedLogger l = main.logger; Client client = new Client( "http: TestKeys.privateKey(3), main.getNodePublicKey(), null ); Binder data = client.command("status"); data.getStringOrThrow("status"); BasicHttpClient.Answer a = client.request("ping"); assertEquals("200: {ping=pong}", a.toString()); Contract c = new Contract(); c.setIssuerKeys(TestKeys.publicKey(3)); c.addSignerKey(TestKeys.privateKey(3)); c.registerRole(new RoleLink("owner", "issuer")); c.registerRole(new RoleLink("creator", "issuer")); c.setExpiresAt(ZonedDateTime.now().plusDays(2)); byte[] sealed = c.seal(); Contract c1 = new Contract(sealed); assertArrayEquals(c.getLastSealedBinary(), c1.getLastSealedBinary()); main.cache.put(c, null); assertNotNull(main.cache.get(c.getId())); URL url = new URL("http: HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); assertEquals(200, con.getResponseCode()); byte[] data2 = Do.read(con.getInputStream()); assertArrayEquals(c.getPackedTransaction(), data2); url = new URL("http: con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); assertEquals(200, con.getResponseCode()); Binder bres = Boss.unpack((Do.read(con.getInputStream()))) .getBinderOrThrow("response"); List<Binder> ni = bres.getBinders("nodes"); String pubUrls = ni.stream().map(x -> x.getStringOrThrow("url")) .collect(Collectors.toList()) .toString(); assertEquals("[http: main.shutdown(); main.logger.stopInterceptingStdOut(); main.logger.getCopy().forEach(x -> System.out.println(x)); } | private void startNode() throws SQLException, IOException { config.setConsensusConfigUpdater((config, n) -> { int negative; int positive; if(n < 3) { negative = 1; positive = n; } else if(n < 10) { negative = 2; positive = n-1; } else { positive = (int) Math.ceil(n * 0.9); negative = n + 1 - positive; } int resyncBreak = (int) Math.ceil(n * 0.2); if (resyncBreak < 1) resyncBreak = 1; if( resyncBreak+positive == n) resyncBreak += 1; log(myInfo.getNumber() + ": Network consensus is set to (negative/positive/resyncBreak): " + negative + " / " + positive + " / " + resyncBreak); config.setPositiveConsensus(positive); config.setNegativeConsensus(negative); config.setResyncBreakConsensus(resyncBreak); }); network = new NetworkV2(netConfig, myInfo, nodeKey); node = new Node(config, myInfo, ledger, network, nodeKey,new File(configRoot+"/config/contracts")); cache = node.getCache(); parcelCache = node.getParcelCache(); paidOperationCache = node.getPaidOperationCache(); envCache = node.getEnvCache(); StateRecord r = ledger.getRecord(HashId.withDigest("bS/c4YMidaVuzTBhHLkGPFAvPbZQHybzQnXAoBwaZYM8eLYb7mAkVYEpuqKRXYc7anqX47BeNdvFN1n7KluH9A==")); if( r != null ) r.destroy(); clientHTTPServer.setConfig(config); clientHTTPServer.setNode(node); clientHTTPServer.setCache(cache); clientHTTPServer.setParcelCache(parcelCache); clientHTTPServer.setPaidOperationCache(paidOperationCache); clientHTTPServer.setEnvCache(envCache); clientHTTPServer.setLocalCors(myInfo.getPublicHost().equals("localhost")); } | Main { private void startNode() throws SQLException, IOException { config.setConsensusConfigUpdater((config, n) -> { int negative; int positive; if(n < 3) { negative = 1; positive = n; } else if(n < 10) { negative = 2; positive = n-1; } else { positive = (int) Math.ceil(n * 0.9); negative = n + 1 - positive; } int resyncBreak = (int) Math.ceil(n * 0.2); if (resyncBreak < 1) resyncBreak = 1; if( resyncBreak+positive == n) resyncBreak += 1; log(myInfo.getNumber() + ": Network consensus is set to (negative/positive/resyncBreak): " + negative + " / " + positive + " / " + resyncBreak); config.setPositiveConsensus(positive); config.setNegativeConsensus(negative); config.setResyncBreakConsensus(resyncBreak); }); network = new NetworkV2(netConfig, myInfo, nodeKey); node = new Node(config, myInfo, ledger, network, nodeKey,new File(configRoot+"/config/contracts")); cache = node.getCache(); parcelCache = node.getParcelCache(); paidOperationCache = node.getPaidOperationCache(); envCache = node.getEnvCache(); StateRecord r = ledger.getRecord(HashId.withDigest("bS/c4YMidaVuzTBhHLkGPFAvPbZQHybzQnXAoBwaZYM8eLYb7mAkVYEpuqKRXYc7anqX47BeNdvFN1n7KluH9A==")); if( r != null ) r.destroy(); clientHTTPServer.setConfig(config); clientHTTPServer.setNode(node); clientHTTPServer.setCache(cache); clientHTTPServer.setParcelCache(parcelCache); clientHTTPServer.setPaidOperationCache(paidOperationCache); clientHTTPServer.setEnvCache(envCache); clientHTTPServer.setLocalCors(myInfo.getPublicHost().equals("localhost")); } } | Main { private void startNode() throws SQLException, IOException { config.setConsensusConfigUpdater((config, n) -> { int negative; int positive; if(n < 3) { negative = 1; positive = n; } else if(n < 10) { negative = 2; positive = n-1; } else { positive = (int) Math.ceil(n * 0.9); negative = n + 1 - positive; } int resyncBreak = (int) Math.ceil(n * 0.2); if (resyncBreak < 1) resyncBreak = 1; if( resyncBreak+positive == n) resyncBreak += 1; log(myInfo.getNumber() + ": Network consensus is set to (negative/positive/resyncBreak): " + negative + " / " + positive + " / " + resyncBreak); config.setPositiveConsensus(positive); config.setNegativeConsensus(negative); config.setResyncBreakConsensus(resyncBreak); }); network = new NetworkV2(netConfig, myInfo, nodeKey); node = new Node(config, myInfo, ledger, network, nodeKey,new File(configRoot+"/config/contracts")); cache = node.getCache(); parcelCache = node.getParcelCache(); paidOperationCache = node.getPaidOperationCache(); envCache = node.getEnvCache(); StateRecord r = ledger.getRecord(HashId.withDigest("bS/c4YMidaVuzTBhHLkGPFAvPbZQHybzQnXAoBwaZYM8eLYb7mAkVYEpuqKRXYc7anqX47BeNdvFN1n7KluH9A==")); if( r != null ) r.destroy(); clientHTTPServer.setConfig(config); clientHTTPServer.setNode(node); clientHTTPServer.setCache(cache); clientHTTPServer.setParcelCache(parcelCache); clientHTTPServer.setPaidOperationCache(paidOperationCache); clientHTTPServer.setEnvCache(envCache); clientHTTPServer.setLocalCors(myInfo.getPublicHost().equals("localhost")); } Main(String[] args); } | Main { private void startNode() throws SQLException, IOException { config.setConsensusConfigUpdater((config, n) -> { int negative; int positive; if(n < 3) { negative = 1; positive = n; } else if(n < 10) { negative = 2; positive = n-1; } else { positive = (int) Math.ceil(n * 0.9); negative = n + 1 - positive; } int resyncBreak = (int) Math.ceil(n * 0.2); if (resyncBreak < 1) resyncBreak = 1; if( resyncBreak+positive == n) resyncBreak += 1; log(myInfo.getNumber() + ": Network consensus is set to (negative/positive/resyncBreak): " + negative + " / " + positive + " / " + resyncBreak); config.setPositiveConsensus(positive); config.setNegativeConsensus(negative); config.setResyncBreakConsensus(resyncBreak); }); network = new NetworkV2(netConfig, myInfo, nodeKey); node = new Node(config, myInfo, ledger, network, nodeKey,new File(configRoot+"/config/contracts")); cache = node.getCache(); parcelCache = node.getParcelCache(); paidOperationCache = node.getPaidOperationCache(); envCache = node.getEnvCache(); StateRecord r = ledger.getRecord(HashId.withDigest("bS/c4YMidaVuzTBhHLkGPFAvPbZQHybzQnXAoBwaZYM8eLYb7mAkVYEpuqKRXYc7anqX47BeNdvFN1n7KluH9A==")); if( r != null ) r.destroy(); clientHTTPServer.setConfig(config); clientHTTPServer.setNode(node); clientHTTPServer.setCache(cache); clientHTTPServer.setParcelCache(parcelCache); clientHTTPServer.setPaidOperationCache(paidOperationCache); clientHTTPServer.setEnvCache(envCache); clientHTTPServer.setLocalCors(myInfo.getPublicHost().equals("localhost")); } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); } | Main { private void startNode() throws SQLException, IOException { config.setConsensusConfigUpdater((config, n) -> { int negative; int positive; if(n < 3) { negative = 1; positive = n; } else if(n < 10) { negative = 2; positive = n-1; } else { positive = (int) Math.ceil(n * 0.9); negative = n + 1 - positive; } int resyncBreak = (int) Math.ceil(n * 0.2); if (resyncBreak < 1) resyncBreak = 1; if( resyncBreak+positive == n) resyncBreak += 1; log(myInfo.getNumber() + ": Network consensus is set to (negative/positive/resyncBreak): " + negative + " / " + positive + " / " + resyncBreak); config.setPositiveConsensus(positive); config.setNegativeConsensus(negative); config.setResyncBreakConsensus(resyncBreak); }); network = new NetworkV2(netConfig, myInfo, nodeKey); node = new Node(config, myInfo, ledger, network, nodeKey,new File(configRoot+"/config/contracts")); cache = node.getCache(); parcelCache = node.getParcelCache(); paidOperationCache = node.getPaidOperationCache(); envCache = node.getEnvCache(); StateRecord r = ledger.getRecord(HashId.withDigest("bS/c4YMidaVuzTBhHLkGPFAvPbZQHybzQnXAoBwaZYM8eLYb7mAkVYEpuqKRXYc7anqX47BeNdvFN1n7KluH9A==")); if( r != null ) r.destroy(); clientHTTPServer.setConfig(config); clientHTTPServer.setNode(node); clientHTTPServer.setCache(cache); clientHTTPServer.setParcelCache(parcelCache); clientHTTPServer.setPaidOperationCache(paidOperationCache); clientHTTPServer.setEnvCache(envCache); clientHTTPServer.setLocalCors(myInfo.getPublicHost().equals("localhost")); } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; } |
@Test public void networkReconfigurationTestSerial() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) { mm.add(createMain("node" + (i + 1), "_dynamic_test", false)); } for (Main m : mm) { m.shutdown(); } mm.clear(); List<String> dbUrls = new ArrayList<>(); Thread.sleep(1000); dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: for (int i = 0; i < 4; i++) { mm.add(createMainFromDb(dbUrls.get(i), false)); } PrivateKey myKey = TestKeys.privateKey(3); Main main = mm.get(3); PrivateKey universaKey = new PrivateKey(Do.read("./src/test_contracts/keys/u_key.private.unikey")); Contract contract = new Contract(universaKey); contract.seal(); assertTrue(contract.isOk()); int attempts = 3; Client client = new Client(universaKey, main.myInfo, null); ItemResult rr = client.register(contract.getPackedTransaction(), 5000); while (attempts-- > 0) { rr = client.getState(contract.getId()); System.out.println(rr); Thread.currentThread().sleep(1000); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.PENDING_POSITIVE); contract = new Contract(universaKey); contract.seal(); assertTrue(contract.isOk()); Client clientKnown = new Client(universaKey, mm.get(0).myInfo, null); clientKnown.register(contract.getPackedTransaction(), 15000); while (true) { rr = clientKnown.getState(contract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); for (int i = 0; i < 3; i++) { mm.get(i).node.addNode(main.myInfo); } contract = new Contract(universaKey); contract.seal(); assertTrue(contract.isOk()); client.register(contract.getPackedTransaction(), 15000); while (true) { rr = client.getState(contract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); for (int i = 0; i < 3; i++) { mm.get(i).node.removeNode(main.myInfo); } contract = new Contract(universaKey); contract.seal(); assertTrue(contract.isOk()); attempts = 3; rr = client.register(contract.getPackedTransaction(), 15000); while (attempts-- > 0) { rr = client.getState(contract.getId()); Thread.currentThread().sleep(1000); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.PENDING_POSITIVE); contract = new Contract(universaKey); contract.seal(); assertTrue(contract.isOk()); clientKnown.register(contract.getPackedTransaction(), 15000); while (true) { rr = clientKnown.getState(contract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); for (Main m : mm) { m.shutdown(); } } | public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; } |
@Ignore @Test public void networkReconfigurationTestParallel() throws Exception { if(1 > 0) return; List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) { mm.add(createMain("node" + (i + 1), "_dynamic_test", false)); } for (Main m : mm) { m.shutdown(); } mm.clear(); List<String> dbUrls = new ArrayList<>(); dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: Random rand = new Random(); rand.setSeed(new Date().getTime()); final ArrayList<Integer> clientSleeps = new ArrayList<>(); final ArrayList<Integer> nodeSleeps = new ArrayList<>(); for (int i = 0; i < 4; i++) { mm.add(createMainFromDb(dbUrls.get(i), false)); nodeSleeps.add(rand.nextInt(100)); } PrivateKey myKey = TestKeys.privateKey(3); final ArrayList<Client> clients = new ArrayList<>(); final ArrayList<Integer> clientNodes = new ArrayList<>(); final ArrayList<Contract> contracts = new ArrayList<>(); final ArrayList<Parcel> parcels = new ArrayList<>(); final ArrayList<Boolean> contractsApproved = new ArrayList<>(); for (int i = 0; i < 40; i++) { Contract contract = new Contract(myKey); contract.seal(); assertTrue(contract.isOk()); contracts.add(contract); contractsApproved.add(false); NodeInfo info = mm.get(rand.nextInt(3)).myInfo; clientNodes.add(info.getNumber()); Client client = new Client(TestKeys.privateKey(i), info, null); clients.add(client); clientSleeps.add(rand.nextInt(100)); Parcel parcel = createParcelWithFreshU(client, contract, Do.listOf(myKey)); parcels.add(parcel); } Semaphore semaphore = new Semaphore(-39); final AtomicInteger atomicInteger = new AtomicInteger(40); for (int i = 0; i < 40; i++) { int finalI = i; Thread th = new Thread(() -> { try { Thread.sleep(clientSleeps.get(finalI)); Contract contract = contracts.get(finalI); Client client = clients.get(finalI); System.out.println("Register item " + contract.getId().toBase64String() + " @ node #" + clientNodes.get(finalI)); client.registerParcelWithState(parcels.get(finalI).pack(), 15000); ItemResult rr; while (true) { rr = client.getState(contract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); semaphore.release(); atomicInteger.decrementAndGet(); contractsApproved.set(finalI, true); } catch (ClientError clientError) { clientError.printStackTrace(); fail(clientError.getMessage()); } catch (InterruptedException e) { e.printStackTrace(); fail(e.getMessage()); } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } }); th.start(); } for (int i = 0; i < 3; i++) { int finalI = i; Thread th = new Thread(() -> { try { Thread.sleep(nodeSleeps.get(finalI)); } catch (InterruptedException e) { e.printStackTrace(); fail(e.getMessage()); } System.out.println("Adding new node @ node #" + (finalI + 1)); mm.get(finalI).node.addNode(mm.get(3).myInfo); System.out.println("Done new node @ node #" + (finalI + 1)); }); th.start(); } Thread.sleep(5000); if (!semaphore.tryAcquire(15, TimeUnit.SECONDS)) { for (int i = 0; i < contractsApproved.size(); i++) { if (!contractsApproved.get(i)) { System.out.println("Stuck item:" + contracts.get(i).getId().toBase64String()); } } System.out.print("Client sleeps: "); for (Integer s : clientSleeps) { System.out.print(s + ", "); } System.out.println(); System.out.print("Node sleeps: "); for (Integer s : nodeSleeps) { System.out.print(s + ", "); } System.out.println(); fail("Items stuck: " + atomicInteger.get()); } for (Main m : mm) { m.shutdown(); } System.gc(); } | public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; } |
@Test public void testToUnikeyRSAOAEP() throws Exception { final RSAOAEPPrivateKey pk1 = new RSAOAEPPrivateKey( pk1E, pk1P, pk1Q, HashType.SHA1, HashType.SHA1, new SecureRandom()); assertArrayEquals( pk1Bytes, UnikeyFactory.toUnikey(pk1)); } | @NonNull static byte[] toUnikey(@NonNull RSAOAEPPrivateKey privateKey) { assert privateKey != null; return privateKey.pack(); } | UnikeyFactory { @NonNull static byte[] toUnikey(@NonNull RSAOAEPPrivateKey privateKey) { assert privateKey != null; return privateKey.pack(); } } | UnikeyFactory { @NonNull static byte[] toUnikey(@NonNull RSAOAEPPrivateKey privateKey) { assert privateKey != null; return privateKey.pack(); } } | UnikeyFactory { @NonNull static byte[] toUnikey(@NonNull RSAOAEPPrivateKey privateKey) { assert privateKey != null; return privateKey.pack(); } @Nullable static PrivateKey fromUnikey(@NonNull byte[] bytes); @NonNull static byte[] toUnikey(@NonNull PrivateKey privateKey); } | UnikeyFactory { @NonNull static byte[] toUnikey(@NonNull RSAOAEPPrivateKey privateKey) { assert privateKey != null; return privateKey.pack(); } @Nullable static PrivateKey fromUnikey(@NonNull byte[] bytes); @NonNull static byte[] toUnikey(@NonNull PrivateKey privateKey); } |
@Ignore @Test public void reconfigurationContractTest() throws Exception { PrivateKey issuerKey = new PrivateKey(Do.read("./src/test_contracts/keys/reconfig_key.private.unikey")); List<Main> mm = new ArrayList<>(); List<PrivateKey> nodeKeys = new ArrayList<>(); List<PrivateKey> nodeKeysNew = new ArrayList<>(); for (int i = 0; i < 4; i++) { mm.add(createMain("node" + (i + 1), "_dynamic_test", false)); if (i < 3) nodeKeys.add(new PrivateKey(Do.read("./src/test_node_config_v2_dynamic_test/node" + (i + 1) + "/tmp/node2_" + (i + 1) + ".private.unikey"))); nodeKeysNew.add(new PrivateKey(Do.read("./src/test_node_config_v2_dynamic_test/node" + (i + 1) + "/tmp/node2_" + (i + 1) + ".private.unikey"))); } List<NodeInfo> netConfig = mm.get(0).netConfig.toList(); List<NodeInfo> netConfigNew = mm.get(3).netConfig.toList(); for (Main m : mm) { m.shutdown(); } mm.clear(); Contract configContract = createNetConfigContract(netConfig, issuerKey); List<String> dbUrls = new ArrayList<>(); dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: for (int i = 0; i < 4; i++) { mm.add(createMainFromDb(dbUrls.get(i), false)); } Client client = new Client(TestKeys.privateKey(0), mm.get(0).myInfo, null); Parcel parcel = createParcelWithFreshU(client, configContract, Do.listOf(issuerKey)); client.registerParcelWithState(parcel.pack(), 15000); ItemResult rr; while (true) { rr = client.getState(configContract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); configContract = createNetConfigContract(configContract, netConfigNew, nodeKeys); parcel = createParcelWithFreshU(client, configContract, nodeKeys); client.registerParcelWithState(parcel.pack(), 15000); while (true) { rr = client.getState(configContract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); Thread.sleep(1000); for (Main m : mm) { assertEquals(m.config.getPositiveConsensus(), 3); } configContract = createNetConfigContract(configContract, netConfig, nodeKeys); parcel = createParcelWithFreshU(client, configContract, nodeKeys); client.registerParcelWithState(parcel.pack(), 15000); while (true) { rr = client.getState(configContract.getId()); Thread.currentThread().sleep(500); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); Thread.sleep(1000); for (Main m : mm) { assertEquals(m.config.getPositiveConsensus(), 2); } for (Main m : mm) { m.shutdown(); } } | public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; } |
@Test public void checkShutdown() throws Exception { List<Main> mm = new ArrayList<>(); for (int i = 0; i < 3; i++) { mm.add(createMain("node" + (i + 1), false)); } Main main = mm.get(0); PrivateKey myKey = TestKeys.privateKey(3); Client client = null; try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Contract testContract = new Contract(myKey); for (int i = 0; i < 10; i++) { Contract nc = new Contract(myKey); testContract.addNewItems(nc); } testContract.seal(); assertTrue(testContract.isOk()); Parcel parcel = createParcelWithFreshU(client, testContract, Do.listOf(myKey)); client.registerParcelWithState(parcel.pack(), 5000); System.out.println(">> before shutdown state: " + client.getState(parcel.getPayloadContract().getId())); System.out.println(">> before shutdown state: " + client.getState(parcel.getPayloadContract().getNew().get(0).getId())); main.shutdown(); Thread.sleep(8000); mm.remove(main); main = createMain("node1", false); mm.add(main); try { client = new Client(myKey, main.myInfo, null); } catch (Exception e) { System.out.println("prepareClient exception: " + e.toString()); } Thread.currentThread().sleep(8000); ItemResult itemResult = client.getState(parcel.getPayloadContract().getId()); ItemResult itemResult2 = client.getState(parcel.getPayloadContract().getNew().get(0).getId()); System.out.println(">> after shutdown state: " + itemResult + " and new " + itemResult2); while (itemResult.state.isPending()) { Thread.currentThread().sleep(500); itemResult = client.getState(parcel.getPayloadContract().getId()); System.out.println(">> wait result: " + itemResult); } itemResult2 = client.getState(parcel.getPayloadContract().getNew().get(0).getId()); assertEquals(ItemState.APPROVED, itemResult.state); assertEquals(ItemState.APPROVED, itemResult2.state); mm.forEach(x -> x.shutdown()); } | public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; } |
@Test public void registerContractWithAnonymousId() throws Exception { TestSpace ts = prepareTestSpace(); PrivateKey newPrivateKey = new PrivateKey(Do.read("./src/test_contracts/keys/u_key.private.unikey")); byte[] myAnonId = newPrivateKey.createAnonymousId(); Contract contract = new Contract(); contract.setExpiresAt(ZonedDateTime.now().plusDays(90)); Role r = contract.setIssuerKeys(AnonymousId.fromBytes(myAnonId)); contract.registerRole(new RoleLink("owner", "issuer")); contract.registerRole(new RoleLink("creator", "issuer")); contract.addPermission(new ChangeOwnerPermission(r)); contract.addSignerKey(newPrivateKey); contract.seal(); assertTrue(contract.isOk()); System.out.println("contract.check(): " + contract.check()); contract.traceErrors(); ts.client.getSession().setPrivateKey(newPrivateKey); ts.client.restart(); ItemResult itemResult = ts.client.register(contract.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, itemResult.state); ts.nodes.forEach(x -> x.shutdown()); } | public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; } |
@Ignore @Test public void udpDisruptionTest() throws Exception { List<Main> mm = new ArrayList<>(); final int NODE_COUNT = 4; final int PORT_BASE = 12000; final int TEST_MODE = UDPAdapter.PacketTypes.HELLO; for (int i = 0; i < NODE_COUNT; i++) { mm.add(createMain("node" + (i + 1), false)); } class TestRunnable implements Runnable { int finalI; int finalJ; boolean alive = true; @Override public void run() { try { NodeInfo source = mm.get(finalI).myInfo; NodeInfo destination = mm.get(finalJ).myInfo; DatagramSocket socket = new DatagramSocket(PORT_BASE + finalI * NODE_COUNT + finalJ); while (alive) { if (TEST_MODE == UDPAdapter.PacketTypes.HELLO) sendHello(source, destination, mm.get(finalI).network.getUDPAdapter(), socket); else if (TEST_MODE == UDPAdapter.PacketTypes.WELCOME) sendWelcome(source, destination, mm.get(finalI).network.getUDPAdapter(), socket); else sendDataGarbage(source, destination, mm.get(finalI).network.getUDPAdapter(), socket); Thread.sleep(4); } } catch (Exception e) { System.out.println("runnable exception: " + e.toString()); } } } List<Thread> threadsList = new ArrayList<>(); List<TestRunnable> runnableList = new ArrayList<>(); for (int i = 0; i < NODE_COUNT; i++) { for (int j = 0; j < NODE_COUNT; j++) { if (j == i) continue; final int finalI = i; final int finalJ = j; TestRunnable runnableSingle = new TestRunnable(); runnableList.add(runnableSingle); threadsList.add( new Thread(() -> { runnableSingle.finalI = finalI; runnableSingle.finalJ = finalJ; runnableSingle.run(); })); } } for (Thread th : threadsList) { th.start(); } Thread.sleep(5000); PrivateKey myKey = TestKeys.privateKey(0); Client client = new Client(myKey, mm.get(0).myInfo, null); Contract contract = new Contract(myKey); contract.seal(); Parcel parcel = createParcelWithFreshU(client, contract, Do.listOf(myKey)); client.registerParcelWithState(parcel.pack(), 60000); ItemResult rr; while (true) { rr = client.getState(contract.getId()); if (!rr.state.isPending()) break; } assertEquals(rr.state, ItemState.APPROVED); for (TestRunnable tr : runnableList) { tr.alive = false; } for (Thread th : threadsList) { th.interrupt(); } mm.forEach(x -> x.shutdown()); } | public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; } |
@Ignore @Test public void dbSanitationTest() throws Exception { final int NODE_COUNT = 4; PrivateKey myKey = TestKeys.privateKey(NODE_COUNT); List<String> dbUrls = new ArrayList<>(); dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: dbUrls.add("jdbc:postgresql: List<Ledger> ledgers = new ArrayList<>(); dbUrls.stream().forEach(url -> { try { PostgresLedger ledger = new PostgresLedger(url); ledgers.add(ledger); } catch (Exception e) { e.printStackTrace(); } }); Random random = new Random(123); List<Contract> origins = new ArrayList<>(); List<Contract> newRevisions = new ArrayList<>(); List<Contract> newContracts = new ArrayList<>(); final int N = 100; for (int i = 0; i < N; i++) { Contract origin = new Contract(myKey); origin.seal(); origins.add(origin); Contract newRevision = origin.createRevision(myKey); if (i < N / 2) { newRevision.setOwnerKeys(TestKeys.privateKey(NODE_COUNT + 1).getPublicKey()); } else { } Contract newContract = new Contract(myKey); newRevision.addNewItems(newContract); newRevision.seal(); newContracts.add(newContract); newRevisions.add(newRevision); int unfinishedNodesCount = random.nextInt(2) + 1; Set<Integer> unfinishedNodesNumbers = new HashSet<>(); while (unfinishedNodesCount > unfinishedNodesNumbers.size()) { unfinishedNodesNumbers.add(random.nextInt(NODE_COUNT) + 1); } System.out.println("item# " + newRevision.getId().toBase64String().substring(0, 6) + " nodes " + unfinishedNodesNumbers.toString()); int finalI = i; for (int j = 0; j < NODE_COUNT; j++) { boolean finished = !unfinishedNodesNumbers.contains(j + 1); Ledger ledger = ledgers.get(j); StateRecord originRecord = ledger.findOrCreate(origin.getId()); originRecord.setExpiresAt(origin.getExpiresAt()); originRecord.setCreatedAt(origin.getCreatedAt()); StateRecord newRevisionRecord = ledger.findOrCreate(newRevision.getId()); newRevisionRecord.setExpiresAt(newRevision.getExpiresAt()); newRevisionRecord.setCreatedAt(newRevision.getCreatedAt()); StateRecord newContractRecord = ledger.findOrCreate(newContract.getId()); newContractRecord.setExpiresAt(newContract.getExpiresAt()); newContractRecord.setCreatedAt(newContract.getCreatedAt()); if (finished) { if (finalI < N / 2) { originRecord.setState(ItemState.REVOKED); newContractRecord.setState(ItemState.APPROVED); newRevisionRecord.setState(ItemState.APPROVED); } else { originRecord.setState(ItemState.APPROVED); newContractRecord.setState(ItemState.UNDEFINED); newRevisionRecord.setState(ItemState.DECLINED); } } else { originRecord.setState(ItemState.LOCKED); originRecord.setLockedByRecordId(newRevisionRecord.getRecordId()); newContractRecord.setState(ItemState.LOCKED_FOR_CREATION); newContractRecord.setLockedByRecordId(newRevisionRecord.getRecordId()); newRevisionRecord.setState(finalI < N / 2 ? ItemState.PENDING_POSITIVE : ItemState.PENDING_NEGATIVE); } originRecord.save(); ledger.putItem(originRecord, origin, Instant.now().plusSeconds(3600 * 24)); newRevisionRecord.save(); ledger.putItem(newRevisionRecord, newRevision, Instant.now().plusSeconds(3600 * 24)); if (newContractRecord.getState() == ItemState.UNDEFINED) { newContractRecord.destroy(); } else { newContractRecord.save(); } } } ledgers.stream().forEach(ledger -> ledger.close()); ledgers.clear(); List<Main> mm = new ArrayList<>(); List<Client> clients = new ArrayList<>(); for (int i = 0; i < NODE_COUNT; i++) { Main m = createMain("node" + (i + 1), false); m.config.setIsFreeRegistrationsAllowedFromYaml(true); mm.add(m); Client client = new Client(TestKeys.privateKey(i), m.myInfo, null); clients.add(client); } while (true) { try { for (int i = 0; i < NODE_COUNT; i++) { clients.get(i).getState(newRevisions.get(0)); } break; } catch (ClientError e) { Thread.sleep(1000); mm.stream().forEach(m -> System.out.println("node#" + m.myInfo.getNumber() + " is " + (m.node.isSanitating() ? "" : "not ") + "sanitating")); } } Contract contract = new Contract(TestKeys.privateKey(3)); contract.seal(); ItemResult ir = clients.get(0).register(contract.getPackedTransaction(), 10000); ir.errors.toString(); for (int i = 0; i < N; i++) { ItemResult rr = clients.get(i % NODE_COUNT).getState(newRevisions.get(i).getId()); ItemState targetState = i < N / 2 ? ItemState.APPROVED : ItemState.DECLINED; assertEquals(rr.state, targetState); } Thread.sleep(1000); mm.stream().forEach(m -> m.shutdown()); Thread.sleep(1000); dbUrls.stream().forEach(url -> { try { PostgresLedger ledger = new PostgresLedger(url); assertTrue(ledger.findUnfinished().isEmpty()); ledger.close(); } catch (Exception e) { e.printStackTrace(); } }); } | public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); } | Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { e.printStackTrace(); } } Main(String[] args); static void main(String[] args); void waitReady(); void shutdown(); void setVerboseLevel(int level); void setUDPVerboseLevel(int level); void restartUDPAdapter(); PublicKey getNodePublicKey(); static final String NODE_VERSION; final Reporter reporter; final BufferedLogger logger; public NetConfig netConfig; public NetworkV2 network; final Config config; public NodeInfo myInfo; public Node node; public ItemCache cache; public ParcelCache parcelCache; public PaidOperationCache paidOperationCache; } |
Subsets and Splits