Search in sources :

Example 1 with ClientError

use of com.icodici.universa.node2.network.ClientError in project universa by UniversaBlockchain.

the class VotingTest method detachedContractsVotingAuthorityLevels.

@Test
public void detachedContractsVotingAuthorityLevels() throws Exception {
    TestSpace ts = prepareTestSpace();
    ts.nodes.forEach(n -> n.config.setIsFreeRegistrationsAllowedFromYaml(true));
    Client client = new Client("test_node_config_v2", null, TestKeys.privateKey(1));
    int N = 3;
    int M = 3;
    int K = 3;
    Contract contract = new Contract(TestKeys.privateKey(TestKeys.binaryKeys.length - 1));
    QuorumVoteRole quorumVoteRole = new QuorumVoteRole("issuer", contract, "refSupplied.state.data.list", "" + (N * M * K));
    contract.addRole(quorumVoteRole);
    Reference refSupplied = new Reference(contract);
    refSupplied.name = "refSupplied";
    refSupplied.type = Reference.TYPE_EXISTING_DEFINITION;
    refSupplied.setConditions(Binder.of("all_of", Do.listOf("ref can_play ref2ndLevelAuth.state.roles.granted_auth")));
    contract.addReference(refSupplied);
    Reference ref2ndLevelAuth = new Reference(contract);
    ref2ndLevelAuth.name = "ref2ndLevelAuth";
    ref2ndLevelAuth.type = Reference.TYPE_EXISTING_DEFINITION;
    ref2ndLevelAuth.setConditions(Binder.of("all_of", Do.listOf("ref can_play refRootAuth.state.roles.granted_auth")));
    contract.addReference(ref2ndLevelAuth);
    Reference refRootAuth = new Reference(contract);
    refRootAuth.name = "refRootAuth";
    refRootAuth.type = Reference.TYPE_EXISTING_DEFINITION;
    refRootAuth.setConditions(Binder.of("all_of", Do.listOf("ref.issuer==this.definition.data.root_authority")));
    contract.addReference(refRootAuth);
    SimpleRole role = new SimpleRole("dummy", contract);
    role.addRequiredReference("refSupplied", Role.RequiredMode.ALL_OF);
    role.addRequiredReference("ref2ndLevelAuth", Role.RequiredMode.ALL_OF);
    role.addRequiredReference("refRootAuth", Role.RequiredMode.ALL_OF);
    contract.addRole(role);
    final int BASE = 0;
    contract.getDefinition().getData().put("root_authority", TestKeys.publicKey(BASE).getLongAddress().toString());
    contract.seal();
    Contract rootAuthorityContract = new Contract(TestKeys.privateKey(BASE));
    List<Contract> scndLvlAuthContracts = new ArrayList<>();
    rootAuthorityContract.setIssuerKeys(TestKeys.publicKey(BASE).getLongAddress());
    ListRole grantedAuth = new ListRole("granted_auth", rootAuthorityContract);
    grantedAuth.setMode(ListRole.Mode.ANY);
    for (int i = 0; i < K; i++) {
        SimpleRole simpleRole = new SimpleRole("@auth" + i, rootAuthorityContract, Do.listOf(TestKeys.publicKey(BASE + 1 + i).getLongAddress()));
        grantedAuth.addRole(simpleRole);
        Contract scndLvlAuth = new Contract(TestKeys.privateKey(BASE + 1 + i));
        ListRole grantedAuth2nd = new ListRole("granted_auth", scndLvlAuth);
        grantedAuth2nd.setMode(ListRole.Mode.ANY);
        scndLvlAuth.addRole(grantedAuth2nd);
        for (int j = 0; j < M; j++) {
            simpleRole = new SimpleRole("@auth" + i, scndLvlAuth, Do.listOf(TestKeys.publicKey(BASE + 1 + K + i * K + j).getLongAddress()));
            grantedAuth2nd.addRole(simpleRole);
        }
        scndLvlAuth.seal();
        scndLvlAuthContracts.add(scndLvlAuth);
    }
    rootAuthorityContract.addRole(grantedAuth);
    rootAuthorityContract.seal();
    ItemResult ir = client.register(rootAuthorityContract.getPackedTransaction(), 100000);
    assertEquals(ir.state, ItemState.APPROVED);
    AtomicInteger readyCounter0 = new AtomicInteger();
    AsyncEvent readyEvent0 = new AsyncEvent();
    scndLvlAuthContracts.forEach(c -> {
        Do.inParallel(() -> {
            ItemResult ir2 = null;
            try {
                ir2 = client.register(c.getPackedTransaction(), 100000);
            } catch (ClientError clientError) {
                clientError.printStackTrace();
            }
            assertEquals(ir2.state, ItemState.APPROVED);
            if (readyCounter0.incrementAndGet() == scndLvlAuthContracts.size()) {
                readyEvent0.fire();
            }
        });
    });
    readyEvent0.await();
    Contract u = Parcel.createPayment(getApprovedUContract(ts), Do.listOf(ts.myKey), 1, false);
    HashId opId = client.initiateVote(u.getPackedTransaction(), contract, "creator", Do.listOf(contract.getId()));
    while (client.getPaidOperationProcessingState(opId).isProcessing()) {
        Thread.sleep(100);
    }
    if (client.getState(u.getId()).state == ItemState.APPROVED) {
        synchronized (ts.uContractLock) {
            ts.uContract = u;
        }
    } else {
        throw new IllegalArgumentException("wrong u");
    }
    for (int i = 0; i < K; i++) {
        for (int j = 0; j < M; j++) {
            Contract supplied = new Contract(TestKeys.privateKey(BASE + 1 + K + i * K + j));
            List<KeyAddress> kas = new ArrayList<>();
            for (int k = 0; k < N; k++) {
                kas.add(TestKeys.publicKey((i * K + j) * M + k).getLongAddress());
            }
            supplied.getStateData().put("list", kas);
            supplied.seal();
            ir = client.register(supplied.getPackedTransaction(), 100000);
            assertEquals(ir.state, ItemState.APPROVED);
            for (int k = 0; k < N; k++) {
                Client c = new Client("test_node_config_v2", null, TestKeys.privateKey((i * K + j) * M + k));
                u = Parcel.createPayment(getApprovedUContract(ts), Do.listOf(ts.myKey), 1, false);
                opId = c.voteForContract(u.getPackedTransaction(), contract.getId(), contract.getId(), Do.listOf(rootAuthorityContract.getLastSealedBinary(), scndLvlAuthContracts.get(i).getLastSealedBinary(), supplied.getLastSealedBinary()));
                while (c.getPaidOperationProcessingState(opId).isProcessing()) {
                    Thread.sleep(100);
                }
                if (c.getState(u.getId()).state == ItemState.APPROVED) {
                    synchronized (ts.uContractLock) {
                        ts.uContract = u;
                    }
                } else {
                    throw new IllegalArgumentException("wrong u");
                }
                System.out.println("VOTE " + ((i * K + j) * M + k));
            }
        }
    }
    ir = client.register(contract.getPackedTransaction(), 100000);
    System.out.println(ir);
    assertEquals(ir.state, ItemState.APPROVED);
    ts.shutdown();
}
Also used : HashId(com.icodici.universa.HashId) Reference(com.icodici.universa.contract.Reference) AtomicReference(java.util.concurrent.atomic.AtomicReference) AsyncEvent(net.sergeych.tools.AsyncEvent) ItemResult(com.icodici.universa.node.ItemResult) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) KeyAddress(com.icodici.crypto.KeyAddress) Client(com.icodici.universa.node2.network.Client) Contract(com.icodici.universa.contract.Contract) ClientError(com.icodici.universa.node2.network.ClientError) Test(org.junit.Test)

