Codota Logo
Contract.fromPackedTransaction
Code IndexAdd Codota to your IDE (free)

How to use
fromPackedTransaction
method
in
com.icodici.universa.contract.Contract

Best Java code snippets using com.icodici.universa.contract.Contract.fromPackedTransaction (Showing top 20 results out of 315)

  • Common ways to obtain Contract
private void myMethod () {
Contract c =
  • Codota Iconnew Contract()
  • Codota IconString fileName;Contract.fromDslFile(fileName)
  • Codota IconParcel parcel;parcel.getPaymentContract()
  • Smart code suggestions by Codota
}
origin: UniversaBlockchain/universa

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());
  }
}
origin: UniversaBlockchain/universa

@Override
public void deserialize(Binder data, BiDeserializer deserializer) throws IOException {
  packedContract = data.getBinary("packedContract");
  trackingContract = Contract.fromPackedTransaction(packedContract);
  expiresAt = data.getZonedDateTimeOrThrow("expiresAt");
}
origin: UniversaBlockchain/universa

@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;
      }
    });
}
origin: UniversaBlockchain/universa

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();
}
origin: UniversaBlockchain/universa

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();
}
origin: UniversaBlockchain/universa

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();
}
origin: UniversaBlockchain/universa

  contract = Contract.fromPackedTransaction(data);
} else {
  contract = new Contract(data);
origin: UniversaBlockchain/universa

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();
}
origin: UniversaBlockchain/universa

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;
}
origin: UniversaBlockchain/universa

@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"));
}
origin: UniversaBlockchain/universa

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);
    }
  });
}
origin: UniversaBlockchain/universa

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();
}
origin: UniversaBlockchain/universa

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;
}
origin: UniversaBlockchain/universa

/**
 * 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;
}
origin: UniversaBlockchain/universa

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;
}
origin: UniversaBlockchain/universa

@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());
}
origin: UniversaBlockchain/universa

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);
  }
}
origin: UniversaBlockchain/universa

@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"));
}
origin: UniversaBlockchain/universa

@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());
}
origin: UniversaBlockchain/universa

transactionRoot.getTransactionPack().addReferencedItem(referencedContract);
transactionRoot = Contract.fromPackedTransaction(transactionRoot.getPackedTransaction());
transactionRoot.check();
assertTrue(transactionRoot.isOk());
com.icodici.universa.contractContractfromPackedTransaction

Javadoc

Main .unicon read routine. Load any .unicon version and construct a linked Contract with counterparts (new and revoking items if present) and corresponding TransactionPack instance to pack it to store or send to approval.

The supported file variants are:

- v2 legacy unicon. Is loaded with packed counterparts if any. Only for compatibility, avoid using it.

- v3 compacted unicon. Is loaded without counterparts, should be added later if need with #addNewItems(Contract...) and #addRevokingItems(Contract...). This is a good way to keep the long contract chain.

- packed TransactionPack. This is a preferred way to keep current contract state.

To pack and write corresponding .unicon file use #getPackedTransaction().

Popular methods of Contract

  • <init>
    Extract old, deprecated v2 self-contained binary partially unpacked by the TransactionPack, and fill
  • addNewItems
    Add one or more siblings to the contract. Note that those must be sealed before calling #seal() or #
  • addSignerKey
    Add private key to keys contract binary to be signed with when sealed next time. It is called before
  • getExpiresAt
    Get contract expiration time
  • getId
    Get the id sealing self if need
  • getPackedTransaction
    Pack the contract to the most modern .unicon format, same as TransactionPack#pack(). Uses bounded Tr
  • registerRole
    Register new role. Name must be unique otherwise existing role will be overwritten
  • seal
    Seal contract to binary. This call adds signatures from #getKeysToSignWith()
  • addSignatureToSeal
    Add signature to sealed (before) contract. Do not deserializing or changing contract bytes, but will
  • check
  • createRevision
    Create new revision to be changed, signed sealed and then ready to approve. Created "revision" contr
  • fromDslFile
    Create contract importing its parameters with passed .yaml file. No signatures are added automatical
  • createRevision,
  • fromDslFile,
  • getCreatedAt,
  • getDefinition,
  • getErrors,
  • getKeysToSignWith,
  • getLastSealedBinary,
  • getNew,
  • getNewItems

Popular in Java

  • Running tasks concurrently on multiple threads
  • setRequestProperty (URLConnection)
  • findViewById (Activity)
  • scheduleAtFixedRate (Timer)
    Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.
  • InetAddress (java.net)
    This class represents an Internet Protocol (IP) address. An IP address is either a 32-bit or 128-bit
  • KeyStore (java.security)
    This class represents an in-memory collection of keys and certificates. It manages two types of entr
  • HashMap (java.util)
    HashMap is an implementation of Map. All optional operations are supported.All elements are permitte
  • Executors (java.util.concurrent)
    Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory,
  • Cipher (javax.crypto)
    This class provides access to implementations of cryptographic ciphers for encryption and decryption
  • DateTimeFormat (org.joda.time.format)
    Factory that creates instances of DateTimeFormatter from patterns and styles. Datetime formatting i
Codota Logo
  • Products

    Search for Java codeSearch for JavaScript codeEnterprise
  • IDE Plugins

    IntelliJ IDEAWebStormAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimAtomGoLandRubyMineEmacsJupyter
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogCodota Academy Plugin user guide Terms of usePrivacy policyJava Code IndexJavascript Code Index
Get Codota for your IDE now