public NContractStorage(byte[] packedContract, ZonedDateTime expiresAt) { this.packedContract = packedContract; this.expiresAt = expiresAt; try { this.trackingContract = Contract.fromPackedTransaction(packedContract); } catch (IOException e) { throw new IllegalArgumentException("NContractStorage unable to unpack TP " + e.getMessage()); } }
@Override public void deserialize(Binder data, BiDeserializer deserializer) throws IOException { packedContract = data.getBinary("packedContract"); trackingContract = Contract.fromPackedTransaction(packedContract); expiresAt = data.getZonedDateTimeOrThrow("expiresAt"); }
@Override public Approvable getItem(final StateRecord record) { return protect(() -> { try (ResultSet rs = inPool(db -> db.queryRow("select * from items where id = ?", record.getRecordId()))) { if (rs == null) return null; return Contract.fromPackedTransaction(rs.getBytes("packed")); } catch (Exception e) { e.printStackTrace(); throw e; } }); }
private static void doShowId() throws Exception { String contractFile = (String) options.valueOf("id"); Contract c = Contract.fromPackedTransaction(Files.readAllBytes(Paths.get(contractFile))); reporter.message(c.getId().toBase64String()); finish(); }
private static void doProbeFile() throws IOException { String contractFile = (String) options.valueOf("probe-file"); Contract c = Contract.fromPackedTransaction(Files.readAllBytes(Paths.get(contractFile))); if(c != null) { getClientNetwork().check(c.getId()); } finish(); }
private static void doSign() throws IOException { String source = (String) options.valueOf("sign"); List<String> names = (List) options.valuesOf("output"); Contract c = Contract.fromPackedTransaction(Files.readAllBytes(Paths.get(source))); if(c != null) { keysMap().values().forEach( k -> c.addSignatureToSeal(k)); String name; if(names.size() > 0) { name = names.get(0); } else { String suffix = "_signedby_"+String.join("_",c.getSealedByKeys().stream().map(k->k.getShortAddress().toString()).collect(Collectors.toSet())); name = new FilenameTool(source).addSuffixToBase(suffix).toString(); } saveContract(c,name,true,false); } finish(); }
contract = Contract.fromPackedTransaction(data); } else { contract = new Contract(data);
private Binder startApproval(final Binder params, Session session) throws IOException, Quantiser.QuantiserException { if (config == null || config.limitFreeRegistrations()) if(config == null || ( !config.getKeysWhiteList().contains(session.getPublicKey()) && !config.getAddressesWhiteList().stream().anyMatch(addr -> addr.isMatchingKey(session.getPublicKey())))) { System.out.println("startApproval ERROR: session key shoild be in the white list"); return Binder.of( "itemResult", itemResultOfError(Errors.BAD_CLIENT_KEY,"startApproval", "command needs client key from whitelist")); } int n = asyncStarts.incrementAndGet(); AtomicInteger k = new AtomicInteger(); params.getListOrThrow("packedItems").forEach((item) -> es.execute(() -> { try { checkNode(session); System.out.println("Request to start registration #"+n+":"+k.incrementAndGet()); node.registerItem(Contract.fromPackedTransaction(((Bytes)item).toArray())); } catch (Exception e) { e.printStackTrace(); } }) ); //TODO: return ItemResult return new Binder(); }
protected Contract readContractBase(String fileName, boolean isTransaction) throws Exception { Contract contract = null; Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (isTransaction) { contract = Contract.fromPackedTransaction(data); } else contract = new Contract(data); } catch (Exception e) { e.printStackTrace(); } assertNotEquals(contract, null); return contract; }
@Override public void deserialize(Binder data, BiDeserializer deserializer) throws IOException { createdAt = deserializer.deserialize(data.getZonedDateTimeOrThrow("createdAt")); subscriptionsSet.addAll(deserializer.deserialize(data.getListOrThrow("subscriptions"))); storagesSet.addAll(deserializer.deserialize(data.getListOrThrow("storages"))); nameRecordsSet.addAll(deserializer.deserialize(data.getListOrThrow("nameRecords"))); contract = (NSmartContract) Contract.fromPackedTransaction(data.getBinary("contract")); kvStore = deserializer.deserialize(data.getBinderOrThrow("kvStore")); }
public void checkAllContracts() { //final AtomicBoolean needToReload = new AtomicBoolean(false); endpoints.forEach((endpoint, env) -> { HashId slotId = env.getSlotId(); HashId originId = env.getCurrentContract().getOrigin(); byte[] contractBinFromSlot1 = slot1Requestor.queryContract(slotId, originId); if (contractBinFromSlot1 != null) { try { Contract contractFromSlot1 = Contract.fromPackedTransaction(contractBinFromSlot1); if (contractFromSlot1.getRevision() > env.getCurrentContract().getRevision()) { System.err.println("JSApiHttpServer warning: contract origin="+originId+" changed in slot1, endpoint: " + endpoint); env.updateThisEnvironmentByName(contractFromSlot1, execOptions); } } catch (IOException e) { System.err.println("JSApiHttpServer error: unable to unpack latest contract origin=" + originId + " from slot1, update it, endpoint: " + endpoint + ", err: " + e); } catch (Exception e) { System.err.println("JSApiHttpServer error while update JSApiEnvironment: " + e); e.printStackTrace(); } } HashId id = env.getCurrentContract().getId(); if (!contractChecker.isApproved(id)) { System.err.println("JSApiHttpServer warning: contract id="+id+" is not approved, disabled " + endpoint); endpoints.remove(endpoint); } }); }
private static void doExecJs() throws Exception { String contractFile = (String) options.valueOf("exec-js"); String scriptName = null; if (options.has("script-name")) scriptName = (String)options.valueOf("script-name"); Contract c = Contract.fromPackedTransaction(Files.readAllBytes(Paths.get(contractFile))); if(c != null) { ItemResult itemResult = getClientNetwork().client.getState(c.getId(), reporter); if (itemResult.state == ItemState.APPROVED) { if (scriptName != null) { c.execJSByName(scriptName); } else { List<String> scriptNames = c.extractJSNames(); if (scriptNames.size() == 1) c.execJSByName(scriptNames.get(0)); else if (scriptNames.size() > 1) report("error: contract has " + scriptNames.size() + " scripts attached, specify script filename please"); else report("error: contract has no scripts attached"); } } else { report("error: contract should be approved"); } } finish(); }
private Binder queryFollowerInfo(Binder params, Session session) throws IOException { checkNode(session, true); Binder res = new Binder(); res.set("follower_state", null); byte[] follower_id = params.getBinary("follower_id"); byte[] followerBin = node.getLedger().getSmartContractById(HashId.withDigest(follower_id)); if (followerBin != null) { FollowerContract followerContract = (FollowerContract) Contract.fromPackedTransaction(followerBin); res.set("follower_state", followerContract.getStateData()); } return res; }
/** * Imitate procedure of contract processing as it will be on the Node. * Gte contract from param, create from it new contract, * that will be processed and return processed contract with cost inside. * @param contract - from which contract will be created contract for processing. * @param limit - Quantizer limit. * @return new contract that was processed. * @throws Exception */ public Contract processContractAsItWillBeOnTheNode(Contract contract, int limit) throws Exception { Contract processingContract; try { System.out.println("------ Imitate registering -------"); Contract.setTestQuantaLimit(limit); byte[] data = contract.getPackedTransaction(); processingContract = Contract.fromPackedTransaction(data); System.out.println("------ final check -------"); processingContract.check(); } catch (Exception e) { throw e; } finally { Contract.setTestQuantaLimit(-1); } return processingContract; }
private Binder querySlotInfo(Binder params, Session session) throws IOException { checkNode(session, true); Binder res = new Binder(); res.set("slot_state", null); byte[] slot_id = params.getBinary("slot_id"); byte[] slotBin = node.getLedger().getSmartContractById(HashId.withDigest(slot_id)); if (slotBin != null) { SlotContract slotContract = (SlotContract) Contract.fromPackedTransaction(slotBin); res.set("slot_state", slotContract.getStateData()); } return res; }
@Ignore @Test public void registerFromFile() throws Exception { TestSpace testSpace = prepareTestSpace(TestKeys.privateKey(0)); testSpace.nodes.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(true)); Path path = Paths.get("/tmp/not3.unicon"); byte[] testTransactionPackBytes = Files.readAllBytes(path); Contract contract = Contract.fromPackedTransaction(testTransactionPackBytes); System.out.println("======================"); System.out.println("check(): " + contract.check()); System.out.println("------- errors -------"); contract.traceErrors(); int i = 0; for (Approvable a : contract.getNewItems()) { Contract nc = (Contract) a; System.out.println("------- errors n"+i+" ----"); System.out.println(" check: " + nc.check()); nc.traceErrors(); ++i; } System.out.println("======================"); System.out.println("hashId: " + contract.getId().toBase64String()); testSpace.node.setVerboseLevel(DatagramAdapter.VerboseLevel.BASE); ItemResult itemResult = testSpace.client.register(testTransactionPackBytes, 5000); ItemResult itemResult2 = testSpace.client.getState(contract.getId()); System.out.println("itemResult: " + itemResult); System.out.println("itemResult2: " + itemResult2); testSpace.nodes.forEach(m -> m.shutdown()); }
public void asd() throws Exception { PrivateKey key = new PrivateKey(Do.read("/Users/romanu/Downloads/ru/roman.uskov.privateKey.unikey")); Set<PrivateKey> issuers = new HashSet<>(); issuers.add(key); Set<PublicKey> owners = new HashSet<>(); owners.add(key.getPublicKey()); TestSpace testSpace = prepareTestSpace(); testSpace.nodes.forEach(n->n.config.setIsFreeRegistrationsAllowedFromYaml(true)); for(int i = 109; i < 110; i++) { Contract c = ContractsService.createTokenContract(issuers, owners, new BigDecimal("100000.9"), new BigDecimal("0.01")); c.setIssuerKeys(key.getPublicKey().getShortAddress()); c.setCreatorKeys(key.getPublicKey().getShortAddress()); c.setExpiresAt(ZonedDateTime.now().plusDays(10)); c.seal(); new FileOutputStream("/Users/romanu/Downloads/ru/token"+i+".unicon").write(c.getPackedTransaction()); assertEquals(testSpace.client.register(Contract.fromPackedTransaction(Do.read("/Users/romanu/Downloads/ru/token"+i+".unicon")).getPackedTransaction(),10000).state,ItemState.APPROVED); } }
@Test public void transactionalData() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); String testValue = HashId.createRandom().toBase64String(); contract.getTransactionalData().set("test_value", testValue); contract.seal(); byte[] packedData = contract.getPackedTransaction(); Contract unpackedContract = Contract.fromPackedTransaction(packedData); System.out.println("unpackedContract.transactional.data.test_value: " + unpackedContract.getTransactionalData().getStringOrThrow("test_value")); assertEquals(testValue, unpackedContract.getTransactionalData().getStringOrThrow("test_value")); }
@Test public void references() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); String js = ""; js += "print('references');"; js += "var ref = jsApi.getReferenceBuilder().createReference('EXISTING_STATE');"; js += "ref.setConditions({'all_of':['ref.issuer=="+TestKeys.publicKey(1).getShortAddress().toString()+"']});"; js += "jsApi.getCurrentContract().addReference(ref);"; contract.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters()); contract.seal(); contract = Contract.fromPackedTransaction(contract.getPackedTransaction()); Contract batchContract = new Contract(TestKeys.privateKey(3)); batchContract.addNewItems(contract); batchContract.seal(); assertTrue(batchContract.check()); contract.execJS(new JSApiExecOptions(), js.getBytes()); contract.seal(); batchContract.seal(); assertFalse(batchContract.check()); }
transactionRoot.getTransactionPack().addReferencedItem(referencedContract); transactionRoot = Contract.fromPackedTransaction(transactionRoot.getPackedTransaction()); transactionRoot.check(); assertTrue(transactionRoot.isOk());