Example 2 with ClientError

use of com.icodici.universa.node2.network.ClientError in project universa by UniversaBlockchain.

the class ScriptEngineTest method latestHttpContractFromSlot1.

@Test
public void latestHttpContractFromSlot1() throws Exception {
    System.out.println("============= start nodes...");
    TestSpace testSpace = prepareTestSpace(TestKeys.privateKey(0));
    testSpace.nodes.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(true));
    System.out.println("============= start nodes done\n\n\n");
    Contract contractServer = new Contract(TestKeys.privateKey(0));
    String js = "";
    js += "var jsApiEvents = new Object();";
    js += "jsApiEvents.httpHandler_getVersion = function(request, response){" + "  response.setBodyAsJson({" + "    version: 1" + "  });" + "};";
    contractServer.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters(), true);
    RoleLink issuerLink = new RoleLink("issuer_link", "issuer");
    contractServer.registerRole(issuerLink);
    Permission perm = new ModifyDataPermission(issuerLink, Binder.of("fields", Binder.of("scripts", null)));
    contractServer.addPermission(perm);
    contractServer.seal();
    contractServer = Contract.fromPackedTransaction(contractServer.getPackedTransaction());
    ItemResult itemResult = testSpace.client.register(contractServer.getPackedTransaction(), 5000);
    assertEquals(ItemState.APPROVED, itemResult.state);
    // put contractServer rev1 into slot1
    SlotContract slotContract = ContractsService.createSlotContract(new HashSet<>(Arrays.asList(TestKeys.privateKey(0))), new HashSet<>(Arrays.asList(TestKeys.publicKey(0))), nodeInfoProvider);
    slotContract.setNodeInfoProvider(nodeInfoProvider);
    slotContract.putTrackingContract(contractServer);
    Contract stepaU = InnerContractsService.createFreshU(100000000, new HashSet<>(Arrays.asList(TestKeys.publicKey(0))));
    itemResult = testSpace.client.register(stepaU.getPackedTransaction(), 5000);
    System.out.println("stepaU : " + itemResult);
    assertEquals(ItemState.APPROVED, itemResult.state);
    Parcel parcel = ContractsService.createPayingParcel(slotContract.getTransactionPack(), stepaU, 1, 100, new HashSet<>(Arrays.asList(TestKeys.privateKey(0))), false);
    testSpace.client.registerParcelWithState(parcel.pack(), 5000);
    itemResult = testSpace.client.getState(slotContract.getId());
    System.out.println("slot : " + itemResult);
    assertEquals(ItemState.APPROVED, itemResult.state);
    // start http server
    JSApiHttpServerRoutes routes = new JSApiHttpServerRoutes();
    routes.setPortToListen(8880);
    routes.addNewRoute("/contract1/getVersion", "httpHandler_getVersion", contractServer, "client script.js", null, slotContract.getId());
    JSApiHttpServer httpServer = new JSApiHttpServer(routes, new JSApiExecOptions(), hashId -> {
        try {
            return testSpace.client.getState(hashId).state == ItemState.APPROVED;
        } catch (ClientError e) {
            e.printStackTrace();
            return false;
        }
    }, (slotId, originId) -> {
        try {
            Binder slotInfo = testSpace.client.querySlotInfo(slotId);
            return testSpace.client.queryContract(slotId, originId, null);
        } catch (ClientError e) {
            e.printStackTrace();
            return null;
        }
    });
    // here can be any http client. JSApiHttpClient used just for easiness
    JSApiScriptParameters scriptParameters = new JSApiScriptParameters();
    scriptParameters.domainMasks.add("localhost:*");
    JSApiHttpClient httpClient = new JSApiHttpClient(scriptParameters);
    // http access to contractServer rev1
    List httpRes = httpClient.sendGetRequest("http://localhost:8880/contract1/getVersion", JSApiHttpClient.RESPTYPE_JSON);
    System.out.println("httpRes: " + httpRes);
    assertEquals(1l, ((HashMap) httpRes.get(1)).get("version"));
    // create and register contractServer rev2
    Contract contractServer2 = contractServer.createRevision();
    contractServer2.addSignerKey(TestKeys.privateKey(0));
    String js2 = "";
    js2 += "var jsApiEvents = new Object();";
    js2 += "jsApiEvents.httpHandler_getVersion = function(request, response){" + "  response.setBodyAsJson({" + "    version: 2" + "  });" + "};";
    contractServer2.getState().setJS(js2.getBytes(), "client script.js", new JSApiScriptParameters(), true);
    contractServer2.seal();
    contractServer2 = Contract.fromPackedTransaction(contractServer2.getPackedTransaction());
    ItemResult itemResult2 = testSpace.client.register(contractServer2.getPackedTransaction(), 5000);
    assertEquals(ItemState.APPROVED, itemResult2.state);
    assertEquals(ItemState.REVOKED, testSpace.client.getState(contractServer.getId()).state);
    // force update server contracts from slot1
    httpServer.checkAllContracts();
    // http access to contractServer rev2
    httpRes = httpClient.sendGetRequest("http://localhost:8880/contract1/getVersion", JSApiHttpClient.RESPTYPE_JSON);
    System.out.println("httpRes: " + httpRes);
    assertEquals(2l, ((HashMap) httpRes.get(1)).get("version"));
    System.out.println("\n\n\n============= shutdown...");
    testSpace.nodes.forEach(m -> m.shutdown());
    httpServer.stop();
}
Also used : RoleLink(com.icodici.universa.contract.roles.RoleLink) Parcel(com.icodici.universa.contract.Parcel) SlotContract(com.icodici.universa.contract.services.SlotContract) Binder(net.sergeych.tools.Binder) ItemResult(com.icodici.universa.node.ItemResult) JSApiChangeNumberPermission(com.icodici.universa.contract.jsapi.permissions.JSApiChangeNumberPermission) JSApiPermission(com.icodici.universa.contract.jsapi.permissions.JSApiPermission) JSApiSplitJoinPermission(com.icodici.universa.contract.jsapi.permissions.JSApiSplitJoinPermission) Contract(com.icodici.universa.contract.Contract) NSmartContract(com.icodici.universa.contract.services.NSmartContract) SlotContract(com.icodici.universa.contract.services.SlotContract) ClientError(com.icodici.universa.node2.network.ClientError) Test(org.junit.Test)

