@Test public void testSharedFolders_write() throws Exception { String f1content = "f1 content"; String f2content = "f2 content"; String f3content = "f3 content"; String f4content = "f4 content"; List<String> sharedFolders = prepareSharedFoldersForTest(f1content, f2content, f3content); Paths.get(sharedFolders.get(0) + "/folder2/f4.txt").toFile().delete(); Paths.get(sharedFolders.get(0) + "/folder2/f4.txt").toFile().getParentFile().delete(); Contract contract = new Contract(TestKeys.privateKey(0)); String js = ""; js += "print('testSharedFolders_write');"; js += "var file4Content = '"+f4content+"';"; js += "jsApi.getSharedFolders().writeNewFile('folder2/f4.txt', jsApi.string2bin(file4Content));"; JSApiExecOptions execOptions = new JSApiExecOptions(); execOptions.sharedFolders.addAll(sharedFolders); contract.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters()); contract.seal(); contract.execJS(execOptions, js.getBytes()); String f4readed = new String(Files.readAllBytes(Paths.get(sharedFolders.get(0) + "/folder2/f4.txt"))); System.out.println("f4: " + f4readed); assertEquals(f4content, f4readed); }
scriptParameters.domainMasks.add("localhost:*"); scriptParameters.setPermission(JSApiScriptParameters.ScriptPermissions.PERM_HTTP_CLIENT, true); contract.getState().setJS(jsFileBytes, filename, scriptParameters, true); contract.seal(); String createdFileName = FileTool.writeFileContentsWithRenaming(outputFile, contract.getPackedTransaction());
scriptParameters.ipMasks.add("192.168.1.*"); scriptParameters.setPermission(JSApiScriptParameters.ScriptPermissions.PERM_HTTP_CLIENT, true); contract.getState().setJS(js.getBytes(), "client script.js", scriptParameters); contract.seal(); contract = Contract.fromPackedTransaction(contract.getPackedTransaction());
JSApiScriptParameters scriptParameters = new JSApiScriptParameters(); scriptParameters.timeLimitMillis = 3000; contract.getState().setJS(js.getBytes(), "client script.js", scriptParameters, true); contract.seal(); contract = Contract.fromPackedTransaction(contract.getPackedTransaction());
JSApiScriptParameters scriptParameters = new JSApiScriptParameters(); scriptParameters.setPermission(JSApiScriptParameters.ScriptPermissions.PERM_ORIGIN_STORAGE, true); contract.getState().setJS(js.getBytes(), "client script.js", scriptParameters); contract.seal(); Paths.get(originStoragePath + JSApiHelpers.hashId2hex(contract.getOrigin()) + "/" + testFileName).toFile().delete(); js2 += "var file1readed = bin2string(originStorage.readAllBytes('"+testFileName+"'));"; js2 += "var result = [file1readed, file2readed]"; contract2.getState().setJS(js2.getBytes(), "client script.js", scriptParameters); contract2.addSignerKey(TestKeys.privateKey(0)); contract2.seal();
" });" + "};"; contractServer.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters(), true); contractServer.seal(); contractServer = Contract.fromPackedTransaction(contractServer.getPackedTransaction());
@Test public void extractContractShouldBeRestricted() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); String js1 = ""; js1 += "var c = jsApi.getCurrentContract();"; js1 += "var rc = c.extractContract(new Object());"; js1 += "print('extractContract: ' + rc);"; String js2 = ""; js2 += "var c = jsApi.getCurrentContract();"; js2 += "var rc = c.extractContract(null);"; js2 += "print('extractContract: ' + rc);"; contract.getState().setJS(js1.getBytes(), "client script 1.js", new JSApiScriptParameters()); contract.getState().setJS(js2.getBytes(), "client script 2.js", new JSApiScriptParameters()); contract.seal(); contract = Contract.fromPackedTransaction(contract.getPackedTransaction()); try { contract.execJS(js1.getBytes()); assert false; } catch (ClassCastException e) { System.out.println(e); assert true; } try { contract.execJS(js2.getBytes()); assert false; } catch (ClassCastException e) { System.out.println(e); assert true; } }
@Test // checks that application/x-www-form-urlencoded request correctly parsed at server public void httpServerTest2() throws Exception { Contract contractServer = new Contract(TestKeys.privateKey(0)); String js = ""; js += "var jsApiEvents = new Object();"; js += "jsApiEvents.httpHandler_test = function(request, response){" + " response.setBodyAsJson({req_params: request.getParams()});" + "};"; contractServer.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters(), true); contractServer.seal(); contractServer = Contract.fromPackedTransaction(contractServer.getPackedTransaction()); JSApiHttpServerRoutes routes = new JSApiHttpServerRoutes(); routes.setPortToListen(8880); routes.addNewRoute("/test", "httpHandler_test", contractServer, "client script.js", null); JSApiHttpServer httpServer = new JSApiHttpServer(routes, new JSApiExecOptions(), hashId -> true, (slotId, originId) -> 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); Map<String, Object> params = new HashMap<>(); params.put("param1", "value1"); params.put("param2", 42l); List httpRes = httpClient.sendPostRequest("http://localhost:8880/test", JSApiHttpClient.RESPTYPE_JSON, params, "form"); System.out.println("httpRes: " + httpRes); assertEquals("value1", ((HashMap)((HashMap)httpRes.get(1)).get("req_params")).get("param1")); assertEquals("42", ((HashMap)((HashMap)httpRes.get(1)).get("req_params")).get("param2")); httpServer.stop(); }
@Test public void testSharedStorage() throws Exception { String sharedStoragePath = JSApiStorage.getSharedStoragePath(); String testFileName = "./someFolder/file1.txt"; Paths.get(sharedStoragePath + testFileName).toFile().delete(); String testString1 = "testString1_" + HashId.createRandom().toBase64String(); String testString2 = "testString2_" + HashId.createRandom().toBase64String(); System.out.println("testString1: " + testString1); System.out.println("testString2: " + testString2); Contract contract = new Contract(TestKeys.privateKey(0)); String js = ""; js += "print('testSharedStorage');"; js += "function bin2string(array){var result = '';for(var i = 0; i < array.length; ++i){result+=(String.fromCharCode(array[i]));}return result;}"; js += "var sharedStorage = jsApi.getSharedStorage();"; js += "sharedStorage.writeNewFile('"+testFileName+"', jsApi.string2bin('"+testString1+"'));"; js += "var file1readed = bin2string(sharedStorage.readAllBytes('"+testFileName+"'));"; js += "sharedStorage.rewriteExistingFile('"+testFileName+"', jsApi.string2bin('"+testString2+"'));"; js += "var file2readed = bin2string(sharedStorage.readAllBytes('"+testFileName+"'));"; js += "var result = [file1readed, file2readed]"; JSApiScriptParameters scriptParameters = new JSApiScriptParameters(); scriptParameters.setPermission(JSApiScriptParameters.ScriptPermissions.PERM_SHARED_STORAGE, true); contract.getState().setJS(js.getBytes(), "client script.js", scriptParameters); contract.seal(); ScriptObjectMirror res = (ScriptObjectMirror)contract.execJS(new JSApiExecOptions(), js.getBytes()); assertEquals(testString1, res.get("0")); assertEquals(testString2, res.get("1")); }
@Test public void testHttpClientFromJS() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); String js = ""; js += "print('testHttpClientFromJS');"; js += "var httpClient = jsApi.getHttpClient();"; js += "var res0 = httpClient.sendGetRequest('https://httpbin.org/get?param=333', 'json');"; js += "var res1 = httpClient.sendPostRequest('http://httpbin.org/post', 'json', {postparam:44}, 'form');"; js += "var res2 = httpClient.sendPostRequest('http://httpbin.org/post', 'json', {jsonparam:55}, 'json');"; js += "var result = [res0, res1, res2];"; JSApiScriptParameters scriptParameters = new JSApiScriptParameters(); scriptParameters.domainMasks.add("httpbin.org"); scriptParameters.setPermission(JSApiScriptParameters.ScriptPermissions.PERM_HTTP_CLIENT, true); contract.getState().setJS(js.getBytes(), "client script.js", scriptParameters); contract.seal(); contract = Contract.fromPackedTransaction(contract.getPackedTransaction()); ScriptObjectMirror res = (ScriptObjectMirror)contract.execJS(new JSApiExecOptions(), js.getBytes()); List res0 = (List)res.get("0"); assertEquals(200, res0.get(0)); assertEquals("333", ((Map)((Map)res0.get(1)).get("args")).get("param")); List res1 = (List)res.get("1"); assertEquals(200, res1.get(0)); assertEquals("44", ((Map)((Map)res1.get(1)).get("form")).get("postparam")); List res2 = (List)res.get("2"); assertEquals(200, res2.get(0)); assertEquals(55l, ((Map)((Map)res2.get(1)).get("json")).get("jsonparam")); }
@Test // checks that application/json request correctly parsed at server public void httpServerTest3() throws Exception { Contract contractServer = new Contract(TestKeys.privateKey(0)); String js = ""; js += "var jsApiEvents = new Object();"; js += "jsApiEvents.httpHandler_test = function(request, response){" + " response.setBodyAsJson({req_params: request.getParams()});" + "};"; contractServer.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters(), true); contractServer.seal(); contractServer = Contract.fromPackedTransaction(contractServer.getPackedTransaction()); JSApiHttpServerRoutes routes = new JSApiHttpServerRoutes(); routes.setPortToListen(8880); routes.addNewRoute("/test", "httpHandler_test", contractServer, "client script.js", null); JSApiHttpServer httpServer = new JSApiHttpServer(routes, new JSApiExecOptions(), hashId -> true, (slotId, originId) -> 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); Map<String, Object> params = new HashMap<>(); params.put("param1", "value1"); params.put("param2", 42l); List httpRes = httpClient.sendPostRequest("http://localhost:8880/test", JSApiHttpClient.RESPTYPE_JSON, params, "json"); System.out.println("httpRes: " + httpRes); assertEquals("value1", ((HashMap)((HashMap)httpRes.get(1)).get("req_params")).get("param1")); assertEquals(42l, ((HashMap)((HashMap)httpRes.get(1)).get("req_params")).get("param2")); httpServer.stop(); }
@Test public void jsAddPermission() throws Exception { TestSpace testSpace = prepareTestSpace(TestKeys.privateKey(0)); testSpace.nodes.forEach(m -> m.config.setIsFreeRegistrationsAllowedFromYaml(true)); KeyAddress k0 = TestKeys.publicKey(0).getShortAddress(); Contract contract = new Contract(TestKeys.privateKey(0)); contract.getStateData().set("testval", 3); String js = ""; js += "print('addPermission');"; js += "var simpleRole = jsApi.getRoleBuilder().createSimpleRole('owner', '"+k0.toString()+"');"; js += "var changeNumberPermission = jsApi.getPermissionBuilder().createChangeNumberPermission(simpleRole, " + "{field_name: 'testval', min_value: 3, max_value: 80, min_step: 1, max_step: 3}" + ");"; js += "jsApi.getCurrentContract().addPermission(changeNumberPermission);"; contract.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters()); contract.execJS(js.getBytes()); contract.seal(); ItemResult ir = testSpace.client.register(contract.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, ir.state); Contract newRev = contract.createRevision(); newRev.addSignerKey(TestKeys.privateKey(0)); newRev.getStateData().set("testval", 5); newRev.seal(); ir = testSpace.client.register(newRev.getPackedTransaction(), 5000); assertEquals(ItemState.APPROVED, ir.state); testSpace.nodes.forEach(m -> m.shutdown()); }
@Test public void testSharedFolders_read() throws Exception { String f1content = "f1 content"; String f2content = "f2 content"; String f3content = "f3 content"; List<String> sharedFolders = prepareSharedFoldersForTest(f1content, f2content, f3content); Contract contract = new Contract(TestKeys.privateKey(0)); String js = ""; js += "print('testSharedFolders_read');"; js += "function bin2string(array){var result = '';for(var i = 0; i < array.length; ++i){result+=(String.fromCharCode(array[i]));}return result;}"; js += "var file1Content = jsApi.getSharedFolders().readAllBytes('f1.txt');"; js += "var file2Content = jsApi.getSharedFolders().readAllBytes('folder/f2.txt');"; js += "print('file1Content: ' + bin2string(file1Content));"; js += "print('file2Content: ' + bin2string(file2Content));"; js += "result = [bin2string(file1Content), bin2string(file2Content)];"; JSApiExecOptions execOptions = new JSApiExecOptions(); execOptions.sharedFolders.addAll(sharedFolders); contract.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters()); contract.seal(); ScriptObjectMirror res = (ScriptObjectMirror)contract.execJS(execOptions, js.getBytes()); assertEquals(f1content, res.get("0")); assertEquals(f2content, res.get("1")); }
@Test public void testSharedFolders_rewrite() throws Exception { String f1content = "f1 content"; String f1contentUpdated = "f1 content updated"; String f2content = "f2 content"; String f2contentUpdated = "f2 content updated"; String f3content = "f3 content"; List<String> sharedFolders = prepareSharedFoldersForTest(f1content, f2content, f3content); Contract contract = new Contract(TestKeys.privateKey(0)); String js = ""; js += "print('testSharedFolders_rewrite');"; js += "jsApi.getSharedFolders().rewriteExistingFile('f1.txt', jsApi.string2bin('"+f1contentUpdated+"'));"; js += "jsApi.getSharedFolders().rewriteExistingFile('folder/f2.txt', jsApi.string2bin('"+f2contentUpdated+"'));"; JSApiExecOptions execOptions = new JSApiExecOptions(); execOptions.sharedFolders.addAll(sharedFolders); contract.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters()); contract.seal(); contract.execJS(execOptions, js.getBytes()); String f1readed = new String(Files.readAllBytes(Paths.get(sharedFolders.get(0) + "/f1.txt"))); String f2readed = new String(Files.readAllBytes(Paths.get(sharedFolders.get(1) + "/folder/f2.txt"))); assertNotEquals(f1content, f1readed); assertNotEquals(f2content, f2readed); assertEquals(f1contentUpdated, f1readed); assertEquals(f2contentUpdated, f2readed); }
@Test public void testSharedFolders_restrictedPath() throws Exception { String f1content = "f1 content"; String f2content = "f2 content"; String f3content = "f3 content"; List<String> sharedFolders = prepareSharedFoldersForTest(f1content, f2content, f3content); Contract contract = new Contract(TestKeys.privateKey(0)); String js = ""; js += "print('testSharedFolders_restrictedPath');"; js += "function bin2string(array){var result = '';for(var i = 0; i < array.length; ++i){result+=(String.fromCharCode(array[i]));}return result;}"; js += "try {"; js += " var file3Content = jsApi.getSharedFolders().readAllBytes('../f3.txt');"; js += " print('file3Content: ' + bin2string(file3Content));"; js += "} catch (err) {"; js += " result = err;"; js += "}"; JSApiExecOptions execOptions = new JSApiExecOptions(); execOptions.sharedFolders.addAll(sharedFolders); contract.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters()); contract.seal(); IOException res = (IOException) contract.execJS(execOptions, js.getBytes()); System.out.println("IOException from js: " + res); assertTrue(res.toString().contains("file '../f3.txt' not found in shared folders")); }
@Test public void twoJsInContract() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); String js1d = "var result = 'return_from_script_1d';"; String js2d = "var result = 'return_from_script_2d';"; String js1s = "var result = 'return_from_script_1s';"; String js2s = "var result = 'return_from_script_2s';"; contract.getDefinition().setJS(js1d.getBytes(), "js1d.js", new JSApiScriptParameters()); contract.getDefinition().setJS(js2d.getBytes(), "js2d.js", new JSApiScriptParameters()); contract.getState().setJS(js1s.getBytes(), "js1s.js", new JSApiScriptParameters()); contract.getState().setJS(js2s.getBytes(), "js2s.js", new JSApiScriptParameters()); contract.seal(); assertEquals("return_from_script_1d", contract.execJS(js1d.getBytes())); assertEquals("return_from_script_2d", contract.execJS(js2d.getBytes())); assertEquals("return_from_script_1s", contract.execJS(js1s.getBytes())); assertEquals("return_from_script_2s", contract.execJS(js2s.getBytes())); try { contract.execJS("print('another script');".getBytes()); assert false; } catch (IllegalArgumentException e) { System.out.println(e); assert true; } }
@Test public void jsInStateAndDefinition() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.setOwnerKeys(TestKeys.publicKey(1), TestKeys.publicKey(2), TestKeys.publicKey(3)); contract.setCreatorKeys(TestKeys.publicKey(4), TestKeys.publicKey(5).getLongAddress()); String jsDefinitionA = "print('hello world from definition A'); result = 'dA';"; String jsDefinitionB = "print('hello world from definition B'); result = 'dB';"; String jsStateA = "print('hello world from state A'); result = 'sA';"; String jsStateB = "print('hello world from state B'); result = 'sB';"; contract.getDefinition().setJS(jsDefinitionA.getBytes(), "script1.js", new JSApiScriptParameters(), true); contract.getDefinition().setJS(jsDefinitionB.getBytes(), "script2.js", new JSApiScriptParameters(), true); contract.getState().setJS(jsStateA.getBytes(), "script3.js", new JSApiScriptParameters(), true); contract.getState().setJS(jsStateB.getBytes(), "script4.js", new JSApiScriptParameters(), true); contract.seal(); String res1 = (String)contract.execJSByName("script1.js"); String res2 = (String)contract.execJSByName("script2.js"); String res3 = (String)contract.execJSByName("script3.js"); String res4 = (String)contract.execJSByName("script4.js"); assertEquals("dA", res1); assertEquals("dB", res2); assertEquals("sA", res3); assertEquals("sB", res4); }
@Test public void testTransactionalAccess() throws Exception { String t1value = "t1value"; String t2value = "t2value"; Contract contract = new Contract(TestKeys.privateKey(0)); contract.getTransactionalData().set("t1", t1value); String js = ""; js += "print('testTransactionalAccess');"; js += "var t1 = jsApi.getCurrentContract().getTransactionalDataField('t1');"; js += "print('t1: ' + t1);"; js += "jsApi.getCurrentContract().setTransactionalDataField('t2', '"+t2value+"');"; js += "result = t1;"; contract.getState().setJS(js.getBytes(), "client script.js", new JSApiScriptParameters()); contract.seal(); String res = (String)contract.execJS(js.getBytes()); assertEquals(t1value, res); assertEquals(t2value, contract.getTransactionalData().getStringOrThrow("t2")); System.out.println("t2: " + contract.getTransactionalData().getStringOrThrow("t2")); }
@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()); }
public void setJS(byte[] jsFileContent, String jsFileName, JSApiScriptParameters scriptParameters) { setJS(jsFileContent, jsFileName, scriptParameters, false); }