Example 3 with ClientError

use of com.icodici.universa.node2.network.ClientError in project universa by UniversaBlockchain.

the class ScriptEngineTest method initHttpRoutesFromSlot1.

@Test
public void initHttpRoutesFromSlot1() throws Exception {
    System.out.println("============= start nodes...");
    TestSpace testSpace = prepareTestSpace(TestKeys.privateKey(0));
    testSpace.nodes.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(true));
    System.out.println("============= start nodes done\n\n\n");
    Contract contractServer = new Contract(TestKeys.privateKey(0));
    String js = "";
    js += "var jsApiEvents = new Object();";
    js += "jsApiEvents.httpHandler_getVersion = function(request, response){" + "  response.setBodyAsJson({" + "    version: 1" + "  });" + "};";
    contractServer.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters(), true);
    RoleLink issuerLink = new RoleLink("issuer_link", "issuer");
    contractServer.registerRole(issuerLink);
    Permission perm = new ModifyDataPermission(issuerLink, Binder.of("fields", Binder.of("scripts", null)));
    contractServer.addPermission(perm);
    contractServer.seal();
    contractServer = Contract.fromPackedTransaction(contractServer.getPackedTransaction());
    ItemResult itemResult = testSpace.client.register(contractServer.getPackedTransaction(), 5000);
    assertEquals(ItemState.APPROVED, itemResult.state);
    // put contractServer rev1 into slot1
    SlotContract slotContract = ContractsService.createSlotContract(new HashSet<>(Arrays.asList(TestKeys.privateKey(0))), new HashSet<>(Arrays.asList(TestKeys.publicKey(0))), nodeInfoProvider);
    slotContract.setNodeInfoProvider(nodeInfoProvider);
    slotContract.putTrackingContract(contractServer);
    Contract stepaU = InnerContractsService.createFreshU(100000000, new HashSet<>(Arrays.asList(TestKeys.publicKey(0))));
    itemResult = testSpace.client.register(stepaU.getPackedTransaction(), 5000);
    System.out.println("stepaU : " + itemResult);
    assertEquals(ItemState.APPROVED, itemResult.state);
    Parcel parcel = ContractsService.createPayingParcel(slotContract.getTransactionPack(), stepaU, 1, 100, new HashSet<>(Arrays.asList(TestKeys.privateKey(0))), false);
    testSpace.client.registerParcelWithState(parcel.pack(), 5000);
    itemResult = testSpace.client.getState(slotContract.getId());
    System.out.println("slot : " + itemResult);
    assertEquals(ItemState.APPROVED, itemResult.state);
    JSApiHttpServer.ISlot1Requestor slot1Requestor = (slotId, originId) -> {
        try {
            Binder slotInfo = testSpace.client.querySlotInfo(slotId);
            return testSpace.client.queryContract(slotId, originId, null);
        } catch (ClientError e) {
            e.printStackTrace();
            return null;
        }
    };
    // start http server
    String routesJsonString = "{\n" + "  \"listenPort\": \"8880\",\n" + "  \"routes\": [\n" + "    {\"endpoint\": \"/contract1/getVersion\", \"handlerName\": \"httpHandler_getVersion\", \"scriptName\": \"client script.js\", \"slotId\":\"" + slotContract.getId().toBase64String() + "\", \"originId\":\"" + contractServer.getOrigin().toBase64String() + "\"}\n" + "  ]\n" + "}\n";
    String tmpdir = System.getProperty("java.io.tmpdir");
    String strPathRoutes = tmpdir + "/" + "routes.json";
    Files.deleteIfExists(Paths.get(strPathRoutes));
    new File(strPathRoutes).createNewFile();
    Files.write(Paths.get(strPathRoutes), routesJsonString.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
    JSApiHttpServerRoutes routes = new JSApiHttpServerRoutes(strPathRoutes, slot1Requestor);
    JSApiHttpServer httpServer = new JSApiHttpServer(routes, new JSApiExecOptions(), hashId -> {
        try {
            return testSpace.client.getState(hashId).state == ItemState.APPROVED;
        } catch (ClientError e) {
            e.printStackTrace();
            return false;
        }
    }, slot1Requestor);
    // here can be any http client. JSApiHttpClient used just for easiness
    JSApiScriptParameters scriptParameters = new JSApiScriptParameters();
    scriptParameters.domainMasks.add("localhost:*");
    JSApiHttpClient httpClient = new JSApiHttpClient(scriptParameters);
    // http access to contractServer rev1
    List httpRes = httpClient.sendGetRequest("http://localhost:8880/contract1/getVersion", JSApiHttpClient.RESPTYPE_JSON);
    System.out.println("httpRes: " + httpRes);
    assertEquals(1l, ((HashMap) httpRes.get(1)).get("version"));
    // create and register contractServer rev2
    Contract contractServer2 = contractServer.createRevision();
    contractServer2.addSignerKey(TestKeys.privateKey(0));
    String js2 = "";
    js2 += "var jsApiEvents = new Object();";
    js2 += "jsApiEvents.httpHandler_getVersion = function(request, response){" + "  response.setBodyAsJson({" + "    version: 2" + "  });" + "};";
    contractServer2.getState().setJS(js2.getBytes(), "client script.js", new JSApiScriptParameters(), true);
    contractServer2.seal();
    contractServer2 = Contract.fromPackedTransaction(contractServer2.getPackedTransaction());
    ItemResult itemResult2 = testSpace.client.register(contractServer2.getPackedTransaction(), 5000);
    assertEquals(ItemState.APPROVED, itemResult2.state);
    assertEquals(ItemState.REVOKED, testSpace.client.getState(contractServer.getId()).state);
    // force update server contracts from slot1
    httpServer.checkAllContracts();
    // http access to contractServer rev2
    httpRes = httpClient.sendGetRequest("http://localhost:8880/contract1/getVersion", JSApiHttpClient.RESPTYPE_JSON);
    System.out.println("httpRes: " + httpRes);
    assertEquals(2l, ((HashMap) httpRes.get(1)).get("version"));
    System.out.println("\n\n\n============= shutdown...");
    testSpace.nodes.forEach(m -> m.shutdown());
    httpServer.stop();
}
Also used : NashornScriptEngineFactory(jdk.nashorn.api.scripting.NashornScriptEngineFactory) JSApiRole(com.icodici.universa.contract.jsapi.roles.JSApiRole) java.util(java.util) JSApiChangeNumberPermission(com.icodici.universa.contract.jsapi.permissions.JSApiChangeNumberPermission) Client(com.icodici.universa.node2.network.Client) Binder(net.sergeych.tools.Binder) SimpleRole(com.icodici.universa.contract.roles.SimpleRole) JSApiStorage(com.icodici.universa.contract.jsapi.storage.JSApiStorage) BigDecimal(java.math.BigDecimal) com.icodici.universa.contract.permissions(com.icodici.universa.contract.permissions) PublicKey(com.icodici.crypto.PublicKey) Contract(com.icodici.universa.contract.Contract) com.icodici.universa.contract.jsapi(com.icodici.universa.contract.jsapi) NSmartContract(com.icodici.universa.contract.services.NSmartContract) ClassFilter(jdk.nashorn.api.scripting.ClassFilter) ContractsService(com.icodici.universa.contract.ContractsService) Before(org.junit.Before) ScriptException(javax.script.ScriptException) ItemResult(com.icodici.universa.node.ItemResult) PrivateKey(com.icodici.crypto.PrivateKey) TestKeys(com.icodici.universa.TestKeys) Files(java.nio.file.Files) InnerContractsService(com.icodici.universa.contract.InnerContractsService) JSApiPermission(com.icodici.universa.contract.jsapi.permissions.JSApiPermission) KeyAddress(com.icodici.crypto.KeyAddress) Do(net.sergeych.tools.Do) StandardOpenOption(java.nio.file.StandardOpenOption) Test(org.junit.Test) IOException(java.io.IOException) ClientError(com.icodici.universa.node2.network.ClientError) Bytes(net.sergeych.utils.Bytes) Field(java.lang.reflect.Field) JSApiSplitJoinPermission(com.icodici.universa.contract.jsapi.permissions.JSApiSplitJoinPermission) ItemState(com.icodici.universa.node.ItemState) File(java.io.File) Base64(net.sergeych.utils.Base64) Parcel(com.icodici.universa.contract.Parcel) HashId(com.icodici.universa.HashId) Ignore(org.junit.Ignore) Invocable(javax.script.Invocable) Paths(java.nio.file.Paths) ScriptEngine(javax.script.ScriptEngine) RoleLink(com.icodici.universa.contract.roles.RoleLink) ScriptObjectMirror(jdk.nashorn.api.scripting.ScriptObjectMirror) Assert(org.junit.Assert) SlotContract(com.icodici.universa.contract.services.SlotContract) RoleLink(com.icodici.universa.contract.roles.RoleLink) Parcel(com.icodici.universa.contract.Parcel) SlotContract(com.icodici.universa.contract.services.SlotContract) Binder(net.sergeych.tools.Binder) ItemResult(com.icodici.universa.node.ItemResult) JSApiChangeNumberPermission(com.icodici.universa.contract.jsapi.permissions.JSApiChangeNumberPermission) JSApiPermission(com.icodici.universa.contract.jsapi.permissions.JSApiPermission) JSApiSplitJoinPermission(com.icodici.universa.contract.jsapi.permissions.JSApiSplitJoinPermission) Contract(com.icodici.universa.contract.Contract) NSmartContract(com.icodici.universa.contract.services.NSmartContract) SlotContract(com.icodici.universa.contract.services.SlotContract) ClientError(com.icodici.universa.node2.network.ClientError) File(java.io.File) Test(org.junit.Test)

Example 4 with ClientError

use of com.icodici.universa.node2.network.ClientError in project universa by UniversaBlockchain.

the class MainClass method main.

public static void main(String... args) throws Exception {
    if (args.length == 1 && args[0].equals("--info")) {
        System.out.println("AVG0 represents pure client TPS. Measurement starts at the moment\n" + "first registration request is INITIATED. It doesn't take into account\n" + "network latency and contracts upload time. AVG0 is always the lowest.\n");
        System.out.println("AVG1 represents server TPS. Measurement starts at the moment\n" + "FIRST registration request is COMPLETE - node got contracts\n" + "and started registration. It takes into account network latency and\n" + "measures pure nodes working time.\n");
        System.out.println("AVG2 is very similar to AVG1. The difference is that measurement starts\n" + "at the moment LAST registration request is COMPLETE - ALL nodes got contracts\n" + "and started registration. A good test run is represented by AVG1 and AVG2 being\n" + "very close to each other as requests are performed to different nodes in parallel\n" + "and must be completed nearly simultaneously.");
        System.out.println("PEAK represents maximum value of AVG1 calculated every time a single contract is getting\n" + "APPROVED status.\n");
        return;
    } else if (args.length != 2) {
        System.out.println("expected format: java -jar uniperformance.jar TOPOLOGY PATH_TO_ADMIN_KEY");
    }
    final int BUNCHES_PER_NODE = 1;
    final int TIME_BETWEEN_BUNCHES = 3000;
    final int PACK_SIZE = 500;
    final int PACKS_IN_BUNCH = 5;
    System.out.println("Connecting to nodes...");
    Client client = new Client(args[0], null, new PrivateKey(Do.read(args[1])));
    System.out.println("Network version: " + client.getVersion());
    final int NODES_COUNT = client.size();
    final int PACKES_COUNT = BUNCHES_PER_NODE * NODES_COUNT * PACKS_IN_BUNCH;
    HashMap<Integer, Client> clients = new HashMap<>();
    HashMap<Pair<Integer, Integer>, ArrayList<byte[]>> bytes = new HashMap<>();
    HashMap<Pair<Integer, Integer>, ArrayList<Contract>> contracts = new HashMap<>();
    for (int i = 0; i < NODES_COUNT; i++) {
        clients.put(i, client.getClient(i));
        clients.get(i).ping();
    }
    System.out.println("Preparig contracts...");
    ExecutorService executorService = new ScheduledThreadPoolExecutor(NODES_COUNT);
    int l = 0;
    for (int k = 0; k < BUNCHES_PER_NODE; k++) {
        for (int i = 0; i < NODES_COUNT; i++) {
            contracts.put(Pair.of(k, i), new ArrayList<>());
            bytes.put(Pair.of(k, i), new ArrayList<>());
            for (int j = 0; j < PACKS_IN_BUNCH; j++) {
                l++;
                final int fk = k;
                final int fi = i;
                final int fl = l;
                executorService.submit(() -> {
                    try {
                        Contract c = createComplexConctract(TestKeys.privateKey(1), PACK_SIZE, fl);
                        synchronized (contracts) {
                            contracts.get(Pair.of(fk, fi)).add(c);
                            bytes.get(Pair.of(fk, fi)).add(c.getPackedTransaction());
                        }
                    } catch (EncryptionError encryptionError) {
                        encryptionError.printStackTrace();
                    }
                });
            }
        }
    }
    AtomicLong start0 = new AtomicLong(System.currentTimeMillis());
    AtomicLong start1 = new AtomicLong(System.currentTimeMillis());
    AtomicLong start2 = new AtomicLong(System.currentTimeMillis());
    AtomicLong end = new AtomicLong();
    System.out.println("Registering contracts...");
    AtomicInteger sentCounter = new AtomicInteger(0);
    AtomicInteger doneCounter = new AtomicInteger(0);
    AsyncEvent eventReady = new AsyncEvent();
    AtomicInteger peakFps = new AtomicInteger(0);
    for (int i = 0; i < NODES_COUNT; i++) {
        int fI = i;
        executorService.submit(() -> {
            for (int k = 0; k < BUNCHES_PER_NODE; k++) {
                long from = System.currentTimeMillis();
                try {
                    clients.get(fI).command("startApproval", "packedItems", bytes.get(Pair.of(k, fI)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("Sent " + k + " " + fI);
                long to = System.currentTimeMillis();
                if (BUNCHES_PER_NODE == 1) {
                    if (to - from < TIME_BETWEEN_BUNCHES) {
                        try {
                            Thread.sleep(TIME_BETWEEN_BUNCHES - (to - from));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            int currentSent = sentCounter.incrementAndGet();
            if (BUNCHES_PER_NODE == 1) {
                if (currentSent == 1) {
                    start1.set(System.currentTimeMillis());
                }
                if (currentSent == NODES_COUNT) {
                    start2.set(System.currentTimeMillis());
                }
            }
            boolean found;
            for (int k = 0; k < BUNCHES_PER_NODE; k++) {
                do {
                    found = false;
                    for (int j = 0; j < contracts.get(Pair.of(k, fI)).size(); j++) {
                        try {
                            ItemResult rr;
                            Contract c = contracts.get(Pair.of(k, fI)).get(j);
                            rr = clients.get(fI).getState(c.getId());
                            if (!rr.state.isApproved()) {
                                found = true;
                                if (rr.state == ItemState.DECLINED) {
                                    System.out.println(c.getId() + " is DECLINED " + c.getErrors());
                                    System.exit(1);
                                }
                            } else {
                                contracts.get(Pair.of(k, fI)).remove(j);
                                j--;
                                int done = doneCounter.incrementAndGet();
                                System.out.print("\rDone:" + done);
                                if (done == BUNCHES_PER_NODE * PACKS_IN_BUNCH * NODES_COUNT) {
                                    end.set(System.currentTimeMillis());
                                    eventReady.fire();
                                }
                                if (BUNCHES_PER_NODE == 1) {
                                    final int newPeak = (int) (PACK_SIZE * done / ((System.currentTimeMillis() - start1.get()) / 1000f));
                                    peakFps.getAndUpdate(curPeak -> newPeak > curPeak ? newPeak : curPeak);
                                }
                            }
                        } catch (ClientError clientError) {
                            clientError.printStackTrace();
                        }
                    }
                    if (found) {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                } while (found);
            }
        });
    }
    eventReady.await();
    float tps0 = PACK_SIZE * PACKES_COUNT / ((end.get() - start0.get()) / 1000.0f);
    float tps1 = PACK_SIZE * PACKES_COUNT / ((end.get() - start1.get()) / 1000.0f);
    float tps2 = PACK_SIZE * PACKES_COUNT / ((end.get() - start2.get()) / 1000.0f);
    System.out.println("\nTPS\n");
    System.out.println("AVG0: " + tps0 + "\n");
    if (BUNCHES_PER_NODE == 1) {
        System.out.println("AVG1: " + tps1 + "\n");
        System.out.println("AVG2: " + tps2 + "\n");
        System.out.println("PEAK: " + peakFps + "\n");
    }
    System.out.println("Run with --info to get values explained\n");
    executorService.shutdownNow();
    System.exit(0);
}
Also used : PrivateKey(com.icodici.crypto.PrivateKey) HashMap(java.util.HashMap) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) ArrayList(java.util.ArrayList) Client(com.icodici.universa.node2.network.Client) IOException(java.io.IOException) AsyncEvent(net.sergeych.tools.AsyncEvent) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicLong(java.util.concurrent.atomic.AtomicLong) ItemResult(com.icodici.universa.node.ItemResult) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) EncryptionError(com.icodici.crypto.EncryptionError) Contract(com.icodici.universa.contract.Contract) ClientError(com.icodici.universa.node2.network.ClientError)

Example 5 with ClientError

use of com.icodici.universa.node2.network.ClientError in project universa by UniversaBlockchain.

the class CLIMain method checkContract.

/**
 * Check contract for errors. Print errors if found.
 *
 * @param contract - contract to check.
 */
private static void checkContract(Contract contract) {
    // First, check the sealed state
    if (!contract.isOk()) {
        reporter.message("The capsule is not sealed properly:");
        contract.getErrors().forEach(e -> reporter.error(e.getError().toString(), e.getObjectName(), e.getMessage()));
    }
    Yaml yaml = new Yaml();
    if (reporter.isVerboseMode()) {
        report("api level:   " + contract.getApiLevel());
        report("contract id: " + contract.getId().toBase64String());
        report("issued:      " + contract.getIssuedAt());
        report("revision:    " + contract.getRevision());
        report("created:     " + contract.getCreatedAt());
        report("expires:     " + contract.getExpiresAt());
        System.out.println();
        Set<PublicKey> keys = contract.getSealedByKeys();
        contract.getRevoking().forEach(r -> {
            try {
                ClientNetwork n = getClientNetwork();
                System.out.println();
                report("revoking item exists: " + r.getId().toBase64String());
                report("\tstate: " + n.check(r.getId()));
                HashId origin = r.getOrigin();
                boolean m = origin.equals(contract.getOrigin());
                report("\tOrigin: " + origin);
                report("\t" + (m ? "matches main contract origin" : "does not match main contract origin"));
                if (r.canBeRevoked(keys)) {
                    report("\trevocation is allowed");
                } else
                    reporter.error(Errors.BAD_REVOKE.name(), r.getId().toString(), "revocation not allowed");
            } catch (Exception clientError) {
                clientError.printStackTrace();
            }
        });
        contract.getNewItems().forEach(n -> {
            System.out.println();
            report("New item exists:      " + n.getId().toBase64String());
            Contract nc = (Contract) n;
            boolean m = nc.getOrigin().equals(contract.getOrigin());
            report("\tOrigin: " + ((Contract) n).getOrigin());
            report("\t" + (m ? "matches main contract origin" : "does not match main contract origin"));
        });
        if (keys.size() > 0) {
            report("\nSignature contains " + keys.size() + " valid key(s):\n");
            keys.forEach(k -> {
                KeyInfo i = k.info();
                report("\t✔︎ " + i.getAlgorythm() + ":" + i.getKeyLength() * 8 + ":" + i.getBase64Tag());
            });
            report("\nWhich can play roles:\n");
            contract.getRoles().forEach((name, role) -> {
                String canPlay = role.isAllowedForKeys(keys) ? "✔" : "✘";
                report("\t" + canPlay + " " + role.getName());
            });
            report("\nAnd have permissions:\n");
            contract.getPermissions().values().forEach(perm -> {
                String canPlay = perm.isAllowedForKeys(keys) ? "✔" : "✘";
                report("\t" + canPlay + " " + perm.getName());
                Binder x = DefaultBiMapper.serialize(perm.getParams());
                BufferedReader br = new BufferedReader(new StringReader(yaml.dumpAsMap(x)));
                try {
                    for (String line; (line = br.readLine()) != null; ) {
                        report("\t    " + line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            reporter.newLine();
        }
    }
    Multimap<String, Permission> permissions = contract.getPermissions();
    Collection<Permission> sjs = permissions.get("split_join");
    if (sjs != null) {
        sjs.forEach(sj -> checkSj(contract, sj));
    }
    try {
        contract.check();
    } catch (Quantiser.QuantiserException e) {
        addError("QUANTIZER_COST_LIMIT", contract.toString(), e.getMessage());
    } catch (Exception e) {
        addError(Errors.FAILURE.name(), contract.toString(), e.getMessage());
    }
    addErrors(contract.getErrors());
    if (contract.getErrors().size() == 0) {
        report("Contract is valid");
    }
}
Also used : Quantiser(com.icodici.universa.node2.Quantiser) Yaml(org.yaml.snakeyaml.Yaml) BackingStoreException(java.util.prefs.BackingStoreException) OptionException(joptsimple.OptionException) ChangeOwnerPermission(com.icodici.universa.contract.permissions.ChangeOwnerPermission) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) Permission(com.icodici.universa.contract.permissions.Permission) SplitJoinPermission(com.icodici.universa.contract.permissions.SplitJoinPermission)

Aggregations

ItemResult (com.icodici.universa.node.ItemResult)8 PrivateKey (com.icodici.crypto.PrivateKey)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 EncryptionError (com.icodici.crypto.EncryptionError)5 PublicKey (com.icodici.crypto.PublicKey)5 NSmartContract (com.icodici.universa.contract.services.NSmartContract)5 ClientError (com.icodici.universa.node2.network.ClientError)5 java.util (java.util)5 Test (org.junit.Test)5 com.icodici.universa (com.icodici.universa)4 com.icodici.universa.contract (com.icodici.universa.contract)4 Contract (com.icodici.universa.contract.Contract)4 ItemState (com.icodici.universa.node.ItemState)4 Client (com.icodici.universa.node2.network.Client)4 IOException (java.io.IOException)4 Instant (java.time.Instant)4 ZonedDateTime (java.time.ZonedDateTime)4 ExecutorService (java.util.concurrent.ExecutorService)4 Collectors (java.util.stream.Collectors)4 BossBiMapper (net.sergeych.biserializer.BossBiMapper)4