├── .npmignore ├── .prettierrc ├── template ├── state.json ├── blockchain.json └── message.json ├── test ├── init.json ├── scilla │ ├── chain-call-balance-c.scilla │ ├── chain-call-balance-b.scilla │ ├── chain-call-balance-a.scilla │ └── mining.scilla ├── scripts │ ├── HelloWorld.scilla │ └── testblockchain.js ├── account-fixtures.json ├── sample-export.json ├── mining.test.js ├── multicontract.test.js └── server.test.js ├── .travis.yml ├── src ├── components │ ├── scilla │ │ ├── stdlib │ │ │ ├── PairUtils.scillib │ │ │ ├── BoolUtils.scillib │ │ │ ├── NatUtils.scillib │ │ │ ├── IntUtils.scillib │ │ │ └── ListUtils.scillib │ │ └── scilla.js │ ├── blockchain.js │ ├── CustomErrors.js │ └── wallet │ │ └── wallet.js ├── server.js ├── argv.js ├── config.js ├── provider.js ├── utilities.js ├── app.js └── logic.js ├── .github ├── CODEOWNERS └── PULL_REQUEST_TEMPLATE.md ├── .eslintrc.json ├── jest.config.js ├── package.json ├── .gitignore ├── README.md └── LICENSE /.npmignore: -------------------------------------------------------------------------------- 1 | .npmignore 2 | .vscode 3 | .travis.yml 4 | .eslintrc.js 5 | *.log 6 | data 7 | ROADMAP 8 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 100, 3 | "parser": "flow", 4 | "semi": true, 5 | "trailingComma": "es5" 6 | } -------------------------------------------------------------------------------- /template/state.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "vname": "_balance", 4 | "type" : "Uint128", 5 | "value": "0" 6 | } 7 | ] -------------------------------------------------------------------------------- /template/blockchain.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "vname": "BLOCKNUMBER", 4 | "type": "BNum", 5 | "value": "100" 6 | } 7 | ] -------------------------------------------------------------------------------- /test/init.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "vname" : "owner", 4 | "type" : "Address", 5 | "value" : "0x1234567890123456789012345678901234567890" 6 | } 7 | ] 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | sudo: true 3 | dist: trusty 4 | node_js: 5 | - 10 6 | install: 7 | - npm install 8 | script: 9 | - npm run test 10 | branches: 11 | only: 12 | - /.*/ 13 | cache: 14 | directories: 15 | - $HOME/.npm 16 | -------------------------------------------------------------------------------- /template/message.json: -------------------------------------------------------------------------------- 1 | { 2 | "_tag": "setHello", 3 | "_amount": "0", 4 | "_sender" : "0x1234567890123456789012345678901234567890", 5 | "params": [ 6 | { 7 | "vname": "msg", 8 | "type": "String", 9 | "value": "Hello World" 10 | } 11 | ] 12 | } -------------------------------------------------------------------------------- /src/components/scilla/stdlib/PairUtils.scillib: -------------------------------------------------------------------------------- 1 | library PairUtils 2 | 3 | let fst = 4 | tfun 'A => 5 | tfun 'B => 6 | fun (p : Pair ('A) ('B)) => 7 | match p with 8 | | Pair a b => a 9 | end 10 | 11 | let snd = 12 | tfun 'A => 13 | tfun 'B => 14 | fun (p : Pair ('A) ('B)) => 15 | match p with 16 | | Pair a b => b 17 | end 18 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | ########## Global owners ########## 2 | 3 | * @edisonljh @AmritKumar 4 | 5 | ########## Source Code ########## 6 | 7 | *.js @edisonljh 8 | 9 | ########## Documentation ########## 10 | 11 | /README.md @edisonljh @evesnow91 @AmritKumar 12 | 13 | ########## GitHub metadata, including this file ########## 14 | 15 | /.github/ @edisonljh @AmritKumar 16 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | 4 | 5 | 6 | ## Review Suggestion 7 | 8 | 9 | 10 | ## Status 11 | 12 | ### Implementation 13 | 14 | - [ ] **ready for review** 15 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "rules": { 4 | "no-console": 0, 5 | "no-underscore-dangle": 0, 6 | "no-return-assign": 0, 7 | "no-extend-native": 0, 8 | "no-lonely-if": 0, 9 | "prefer-destructuring": 0, 10 | "no-multi-assign": 0, 11 | "import/no-extraneous-dependencies": 0 12 | }, 13 | "env": { 14 | "es6": true, 15 | "node": true 16 | }, 17 | "extends": [ 18 | "airbnb-base" 19 | ], 20 | "overrides": [ 21 | { 22 | "files": ["*.test.js"], 23 | "env": { 24 | "jest": true 25 | } 26 | } 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /test/scilla/chain-call-balance-c.scilla: -------------------------------------------------------------------------------- 1 | scilla_version 0 2 | 3 | library Test 4 | 5 | let one_msg = 6 | fun (msg : Message) => 7 | let nil_msg = Nil {Message} in 8 | Cons {Message} msg nil_msg 9 | 10 | contract Test 11 | () 12 | 13 | field last_amount: Uint128 = Uint128 0 14 | 15 | (* Do not accept _amount. Emit event. *) 16 | transition noAcceptC () 17 | last_amount := _amount; 18 | 19 | e = {_eventname: "C"}; 20 | event e 21 | end 22 | 23 | transition simplyAccept () 24 | accept; 25 | 26 | last_amount := _amount; 27 | 28 | e = {_eventname: "C"}; 29 | event e 30 | end 31 | -------------------------------------------------------------------------------- /test/scilla/chain-call-balance-b.scilla: -------------------------------------------------------------------------------- 1 | scilla_version 0 2 | 3 | library Test 4 | 5 | let one_msg = 6 | fun (msg : Message) => 7 | let nil_msg = Nil {Message} in 8 | Cons {Message} msg nil_msg 9 | 10 | contract Test 11 | () 12 | 13 | field last_amount: Uint128 = Uint128 0 14 | 15 | (* Call contrC. Also pass on _amount. Emit event. *) 16 | transition acceptBAndTransferToC (addrC : ByStr20) 17 | accept; 18 | 19 | last_amount := _amount; 20 | 21 | e = {_eventname: "B"}; 22 | event e; 23 | 24 | msg = { _tag : "simplyAccept"; _amount : _amount; _recipient : addrC }; 25 | msgs = one_msg msg; 26 | send msgs 27 | end 28 | 29 | transition simplyAccept () 30 | accept; 31 | 32 | last_amount := _amount; 33 | 34 | e = {_eventname: "B"}; 35 | event e 36 | end 37 | -------------------------------------------------------------------------------- /src/components/scilla/stdlib/BoolUtils.scillib: -------------------------------------------------------------------------------- 1 | library BoolUtils 2 | 3 | let andb = 4 | fun (b : Bool) => 5 | fun (c : Bool) => 6 | match b with 7 | | False => False 8 | | True => 9 | match c with 10 | | False => False 11 | | True => True 12 | end 13 | end 14 | 15 | let orb = 16 | fun (b : Bool) => fun (c : Bool) => 17 | match b with 18 | | True => True 19 | | False => 20 | match c with 21 | | False => False 22 | | True => True 23 | end 24 | end 25 | 26 | let negb = fun (b : Bool) => 27 | match b with 28 | | True => False 29 | | False => True 30 | end 31 | 32 | let bool_to_string = fun (flag: Bool) => 33 | match flag with 34 | | True => "True" 35 | | False => "False" 36 | end 37 | -------------------------------------------------------------------------------- /test/scilla/chain-call-balance-a.scilla: -------------------------------------------------------------------------------- 1 | scilla_version 0 2 | 3 | library Test 4 | 5 | let one_msg = 6 | fun (msg : Message) => 7 | let nil_msg = Nil {Message} in 8 | Cons {Message} msg nil_msg 9 | 10 | contract Test 11 | () 12 | 13 | field last_amount: Uint128 = Uint128 0 14 | 15 | (* Call contrB, passing contrC to it. Also pass on _amount. Emit event. *) 16 | transition acceptAAndTransferToBAndCallC (addrB : ByStr20, addrC : ByStr20) 17 | accept; 18 | 19 | last_amount := _amount; 20 | 21 | e = {_eventname: "A"}; 22 | event e; 23 | 24 | msg = { _tag : "acceptBAndTransferToC"; _amount : _amount; _recipient : addrB; addrC : addrC }; 25 | msgs = one_msg msg; 26 | send msgs 27 | end 28 | 29 | transition simplyAccept () 30 | accept; 31 | 32 | last_amount := _amount; 33 | 34 | e = {_eventname: "B"}; 35 | event e 36 | end 37 | -------------------------------------------------------------------------------- /test/scilla/mining.scilla: -------------------------------------------------------------------------------- 1 | scilla_version 0 2 | 3 | import BoolUtils 4 | 5 | library MiningTest 6 | 7 | let success_block_count = Uint32 3 8 | 9 | (* Contract starts timer based on block number. *) 10 | contract MiningTest 11 | () 12 | 13 | field timer_start: BNum = BNum 0 14 | 15 | transition startTimer () 16 | accept; 17 | blk <- & BLOCKNUMBER; 18 | timer_start := blk 19 | end 20 | 21 | (* Emit "success" if timer is complete. Emit "pending" if not. *) 22 | transition checkTimer () 23 | accept; 24 | blk <- & BLOCKNUMBER; 25 | start_blk <- timer_start; 26 | success_blk = builtin badd start_blk success_block_count; 27 | success_is_current = builtin eq success_blk blk; 28 | success_is_passed = builtin blt success_blk blk; 29 | 30 | is_success = orb success_is_current success_is_passed; 31 | match is_success with 32 | | False => 33 | e = {_eventname: "pending"}; 34 | event e 35 | | True => 36 | e = {_eventname: "success"}; 37 | event e 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /src/components/blockchain.js: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of kaya. 3 | Copyright (c) 2018 - present Zilliqa Research Pte. Ltd. 4 | 5 | kaya is free software: you can redistribute it and/or modify it under the 6 | terms of the GNU General Public License as published by the Free Software 7 | Foundation, either version 3 of the License, or (at your option) any later 8 | version. 9 | 10 | kaya is distributed in the hope that it will be useful, but WITHOUT ANY 11 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 12 | A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License along with 15 | kaya. If not, see . 16 | */ 17 | 18 | const config = require('../config'); 19 | 20 | let bnum = config.blockchain.blockStart; 21 | 22 | function addBnum() { 23 | bnum += 1; 24 | return bnum; 25 | } 26 | 27 | // blockinterval is duration for each block number increment 28 | if (config.blockchain.blockInterval > 0) setInterval(addBnum, config.blockchain.blockInterval); 29 | 30 | module.exports = { 31 | getBlockNum: () => bnum, 32 | addBnum, 33 | }; 34 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | This file is part of kaya. 3 | Copyright (c) 2018 - present Zilliqa Research Pte. Ltd. 4 | 5 | kaya is free software: you can redistribute it and/or modify it under the 6 | terms of the GNU General Public License as published by the Free Software 7 | Foundation, either version 3 of the License, or (at your option) any later 8 | version. 9 | 10 | kaya is distributed in the hope that it will be useful, but WITHOUT ANY 11 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 12 | A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License along with 15 | kaya. If not, see . 16 | **/ 17 | 18 | const config = { 19 | verbose: true, 20 | collectCoverage: true, 21 | collectCoverageFrom: [ 22 | '**/*.{js,jsx}', 23 | '!**/node_modules/**', 24 | '!**/vendor/**', 25 | '!**/coverage/**', 26 | '!**/test/**', 27 | ], 28 | 29 | // coverageThreshold: { 30 | // "global": { 31 | // "branches": 80, 32 | // "functions": 80, 33 | // "lines": 80, 34 | // "statements": 80 35 | // } 36 | // } 37 | }; 38 | module.exports = config; 39 | -------------------------------------------------------------------------------- /src/components/CustomErrors.js: -------------------------------------------------------------------------------- 1 | const zCore = require('@zilliqa-js/core'); 2 | 3 | const errorCodes = zCore.RPCErrorCode; 4 | 5 | class InterpreterError extends Error { 6 | constructor(message) { 7 | super(message); 8 | this.name = 'InterpreterError'; 9 | } 10 | } 11 | 12 | class BalanceError extends Error { 13 | constructor(message) { 14 | super(message); 15 | this.name = 'BalanceError'; 16 | this.code = errorCodes.RPC_INVALID_ADDRESS_OR_KEY; 17 | this.data = null; 18 | } 19 | } 20 | 21 | // Cast all RPC errors to this error class 22 | // Reference: https://github.com/Zilliqa/Zilliqa/blob/master/src/libServer/Server.cpp 23 | class RPCError extends Error { 24 | constructor(message, errCode, errData) { 25 | super(message); 26 | this.name = 'RPCError'; 27 | this.code = errCode; 28 | this.data = errData; 29 | } 30 | } 31 | 32 | class MultiContractError extends Error { 33 | constructor(message) { 34 | super(message); 35 | this.name = 'MulticontractError'; 36 | } 37 | } 38 | 39 | class InsufficientGasError extends Error { 40 | constructor(message) { 41 | super(message); 42 | this.name = 'InsufficientGasError'; 43 | } 44 | } 45 | 46 | module.exports = { 47 | InterpreterError, 48 | BalanceError, 49 | MultiContractError, 50 | InsufficientGasError, 51 | RPCError, 52 | }; 53 | -------------------------------------------------------------------------------- /test/scripts/HelloWorld.scilla: -------------------------------------------------------------------------------- 1 | scilla_version 0 2 | 3 | (* HelloWorld contract *) 4 | 5 | import ListUtils 6 | 7 | (***************************************************) 8 | (* Associated library *) 9 | (***************************************************) 10 | library HelloWorld 11 | 12 | let one_msg = 13 | fun (msg : Message) => 14 | let nil_msg = Nil {Message} in 15 | Cons {Message} msg nil_msg 16 | 17 | let not_owner_code = Int32 1 18 | let set_hello_code = Int32 2 19 | 20 | (***************************************************) 21 | (* The contract definition *) 22 | (***************************************************) 23 | 24 | contract HelloWorld 25 | (owner: ByStr20) 26 | 27 | field welcome_msg : String = "" 28 | 29 | transition setHello (msg : String) 30 | is_owner = builtin eq owner _sender; 31 | match is_owner with 32 | | False => 33 | e = {_eventname : "setHello()"; code : not_owner_code}; 34 | event e 35 | | True => 36 | welcome_msg := msg; 37 | e = {_eventname : "setHello()"; code : set_hello_code}; 38 | event e 39 | end 40 | end 41 | 42 | 43 | transition getHello () 44 | r <- welcome_msg; 45 | e = {_eventname: "getHello()"; msg: r}; 46 | event e 47 | end 48 | 49 | transition multipleMsgs() 50 | msg1 = {_tag : ""; _recipient : _sender; _amount : Uint128 0}; 51 | msg2 = {_tag : ""; _recipient : _sender; _amount : Uint128 0}; 52 | msgs1 = one_msg msg1; 53 | msgs2 = Cons {Message} msg2 msgs1; 54 | send msgs2 55 | end 56 | 57 | transition contrAddr() 58 | msg1 = {_eventname : "ContractAddress"; addr : _this_address }; 59 | event msg1 60 | end 61 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "kaya-cli", 3 | "version": "0.2.9", 4 | "description": "Zilliqa's RPC Server", 5 | "main": "src/server.js", 6 | "scripts": { 7 | "test": "jest -c jest.config.js", 8 | "dev": "cross-env NODE_ENV=dev node src/server.js", 9 | "start": "node src/server.js", 10 | "start:fixtures": "node src/server.js --f test/account-fixtures.json", 11 | "debug": "node src/server.js -v", 12 | "debug:fixtures": "node src/server.js -f test/account-fixtures.json -v" 13 | }, 14 | "author": "Edison Lim", 15 | "license": "GPL-3.0-or-later", 16 | "repository": { 17 | "type": "git", 18 | "url": "https://github.com/Zilliqa/kaya" 19 | }, 20 | "bin": { 21 | "kaya-cli": "./src/server.js" 22 | }, 23 | "devDependencies": { 24 | "babel-cli": "^6.26.0", 25 | "babel-preset-env": "^1.7.0", 26 | "cross-env": "^5.2.0", 27 | "eslint": "^5.15.0", 28 | "eslint-config-airbnb-base": "^13.1.0", 29 | "eslint-config-prettier": "^4.1.0", 30 | "eslint-plugin-import": "^2.14.0", 31 | "eslint-plugin-prettier": "^3.0.1", 32 | "jest": "^24.1.0", 33 | "prettier": "^1.14.2", 34 | "superagent": "^4.1.0", 35 | "supertest": "^3.1.0", 36 | "tslib": "^1.9.3" 37 | }, 38 | "dependencies": { 39 | "@zilliqa-js/zilliqa": "^0.8.1", 40 | "bn.js": "^4.11.8", 41 | "body-parser": "^1.18.3", 42 | "colors": "^1.3.0", 43 | "cors": "^2.8.4", 44 | "es6-promise": "^4.2.4", 45 | "express": "^4.16.3", 46 | "glob": "^7.1.3", 47 | "hash.js": "^1.1.5", 48 | "isomorphic-fetch": "^2.2.1", 49 | "moment": "^2.22.2", 50 | "node-fs": "^0.1.7", 51 | "request": "^2.88.0", 52 | "request-promise": "^4.2.2", 53 | "rimraf": "^2.6.2", 54 | "yargs": "^13.2.1" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # parcel-bundler cache (https://parceljs.org/) 61 | .cache 62 | 63 | # next.js build output 64 | .next 65 | 66 | # nuxt.js build output 67 | .nuxt 68 | 69 | # vuepress build output 70 | .vuepress/dist 71 | 72 | # Serverless directories 73 | .serverless 74 | 75 | # Custom files 76 | saved/ 77 | tmp/ 78 | data/ 79 | *scilla-runner 80 | *scilla-checker 81 | 82 | # Swap 83 | [._]*.s[a-v][a-z] 84 | [._]*.sw[a-p] 85 | [._]s[a-rt-v][a-z] 86 | [._]ss[a-gi-z] 87 | [._]sw[a-p] 88 | 89 | # # Session 90 | Session.vim 91 | 92 | # Temporary 93 | .netrwhist 94 | *~ 95 | # Auto-generated tag files 96 | tags 97 | # Persistent undo 98 | [._]*.un~ 99 | -------------------------------------------------------------------------------- /src/server.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /* 3 | This file is part of kaya. 4 | Copyright (c) 2018 - present Zilliqa Research Pte. Ltd. 5 | 6 | kaya is free software: you can redistribute it and/or modify it under the 7 | terms of the GNU General Public License as published by the Free Software 8 | Foundation, either version 3 of the License, or (at your option) any later 9 | version. 10 | 11 | kaya is distributed in the hope that it will be useful, but WITHOUT ANY 12 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 13 | A PARTICULAR PURPOSE. See the GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License along with 16 | kaya. If not, see . 17 | */ 18 | 19 | const yargs = require('yargs'); 20 | 21 | const config = require('./config'); 22 | const initArgv = require('./argv'); 23 | 24 | let serverPort; 25 | let argv; 26 | if (process.env.NODE_ENV !== 'test') { 27 | argv = initArgv(yargs).argv; 28 | serverPort = argv.p ? argv.p : config.port; 29 | } else { 30 | console.log('-------- TEST MODE -------------'); 31 | argv = config.testconfigs.args; 32 | } 33 | 34 | /* Information about Kaya RPC Server */ 35 | 36 | console.log(`ZILLIQA KAYA RPC SERVER (ver: ${config.version})`); 37 | console.log(`Server listening on 127.0.0.1:${serverPort}`); 38 | 39 | const app = require('./app'); 40 | 41 | const server = app.expressjs.listen(serverPort, (err) => { 42 | if (err) { 43 | process.exit(1); 44 | } 45 | }); 46 | 47 | // Listener for connections opening on the server 48 | let connections = []; 49 | server.on('connection', (connection) => { 50 | connections.push(connection); 51 | connection.on( 52 | 'close', 53 | () => (connections = connections.filter(curr => curr !== connection)), 54 | ); 55 | }); 56 | -------------------------------------------------------------------------------- /src/components/scilla/stdlib/NatUtils.scillib: -------------------------------------------------------------------------------- 1 | library NatUtils 2 | 3 | (* Nat -> Option Nat *) 4 | let nat_prev = fun (n: Nat) => 5 | match n with 6 | | Succ n1 => Some {Nat} n1 7 | | Zero => None {Nat} 8 | end 9 | 10 | (* Nat -> Bool *) 11 | let is_some_zero = fun (n: Nat) => 12 | match n with 13 | | Zero => True 14 | | _ => False 15 | end 16 | 17 | (* Nat -> Nat -> Bool *) 18 | let nat_eq = fun (n : Nat) => fun (m : Nat) => 19 | let z = Some {Nat} m in 20 | let f = fun (res : Option Nat) => fun (n : Nat) => 21 | match res with 22 | | None => None {Nat} 23 | | Some m1 => nat_prev m1 24 | end in 25 | let folder = @nat_fold (Option Nat) in 26 | let e = folder f z n in 27 | match e with 28 | | Some Zero => True 29 | | _ => False 30 | end 31 | 32 | (* Nat -> Uint32 *) 33 | let nat_to_int = 34 | fun (n : Nat) => 35 | let f = 36 | fun (z : Uint32) => 37 | fun (n : Nat) => 38 | match n with 39 | | _ => 40 | let one_int = Uint32 1 in 41 | builtin add z one_int 42 | end 43 | in 44 | let folder = @nat_fold Uint32 in 45 | let zero_int = Uint32 0 in 46 | folder f zero_int n 47 | 48 | let uint32_to_nat_helper = 49 | fun (m : Option Uint32) => 50 | match m with 51 | | Some x => 52 | let res = builtin to_nat x in 53 | Some {Nat} res 54 | | None => None {Nat} 55 | end 56 | 57 | (* UintX/IntX -> Option Nat *) 58 | let uint32_to_nat = 59 | fun (n : Uint32) => 60 | let m = builtin to_uint32 n in 61 | uint32_to_nat_helper m 62 | 63 | let uint64_to_nat = 64 | fun (n : Uint64) => 65 | let m = builtin to_uint32 n in 66 | uint32_to_nat_helper m 67 | 68 | let uint128_to_nat = 69 | fun (n : Uint128) => 70 | let m = builtin to_uint32 n in 71 | uint32_to_nat_helper m 72 | 73 | let int32_to_nat = 74 | fun (n : Int32) => 75 | let m = builtin to_uint32 n in 76 | uint32_to_nat_helper m 77 | 78 | let int64_to_nat = 79 | fun (n : Int64) => 80 | let m = builtin to_uint32 n in 81 | uint32_to_nat_helper m 82 | 83 | let int128_to_nat = 84 | fun (n : Int128) => 85 | let m = builtin to_uint32 n in 86 | uint32_to_nat_helper m 87 | 88 | -------------------------------------------------------------------------------- /test/account-fixtures.json: -------------------------------------------------------------------------------- 1 | { 2 | "7bb3b0e8a59f3f61d9bff038f4aeb42cae2ecce8": { 3 | "privateKey": "db11cfa086b92497c8ed5a4cc6edb3a5bfe3a640c43ffb9fc6aa0873c56f2ee3", 4 | "amount": "1000000000000000000", 5 | "nonce": 0 6 | }, 7 | "d90f2e538ce0df89c8273cad3b63ec44a3c4ed82": { 8 | "privateKey": "e53d1c3edaffc7a7bab5418eb836cf75819a82872b4a1a0f1c7fcf5c3e020b89", 9 | "amount": "1000000000000000000", 10 | "nonce": 0 11 | }, 12 | "381f4008505e940ad7681ec3468a719060caf796": { 13 | "privateKey": "d96e9eb5b782a80ea153c937fa83e5948485fbfc8b7e7c069d7b914dbc350aba", 14 | "amount": "1000000000000000000", 15 | "nonce": 0 16 | }, 17 | "b028055ea3bc78d759d10663da40d171dec992aa": { 18 | "privateKey": "e7f59a4beb997a02a13e0d5e025b39a6f0adc64d37bb1e6a849a4863b4680411", 19 | "amount": "1000000000000000000", 20 | "nonce": 0 21 | }, 22 | "f6dad9e193fa2959a849b81caf9cb6ecde466771": { 23 | "privateKey": "589417286a3213dceb37f8f89bd164c3505a4cec9200c61f7c6db13a30a71b45", 24 | "amount": "1000000000000000000", 25 | "nonce": 0 26 | }, 27 | "10200e3da08ee88729469d6eabc055cb225821e7": { 28 | "privateKey": "5430365143ce0154b682301d0ab731897221906a7054bbf5bd83c7663a6cbc40", 29 | "amount": "1000000000000000000", 30 | "nonce": 0 31 | }, 32 | "ac941274c3b6a50203cc5e7939b7dad9f32a0c12": { 33 | "privateKey": "1080d2cca18ace8225354ac021f9977404cee46f1d12e9981af8c36322eac1a4", 34 | "amount": "1000000000000000000", 35 | "nonce": 0 36 | }, 37 | "ec902fe17d90203d0bddd943d97b29576ece3177": { 38 | "privateKey": "254d9924fc1dcdca44ce92d80255c6a0bb690f867abde80e626fbfef4d357004", 39 | "amount": "1000000000000000000", 40 | "nonce": 0 41 | }, 42 | "c2035715831ab100ec42e562ce341b834bed1f4c": { 43 | "privateKey": "b8fc4e270594d87d3f728d0873a38fb0896ea83bd6f96b4f3c9ff0a29122efe4", 44 | "amount": "1000000000000000000", 45 | "nonce": 0 46 | }, 47 | "6cd3667ba79310837e33f0aecbe13688a6cbca32": { 48 | "privateKey": "b87f4ba7dcd6e60f2cca8352c89904e3993c5b2b0b608d255002edcda6374de4", 49 | "amount": "1000000000000000000", 50 | "nonce": 0 51 | } 52 | } -------------------------------------------------------------------------------- /src/argv.js: -------------------------------------------------------------------------------- 1 | const config = require('./config'); 2 | 3 | module.exports = exports = (yargs) => { 4 | const yargsOptions = yargs 5 | .strict() 6 | .usage('Usage: node $0 [options]') 7 | .example('node server.js -f -v', 'Starts server based on predefined wallet files with verbose mode') 8 | .option('p', { 9 | group: 'Network', 10 | alias: 'port', 11 | type: 'number', 12 | default: config.port, 13 | describe: 'Port number to listen', 14 | }) 15 | .option('d', { 16 | group: 'Blockchain', 17 | alias: 'data', 18 | type: 'string', 19 | default: config.dataPath, 20 | describe: 'Relative path where state data will be stored. Creates directory if path does not exists', 21 | }) 22 | .option('r', { 23 | group: 'Blockchain', 24 | alias: 'remote', 25 | type: 'boolean', 26 | default: config.scilla.remote, 27 | describe: 'Option to use remote interpreter or local interpreter. True = remote', 28 | }) 29 | .option('f', { 30 | group: 'Other', 31 | alias: 'fixtures', 32 | type: 'string', 33 | default: null, 34 | describe: 'Path to JSON file which contains the private keys to predefined set of wallets', 35 | }) 36 | .option('n', { 37 | group: 'Other', 38 | alias: 'numAccounts', 39 | type: 'number', 40 | default: config.wallet.numAccounts, 41 | describe: 'Number of accounts to load at start up. Only used if fixtures file is not defined.', 42 | }) 43 | .option('l', { 44 | group: 'Other', 45 | alias: 'load', 46 | type: 'string', 47 | default: null, 48 | describe: 'Load data files from a path', 49 | }) 50 | .option('s', { 51 | group: 'Other', 52 | alias: 'save', 53 | type: 'boolean', 54 | default: null, 55 | describe: 'Saves data by the end of the session', 56 | }) 57 | .option('v', { 58 | group: 'Other', 59 | alias: 'verbose', 60 | type: 'boolean', 61 | default: false, 62 | describe: 'Log messages to console to stdout', 63 | }) 64 | .showHelpOnFail(false, 'Specify --help for available options') 65 | .help('help') 66 | .alias('help', '?') 67 | .version(config.version); 68 | 69 | return yargsOptions; 70 | }; 71 | -------------------------------------------------------------------------------- /test/sample-export.json: -------------------------------------------------------------------------------- 1 | { 2 | "transactions": {}, 3 | "createdContractsByUsers": {}, 4 | "accounts": { 5 | "7bb3b0e8a59f3f61d9bff038f4aeb42cae2ecce8": { 6 | "privateKey": "db11cfa086b92497c8ed5a4cc6edb3a5bfe3a640c43ffb9fc6aa0873c56f2ee3", 7 | "amount": 100000, 8 | "nonce": 0 9 | }, 10 | "d90f2e538ce0df89c8273cad3b63ec44a3c4ed82": { 11 | "privateKey": "e53d1c3edaffc7a7bab5418eb836cf75819a82872b4a1a0f1c7fcf5c3e020b89", 12 | "amount": 100000, 13 | "nonce": 0 14 | }, 15 | "c2035715831ab100ec42e562ce341b834bed1f4c": { 16 | "privateKey": "b8fc4e270594d87d3f728d0873a38fb0896ea83bd6f96b4f3c9ff0a29122efe4", 17 | "amount": 100000, 18 | "nonce": 0 19 | }, 20 | "6cd3667ba79310837e33f0aecbe13688a6cbca32": { 21 | "privateKey": "b87f4ba7dcd6e60f2cca8352c89904e3993c5b2b0b608d255002edcda6374de4", 22 | "amount": 50000, 23 | "nonce": 0 24 | } 25 | }, 26 | "states": { 27 | "cef48d2ec4086bd5799b659261948daab02b760d_state.json": [ 28 | { 29 | "vname": "_balance", 30 | "type": "Uint128", 31 | "value": "0" 32 | } 33 | ] 34 | }, 35 | "init": { 36 | "cef48d2ec4086bd5799b659261948daab02b760d_init.json": [ 37 | { 38 | "vname": "owner", 39 | "type": "ByStr20", 40 | "value": "0x7bb3b0e8a59f3f61d9bff038f4aeb42cae2ecce8" 41 | }, 42 | { 43 | "vname": "_creation_block", 44 | "type": "BNum", 45 | "value": "100" 46 | } 47 | ] 48 | }, 49 | "codes": { 50 | "cef48d2ec4086bd5799b659261948daab02b760d_code.scilla": " import ListUtils library HelloWorld let one_msg = fun (msg : Message) => let nil_msg = Nil {Message} in Cons {Message} msg nil_msg let not_owner_code = Int32 1 let set_hello_code = Int32 2 contract HelloWorld (owner: ByStr20) field welcome_msg : String = \"\" transition setHello (msg : String) is_owner = builtin eq owner _sender; match is_owner with | False => msg = {_tag : \"Main\"; _recipient : _sender; _amount : Uint128 0; code : not_owner_code}; msgs = one_msg msg; send msgs | True => welcome_msg := msg; msg = {_tag : \"Main\"; _recipient : _sender; _amount : Uint128 0; code : set_hello_code}; msgs = one_msg msg; send msgs end end transition getHello () r <- welcome_msg; msg = {_tag : \"Main\"; _recipient : _sender; _amount : Uint128 0; msg : r}; msgs = one_msg msg; send msgs end" 51 | } 52 | } -------------------------------------------------------------------------------- /test/scripts/testblockchain.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const { BN, Long, bytes } = require('@zilliqa-js/util'); 3 | const { Zilliqa } = require('@zilliqa-js/zilliqa'); 4 | 5 | const zilliqa = new Zilliqa('http://localhost:4200'); 6 | 7 | const CHAIN_ID = 111; 8 | const MSG_VERSION = 1; 9 | const VERSION = bytes.pack(CHAIN_ID, MSG_VERSION); 10 | 11 | // Populate the wallet with an account 12 | zilliqa.wallet.addByPrivateKey( 13 | 'db11cfa086b92497c8ed5a4cc6edb3a5bfe3a640c43ffb9fc6aa0873c56f2ee3', 14 | ); 15 | 16 | async function testBlockchain() { 17 | try { 18 | // Send a transaction to the network 19 | const tx = await zilliqa.blockchain.createTransaction( 20 | zilliqa.transactions.new({ 21 | version: VERSION, 22 | toAddr: 'd90f2e538ce0df89c8273cad3b63ec44a3c4ed82', 23 | amount: new BN(888), 24 | // gasPrice must be >= minGasPrice 25 | gasPrice: new BN('1_000_000_000'), 26 | // can be `number` if size is <= 2^53 (i.e., window.MAX_SAFE_INTEGER) 27 | gasLimit: Long.fromNumber(10), 28 | }), 29 | ); 30 | console.log(tx); 31 | 32 | console.log('Deploying a contract now'); 33 | // Deploy a contract 34 | const code = fs.readFileSync('HelloWorld.scilla', 'utf-8'); 35 | const init = [ 36 | { 37 | vname: '_scilla_version', 38 | type: 'Uint32', 39 | value: '0', 40 | }, 41 | { 42 | vname: 'owner', 43 | type: 'ByStr20', 44 | // NOTE: all byte strings passed to Scilla contracts _must_ be 45 | // prefixed with 0x. Failure to do so will result in the network 46 | // rejecting the transaction while consuming gas! 47 | value: '0x7bb3b0e8a59f3f61d9bff038f4aeb42cae2ecce8', 48 | }, 49 | ]; 50 | 51 | // instance of class Contract 52 | const contract = zilliqa.contracts.new(code, init); 53 | 54 | const [deployTx, hello] = await contract.deploy({ 55 | version: VERSION, 56 | gasPrice: new BN('1_000_000_000'), 57 | gasLimit: Long.fromNumber(5000), 58 | }); 59 | 60 | // Introspect the state of the underlying transaction 61 | console.log('Deployment Transaction ID: ', deployTx.id); 62 | console.log('Deployment Transaction Receipt: ', deployTx.txParams.receipt); 63 | 64 | const callTx = await hello.call('setHello', [ 65 | { 66 | vname: 'msg', 67 | type: 'String', 68 | value: 'Hello World', 69 | }], 70 | { 71 | version: VERSION, 72 | amount: new BN(0), 73 | gasPrice: new BN('1_000_000_000'), 74 | gasLimit: Long.fromNumber(5000), 75 | }); 76 | const { receipt } = callTx.txParams; 77 | console.log(receipt); 78 | const state = await hello.getState(); 79 | console.log(state); 80 | } catch (err) { 81 | console.log('Blockchain Error'); 82 | console.log(err); 83 | } 84 | } 85 | 86 | testBlockchain(); 87 | -------------------------------------------------------------------------------- /src/config.js: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of kaya. 3 | Copyright (c) 2018 - present Zilliqa Research Pte. Ltd. 4 | 5 | kaya is free software: you can redistribute it and/or modify it under the 6 | terms of the GNU General Public License as published by the Free Software 7 | Foundation, either version 3 of the License, or (at your option) any later 8 | version. 9 | 10 | kaya is distributed in the hope that it will be useful, but WITHOUT ANY 11 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 12 | A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License along with 15 | kaya. If not, see . 16 | */ 17 | 18 | /* Configuration file */ 19 | /* Feel free to add more things to this file that will help you in development */ 20 | const { BN } = require('@zilliqa-js/util'); 21 | 22 | const packagejs = require('../package.json'); 23 | 24 | module.exports = { 25 | port: 4200, 26 | version: packagejs.version, 27 | dataPath: '../data/', 28 | savedFilesDir: '../saved/', 29 | chainId: 111, 30 | msgVersion: 1, 31 | // blockchain specific configuration 32 | blockchain: { 33 | // sets timer for the block confirmation 34 | blockInterval: 0, // automatic block confirmation time in ms, 0 disables automatic confirmation 35 | blockStart: 0, 36 | minimumGasPrice: new BN('1000000000'), 37 | transferGasCost: 1, // Amount of gas consumed for each transfer 38 | }, 39 | 40 | wallet: { 41 | numAccounts: 10, // number of default accounts 42 | defaultAmt: new BN('1000000000000000000'), // default amount of zils assigned to each wallet 43 | defaultNonce: 0, 44 | }, 45 | 46 | // Relevant constants config copied from core zilliqa repo (constants.xml) 47 | constants: { 48 | gas: { 49 | CONTRACT_CREATE_GAS: 50, 50 | CONTRACT_INVOKE_GAS: 10, 51 | NORMAL_TRAN_GAS: 1, 52 | }, 53 | smart_contract: { 54 | SCILLA_RUNNER: `${__dirname}/components/scilla/scilla-runner`, 55 | SCILLA_CHECKER: `${__dirname}/components/scilla/scilla-checker`, 56 | SCILLA_LIB: `${__dirname}/components/scilla/stdlib`, 57 | }, 58 | }, 59 | 60 | /* 61 | Settings for the scilla interpreter 62 | - runner-path: Relative path to your scilla-runner 63 | - remote: Use the remote scilla interpreter. (Default: True). False: Use local scilla interpreter 64 | - url: URL to the remote scilla interpreter 65 | */ 66 | scilla: { 67 | remote: true, 68 | CHECKER_URL: 'https://scilla-runner.zilliqa.com/contract/check', 69 | RUNNER_URL: 'https://scilla-runner.zilliqa.com/contract/call', 70 | }, 71 | 72 | testconfigs: { 73 | gasPrice: '1_000_000_000', 74 | gasLimit: 10, 75 | transferAmt: 100, 76 | args: { 77 | r: true, 78 | remote: true, 79 | s: null, 80 | save: null, 81 | v: true, 82 | verbose: true, 83 | version: false, 84 | f: 'test/account-fixtures.json', 85 | fixtures: 'test/account-fixtures.json', 86 | p: 4200, 87 | port: 4200, 88 | d: 'data/', 89 | data: 'data/', 90 | n: 10, 91 | numAccounts: 10, 92 | l: null, 93 | load: null, 94 | $0: 'server.js', 95 | }, 96 | }, 97 | }; 98 | -------------------------------------------------------------------------------- /src/provider.js: -------------------------------------------------------------------------------- 1 | const zCore = require('@zilliqa-js/core'); 2 | const logic = require('./logic'); 3 | const wallet = require('./components/wallet/wallet'); 4 | const config = require('./config'); 5 | const { RPCError } = require('./components/CustomErrors'); 6 | const { addBnum, getBlockNum } = require('./components/blockchain'); 7 | 8 | const errorCodes = zCore.RPCErrorCode; 9 | 10 | class Provider { 11 | constructor(options) { 12 | this.options = options; 13 | this.middleware = { 14 | request: { 15 | use: () => {}, 16 | }, 17 | response: { 18 | use: () => {}, 19 | }, 20 | }; 21 | } 22 | 23 | /** 24 | * Process the JSON RPC call 25 | * @async 26 | * @param { String } method - Zilliqa RPC method name 27 | * @param { Array } params - Zilliqa RPC method parameters 28 | * @returns { Promise } - returned parameters 29 | */ 30 | async send(method, ...params) { 31 | try { 32 | const result = await this.rpcResponse(method, ...params); 33 | return { result }; 34 | } catch (err) { 35 | return { 36 | error: { 37 | code: err.code, 38 | data: err.data, 39 | message: err.message, 40 | }, 41 | }; 42 | } 43 | } 44 | 45 | /** 46 | * Returns RPC response. 47 | * 48 | * @private 49 | * @async 50 | * @param { String } method - Zilliqa RPC method name 51 | * @param { Array } params - Zilliqa RPC method parameters 52 | * @returns { Object } - returned parameters 53 | */ 54 | async rpcResponse(method, ...params) { 55 | switch (method) { 56 | case 'GetBalance': { 57 | const paramAddr = params[0]; 58 | const addr = typeof paramAddr === 'object' 59 | ? JSON.stringify(paramAddr) 60 | : paramAddr; 61 | return wallet.getBalance(addr); 62 | } 63 | case 'GetNetworkId': 64 | return config.chainId.toString(); 65 | case 'GetSmartContractCode': 66 | return logic.processGetDataFromContract(params, this.options.dataPath, 'code'); 67 | case 'GetSmartContractState': 68 | return logic.processGetDataFromContract(params, this.options.dataPath, 'state'); 69 | case 'GetSmartContractInit': 70 | return logic.processGetDataFromContract(params, this.options.dataPath, 'init'); 71 | case 'GetSmartContracts': 72 | return logic.processGetSmartContracts(params, this.options.dataPath); 73 | case 'CreateTransaction': 74 | return logic.processCreateTxn(params, this.options.dataPath); 75 | case 'GetTransaction': 76 | return logic.processGetTransaction(params); 77 | case 'GetRecentTransactions': 78 | return logic.processGetRecentTransactions(); 79 | case 'GetContractAddressFromTransactionID': 80 | return logic.processGetContractAddressByTransactionID(params); 81 | case 'GetMinimumGasPrice': 82 | return config.blockchain.minimumGasPrice.toString(); 83 | case 'KayaMine': 84 | return addBnum(); 85 | case 'GetNumTxBlocks': 86 | return getBlockNum(); 87 | default: 88 | throw new RPCError( 89 | 'METHOD_NOT_FOUND: The method being requested is not available on this server', 90 | errorCodes.RPC_INVALID_REQUEST, 91 | null, 92 | ); 93 | } 94 | } 95 | } 96 | 97 | module.exports = Provider; 98 | -------------------------------------------------------------------------------- /test/mining.test.js: -------------------------------------------------------------------------------- 1 | const { readFileSync } = require('fs'); 2 | const { BN, bytes, Long } = require('@zilliqa-js/util'); 3 | const { Zilliqa } = require('@zilliqa-js/zilliqa'); 4 | const { getAddressFromPrivateKey, getPubKeyFromPrivateKey } = require('@zilliqa-js/crypto'); 5 | const KayaProvider = require('../src/provider'); 6 | const { loadAccounts } = require('../src/components/wallet/wallet'); 7 | 8 | const privateKey = '67bc010005e3e5b0d71e06e1240f645ffd39f2d0da78cf33e7860dee56c6f38e' 9 | 10 | const testWallet = { 11 | address: getAddressFromPrivateKey(privateKey), 12 | privateKey, 13 | publicKey: getPubKeyFromPrivateKey(privateKey), 14 | amount: '1000000000000000', 15 | nonce: 0, 16 | }; 17 | 18 | const getProvider = () => { 19 | // sets up transaction history for accounts 20 | loadAccounts({ 21 | [testWallet.address.replace('0x', '').toLowerCase()]: { 22 | privateKey: testWallet.privateKey, 23 | amount: testWallet.amount, 24 | nonce: testWallet.nonce, 25 | }, 26 | }); 27 | return new KayaProvider({ dataPath: 'data/' }); 28 | }; 29 | 30 | const CHAIN_ID = 111; 31 | const MSG_VERSION = 1; 32 | const version = bytes.pack(CHAIN_ID, MSG_VERSION); 33 | 34 | const getZilliqa = () => { 35 | const zilliqa = new Zilliqa(null, getProvider()); 36 | zilliqa.wallet.addByPrivateKey(testWallet.privateKey); 37 | zilliqa.wallet.setDefault(testWallet.address); 38 | return zilliqa; 39 | }; 40 | 41 | const defaultParams = { 42 | version, 43 | toAddr: `0x${'0'.repeat(40)}`, 44 | amount: new BN(0), 45 | gasPrice: new BN(1000000000), 46 | gasLimit: Long.fromNumber(25000), 47 | }; 48 | 49 | const deploymentParams = { 50 | ...defaultParams, 51 | gasLimit: Long.fromNumber(100000), 52 | }; 53 | 54 | const transactionEventNames = tx => ( 55 | (tx.txParams.receipt.event_logs || []).map(l => l._eventname) 56 | ); 57 | 58 | describe('Test Mining support', () => { 59 | beforeAll(() => { 60 | jest.setTimeout(20000); 61 | }); 62 | 63 | test('Block number should increase', async () => { 64 | const zilliqa = getZilliqa(); 65 | const blockNumber0 = await zilliqa.blockchain.getNumTxBlocks(); 66 | expect(blockNumber0.result).toBe(0); 67 | await zilliqa.provider.send('KayaMine'); 68 | const blockNumber1 = await zilliqa.blockchain.getNumTxBlocks(); 69 | expect(blockNumber1.result).toBe(1); 70 | await zilliqa.provider.send('KayaMine'); 71 | const blockNumber2 = await zilliqa.blockchain.getNumTxBlocks(); 72 | expect(blockNumber2.result).toBe(2); 73 | }); 74 | 75 | test('Scilla interpreter should get different block numbers', async () => { 76 | const zilliqa = getZilliqa(); 77 | const [deployContract, contract] = await zilliqa.contracts 78 | .new( 79 | readFileSync(`${__dirname}/scilla/mining.scilla`, 'utf8'), 80 | [ 81 | { vname: '_scilla_version', type: 'Uint32', value: '0' }, 82 | ], 83 | ) 84 | .deploy(deploymentParams); 85 | expect(deployContract.isConfirmed()).toBe(true); 86 | 87 | const startTimerCall = await contract.call('startTimer', [], defaultParams); 88 | expect(startTimerCall.isConfirmed()).toBe(true); 89 | 90 | const checkCallBefore = await contract.call('checkTimer', [], defaultParams); 91 | expect(transactionEventNames(checkCallBefore)).toEqual(['pending']); 92 | 93 | // mine 3 blocks 94 | await zilliqa.provider.send('KayaMine'); 95 | await zilliqa.provider.send('KayaMine'); 96 | await zilliqa.provider.send('KayaMine'); 97 | 98 | const checkCallAfter = await contract.call('checkTimer', [], defaultParams); 99 | expect(transactionEventNames(checkCallAfter)).toEqual(['success']); 100 | }); 101 | }); 102 | -------------------------------------------------------------------------------- /test/multicontract.test.js: -------------------------------------------------------------------------------- 1 | const { readFileSync } = require('fs'); 2 | const { BN, bytes, Long } = require('@zilliqa-js/util'); 3 | const { Zilliqa } = require('@zilliqa-js/zilliqa'); 4 | const { toChecksumAddress, getAddressFromPrivateKey, getPubKeyFromPrivateKey } = require('@zilliqa-js/crypto'); 5 | const KayaProvider = require('../src/provider'); 6 | const { loadAccounts } = require('../src/components/wallet/wallet'); 7 | 8 | const privateKey = 'ebe9139f853d3ba3f509741d3068ccae5215793ed82b0dcf982dd38462a7ab7e' 9 | 10 | const testWallet = { 11 | address: getAddressFromPrivateKey(privateKey), 12 | privateKey, 13 | publicKey: getPubKeyFromPrivateKey(privateKey), 14 | amount: '1000000000000000', 15 | nonce: 0, 16 | }; 17 | 18 | const getProvider = () => { 19 | // sets up transaction history for accounts 20 | loadAccounts({ 21 | [testWallet.address.toLowerCase().replace('0x', '')]: { 22 | privateKey: testWallet.privateKey, 23 | amount: testWallet.amount, 24 | nonce: testWallet.nonce, 25 | }, 26 | }); 27 | return new KayaProvider({ dataPath: 'data/' }); 28 | }; 29 | 30 | const CHAIN_ID = 111; 31 | const MSG_VERSION = 1; 32 | const version = bytes.pack(CHAIN_ID, MSG_VERSION); 33 | 34 | const getZilliqa = () => { 35 | const zilliqa = new Zilliqa(null, getProvider()); 36 | zilliqa.wallet.addByPrivateKey(testWallet.privateKey); 37 | zilliqa.wallet.setDefault(testWallet.address); 38 | return zilliqa; 39 | }; 40 | 41 | const defaultParams = { 42 | version, 43 | toAddr: `0x${'0'.repeat(40)}`, 44 | amount: new BN(0), 45 | gasPrice: new BN(1000000000), 46 | gasLimit: Long.fromNumber(25000), 47 | }; 48 | 49 | const deploymentParams = { 50 | ...defaultParams, 51 | gasLimit: Long.fromNumber(100000), 52 | }; 53 | 54 | const transactionEventNames = tx => ( 55 | (tx.txParams.receipt.event_logs || []).map(l => l._eventname) 56 | ); 57 | 58 | describe('Test Multicontract support', () => { 59 | beforeAll(() => { 60 | jest.setTimeout(55000); 61 | }); 62 | 63 | test('Contract call chain should work', async () => { 64 | const zilliqa = getZilliqa(); 65 | const [deployCTx, contractC] = await zilliqa.contracts 66 | .new( 67 | readFileSync(`${__dirname}/scilla/chain-call-balance-c.scilla`, 'utf8'), 68 | [ 69 | { vname: '_scilla_version', type: 'Uint32', value: '0' }, 70 | ], 71 | ) 72 | .deploy(deploymentParams); 73 | expect(deployCTx.isConfirmed()).toBe(true); 74 | 75 | const [deployBTx, contractB] = await zilliqa.contracts 76 | .new( 77 | readFileSync(`${__dirname}/scilla/chain-call-balance-b.scilla`, 'utf8'), 78 | [ 79 | { vname: '_scilla_version', type: 'Uint32', value: '0' }, 80 | ], 81 | ) 82 | .deploy(deploymentParams); 83 | expect(deployBTx.isConfirmed()).toBe(true); 84 | 85 | const [deployATx, contractA] = await zilliqa.contracts 86 | .new( 87 | readFileSync(`${__dirname}/scilla/chain-call-balance-a.scilla`, 'utf8'), 88 | [ 89 | { vname: '_scilla_version', type: 'Uint32', value: '0' }, 90 | ], 91 | ) 92 | .deploy(deploymentParams); 93 | expect(deployATx.isConfirmed()).toBe(true); 94 | 95 | const transitionCall = await contractA.call( 96 | 'acceptAAndTransferToBAndCallC', 97 | [ 98 | { vname: 'addrB', type: 'ByStr20', value: contractB.address }, 99 | { vname: 'addrC', type: 'ByStr20', value: contractC.address }, 100 | ], 101 | { 102 | ...defaultParams, 103 | amount: new BN(5), 104 | }, 105 | ); 106 | expect(transitionCall.isConfirmed()).toBe(true); 107 | expect(transactionEventNames(transitionCall)) 108 | .toEqual(['A', 'B', 'C']); 109 | const [walletBalance, contractAState, contractBState, contractCState] = await ( 110 | Promise.all([ 111 | zilliqa.blockchain.getBalance(testWallet.address), 112 | contractA.getState(), 113 | contractB.getState(), 114 | contractC.getState(), 115 | ]) 116 | ); 117 | expect(walletBalance.result.nonce).toBe(4); 118 | expect(contractAState).toEqual({_balance: '0', last_amount: '5'}); 119 | expect(contractBState).toEqual({_balance: '0', last_amount: '5'}) 120 | expect(contractCState).toEqual({_balance: '5', last_amount: '5'}) 121 | }); 122 | }); 123 | -------------------------------------------------------------------------------- /src/components/scilla/stdlib/IntUtils.scillib: -------------------------------------------------------------------------------- 1 | library IntUtils 2 | 3 | let int_neq = 4 | tfun 'A => 5 | fun (eq : 'A -> 'A -> Bool) => 6 | fun (a : 'A) => 7 | fun (b : 'A) => 8 | let eqr = eq a b in 9 | match eqr with 10 | | True => False 11 | | False => True 12 | end 13 | 14 | let int_le = 15 | tfun 'A => 16 | fun (eq : 'A -> 'A -> Bool) => 17 | fun (lt : 'A -> 'A -> Bool) => 18 | fun (a : 'A) => 19 | fun (b : 'A) => 20 | let ltr = lt a b in 21 | match ltr with 22 | | True => True 23 | | False => eq a b 24 | end 25 | 26 | let int_gt = 27 | tfun 'A => 28 | fun (lt : 'A -> 'A -> Bool) => 29 | fun (a : 'A) => 30 | fun (b : 'A) => 31 | lt b a 32 | 33 | let int_ge = 34 | tfun 'A => 35 | fun (eq : 'A -> 'A -> Bool) => 36 | fun (lt : 'A -> 'A -> Bool) => 37 | fun (a : 'A) => 38 | fun (b : 'A) => 39 | let le = @int_le 'A in 40 | le eq lt b a 41 | 42 | (* int_eq instantiations *) 43 | let int32_eq = 44 | fun (a : Int32) => 45 | fun (b : Int32) => 46 | builtin eq a b 47 | let int64_eq = 48 | fun (a : Int64) => 49 | fun (b : Int64) => 50 | builtin eq a b 51 | let int128_eq = 52 | fun (a : Int128) => 53 | fun (b : Int128) => 54 | builtin eq a b 55 | let int256_eq = 56 | fun (a : Int256) => 57 | fun (b : Int256) => 58 | builtin eq a b 59 | let uint32_eq = 60 | fun (a : Uint32) => 61 | fun (b : Uint32) => 62 | builtin eq a b 63 | let uint64_eq = 64 | fun (a : Uint64) => 65 | fun (b : Uint64) => 66 | builtin eq a b 67 | let uint128_eq = 68 | fun (a : Uint128) => 69 | fun (b : Uint128) => 70 | builtin eq a b 71 | let uint256_eq = 72 | fun (a : Uint256) => 73 | fun (b : Uint256) => 74 | builtin eq a b 75 | 76 | (* int_lt instantiations *) 77 | let int32_lt = 78 | fun (a : Int32) => 79 | fun (b : Int32) => 80 | builtin lt a b 81 | let int64_lt = 82 | fun (a : Int64) => 83 | fun (b : Int64) => 84 | builtin lt a b 85 | let int128_lt = 86 | fun (a : Int128) => 87 | fun (b : Int128) => 88 | builtin lt a b 89 | let int256_lt = 90 | fun (a : Int256) => 91 | fun (b : Int256) => 92 | builtin lt a b 93 | let uint32_lt = 94 | fun (a : Uint32) => 95 | fun (b : Uint32) => 96 | builtin lt a b 97 | let uint64_lt = 98 | fun (a : Uint64) => 99 | fun (b : Uint64) => 100 | builtin lt a b 101 | let uint128_lt = 102 | fun (a : Uint128) => 103 | fun (b : Uint128) => 104 | builtin lt a b 105 | let uint256_lt = 106 | fun (a : Uint256) => 107 | fun (b : Uint256) => 108 | builtin lt a b 109 | 110 | (* int_neq instantiations *) 111 | let int32_neq = let t = @int_neq Int32 in t int32_eq 112 | let int64_neq = let t = @int_neq Int64 in t int64_eq 113 | let int128_neq = let t = @int_neq Int128 in t int128_eq 114 | let int256_neq = let t = @int_neq Int256 in t int256_eq 115 | let uint32_neq = let t = @int_neq Uint32 in t uint32_eq 116 | let uint64_neq = let t = @int_neq Uint64 in t uint64_eq 117 | let uint128_neq = let t = @int_neq Uint128 in t uint128_eq 118 | let uint256_neq = let t = @int_neq Uint256 in t uint256_eq 119 | (* int_le instantiations *) 120 | let int32_le = let t = @int_le Int32 in t int32_eq int32_lt 121 | let int64_le = let t = @int_le Int64 in t int64_eq int64_lt 122 | let int128_le = let t = @int_le Int128 in t int128_eq int128_lt 123 | let int256_le = let t = @int_le Int256 in t int256_eq int256_lt 124 | let uint32_le = let t = @int_le Uint32 in t uint32_eq uint32_lt 125 | let uint64_le = let t = @int_le Uint64 in t uint64_eq uint64_lt 126 | let uint128_le = let t = @int_le Uint128 in t uint128_eq uint128_lt 127 | let uint256_le = let t = @int_le Uint256 in t uint256_eq uint256_lt 128 | (* int_gt instantiations *) 129 | let int32_gt = let t = @int_gt Int32 in t int32_lt 130 | let int64_gt = let t = @int_gt Int64 in t int64_lt 131 | let int128_gt = let t = @int_gt Int128 in t int128_lt 132 | let int256_gt = let t = @int_gt Int256 in t int256_lt 133 | let uint32_gt = let t = @int_gt Uint32 in t uint32_lt 134 | let uint64_gt = let t = @int_gt Uint64 in t uint64_lt 135 | let uint128_gt = let t = @int_gt Uint128 in t uint128_lt 136 | let uint256_gt = let t = @int_gt Uint256 in t uint256_lt 137 | (* int_ge instantiations *) 138 | let int32_ge = let t = @int_ge Int32 in t int32_eq int32_lt 139 | let int64_ge = let t = @int_ge Int64 in t int64_eq int64_lt 140 | let int128_ge = let t = @int_ge Int128 in t int128_eq int128_lt 141 | let int256_ge = let t = @int_ge Int256 in t int256_eq int256_lt 142 | let uint32_ge = let t = @int_ge Uint32 in t uint32_eq uint32_lt 143 | let uint64_ge = let t = @int_ge Uint64 in t uint64_eq uint64_lt 144 | let uint128_ge = let t = @int_ge Uint128 in t uint128_eq uint128_lt 145 | let uint256_ge = let t = @int_ge Uint256 in t uint256_eq uint256_lt 146 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kaya - Zilliqa's RPC client for testing and development 2 | [![Discord chat](https://img.shields.io/discord/370992535725932544.svg)](https://discord.gg/mWp9HdR) 3 | [![Build Status](https://travis-ci.com/Zilliqa/kaya.svg?branch=master)](https://travis-ci.com/Zilliqa/kaya) 4 | 5 | 6 | ## Deprecation Notice 7 | 8 | This repository is deprecated. Please use [isolated server](https://github.com/Zilliqa/Zilliqa/blob/master/ISOLATED_SERVER_setup.md) for your local testing. 9 | 10 | ## Introduction 11 | 12 | Kaya is Zilliqa's RPC server for testing and development. It is personal blockchain which makes developing application easier and faster. Kaya emulates the Zilliqa's blockchain behavior, and follows the expected server behavior as seen in the [`zilliqa-js`](https://github.com/Zilliqa/Zilliqa-JavaScript-Library). 13 | 14 | The goal of the project is to support all endpoints in Zilliqa Javascript API, making it easy for app developers to build Dapps on our platform. 15 | 16 | Kaya is under development. See [roadmap here](https://github.com/Zilliqa/kaya/blob/master/ROADMAP.md). 17 | 18 | Currently, Kaya supports the following functions: 19 | * `CreateTransaction` 20 | * `GetTransaction` 21 | * `GetRecentTransactions` 22 | * `GetNetworkId` 23 | * `GetSmartContractState` 24 | * `GetSmartContracts` 25 | * `GetBalance` 26 | * `GetSmartContractInit` 27 | * `GetSmartContractCode` 28 | * `GetContractAddressFromTransactionID` 29 | * `GetMinimumGasPrice` 30 | 31 | Methods that are NOT supported: 32 | * `GetShardingStructure` 33 | * `GetNumDSBlocks` 34 | * `GetDSBlockRate` 35 | * `GetNumTxBlocks` 36 | * `GetTxBlockRate` 37 | * `GetNumTransactions` 38 | * `GetTransactionRate` 39 | * `GetCurrentMiniEpoch` 40 | * `GetCurrentDSEpoch` 41 | * `GetNumTxnsTxEpoch` 42 | * `GetNumTxnsDSEpoch` 43 | 44 | 45 | In addition, the following features are not supported yet: 46 | * Multi-contract calls 47 | * Events 48 | 49 | ## Getting Started 50 | ### Installation 51 | 52 | Kaya RPC server is distributed as a Node package via `npm`. Ensure that you have [Node.js](https://nodejs.org/en/) (>= 10.13.0). 53 | 54 | ``` 55 | npm install -g kaya-cli 56 | ``` 57 | 58 | Scilla files must be processed using the `scilla-interpreter`. The [Scilla interpreter](https://scilla.readthedocs.io/en/latest/interface.html) executable provides a calling interface that enables users to invoke transitions with specified inputs and obtain outputs. 59 | 60 | #### Using Remote Scilla Interpreter (Default) 61 | 62 | By default, Kaya RPC uses the remote scilla interpreter to process `.scilla` files. You do not have to change any configurations. 63 | 64 | #### Using Local Scilla Interpreter 65 | You can choose to use your own scilla interpreter locally. To do it, you will have to compile the binaries yourself from the [scilla repository](https://github.com/Zilliqa/scilla) and transfer it to the correct directory within Kaya RPC. 66 | 67 | Instructions: 68 | 1. Ensure that you have installed the related dependencies: [INSTALL.md](https://github.com/Zilliqa/scilla/blob/master/INSTALL.md) 69 | 2. Then, run `make clean; make` 70 | 3. Copy the `scilla-runner` from `[SCILLA_DIR]/bin` into `[Kaya_DIR]/components/scilla/` 71 | 4. Open `config.js` file and set the `config.scilla.remote` to `false`. Alternative, use `-r false` at startup. 72 | 73 | ### Usage 74 | 75 | #### Command Line 76 | ``` 77 | $ kaya-cli 78 | ``` 79 | Options: 80 | * `-d` or `--data`: Relative path where state data will be stored. Creates directory if path does not exists 81 | * `-f` or `--fixtures`: Load fixed account addresses and keys (fixtures) from a JSON-file 82 | * `-l` or `--load`: Load data files from a JSON file 83 | * `-n` or `--numAccounts`: Number of accounts to load at start up. Only used if fixtures file is not defined. 84 | * `-p` or `--port`: Port number to listen to (Default: `4200`) 85 | * `-r` or `--remote`: Option to use remote interpreter or local interpreter. Remote if True 86 | * `-s` or `--save`: Saves data files to `saved/` directory by the end of the session 87 | * `-v` or `--verbose`: Log all requests and responses to stdout 88 | 89 | #### Example Usage 90 | * Starts server based on predefined wallet files with verbose mode. 91 | ``` 92 | node server.js -v -f test/account-fixtures.json 93 | ``` 94 | * Load data files from a previous session and save the data at the end of the session 95 | ``` 96 | node server.js -v -s --load test/sample-export.json 97 | ``` 98 | 99 | #### Presents 100 | 101 | KayaRPC comes with a few preset configurations for lazy programmers: 102 | 103 | * `npm run debug`: Use server with random account keypairs 104 | * `npm run debug:fixtures`: Use server with fixed account keypairs loaded from `test/account-fixtures.json` 105 | * `npm start`: The same as `node server.js` - random account keypair generations with no verbosity 106 | 107 | ## Testing 108 | 109 | Some of the functions in Kaya RPC are covered under automated testing using `jest`. However, scilla related transactions are not covered through automated testing. To test the `CreateTransaction` functionalities, you will have to test it manually. 110 | 111 | From `test/scripts/`, you can use run `node TestBlockchain.js` to test the Kaya RPC. The script will make a payment transaction, deployment transaction and transition invocation. 112 | 113 | ## License 114 | 115 | kaya is released under GPLv3. See [license here](https://github.com/Zilliqa/kaya/blob/master/LICENSE) 116 | -------------------------------------------------------------------------------- /src/utilities.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-param-reassign */ 2 | /* eslint-disable no-cond-assign */ 3 | /* 4 | This file is part of kaya. 5 | Copyright (c) 2018 - present Zilliqa Research Pte. Ltd. 6 | 7 | kaya is free software: you can redistribute it and/or modify it under the 8 | terms of the GNU General Public License as published by the Free Software 9 | Foundation, either version 3 of the License, or (at your option) any later 10 | version. 11 | 12 | kaya is distributed in the hope that it will be useful, but WITHOUT ANY 13 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 14 | A PARTICULAR PURPOSE. See the GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License along with 17 | kaya. If not, see . 18 | */ 19 | 20 | const fs = require('fs'); 21 | const moment = require('moment'); 22 | const glob = require('glob'); 23 | const yargs = require('yargs'); 24 | const initArgv = require('./argv'); 25 | const config = require('./config'); 26 | 27 | 28 | // Configure the argument flags based on test environment 29 | let argv; 30 | if (process.env.NODE_ENV !== 'test') { 31 | argv = initArgv(yargs).argv; 32 | } else { 33 | argv = config.testconfigs.args; 34 | } 35 | 36 | const logLabel = 'Utilities'; 37 | 38 | module.exports = { 39 | 40 | /** 41 | * Utility function to extract data from the working directory 42 | * according to file extension (called from app.js) 43 | * @param: { String } dataPath - Path to the working directory 44 | * @param : { String } fileExtension - One of the following: 45 | * { code.scilla, state.json, init.json} 46 | * @returns : { Object } - Data object for the specified file extension 47 | */ 48 | getDataFromDir: (dataPath, fileExt) => { 49 | const files = glob.sync(`${dataPath}*_${fileExt}`); 50 | const result = {}; 51 | const isCode = (fileExt === 'code.scilla'); 52 | files.forEach((file) => { 53 | const fileData = fs.readFileSync(file, 'utf-8'); 54 | result[file.slice(dataPath.length)] = isCode ? fileData : JSON.parse(fileData); 55 | }); 56 | return result; 57 | }, 58 | 59 | /** 60 | * Called when the user chooses to load from an existing file 61 | * @param: { string } filepath to directory 62 | */ 63 | loadData: (filePath) => { 64 | // FIXME : Validate the file 65 | const data = JSON.parse(fs.readFileSync(filePath)); 66 | return data; 67 | }, 68 | 69 | /* 70 | * Writes the data files from the saved session into the working directory 71 | * @params : { String } dataPath - Path to the working data directory 72 | * @params : { Object } data - Object that includes the init, code and state files 73 | */ 74 | loadDataToDir: (dataPath, data) => { 75 | const states = data.states; 76 | const stateFileNames = Object.keys(states); 77 | stateFileNames.forEach((file) => { 78 | fs.writeFileSync(`${dataPath}/${file}`, JSON.stringify(states[file])); 79 | }); 80 | module.exports.logVerbose(logLabel, `State files loaded into ${dataPath}`); 81 | 82 | const inits = data.init; 83 | const initFileNames = Object.keys(inits); 84 | initFileNames.forEach((file) => { 85 | fs.writeFileSync(`${dataPath}/${file}`, JSON.stringify(inits[file])); 86 | }); 87 | module.exports.logVerbose(logLabel, `Init files loaded into ${dataPath}`); 88 | 89 | const codes = data.codes; 90 | const codeFileNames = Object.keys(codes); 91 | codeFileNames.forEach((file) => { 92 | fs.writeFileSync(`${dataPath}/${file}`, codes[file]); 93 | }); 94 | module.exports.logVerbose(logLabel, `Code files loaded into ${dataPath}`); 95 | }, 96 | 97 | // log function that logs only when verbose mode is on 98 | logVerbose: (src, msg) => { 99 | if (argv.v && process.env.NODE_ENV !== 'test') { 100 | console.log(`[${src}]\t : ${msg}`); 101 | } 102 | }, 103 | 104 | // wrapper: print only when not in test mode 105 | consolePrint: (text) => { 106 | if (process.env.NODE_ENV !== 'test') { 107 | console.log(text); 108 | } 109 | }, 110 | 111 | /** 112 | * @returns : { string } : Datetime format (e.g. 20181001T154832 ) 113 | */ 114 | getDateTimeString: () => moment().format('YYYYMMDD_hhmmss'), 115 | 116 | /** 117 | * Given a piece of scilla code, removes comments 118 | * @param : { string } : scilla code 119 | * @returns : { string } : scilla code without comments 120 | */ 121 | removeComments: (str) => { 122 | let commentStart; 123 | let commentEnd; 124 | let str1; 125 | let str2; 126 | let str3; 127 | const originalStr = str; 128 | 129 | try { 130 | // loop till all comments beginning with '(*' are removed 131 | while ((commentStart = str.match(/\(\*/))) { 132 | // get the string till comment start 133 | str1 = str.substr(0, commentStart.index); 134 | 135 | // get the string after comment start 136 | str2 = str.substr(commentStart.index); 137 | commentEnd = str2.match(/\*\)/); 138 | str3 = str2.substr(commentEnd.index + 2); 139 | 140 | str = str1 + str3; 141 | } 142 | } catch (e) { 143 | return originalStr; 144 | } 145 | return str; 146 | }, 147 | 148 | /* 149 | * Clean up the code received from POST requests. Converts raw code from editor 150 | * into format that can be read by the interpreter 151 | */ 152 | codeCleanup: (str) => { 153 | let cleanedCode = module.exports.removeComments(str); 154 | cleanedCode = cleanedCode.replace(/\\n|\\t/g, ' ').replace(/\\"/g, '"'); 155 | cleanedCode = cleanedCode.substring(1, cleanedCode.length - 1); 156 | return cleanedCode; 157 | }, 158 | 159 | /* 160 | * Clean up the incoming message from POST requests 161 | */ 162 | paramsCleanup: (initParams) => { 163 | let cleanedParams = initParams.trim(); 164 | cleanedParams = cleanedParams 165 | .substring(1, cleanedParams.length - 1) 166 | .replace(/\\"/g, '"'); 167 | return cleanedParams; 168 | }, 169 | 170 | /** 171 | * prepareDirectories: Prepare the directories required 172 | * @param: { String } dataPath : Full path to file 173 | */ 174 | prepareDirectories: (dataPath) => { 175 | if (!fs.existsSync(dataPath)) { 176 | fs.mkdirSync(dataPath); 177 | module.exports.logVerbose(logLabel, `${__dirname}/${dataPath} created`); 178 | } 179 | }, 180 | 181 | 182 | isDeployContract: (toAddress) => { 183 | return toAddress.replace('0x', '') === '0'.repeat(40) 184 | } 185 | }; 186 | -------------------------------------------------------------------------------- /src/app.js: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of kaya. 3 | Copyright (c) 2018 - present Zilliqa Research Pte. Ltd. 4 | 5 | kaya is free software: you can redistribute it and/or modify it under the 6 | terms of the GNU General Public License as published by the Free Software 7 | Foundation, either version 3 of the License, or (at your option) any later 8 | version. 9 | 10 | kaya is distributed in the hope that it will be useful, but WITHOUT ANY 11 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 12 | A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License along with 15 | kaya. If not, see . 16 | */ 17 | const bodyParser = require('body-parser'); 18 | const cors = require('cors'); 19 | const express = require('express'); 20 | const fs = require('fs'); 21 | const rimraf = require('rimraf'); 22 | const yargs = require('yargs'); 23 | 24 | const expressjs = express(); 25 | const config = require('./config'); 26 | const logic = require('./logic'); 27 | const wallet = require('./components/wallet/wallet'); 28 | const utils = require('./utilities'); 29 | const initArgv = require('./argv'); 30 | const Provider = require('./provider'); 31 | 32 | expressjs.use(bodyParser.json({ extended: false })); 33 | let argv; 34 | if (process.env.NODE_ENV !== 'test') { 35 | argv = initArgv(yargs).argv; 36 | } else { 37 | console.log('-------- TEST MODE -------------'); 38 | argv = config.testconfigs.args; 39 | } 40 | 41 | const logLabel = 'App.js'; 42 | 43 | const wrapAsync = fn => (req, res, next) => { 44 | Promise.resolve(fn(req, res, next)).catch(next); 45 | }; 46 | 47 | if (argv.d.trim() === 'saved/') { 48 | throw new Error('Saved dir is reserved for saved files'); 49 | } 50 | 51 | // Stores all the option flags and configurations 52 | // Console defined flag will override the config settings 53 | const options = { 54 | fixtures: argv.f, 55 | numAccts: argv.n, 56 | dataPath: argv.d, 57 | remote: argv.r, 58 | verbose: argv.v, 59 | save: argv.s, 60 | load: argv.l, 61 | }; 62 | 63 | utils.consolePrint(`Running from ${options.remote ? 'remote' : 'local'} interpreter`); 64 | if (options.remote) { utils.consolePrint(config.scilla.RUNNER_URL); } 65 | utils.consolePrint('='.repeat(80)); 66 | 67 | utils.prepareDirectories(options.dataPath); // prepare the directories required 68 | 69 | if (options.save) { 70 | utils.logVerbose(logLabel, 'Save enabled. Data files from this session will be saved'); 71 | } 72 | 73 | if (options.load) { 74 | // loading option specified 75 | utils.logVerbose(logLabel, 'Loading option specified. Loading files now...'); 76 | // loads file into dbPath from the given bootstrap file 77 | const importedData = utils.loadData(options.load); 78 | wallet.loadAccounts(importedData.accounts); 79 | logic.utils.loadData(importedData.transactions, importedData.createdContractsByUsers); 80 | utils.loadDataToDir(options.dataPath, importedData); 81 | utils.logVerbose(logLabel, 'Load completed'); 82 | } 83 | 84 | if (process.env.NODE_ENV === 'test') { 85 | options.fixtures = 'test/account-fixtures.json'; 86 | } 87 | 88 | /* 89 | * Account creation/loading based on presets given 90 | * @dev : Only create wallets if the user does not supply any load file 91 | */ 92 | if (!options.load) { 93 | if (options.fixtures) { 94 | utils.logVerbose(logLabel, `Bootstrapping from account fixture files: ${options.fixtures}`); 95 | const accountsPath = options.fixtures; 96 | if (!fs.existsSync(accountsPath)) { 97 | throw new Error('Account Path Invalid'); 98 | } 99 | const accounts = JSON.parse(fs.readFileSync(accountsPath, 'utf-8')); 100 | wallet.loadAccounts(accounts); 101 | } else { 102 | /* Create Dummy Accounts */ 103 | wallet.createWallets(options.numAccts); 104 | } 105 | } 106 | 107 | wallet.printWallet(); 108 | 109 | // cross region settings with Env 110 | if (process.env.NODE_ENV === 'dev') { 111 | expressjs.use(cors()); 112 | utils.logVerbose(logLabel, 'CORS Enabled'); 113 | } 114 | 115 | expressjs.get('/', (req, res) => { 116 | res.status(200).send('Kaya RPC Server'); 117 | }); 118 | 119 | const provider = new Provider(options); 120 | 121 | // Method handling logic for incoming POST request 122 | const handler = async (req, res) => { 123 | const { body } = req; 124 | utils.logVerbose(logLabel, `Method specified ${body.method}`); 125 | const data = await provider.send(body.method, ...body.params); 126 | res.status(200).send({ id: body.id, jsonrpc: body.jsonrpc, ...data }); 127 | utils.logVerbose(logLabel, 'Sending response back to client'); 128 | }; 129 | 130 | expressjs.post('/', wrapAsync(handler)); 131 | 132 | // Function below handles the end of the session due to SIGINT. It will save 133 | // data files if the `-s` flag is toggled and will remove all files from the data directory 134 | process.on('SIGINT', () => { 135 | utils.consolePrint('Gracefully shutting down from SIGINT (Ctrl-C)'); 136 | 137 | // If `save` is enabled, store files under the saved/ directory 138 | if (options.save) { 139 | console.log('Save mode enabled. Extracting data now..'); 140 | 141 | const dir = config.savedFilesDir; 142 | if (!fs.existsSync(dir)) { 143 | fs.mkdirSync(dir); 144 | } 145 | 146 | // Saved files will be prefixed with the timestamp when the user decides to end the session 147 | const timestamp = utils.getDateTimeString(); 148 | 149 | const outputData = `${dir}${timestamp}`; 150 | const targetFilePath = `${outputData}_data.json`; 151 | utils.consolePrint(`Files will be saved at ${targetFilePath}`); 152 | 153 | // Prepares Data to be exported 154 | utils.consolePrint('Extracting data...'); 155 | const data = logic.exportData(); 156 | data.accounts = wallet.getAccounts(); 157 | utils.consolePrint('[1/5] Transactions and account data extracted'); 158 | data.states = utils.getDataFromDir(options.dataPath, 'state.json'); 159 | utils.consolePrint('[2/5] Contract state data extracted'); 160 | data.init = utils.getDataFromDir(options.dataPath, 'init.json'); 161 | utils.consolePrint('[3/5] Contract init data extracted'); 162 | data.codes = utils.getDataFromDir(options.dataPath, 'code.scilla'); 163 | utils.consolePrint('[4/5] Contract code data extracted'); 164 | 165 | // Writing to the final exported data file in JSON format 166 | fs.writeFileSync(targetFilePath, JSON.stringify(data)); 167 | utils.consolePrint(`[5/5] Data file written to ${targetFilePath}`); 168 | 169 | utils.consolePrint('Save successful'); 170 | } 171 | 172 | // remove files from the db_path 173 | rimraf.sync(`${options.dataPath}*`); 174 | console.log(`Files from ${options.dataPath} removed. Shutting down now.`); 175 | process.exit(0); 176 | }); 177 | 178 | module.exports = { 179 | expressjs, 180 | wallet, 181 | }; 182 | -------------------------------------------------------------------------------- /test/server.test.js: -------------------------------------------------------------------------------- 1 | /** 2 | This file is part of kaya. 3 | Copyright (c) 2018 - present Zilliqa Research Pte. Ltd. 4 | 5 | kaya is free software: you can redistribute it and/or modify it under the 6 | terms of the GNU General Public License as published by the Free Software 7 | Foundation, either version 3 of the License, or (at your option) any later 8 | version. 9 | 10 | kaya is distributed in the hope that it will be useful, but WITHOUT ANY 11 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 12 | A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License along with 15 | kaya. If not, see . 16 | * */ 17 | 18 | require('isomorphic-fetch'); 19 | const request = require('supertest'); 20 | const { Zilliqa } = require('@zilliqa-js/zilliqa'); 21 | const { BN, units } = require('@zilliqa-js/util'); 22 | const app = require('../src/app'); 23 | const config = require('../src/config'); 24 | const Provider = require('../src/provider'); 25 | 26 | const getZilliqa = () => { 27 | const provider = new Provider({ dataPath: 'data/' }); 28 | return new Zilliqa(null, provider); 29 | }; 30 | 31 | const makeQuery = (method, params) => ({ 32 | id: '1', 33 | jsonrpc: '2.0', 34 | method, 35 | params: [params], 36 | }); 37 | 38 | 39 | describe('Test the Server Connection', () => { 40 | test('It should respond to the GET method', (done) => { 41 | request(app.expressjs).get('/').then((response) => { 42 | expect(response.statusCode).toBe(200); 43 | done(); 44 | }); 45 | }); 46 | }); 47 | 48 | /* Server Connection Test */ 49 | 50 | describe('Test the Server Connection', () => { 51 | test('It should respond to network id', async (done) => { 52 | request(app.expressjs).post('/') 53 | .send(makeQuery('GetNetworkId', '')) 54 | .then((response) => { 55 | expect(response.statusCode).toBe(200); 56 | expect(response.body).toEqual({ id: '1', jsonrpc: '2.0', result: '111' }); 57 | done(); 58 | }); 59 | }); 60 | }); 61 | 62 | /* Balance Test */ 63 | 64 | const accounts = app.wallet.getAccounts(); 65 | const testAccount1 = Object.keys(accounts)[0]; 66 | const testAccount2 = Object.keys(accounts)[1]; 67 | 68 | describe('Server Initialization Tests', () => { 69 | test('Test Accounts generated should return the correct balance', async (done) => { 70 | request(app.expressjs).post('/') 71 | .send(makeQuery('GetBalance', testAccount1)) 72 | .then((response1) => { 73 | expect(response1.statusCode).toBe(200); 74 | expect(response1.body).toEqual({ id: '1', jsonrpc: '2.0', result: { balance: config.wallet.defaultAmt.toString(), nonce: config.wallet.defaultNonce } }); 75 | done(); 76 | }); 77 | }); 78 | 79 | test('Uninitialized accounts should return the zero balance', async (done) => { 80 | request(app.expressjs).post('/') 81 | .send(makeQuery('GetBalance', '0'.repeat(40))) 82 | .then((response1) => { 83 | expect(response1.statusCode).toBe(200); 84 | expect(response1.body).toEqual({ error: { code: -5, data: null, message: 'Account is not created' }, id: '1', jsonrpc: '2.0' }); 85 | done(); 86 | }); 87 | }); 88 | 89 | test('Should have zero recent transactions', async (done) => { 90 | request(app.expressjs).post('/') 91 | .send(makeQuery('GetRecentTransactions', '')) 92 | .then((response) => { 93 | expect(response.statusCode).toBe(200); 94 | expect(response.body.result.number).toBe(0); 95 | done(); 96 | }); 97 | }); 98 | }); 99 | 100 | /* Check for presence of smart-contract related methods */ 101 | 102 | describe('Smart Contract related methods Tests', () => { 103 | test('GetSmartContracts should correctly return zero-address error', async (done) => { 104 | request(app.expressjs).post('/') 105 | .send(makeQuery('GetSmartContracts', '50e9247a39e87a734355a203666ff7415c8a0802')) 106 | .then((response) => { 107 | expect(response.statusCode).toBe(200); 108 | expect(response.body).toEqual( 109 | { error: { code: -5, data: null, message: 'Address does not exist' }, id: '1', jsonrpc: '2.0' }, 110 | ); 111 | done(); 112 | }); 113 | }); 114 | 115 | test('GetSmartContractInit should correctly return zero-address error', async (done) => { 116 | request(app.expressjs).post('/') 117 | .send(makeQuery('GetSmartContractInit', '50e9247a39e87a734355a203666ff7415c8a0802')) 118 | .then((response) => { 119 | expect(response.statusCode).toBe(200); 120 | expect(response.body).toEqual( 121 | { error: { code: -5, data: null, message: 'Address does not exist' }, id: '1', jsonrpc: '2.0' }, 122 | ); 123 | done(); 124 | }); 125 | }); 126 | 127 | test('GetSmartContractState should correctly return zero-address error', async (done) => { 128 | request(app.expressjs).post('/') 129 | .send(makeQuery('GetSmartContractState', '50e9247a39e87a734355a203666ff7415c8a0802')) 130 | .then((response) => { 131 | expect(response.statusCode).toBe(200); 132 | expect(response.body).toEqual( 133 | { error: { code: -5, data: null, message: 'Address does not exist' }, id: '1', jsonrpc: '2.0' }, 134 | ); 135 | done(); 136 | }); 137 | }); 138 | 139 | test('GetSmartContractCode should correctly return zero-address error', async (done) => { 140 | request(app.expressjs).post('/') 141 | .send(makeQuery('GetSmartContractCode', '50e9247a39e87a734355a203666ff7415c8a0802')) 142 | .then((response) => { 143 | expect(response.statusCode).toBe(200); 144 | expect(response.body).toEqual( 145 | { error: { code: -5, data: null, message: 'Address does not exist' }, id: '1', jsonrpc: '2.0' }, 146 | ); 147 | done(); 148 | }); 149 | }); 150 | }); 151 | 152 | const getZilliqaBalance = async (zilliqa, address) => { 153 | const data = await zilliqa.blockchain.getBalance(address); 154 | return new BN(data.result.balance); 155 | }; 156 | 157 | describe('Transaction Tests', () => { 158 | const zilliqa = getZilliqa(); 159 | 160 | Object.keys(accounts).forEach((address) => { 161 | zilliqa.wallet.addByPrivateKey( 162 | accounts[address].privateKey, 163 | ); 164 | }); 165 | 166 | const getBalance = address => getZilliqaBalance(zilliqa, address); 167 | 168 | test('CreateTransaction success', async () => { 169 | const amount = units.toQa('333', units.Units.Zil); 170 | const account1balance = await getBalance(testAccount1); 171 | const account2balance = await getBalance(testAccount2); 172 | const t = await zilliqa.blockchain.createTransaction( 173 | zilliqa.transactions.new({ 174 | version: 7274497, 175 | toAddr: testAccount2, 176 | amount, 177 | gasPrice: config.blockchain.minimumGasPrice, 178 | gasLimit: config.blockchain.minimumGasPrice.mul(new BN(2)), 179 | }), 180 | ); 181 | expect(t.txParams.receipt.success).toBeTruthy(); 182 | const gasPrice = t.txParams.gasPrice; 183 | const cumulativeGas = new BN(t.txParams.receipt.cumulative_gas); 184 | expect(await getBalance(testAccount1)) 185 | .toEqual(account1balance.sub(amount).sub(gasPrice.mul(cumulativeGas))); 186 | expect(await getBalance(testAccount2)).toEqual(account2balance.add(amount)); 187 | }); 188 | }); 189 | -------------------------------------------------------------------------------- /src/components/wallet/wallet.js: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of kaya. 3 | Copyright (c) 2018 - present Zilliqa Research Pte. Ltd. 4 | 5 | kaya is free software: you can redistribute it and/or modify it under the 6 | terms of the GNU General Public License as published by the Free Software 7 | Foundation, either version 3 of the License, or (at your option) any later 8 | version. 9 | 10 | kaya is distributed in the hope that it will be useful, but WITHOUT ANY 11 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 12 | A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License along with 15 | kaya. If not, see . 16 | */ 17 | 18 | /* Wallet Component */ 19 | const assert = require('assert'); 20 | const zCrypto = require('@zilliqa-js/crypto'); 21 | const zUtils = require('@zilliqa-js/util'); 22 | const BN = require('bn.js'); 23 | const zCore = require('@zilliqa-js/core'); 24 | const { logVerbose, consolePrint } = require('../../utilities'); 25 | const config = require('../../config'); 26 | 27 | const logLabel = 'Wallet'; 28 | const { RPCError } = require('../CustomErrors'); 29 | 30 | const errorCodes = zCore.RPCErrorCode; 31 | 32 | // @dev: As this is a kaya, private keys will be stored 33 | // note: Real systems do not store private key 34 | 35 | // Wallet will store address, private key and balance 36 | let wallets = {}; 37 | 38 | /** 39 | * Create a new wallet with the settings registered in `config.js` file 40 | * @returns { Object } - wallet containing private key, amount and nonce 41 | */ 42 | 43 | const createNewWallet = () => { 44 | const pk = zCrypto.schnorr.generatePrivateKey(); 45 | const address = zCrypto.getAddressFromPrivateKey(pk).toLowerCase().replace('0x', ''); 46 | const newWallet = { 47 | privateKey: pk, 48 | amount: config.wallet.defaultAmt, 49 | nonce: config.wallet.defaultNonce, 50 | }; 51 | wallets[address] = newWallet; 52 | }; 53 | 54 | // validate an accounts object to check validity 55 | const validateAccounts = (accounts) => { 56 | Object.keys(accounts).forEach((key) => { 57 | if (!zUtils.validation.isAddress(key)) { 58 | throw new Error(`Invalid address ${key}`); 59 | } 60 | const account = accounts[key]; 61 | // check if account has the necessary properties 62 | if (!account.privateKey && !account.nonce && !account.amount) { 63 | throw new Error('Invalid fields'); 64 | } 65 | 66 | const addressFromPK = zCrypto.getAddressFromPrivateKey( 67 | account.privateKey, 68 | ).replace("0x", '').toLowerCase(); 69 | if (addressFromPK !== key) { 70 | logVerbose(logLabel, 'Validation failure: Invalid Address and Private key-pair'); 71 | throw new Error(`Invalid address for ${key}`); 72 | } 73 | if (Number.isInteger(account.nonce)) { 74 | if (account.nonce < 0) { 75 | throw new Error('Invalid nonce or amount'); 76 | } 77 | } else { 78 | logVerbose(logLabel, 'Amount/nonce is not valid type'); 79 | throw new Error('Invalid nonce or amount'); 80 | } 81 | }); 82 | logVerbose(logLabel, 'Valid accounts file'); 83 | }; 84 | 85 | module.exports = { 86 | 87 | createWallets: (n) => { 88 | assert(n > 0); 89 | for (let i = 0; i < n; i += 1) { 90 | createNewWallet(); 91 | } 92 | }, 93 | 94 | // load accounts object into wallets 95 | loadAccounts: (accounts) => { 96 | validateAccounts(accounts); 97 | const loadedAccounts = accounts; 98 | Object.keys(accounts).forEach((addr) => { 99 | loadedAccounts[addr].amount = new BN(accounts[addr].amount); 100 | }); 101 | logVerbose(logLabel, 102 | `${Object.keys(accounts).length} wallets bootstrapped from file`); 103 | wallets = accounts; 104 | }, 105 | 106 | saveAccounts: (savedDir, timestamp) => { 107 | const targetFilePath = `${savedDir}${timestamp}_accounts.json`; 108 | logVerbose(logLabel, `Saving account details to ${targetFilePath}`); 109 | }, 110 | 111 | // @fixme: Convert wallet object's amount field into string before exporting out 112 | getAccounts: () => wallets, 113 | 114 | printWallet: () => { 115 | if (wallets.length === 0) { 116 | console.log('No wallets generated.'); 117 | } else { 118 | consolePrint('Available Accounts'); 119 | consolePrint('='.repeat(80)); 120 | const accountAddresses = Object.keys(wallets); 121 | const keys = []; 122 | accountAddresses.forEach((addr, index) => { 123 | const balanceInZils = zUtils.units.fromQa(wallets[addr].amount, 'zil'); 124 | consolePrint( 125 | `(${index + 1}) ${addr}\t(${balanceInZils} ZILs)\t(Nonce: ${ 126 | wallets[addr].nonce 127 | })`, 128 | ); 129 | keys.push(wallets[addr].privateKey); 130 | }); 131 | 132 | consolePrint('\n Private Keys '); 133 | consolePrint('='.repeat(80)); 134 | keys.forEach((key, i) => { 135 | consolePrint(`(${i + 1}) ${key}`); 136 | }); 137 | consolePrint('='.repeat(80)); 138 | } 139 | }, 140 | 141 | /** 142 | * sufficientFunds : Checks if a given address has sufficient zils 143 | * @param { String } : address 144 | * @param { BN } : amount of zils 145 | * @returns { Boolean } : True if there is sufficient zils, False if otherwise 146 | */ 147 | 148 | sufficientFunds: (address, amount) => { 149 | if (!BN.isBN(amount)) { 150 | throw new Error('Type error'); 151 | } 152 | // checking if an address has sufficient funds for deduction 153 | logVerbose(logLabel, `Checking if ${address} has ${amount}`); 154 | const bnCurrentBalance = wallets[address.toLowerCase()].amount; 155 | const fundsSufficient = !!amount.lte(bnCurrentBalance); 156 | logVerbose(logLabel, `Funds sufficient ${fundsSufficient}`); 157 | return fundsSufficient; 158 | }, 159 | 160 | /** 161 | * Deduct funds from an account 162 | * @param { String }: Address of an account 163 | * @param { BN }: amount to be deducted 164 | * Does not return any value 165 | */ 166 | 167 | deductFunds: (address, amount) => { 168 | if (!BN.isBN(amount)) { 169 | throw new Error('Type error'); 170 | } 171 | 172 | logVerbose(logLabel, `Deducting ${amount} from ${address}`); 173 | if (!zUtils.validation.isAddress(address)) { 174 | throw new Error('Address size not appropriate'); 175 | } 176 | if (!wallets[address] || !module.exports.sufficientFunds(address, amount)) { 177 | throw new Error('Insufficient Funds'); 178 | } 179 | 180 | // deduct funds 181 | const currentBalance = wallets[address].amount; 182 | logVerbose(logLabel, `Sender's previous Balance: ${currentBalance}`); 183 | const newBalance = currentBalance.sub(amount); 184 | wallets[address].amount = newBalance; 185 | logVerbose(logLabel, 186 | `Deduct funds complete. Sender's new balance: ${wallets[address].amount}`); 187 | }, 188 | 189 | /** 190 | * Add funds to an account address 191 | * @param { string }: address - Address of recipient 192 | * @param { Number }: amount - amount of zils to transfer 193 | * Does not return any value 194 | */ 195 | addFunds: (address, amount) => { 196 | logVerbose(logLabel, `Adding ${amount} to ${address}`); 197 | if (!BN.isBN(amount)) { 198 | throw new Error('Type error'); 199 | } 200 | if (!zUtils.validation.isAddress(address)) { 201 | throw new RPCError('Address size not appropriate', errorCodes.RPC_INVALID_ADDRESS_OR_KEY, null); 202 | } 203 | address = address.replace('0x', ''); 204 | if (!wallets[address]) { 205 | // initialize new wallet account 206 | logVerbose(logLabel, `Creating new wallet account for ${address}`); 207 | wallets[address] = {}; 208 | wallets[address].amount = new BN(0); 209 | wallets[address].nonce = 0; 210 | } 211 | const currentBalance = wallets[address].amount; 212 | logVerbose(logLabel, `Recipient's previous Balance: ${currentBalance.toString()}`); 213 | 214 | // add amount 215 | const resultBalance = currentBalance.add(amount); 216 | wallets[address].amount = resultBalance; 217 | 218 | logVerbose(logLabel, 219 | `Adding funds complete. Recipient's new Balance: ${ 220 | wallets[address].amount.toString() 221 | }`); 222 | }, 223 | 224 | /** 225 | * Increases nonce for a given address 226 | * @param { String } address 227 | */ 228 | 229 | increaseNonce: (address) => { 230 | logVerbose(logLabel, `Increasing nonce for ${address}`); 231 | if (!zUtils.validation.isAddress(address)) { 232 | throw new RPCError('Address size not appropriate', errorCodes.RPC_INVALID_ADDRESS_OR_KEY, null); 233 | } 234 | if (!wallets[address]) { 235 | throw new RPCError('Account is not created', errorCodes.RPC_INVALID_ADDRESS_OR_KEY, null); 236 | } else { 237 | const newNonce = wallets[address].nonce + 1; 238 | wallets[address].nonce = newNonce; 239 | logVerbose(logLabel, `New nonce for ${address} : ${newNonce}`); 240 | } 241 | }, 242 | 243 | /** 244 | * GetBalance: Returns the balance for a given address 245 | * Throws if the address is not well-formed 246 | * @param { String } : value - address 247 | * @returns {Object} { balance: {String}, nonce; Number} 248 | */ 249 | 250 | getBalance: (value) => { 251 | if (!zUtils.validation.isAddress(value)) { 252 | throw new RPCError('Address size not appropriate', errorCodes.RPC_INVALID_ADDRESS_OR_KEY, null); 253 | } 254 | 255 | const address = value.toLowerCase(); 256 | logVerbose(logLabel, `Getting balance for ${address}`); 257 | 258 | if (!wallets[address]) { 259 | throw new RPCError('Account is not created', errorCodes.RPC_INVALID_ADDRESS_OR_KEY, null); 260 | } 261 | 262 | return { 263 | balance: (wallets[address].amount).toString(), 264 | nonce: wallets[address].nonce, 265 | }; 266 | }, 267 | }; 268 | -------------------------------------------------------------------------------- /src/components/scilla/scilla.js: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of kaya. 3 | Copyright (c) 2018 - present Zilliqa Research Pte. Ltd. 4 | 5 | kaya is free software: you can redistribute it and/or modify it under the 6 | terms of the GNU General Public License as published by the Free Software 7 | Foundation, either version 3 of the License, or (at your option) any later 8 | version. 9 | 10 | kaya is distributed in the hope that it will be useful, but WITHOUT ANY 11 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 12 | A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License along with 15 | kaya. If not, see . 16 | */ 17 | 18 | const fs = require('fs'); 19 | const path = require('path'); 20 | const { promisify } = require('util'); 21 | const rp = require('request-promise'); 22 | const { execFile } = require('child_process'); 23 | const { codeCleanup, logVerbose } = require('../../utilities'); 24 | const { InterpreterError } = require('../CustomErrors'); 25 | const config = require('../../config'); 26 | 27 | const logLabel = 'SCILLA'; 28 | 29 | const execFileAsync = promisify(execFile); 30 | const fsWriteFileAsync = promisify(fs.writeFile); 31 | const fsMkdirAsync = promisify(fs.mkdir); 32 | 33 | const ensureExists = async (dirPath) => { 34 | const mask = 0o700; 35 | try { 36 | await fsMkdirAsync(dirPath, mask); 37 | } catch (err) { 38 | if (err.code !== 'EEXIST') throw err; // ignore the error if the folder already exists 39 | } 40 | }; 41 | 42 | const writeKayaFile = async (filePath, text) => { 43 | const dir = path.dirname(filePath); 44 | await ensureExists(dir); 45 | return fsWriteFileAsync(filePath, text); 46 | }; 47 | 48 | const makeBlockchainJson = async (val, blockchainPath) => { 49 | const blockchainData = [ 50 | { 51 | vname: 'BLOCKNUMBER', 52 | type: 'BNum', 53 | value: val.toString(), 54 | }, 55 | ]; 56 | await writeKayaFile(blockchainPath, JSON.stringify(blockchainData)); 57 | logVerbose(logLabel, `blockchain.json file prepared for blocknumber: ${val}`); 58 | }; 59 | 60 | // Scilla runner doesn't return the balance correctly 61 | // We need to set it manually 62 | const getStateWithCorrectBalance = (states, amount) => { 63 | logVerbose(logLabel, 'Payload amount', amount); 64 | const balanceIndex = states.findIndex(state => state.vname === '_balance'); 65 | if (balanceIndex !== -1) { 66 | const newStates = [...states]; 67 | newStates[balanceIndex] = { 68 | ...states[balanceIndex], 69 | value: amount.toString(), 70 | }; 71 | return newStates; 72 | } 73 | return states; 74 | }; 75 | 76 | /** 77 | * Runs the remote checker (currently hosted by Zilliqa) 78 | * @async 79 | * @method runRemoteCheckerAsync 80 | * @param { String } filepath to code 81 | */ 82 | const runRemoteCheckerAsync = async (filepath) => { 83 | logVerbose(logLabel, 'Running Remote Checker'); 84 | const fullCode = fs.readFileSync(filepath, 'utf-8'); 85 | const reqBody = { code: fullCode }; 86 | 87 | const options = { 88 | method: 'POST', 89 | url: config.scilla.CHECKER_URL, 90 | json: true, 91 | body: reqBody, 92 | }; 93 | 94 | try { 95 | await rp(options); 96 | logVerbose(logLabel, 'Contract passes type-checker'); 97 | } catch (err) { 98 | if (err.statusCode === 400) { 99 | console.log('Error with type-checking [Remote Checker]'); 100 | } 101 | throw new InterpreterError(`Error: ${err.message}`); 102 | } 103 | }; 104 | 105 | /** 106 | * Runs the remote interpreter (currently hosted by zilliqa) 107 | * @async 108 | * @method runRemoteInterpreterAsync 109 | * @param {Object} data object containing the code, state, init, message and blockchain filepath 110 | * @returns: Output message received from the remote scilla interpreter 111 | */ 112 | const runRemoteInterpreterAsync = async (data) => { 113 | logVerbose(logLabel, 'Running Remote Interpreter'); 114 | 115 | const reqData = { 116 | code: fs.readFileSync(data.code, 'utf-8'), 117 | init: fs.readFileSync(data.init, 'utf-8'), 118 | blockchain: fs.readFileSync(data.blockchain, 'utf-8'), 119 | gaslimit: data.gas, 120 | }; 121 | 122 | if (!data.isDeployment) { 123 | // contract invoke requires state and message 124 | reqData.state = fs.readFileSync(data.state, 'utf-8'); 125 | reqData.message = fs.readFileSync(data.msg, 'utf-8'); 126 | } 127 | 128 | const options = { 129 | method: 'POST', 130 | url: config.scilla.RUNNER_URL, 131 | json: true, 132 | body: reqData, 133 | }; 134 | 135 | logVerbose(logLabel, 'Attempting to run remote interpreter now'); 136 | let response; 137 | try { 138 | response = await rp(options); 139 | } catch (err) { 140 | console.log('Interpreter failed to process code. Error message received:'); 141 | console.log(`${err.message}`); 142 | console.log('Possible fix: Have your code passed type checking?'); 143 | throw new InterpreterError('Remote interpreter failed to run'); 144 | } 145 | 146 | // FIXME: Change error mechanism once the Scilla versioning is completed 147 | // https://github.com/Zilliqa/scilla/issues/291 148 | if (!response.message.gas_remaining) { 149 | console.log( 150 | 'WARNING: You are using an outdated scilla interpreter. Please upgrade to the latest version', 151 | ); 152 | throw new Error('Outdated scilla binaries'); 153 | } 154 | 155 | return response.message; 156 | }; 157 | 158 | /** 159 | * Executes the local interpreter 160 | * @async 161 | * @method runLocalInterpreterAsync 162 | * @param { Object } cmdOptions: Command options required to run the scilla interpreter 163 | * @param { String } outputPath : File path to the output file 164 | * @returns { Object } - response object 165 | */ 166 | 167 | const runLocalInterpreterAsync = async (cmdOptions, outputPath) => { 168 | logVerbose(logLabel, 'Running local scilla interpreter'); 169 | 170 | const SCILLA_BIN_PATH = config.constants.smart_contract.SCILLA_RUNNER; 171 | // Run Scilla Interpreter 172 | if (!fs.existsSync(SCILLA_BIN_PATH)) { 173 | logVerbose(logLabel, 'Scilla runner not found. Hint: Have you compiled the scilla binaries?'); 174 | throw new InterpreterError('Kaya RPC Runtime Error: Scilla-runner not found'); 175 | } 176 | 177 | const result = await execFileAsync(SCILLA_BIN_PATH, cmdOptions); 178 | 179 | if (result.stderr !== '') { 180 | console.log(`Interpreter error: ${result.stderr}`); 181 | throw new InterpreterError(`Interpreter error: ${result.stderr}`); 182 | } 183 | 184 | logVerbose(logLabel, 'Scilla execution completed'); 185 | 186 | const retMsg = JSON.parse(fs.readFileSync(outputPath, 'utf-8')); 187 | return retMsg; 188 | }; 189 | 190 | const runLocalCheckerAsync = async (cmdOptions) => { 191 | logVerbose(logLabel, 'Running local checker'); 192 | const SCILLA_CHECKER_PATH = config.constants.smart_contract.SCILLA_CHECKER; 193 | if (!fs.existsSync(SCILLA_CHECKER_PATH)) { 194 | logVerbose(logLabel, 'Scilla checker not found. Hint: Have you compiled the scilla binaries?'); 195 | throw new InterpreterError('Kaya RPC Runtime Error: Scilla-checker not found'); 196 | } 197 | 198 | try { 199 | await execFileAsync(SCILLA_CHECKER_PATH, cmdOptions); 200 | logVerbose(logLabel, 'Contract passes type-checker'); 201 | } catch (err) { 202 | console.log('Error: Typechecking failed. Possible fix: Run scilla-checker on your contract'); 203 | throw new InterpreterError('Checker fails'); 204 | } 205 | }; 206 | 207 | module.exports = { 208 | 209 | /** 210 | * Takes arguments from `logic.js` and runs the scilla interpreter 211 | * 212 | * @method executeScillaRun 213 | * @async 214 | * @param { Object } payload - payload object from the message 215 | * @param { String } contractAddr - Contract address, only applicable if it is a deployment call 216 | * @param { String } senderAddress - message sender address 217 | * @param { String } directory of the data files 218 | * @param { String } current block number 219 | * @param { String } gasLimit - gasLimit specified by the caller 220 | * @returns {{ gasRemaining, nextAddress, events, message }} - interpreter response 221 | */ 222 | executeScillaRun: async (payload, newContractAddr, senderAddr, dir, currentBnum) => { 223 | // Get the blocknumber into a json file 224 | const blockchainPath = `${dir}blockchain.json`; 225 | await makeBlockchainJson(currentBnum, blockchainPath); 226 | 227 | const toAddr = payload.toAddr && payload.toAddr.toLowerCase().replace('0x', ''); 228 | const isCodeDeployment = payload.code && toAddr === '0'.repeat(40); 229 | const contractAddr = (isCodeDeployment ? newContractAddr : toAddr) 230 | 231 | const initPath = `${dir}${contractAddr}_init.json`; 232 | const codePath = `${dir}${contractAddr}_code.scilla`; 233 | const outputPath = `${dir}${contractAddr}_out.json`; 234 | const statePath = `${dir}${contractAddr}_state.json`; 235 | const msgPath = `${dir}${toAddr}_message.json`; 236 | 237 | const standardOpt = [ 238 | '-libdir', 239 | config.constants.smart_contract.SCILLA_LIB, 240 | '-gaslimit', 241 | payload.gasLimit, 242 | ]; 243 | const initOpt = ['-init', initPath]; 244 | const outputOpt = ['-o', outputPath]; 245 | const codeOpt = ['-i', codePath]; 246 | const blockchainOpt = ['-iblockchain', blockchainPath]; 247 | 248 | const cmdOpt = [].concat.apply([], [standardOpt, initOpt, outputOpt, codeOpt, blockchainOpt]); 249 | 250 | if (isCodeDeployment) { 251 | logVerbose(logLabel, 'Code Deployment'); 252 | 253 | // get init data from payload 254 | const acceptedPayload = JSON.parse(payload.data); 255 | 256 | const thisAddr = { 257 | vname: '_this_address', 258 | type: 'ByStr20', 259 | value: `0x${contractAddr}`, 260 | }; 261 | 262 | const thisCreationBlock = { 263 | vname: '_creation_block', 264 | type: 'BNum', 265 | value: `${currentBnum}`, 266 | }; 267 | 268 | const deploymentPayload = [...acceptedPayload, thisAddr, thisCreationBlock]; 269 | const initParams = JSON.stringify(deploymentPayload); 270 | await writeKayaFile(initPath, initParams); 271 | 272 | const rawCode = JSON.stringify(payload.code); 273 | const cleanedCode = codeCleanup(rawCode); 274 | await writeKayaFile(codePath, cleanedCode); 275 | } else { 276 | // Invoke transition 277 | logVerbose(logLabel, `Calling transition within contract ${payload.toAddr}`); 278 | 279 | logVerbose(logLabel, `Code Path: ${codePath}`); 280 | logVerbose(logLabel, `Init Path: ${initPath}`); 281 | if (!fs.existsSync(codePath) || !fs.existsSync(initPath)) { 282 | logVerbose(logLabel, 'Error, contract has not been created.'); 283 | throw new Error('Address does not exist'); 284 | } 285 | 286 | // Create message object from payload 287 | const msgObj = JSON.parse(payload.data); 288 | msgObj._amount = payload.amount; 289 | msgObj._sender = `0x${senderAddr}`; 290 | await writeKayaFile(msgPath, JSON.stringify(msgObj)); 291 | 292 | // Append additional options for transition calls 293 | cmdOpt.push('-imessage'); 294 | cmdOpt.push(msgPath); 295 | cmdOpt.push('-istate'); 296 | cmdOpt.push(statePath); 297 | } 298 | 299 | if (!fs.existsSync(codePath) || !fs.existsSync(initPath)) { 300 | logVerbose(logLabel, 'Error, contract has not been created.'); 301 | throw new Error('Address does not exist'); 302 | } 303 | 304 | let retMsg; 305 | if (!config.scilla.remote) { 306 | const checkerCmdOpts = [...standardOpt, codePath]; 307 | await runLocalCheckerAsync(checkerCmdOpts); 308 | // local scilla interpreter 309 | retMsg = await runLocalInterpreterAsync(cmdOpt, outputPath); 310 | } else { 311 | await runRemoteCheckerAsync(codePath); 312 | const apiReqParams = { 313 | output: outputPath, 314 | state: statePath, 315 | code: codePath, 316 | msg: msgPath, 317 | init: initPath, 318 | blockchain: blockchainPath, 319 | gas: payload.gasLimit, 320 | isDeployment: isCodeDeployment, 321 | }; 322 | retMsg = await runRemoteInterpreterAsync(apiReqParams); 323 | } 324 | 325 | const prevStates = retMsg.states; 326 | const newStates = isCodeDeployment 327 | ? getStateWithCorrectBalance(prevStates, payload.amount) 328 | : prevStates; 329 | await writeKayaFile(statePath, JSON.stringify(newStates)); 330 | logVerbose(logLabel, `State logged down in ${statePath}`); 331 | if (isCodeDeployment) logVerbose(logLabel, `Contract Address Deployed: ${contractAddr}`); 332 | 333 | const responseData = {}; 334 | responseData.gasRemaining = retMsg.gas_remaining; 335 | if (retMsg.events) { 336 | responseData.events = retMsg.events.map(e => ({ 337 | ...e, 338 | address: payload.toAddr, 339 | })); 340 | } 341 | const message = retMsg.message; 342 | if (message != null) { 343 | responseData.message = message; 344 | 345 | // Obtains the next address based on the message 346 | logVerbose(logLabel, `Next address: ${message._recipient}`); 347 | responseData.nextAddress = message._recipient; 348 | } else { 349 | // Contract deployment do not have the next address 350 | responseData.nextAddress = '0'.repeat(40); 351 | } 352 | return responseData; 353 | }, 354 | }; 355 | -------------------------------------------------------------------------------- /src/components/scilla/stdlib/ListUtils.scillib: -------------------------------------------------------------------------------- 1 | library ListUtils 2 | 3 | (* ('A -> 'B) -> List 'A -> List 'B *) 4 | (* Apply (f : 'A -> 'B) to every element of List 'A *) 5 | (* to generate List 'B. *) 6 | let list_map = tfun 'A => tfun 'B => 7 | fun (f : 'A -> 'B) => fun (l : List 'A) => 8 | let folder = @list_foldr 'A (List 'B) in 9 | let init = Nil {'B} in 10 | let iter = fun (h : 'A) => fun (z : List 'B) => 11 | let h1 = f h in 12 | Cons {'B} h1 z 13 | in folder iter init l 14 | 15 | (* ('A -> Bool) -> List 'A -> List 'A *) 16 | (* Preserving the order of elements in (l : List 'A), *) 17 | (* return new list containing only those elements *) 18 | (* that satisfy the function f. *) 19 | let list_filter = 20 | tfun 'A => 21 | fun (f : 'A -> Bool) => 22 | fun (l : List 'A) => 23 | let folder = @list_foldr 'A (List 'A) in 24 | let init = Nil {'A} in 25 | let iter = 26 | fun (h : 'A) => 27 | fun (z : List 'A) => 28 | let h1 = f h in 29 | match h1 with 30 | | True => 31 | Cons {'A} h z 32 | | False => 33 | z 34 | end 35 | in 36 | folder iter init l 37 | 38 | (* (List 'A) -> (Option 'A) *) 39 | (* Return the head element of a list as Some 'A, None otherwise *) 40 | let list_head = 41 | tfun 'A => 42 | fun (l : List 'A) => 43 | match l with 44 | | Cons h t => 45 | Some {'A} h 46 | | Nil => 47 | None {'A} 48 | end 49 | 50 | (* (List 'A) -> (Option List 'A) *) 51 | (* Return the list except for the head *) 52 | let list_tail = 53 | tfun 'A => 54 | fun (l : List 'A) => 55 | match l with 56 | | Cons h t => 57 | Some {(List 'A)} t 58 | | Nil => 59 | None {(List 'A)} 60 | end 61 | 62 | (* (List 'A -> List 'A -> List 'A) *) 63 | (* Append the second list to the first one and return a new List *) 64 | let list_append = 65 | tfun 'A => 66 | fun (l1 : List 'A) => 67 | fun (l2 : List 'A) => 68 | (* Fold right over l1 and keep prepending elements to l2 *) 69 | (* l2 is the initial accumulator *) 70 | let folder = @list_foldr 'A (List 'A) in 71 | let init = l2 in 72 | let iter = 73 | fun (h : 'A) => 74 | fun (z : List 'A) => 75 | Cons {'A} h z 76 | in 77 | folder iter init l1 78 | 79 | (* (List 'A -> List 'A) *) 80 | (* Return the reverse of the argument list *) 81 | let list_reverse = 82 | tfun 'A => 83 | fun (l : List 'A) => 84 | let folder = @list_foldl 'A (List 'A) in 85 | let init = Nil {'A} in 86 | let iter = 87 | fun (z : List 'A) => 88 | fun (h : 'A) => 89 | Cons {'A} h z 90 | in 91 | folder iter init l 92 | 93 | (* (List List 'A) -> List 'A *) 94 | (* Concatenate a list of lists. The elements of the argument are all *) 95 | (* concatenated together (in the same order) to give the result. *) 96 | let list_flatten = 97 | tfun 'A => 98 | fun (l : List (List 'A)) => 99 | let folder = @list_foldr (List 'A) (List 'A) in 100 | let init = Nil {'A} in 101 | let iter = 102 | fun (h : List 'A) => 103 | fun (z : List 'A) => 104 | let app = @list_append 'A in 105 | app h z 106 | in 107 | folder iter init l 108 | 109 | (* List 'A -> Int32 *) 110 | (* Number of elements in list *) 111 | let list_length = 112 | tfun 'A => 113 | fun (l : List 'A) => 114 | let folder = @list_foldl 'A Uint32 in 115 | let init = Uint32 0 in 116 | let iter = 117 | fun (z : Uint32) => 118 | fun (h : 'A) => 119 | let one = Uint32 1 in 120 | builtin add one z 121 | in 122 | folder iter init l 123 | 124 | (* Helper function for list_eq. Not for public use. *) 125 | (* Returns Some Nil on successul match. None otherwise. *) 126 | let list_eq_helper = 127 | tfun 'A => 128 | fun (eq : 'A -> 'A -> Bool) => 129 | fun (l1 : List 'A) => 130 | fun (l2 : List 'A) => 131 | let folder = @list_foldl 'A (Option (List 'A)) in 132 | let init = Some {(List 'A)} l2 in 133 | let iter = 134 | fun (z : Option (List 'A)) => 135 | fun (h1 : 'A) => 136 | match z with 137 | | Some ll2 => 138 | let headF = @list_head 'A in 139 | let h2o = headF ll2 in 140 | match h2o with 141 | | Some h2 => 142 | let eqb = eq h1 h2 in 143 | match eqb with 144 | | True => 145 | let tailF = @list_tail 'A in 146 | tailF ll2 147 | | False => 148 | None {(List 'A)} 149 | end 150 | | None => 151 | None {(List 'A)} 152 | end 153 | | None => 154 | None {(List 'A)} 155 | end 156 | in 157 | folder iter init l1 158 | 159 | (* ('A -> 'A -> Bool) -> List 'A -> List 'A -> Bool *) 160 | (* Return true iff two lists compare equal. *) 161 | (* Comparison is performed using the "f" function provided. *) 162 | let list_eq = 163 | tfun 'A => 164 | fun (f : 'A -> 'A -> Bool) => 165 | fun (l1 : List 'A) => 166 | fun (l2 : List 'A) => 167 | let eqh = @list_eq_helper 'A in 168 | let res = eqh f l1 l2 in 169 | match res with 170 | | Some l => 171 | match l with 172 | | Nil => 173 | True 174 | | _ => 175 | False 176 | end 177 | | _ => 178 | False 179 | end 180 | 181 | (* ('A -> Bool) -> List 'A -> Bool *) 182 | (* Return True iff all elements of list "l" satisfy predicate "f". *) 183 | let list_forall = 184 | tfun 'A => 185 | fun (f : 'A -> Bool) => 186 | fun (l : List 'A) => 187 | let folder = @list_foldl 'A Bool in 188 | let init = True in 189 | let iter = 190 | fun (z : Bool) => 191 | fun (h : 'A) => 192 | let res = f h in 193 | match res with 194 | | False => 195 | False 196 | | True => 197 | z 198 | end 199 | in 200 | folder iter init l 201 | 202 | (* ('A -> 'A -> Bool) -> List 'A -> List 'A *) 203 | (* Stable sort the input list "l". *) 204 | (* "flt" returns True if the first argument is lesser-than the second *) 205 | let list_sort = 206 | (* Insertion sort *) 207 | tfun 'A => 208 | fun (flt : 'A -> 'A -> Bool) => 209 | fun (ls : List 'A) => 210 | let true = True in 211 | let false = False in 212 | let rec_A_A = @list_foldr 'A (List 'A) in 213 | let rec_A_Pair = @list_foldr 'A (Pair Bool (List 'A)) in 214 | let nil_A = Nil {'A} in 215 | let sink_down = 216 | fun (e : 'A) => fun (ls : List 'A) => 217 | let init = Pair {Bool (List 'A)} false nil_A in 218 | let iter1 = 219 | fun (h : 'A) => 220 | fun (res : Pair Bool (List 'A)) => 221 | match res with 222 | | Pair True rest => 223 | let z = Cons {'A} h rest in 224 | Pair {Bool (List 'A)} true z 225 | | Pair False rest => 226 | let bl = flt h e in 227 | match bl with 228 | | True => 229 | let z = Cons {'A} e rest in 230 | let z2 = Cons {'A} h z in 231 | Pair {Bool (List 'A)} true z2 232 | | False => 233 | let z = Cons {'A} h rest in 234 | Pair {Bool (List 'A)} false z 235 | end 236 | end 237 | in 238 | let res1 = rec_A_Pair iter1 init ls in 239 | match res1 with 240 | | Pair True ls1 => ls1 241 | | Pair False ls1 => Cons {'A} e ls1 242 | end 243 | in 244 | let iter2 = 245 | fun (h : 'A) => 246 | fun (res : List 'A) => 247 | sink_down h res 248 | in 249 | rec_A_A iter2 nil_A ls 250 | 251 | 252 | (* ('A -> Bool) -> 'A -> 'A *) 253 | (* Return Some a, where "a" is the first element of *) 254 | (* "l" that satisfies the predicate "f". *) 255 | (* Return None iff none of the elements in "l" satisfy "f". *) 256 | let list_find = 257 | tfun 'A => 258 | fun (f : 'A -> Bool) => 259 | fun (l : List 'A) => 260 | let folder = @list_foldl 'A (Option 'A) in 261 | let init = None {'A} in 262 | let iter = 263 | fun (z : Option 'A) => 264 | fun (h : 'A) => 265 | match z with 266 | | Some a => 267 | z 268 | | None => 269 | let r = f h in 270 | match r with 271 | | True => 272 | Some {'A} h 273 | | False => 274 | None {'A} 275 | end 276 | end 277 | in 278 | folder iter init l 279 | 280 | (* ('A -> Bool) -> List 'A -> Bool *) 281 | (* Return True iff at least one element of list "l" satisfy predicate "f". *) 282 | let list_exists = 283 | tfun 'A => 284 | fun (f : 'A -> Bool) => 285 | fun (l : List 'A) => 286 | let folder = @list_foldl 'A Bool in 287 | let init = False in 288 | let iter = 289 | fun (z : Bool) => 290 | fun (h : 'A) => 291 | let res = f h in 292 | match res with 293 | | True => 294 | True 295 | | False => 296 | z 297 | end 298 | in 299 | folder iter init l 300 | 301 | (* ('A -> 'A -> Bool) -> 'A -> List 'A -> Bool *) 302 | (* Return True iff "m" is in the list "l", as compared by function "f". *) 303 | let list_mem = 304 | tfun 'A => 305 | fun (f : 'A -> 'A -> Bool) => 306 | fun (m : 'A) => 307 | fun (l : List 'A) => 308 | let ex_pred = f m in 309 | let ex = @list_exists 'A in 310 | ex ex_pred l 311 | 312 | (* List 'A -> List 'B -> List (Pair 'A 'B) *) 313 | (* Combine corresponding elements of m1 and m2 into a pair *) 314 | (* and return the resulting list. In case of different number *) 315 | (* of elements in the lists, the extra elements are ignored. *) 316 | let list_zip = 317 | tfun 'A => 318 | tfun 'B => 319 | fun (m1 : List 'A) => 320 | fun (m2 : List 'B) => 321 | let list_zip_helper = 322 | tfun 'A => 323 | tfun 'B => 324 | fun (l1 : List 'A) => 325 | fun (l2 : List 'B) => 326 | let folder = @list_foldl 'A (Pair (List (Pair 'A 'B)) (List 'B)) in 327 | let nil = Nil {(Pair 'A 'B)} in 328 | let init = Pair {(List (Pair 'A 'B)) (List 'B)} nil l2 in 329 | let iter = 330 | fun (z : Pair (List (Pair 'A 'B)) (List 'B)) => 331 | fun (h : 'A) => 332 | match z with 333 | | Pair r b => 334 | (* Get b's head, pair it with h and add to r. *) 335 | let header = @list_head 'B in 336 | let tailer = @list_tail 'B in 337 | let bhead = header b in 338 | match bhead with 339 | | Some bel => 340 | let newp = Pair {'A 'B} h bel in 341 | let newp_concat = Cons {(Pair 'A 'B)} newp r in 342 | let btail = tailer b in 343 | let newb = 344 | match btail with 345 | | Some t => 346 | t 347 | | None => 348 | let nilb = Nil {'B} in 349 | nilb 350 | end 351 | in 352 | Pair {(List (Pair 'A 'B)) (List 'B)} newp_concat newb 353 | | None => 354 | z 355 | end 356 | end 357 | in 358 | folder iter init l1 359 | in 360 | let zipper = @list_zip_helper 'A 'B in 361 | let res = zipper m1 m2 in 362 | match res with 363 | | Pair x y => 364 | let reverser = @list_reverse (Pair 'A 'B) in 365 | reverser x 366 | end 367 | 368 | (* ('A -> 'B -> 'C) -> List 'A -> List 'B -> List 'C *) 369 | (* Combine corresponding elements of m1 and m2 using "f" *) 370 | (* and return the resulting list of 'C. In case of different number *) 371 | (* of elements in the lists, the extra elements are ignored. *) 372 | let list_zip_with = 373 | tfun 'A => 374 | tfun 'B => 375 | tfun 'C => 376 | fun (f : 'A -> 'B -> 'C) => 377 | fun (m1 : List 'A) => 378 | fun (m2 : List 'B) => 379 | let list_zip_helper = 380 | tfun 'A => 381 | tfun 'B => 382 | tfun 'C => 383 | fun (g : 'A -> 'B -> 'C) => 384 | fun (l1 : List 'A) => 385 | fun (l2 : List 'B) => 386 | let folder = @list_foldl 'A (Pair (List 'C) (List 'B)) in 387 | let nilb = Nil {'B} in 388 | let nilc = Nil {'C} in 389 | let init = Pair {(List 'C) (List 'B)} nilc l2 in 390 | let iter = 391 | fun (z : Pair (List 'C) (List 'B)) => 392 | fun (h : 'A) => 393 | match z with 394 | | Pair r b => 395 | (* Get b's head, pair it with h and add to r. *) 396 | let header = @list_head 'B in 397 | let tailer = @list_tail 'B in 398 | let bhead = header b in 399 | match bhead with 400 | | Some bel => 401 | let newp = g h bel in 402 | let newp_concat = Cons {'C} newp r in 403 | let btail = tailer b in 404 | let newb = 405 | match btail with 406 | | Some t => 407 | t 408 | | None => 409 | nilb 410 | end 411 | in 412 | Pair {(List 'C) (List 'B)} newp_concat newb 413 | | None => 414 | z 415 | end 416 | end 417 | in 418 | folder iter init l1 419 | in 420 | let zipper = @list_zip_helper 'A 'B 'C in 421 | let res = zipper f m1 m2 in 422 | match res with 423 | | Pair x y => 424 | let reverser = @list_reverse 'C in 425 | reverser x 426 | end 427 | 428 | (* List (Pair 'A 'B) -> Pair (List 'A) (List 'B) *) 429 | let list_unzip = 430 | tfun 'A => 431 | tfun 'B => 432 | fun (l : List (Pair 'A 'B)) => 433 | let folder = @list_foldr (Pair 'A 'B) (Pair (List 'A) (List 'B)) in 434 | let nil1 = Nil {'A} in 435 | let nil2 = Nil {'B} in 436 | let init = Pair {(List 'A) (List 'B)} nil1 nil2 in 437 | let iter = 438 | fun (h : Pair 'A 'B) => 439 | fun (z : Pair (List 'A) (List 'B)) => 440 | match h with 441 | | Pair a b => 442 | match z with 443 | | Pair la lb => 444 | let nla = Cons {'A} a la in 445 | let nlb = Cons {'B} b lb in 446 | Pair {(List 'A)(List 'B)} nla nlb 447 | end 448 | end 449 | in 450 | folder iter init l 451 | 452 | (* Uint32 -> List 'A -> Option 'A *) 453 | (* Returns (Some 'A) if n'th element exists in list. None otherwise *) 454 | let list_nth = 455 | tfun 'A => 456 | fun (n_h : Uint32) => 457 | fun (l_h : List 'A) => 458 | let list_nth_helper = 459 | tfun 'A => 460 | fun (n : Uint32) => 461 | fun (l : List 'A) => 462 | let folder = @list_foldl 'A (Pair Uint32 (Option 'A)) in 463 | let zero = Uint32 0 in 464 | let none = None {'A} in 465 | let init = Pair {Uint32 (Option 'A)} zero none in 466 | let iter = 467 | fun (z : Pair Uint32 (Option 'A)) => 468 | fun (h : 'A) => 469 | match z with 470 | | Pair i oe => 471 | let one = Uint32 1 in 472 | let nexti = builtin add i one in 473 | let this = builtin eq n i in 474 | match this with 475 | | True => 476 | let someh = Some {'A} h in 477 | Pair {Uint32 (Option 'A)} nexti someh 478 | | False => 479 | Pair {Uint32 (Option 'A)} nexti oe 480 | end 481 | end 482 | in 483 | folder iter init l 484 | in 485 | let nth = @list_nth_helper 'A in 486 | let res = nth n_h l_h in 487 | match res with 488 | | Pair i oe => 489 | oe 490 | end -------------------------------------------------------------------------------- /src/logic.js: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of kaya. 3 | Copyright (c) 2018 - present Zilliqa Research Pte. Ltd. 4 | 5 | kaya is free software: you can redistribute it and/or modify it under the 6 | terms of the GNU General Public License as published by the Free Software 7 | Foundation, either version 3 of the License, or (at your option) any later 8 | version. 9 | 10 | kaya is distributed in the hope that it will be useful, but WITHOUT ANY 11 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 12 | A PARTICULAR PURPOSE. See the GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License along with 15 | kaya. If not, see . 16 | */ 17 | 18 | // logic.js : Logic Script 19 | const hashjs = require('hash.js'); 20 | const fs = require('fs'); 21 | const BN = require('bn.js'); 22 | const zCrypto = require('@zilliqa-js/crypto'); 23 | const zCore = require('@zilliqa-js/core'); 24 | const { bytes, validation } = require('@zilliqa-js/util'); 25 | const zAccount = require('@zilliqa-js/account'); 26 | const scillaCtrl = require('./components/scilla/scilla'); 27 | const walletCtrl = require('./components/wallet/wallet'); 28 | const blockchain = require('./components/blockchain'); 29 | const { InterpreterError, BalanceError, RPCError } = require('./components/CustomErrors'); 30 | const { logVerbose, consolePrint, isDeployContract } = require('./utilities'); 31 | const config = require('./config'); 32 | 33 | const logLabel = ('LOGIC'); 34 | 35 | const errorCodes = zCore.RPCErrorCode; 36 | 37 | // non-persistent states. Initializes whenever server starts 38 | let transactions = {}; 39 | let createdContractsByUsers = {}; // address => contract addresses 40 | const contractAddressesByTransactionID = {}; // transaction hash => contract address 41 | 42 | /** 43 | * computes the contract address from the sender's address and nonce 44 | * @method computeContractAddr 45 | * @param { String } senderAddr 46 | * @returns { String } contract address to be deployed 47 | */ 48 | const computeContractAddr = (senderAddr) => { 49 | const userNonce = walletCtrl.getBalance(senderAddr).nonce; 50 | return hashjs.sha256() 51 | .update(senderAddr, 'hex') 52 | .update(bytes.intToHexArray(userNonce, 16).join(''), 'hex') 53 | .digest('hex') 54 | .slice(24); 55 | }; 56 | 57 | /** 58 | * Confirms the transaction by logging it 59 | * @method confirmTransaction 60 | * @param { Object } payload - payload of the incoming message 61 | * @param { String } transactionID - transaction ID 62 | * @param { Object } receiptInfo - information about gas and if the transaction is confirmed 63 | * Does not return any message 64 | */ 65 | 66 | const confirmTransaction = (payload, transactionID, receiptInfo) => { 67 | const txnDetails = { 68 | ID: transactionID, 69 | amount: payload.amount, 70 | gasLimit: payload.gasLimit, 71 | gasPrice: payload.gasPrice, 72 | nonce: payload.nonce, 73 | receipt: receiptInfo, 74 | senderPubKey: "0x".concat(payload.pubKey), 75 | signature: "0x".concat(payload.signature), 76 | toAddr: payload.toAddr.replace('0x', ''), 77 | version: payload.version, 78 | }; 79 | transactions[transactionID] = txnDetails; 80 | logVerbose(logLabel, `Transaction logged: ${transactionID}`); 81 | }; 82 | 83 | /** 84 | * 85 | * Computes the transaction hash from a given payload 86 | * @method computeTransactionHash 87 | * @param { Object } payload : Payload of the message 88 | */ 89 | const computeTransactionHash = (payload) => { 90 | // transactionID is a sha256 digest of txndetails 91 | const copyPayload = JSON.parse(JSON.stringify(payload)); 92 | delete copyPayload.signature; // txn hash does not include signature 93 | const buf = Buffer.from(JSON.stringify(copyPayload)); 94 | const transactionHash = hashjs 95 | .sha256() 96 | .update(buf) 97 | .digest('hex'); 98 | return transactionHash; 99 | }; 100 | 101 | /** 102 | * Checks the transaction payload to make sure that it is well-formed 103 | * @method checkTransactionJson 104 | * @param { Object} data : Payload retrieved from message 105 | * @returns { Boolean } : True if the payload is valid, false if it is not 106 | */ 107 | const checkTransactionJson = (data) => { 108 | const CHAIN_ID = config.chainId; 109 | const MSG_VERSION = config.msgVersion; 110 | const EXPECTED_VERSION = bytes.pack(CHAIN_ID, MSG_VERSION); 111 | 112 | if (data !== null && typeof data !== 'object') return false; 113 | const payload = data[0]; 114 | // User must supply the correct chain_id and msg_version 115 | if (payload.version !== EXPECTED_VERSION) { 116 | console.log('Error: Msg is not well-formed'); 117 | console.log('Possible fix: Did you specify the correct chain Id and msg version?'); 118 | return false; 119 | } 120 | return zAccount.util.isTxParams(payload); 121 | }; 122 | 123 | module.exports = { 124 | 125 | exportData: () => { 126 | const data = {}; 127 | data.transactions = transactions; 128 | data.createdContractsByUsers = createdContractsByUsers; 129 | return data; 130 | }, 131 | 132 | loadData: (txns, contractsByUsers) => { 133 | transactions = txns; 134 | createdContractsByUsers = contractsByUsers; 135 | logVerbose(logLabel, 'Transactions and contract data loaded.'); 136 | }, 137 | 138 | /** 139 | * Function that handles the create transaction requests 140 | * @async 141 | * @method processCreateTxn 142 | * @param { Object } data : Message object passed from client through server.js 143 | * @param { String } dataPath : datapath where the state file is stored 144 | * @returns { String } : Transaction hash 145 | * Throws in the event of error. Caller should catch or delegate these errors 146 | */ 147 | processCreateTxn: async (data, dataPath) => { 148 | logVerbose(logLabel, 'Processing transaction...'); 149 | const isPayloadWellformed = checkTransactionJson(data); 150 | logVerbose(logLabel, `Payload well-formed? ${isPayloadWellformed}`); 151 | 152 | // Checks the wellformness of the transaction JSON data 153 | if (!isPayloadWellformed) { 154 | throw new Error('Invalid Tx Json'); 155 | } 156 | 157 | const responseObj = {}; 158 | 159 | const currentBNum = blockchain.getBlockNum(); 160 | 161 | // Getting data from payload 162 | const dataElement = data[0]; 163 | const payload = { 164 | ...dataElement, 165 | amount: dataElement.amount.toString(), // BN - toJSON returns hex string 166 | gasLimit: dataElement.gasLimit.toString(), // Long - toJSON is not defined 167 | gasPrice: dataElement.gasPrice.toString(), // BN - toJSON returns hex string 168 | }; 169 | const bnAmount = new BN(payload.amount); 170 | const bnGasLimit = new BN(payload.gasLimit); 171 | const bnGasPrice = new BN(payload.gasPrice); 172 | const bnInvokeGas = new BN(config.constants.gas.CONTRACT_INVOKE_GAS); 173 | const deductableZils = bnInvokeGas.mul(bnGasPrice); 174 | const senderAddress = zCrypto.getAddressFromPublicKey(payload.pubKey).replace('0x', '').toLowerCase(); 175 | const txnId = computeTransactionHash(payload); 176 | 177 | logVerbose(logLabel, `Sender: ${senderAddress}`); 178 | const userNonce = walletCtrl.getBalance(senderAddress).nonce; 179 | logVerbose(logLabel, `User Nonce: ${userNonce}`); 180 | logVerbose(logLabel, `Payload Nonce: ${payload.nonce}`); 181 | 182 | let receiptInfo = {}; 183 | 184 | try { 185 | if (payload.nonce !== userNonce + 1) { 186 | throw new BalanceError('Nonce incorrect'); 187 | } 188 | // check if payload gasPrice is sufficient 189 | const bnBlockchainGasPrice = new BN(config.blockchain.minimumGasPrice); 190 | if (bnBlockchainGasPrice.gt(bnGasPrice)) { 191 | throw new BalanceError('Insufficient Gas Price'); 192 | } 193 | 194 | if (!payload.code && !payload.data) { 195 | // p2p token transfer 196 | logVerbose(logLabel, 'Transaction Type: P2P Transfer (Type 1)'); 197 | const bnTransferGas = new BN(config.constants.gas.NORMAL_TRAN_GAS); 198 | const bnTransferCostInZils = bnTransferGas.mul(bnGasPrice); 199 | const totalSum = bnAmount.add(bnTransferCostInZils); 200 | walletCtrl.deductFunds(senderAddress, totalSum); 201 | walletCtrl.increaseNonce(senderAddress); 202 | walletCtrl.addFunds(payload.toAddr.toLowerCase(), bnAmount); 203 | responseObj.Info = 'Non-contract txn, sent to shard'; 204 | receiptInfo.cumulative_gas = bnTransferGas.toString(); 205 | receiptInfo.success = true; 206 | } else { 207 | /* contract creation / invoke transition */ 208 | logVerbose(logLabel, 'Task: Contract Deployment / Create Transaction'); 209 | 210 | // Before the scilla interpreter runs 211 | // address should have sufficient zils to pay for gasLimit + amount 212 | const bnGasLimitInZils = bnGasLimit.mul(bnGasPrice); 213 | const bnAmountRequiredForTx = bnAmount.add(bnGasLimitInZils); 214 | 215 | if (!walletCtrl.sufficientFunds(senderAddress, bnAmountRequiredForTx)) { 216 | logVerbose(logLabel, 'Insufficient funds. Returning error to client.'); 217 | throw new BalanceError('Insufficient balance to process transction'); 218 | } 219 | 220 | logVerbose(logLabel, 'Running scilla interpreter now'); 221 | 222 | let bnGasRemaining = bnGasLimit; 223 | const events = []; 224 | let callsLeft = 6; 225 | const executeTransition = async ( 226 | currentPayload, currentDeployedContractAddress, currentSenderAddress, 227 | ) => { 228 | if (callsLeft < 1) throw new Error('Callstack too high'); 229 | if (bnGasRemaining.lt(new BN(0))) throw new Error('Not Enough Gas'); 230 | 231 | const responseData = await scillaCtrl.executeScillaRun( 232 | currentPayload, 233 | currentDeployedContractAddress, 234 | currentSenderAddress, 235 | dataPath, 236 | currentBNum, 237 | ); 238 | 239 | if (responseData.events) { 240 | events.push(...responseData.events); 241 | } 242 | callsLeft -= 1; 243 | bnGasRemaining = new BN(responseData.gasRemaining); 244 | 245 | const currentAddressUnprefixed = currentPayload.toAddr.replace('0x', ''); 246 | const nextAddress = responseData.nextAddress; 247 | const nextAddressUnprefixed = nextAddress.replace('0x', ''); 248 | if (nextAddress !== '0'.repeat(40) && nextAddressUnprefixed !== currentAddressUnprefixed) { 249 | const initPath = `${dataPath}${nextAddressUnprefixed}_init.json`; 250 | const codePath = `${dataPath}${nextAddressUnprefixed}_code.scilla`; 251 | 252 | if (!fs.existsSync(initPath) || !fs.existsSync(codePath)) return; 253 | if (responseData.message._tag === '') return; 254 | 255 | await executeTransition( 256 | { 257 | toAddr: nextAddressUnprefixed, 258 | amount: responseData.message._amount || '0', 259 | gasLimit: bnGasRemaining.toString(10), 260 | data: JSON.stringify(responseData.message), 261 | }, 262 | null, 263 | currentAddressUnprefixed.toLowerCase(), 264 | ); 265 | } 266 | }; 267 | 268 | const isDeployment = payload.code && payload.toAddr === '0x' + '0'.repeat(40); 269 | const deployedContractAddress = isDeployment ? computeContractAddr(senderAddress) : null; 270 | // Always increase nonce whenever the interpreter is run 271 | // Interpreter can throw an InterpreterError 272 | // if contract deployment, increase nonce after computeContractAddr 273 | walletCtrl.increaseNonce(senderAddress); 274 | await executeTransition(payload, deployedContractAddress, senderAddress); 275 | logVerbose(logLabel, 'Scilla interpreter completed'); 276 | 277 | if (events.length) receiptInfo.event_logs = events; 278 | const bnGasConsumed = bnGasLimit.sub(bnGasRemaining); 279 | const gasConsumedInZil = bnGasPrice.mul(bnGasConsumed); 280 | logVerbose(logLabel, `Gas Consumed in Zils ${gasConsumedInZil.toString()}`); 281 | logVerbose(logLabel, `Gas Consumed: ${bnGasConsumed.toString()}`); 282 | const totalSum = new BN(payload.amount).add(gasConsumedInZil); 283 | walletCtrl.deductFunds(senderAddress.replace('0x', ''), totalSum); 284 | 285 | // Only update if it is a deployment call 286 | if (isDeployment) { 287 | logVerbose(logLabel, `Contract deployed at: ${deployedContractAddress}`); 288 | responseObj.Info = 'Contract Creation txn, sent to shard'; 289 | responseObj.ContractAddress = deployedContractAddress; 290 | 291 | // Update address_to_contracts 292 | if (senderAddress in createdContractsByUsers) { 293 | logVerbose(logLabel, 'User has contracts. Appending to list'); 294 | createdContractsByUsers[senderAddress].push(deployedContractAddress); 295 | } else { 296 | logVerbose(logLabel, 'No existing contracts. Creating new entry.'); 297 | createdContractsByUsers[senderAddress] = [deployedContractAddress]; 298 | } 299 | 300 | contractAddressesByTransactionID[txnId] = deployedContractAddress; 301 | logVerbose(logLabel, `TransID: ${txnId} => Contract Address: ${deployedContractAddress}`); 302 | } else { 303 | // Placeholder msg - since there's no shards in Kaya RPC 304 | responseObj.Info = 'Contract Txn, Shards Match of the sender and receiver'; 305 | } 306 | 307 | receiptInfo.cumulative_gas = bnGasConsumed.toString(); 308 | receiptInfo.success = true; 309 | } 310 | 311 | // Confirms transaction by storing the transaction object in-memory 312 | confirmTransaction(payload, txnId, receiptInfo); 313 | logVerbose(logLabel, 'Transaction confirmed by the blockchain'); 314 | } catch (err) { 315 | logVerbose(logLabel, 'Transaction is NOT accepted by the blockchain'); 316 | 317 | // Incorrect Balance (Amt, Nonce) does NOT increase the nonce value 318 | if (err instanceof BalanceError) { 319 | console.log(`Balance Error: ${err.message}`); 320 | walletCtrl.deductFunds(senderAddress, deductableZils); 321 | } else if (err instanceof InterpreterError) { 322 | // Note: Core zilliqa current deducts based on the CONSTANT.XML file config 323 | console.log('Scilla run is not successful.'); 324 | // Deducts the amount of gas as specified in the config.constants settings 325 | walletCtrl.deductFunds(senderAddress, deductableZils); 326 | receiptInfo = {}; 327 | receiptInfo.cumulative_gas = bnInvokeGas.toString(); 328 | receiptInfo.success = false; 329 | confirmTransaction(payload, txnId, receiptInfo); 330 | logVerbose(logLabel, 'Transaction is logged but it is not accepted due to scilla errors.'); 331 | } else { 332 | // Propagate uncaught error to client 333 | console.log('Uncaught error'); 334 | console.log(err); 335 | throw err; 336 | } 337 | } finally { 338 | // Returns output to caller 339 | logVerbose(logLabel, `Returning transactionID to user: ${txnId}`); 340 | responseObj.TranID = txnId; 341 | } 342 | return responseObj; 343 | }, 344 | 345 | /** 346 | * Given a payload, returns the Transaction object if found 347 | * Throws if the payload is invalid 348 | * @method processGetTransaction 349 | * @param { Object } data - payload object 350 | */ 351 | 352 | processGetTransaction: (data) => { 353 | if (!data) { 354 | logVerbose(logLabel, 'Invalid params'); 355 | const err = new RPCError( 356 | 'INVALID_PARAMS: Invalid method parameters (invalid name and/or type) recognised: Size not appropriate', 357 | errorCodes.RPC_INVALID_PARAMS, 358 | null, 359 | ); 360 | throw err; 361 | } 362 | 363 | logVerbose(logLabel, `TxnID: ${data[0]}`); 364 | const res = transactions[data[0]]; 365 | if (res) { 366 | return res; 367 | } 368 | const err = new RPCError( 369 | 'INVALID_PARAMS: Invalid method parameters (invalid name and/or type) recognised: Size not appropriate', 370 | errorCodes.RPC_DATABASE_ERROR, 371 | null, 372 | ); 373 | throw err; 374 | }, 375 | 376 | /** 377 | * Retrieves the last 100 transaction hash 378 | * @method processGetRecentTransactions 379 | * @returns { Object } - 100 transaction hashes 380 | */ 381 | 382 | processGetRecentTransactions: () => { 383 | logVerbose(logLabel, 'Getting Recent Transactions'); 384 | 385 | const txnhashes = Object.keys(transactions); 386 | const responseObj = {}; 387 | responseObj.TxnHashes = txnhashes.reverse(); 388 | responseObj.number = txnhashes.length; 389 | return responseObj; 390 | }, 391 | 392 | /** 393 | * Function to process GetSmartContract's state, init or code 394 | * @param { Object } data : data retrieved from payload 395 | * @param { String } dataPath : datapath where the state file is stored 396 | * @param { String } type - enum of either data, init or state 397 | */ 398 | processGetDataFromContract: (data, dataPath, type) => { 399 | const fileType = type.trim().toLowerCase(); 400 | if (!['init', 'state', 'code'].includes(fileType)) { 401 | const err = new RPCError( 402 | 'INVALID_PARAMS: Invalid method parameters (invalid name and/or type) recognised: Invalid options flag', 403 | errorCodes.RPC_INVALID_PARAMS, 404 | null, 405 | ); 406 | throw err; 407 | } 408 | const ext = fileType === 'code' ? 'scilla' : 'json'; 409 | logVerbose(logLabel, `Getting SmartContract ${fileType}`); 410 | 411 | if (!data) { 412 | logVerbose(logLabel, 'Invalid params'); 413 | const err = new RPCError( 414 | 'INVALID_PARAMS: Invalid method parameters (invalid name and/or type) recognised: Size not appropriate', 415 | errorCodes.RPC_INVALID_PARAMS, 416 | null, 417 | ); 418 | throw err; 419 | } 420 | 421 | // checking contract address's validity 422 | const contractAddress = data[0]; 423 | if (contractAddress == null || !validation.isAddress(contractAddress)) { 424 | consolePrint('Invalid request'); 425 | throw new RPCError('Address size not appropriate', errorCodes.RPC_INVALID_ADDRESS_OR_KEY, null); 426 | } 427 | const filePath = `${dataPath}${contractAddress.toLowerCase()}_${fileType}.${ext}`; 428 | logVerbose(logLabel, `Retrieving data from ${filePath}`); 429 | 430 | if (!fs.existsSync(filePath)) { 431 | consolePrint(`No ${type} file found (Contract: ${contractAddress}`); 432 | throw new RPCError('Address does not exist', errorCodes.RPC_INVALID_ADDRESS_OR_KEY, null); 433 | } 434 | 435 | let responseData = fs.readFileSync(filePath, 'utf-8'); 436 | if (fileType === 'code') { 437 | return { code: responseData }; 438 | } 439 | responseData = JSON.parse(responseData); 440 | 441 | if (fileType === 'state') { 442 | result = {}; 443 | responseData.forEach(field => result[field.vname] = field.value); 444 | return result; 445 | } 446 | return responseData; 447 | }, 448 | 449 | /** 450 | * Retrieves the smart contracts for a given address 451 | * @method processGetSmartContracts 452 | * @param { Object } data : data retrieved from payload 453 | * @param { String } dataPath : datapath where the state file is stored 454 | * @returns { Object } : All the state for contracts deployed by the address 455 | */ 456 | 457 | processGetSmartContracts: (data, dataPath) => { 458 | if (!data) { 459 | logVerbose(logLabel, 'Invalid params'); 460 | const err = new Error( 461 | 'INVALID_PARAMS: Invalid method parameters (invalid name and/or type) recognised', 462 | ); 463 | throw err; 464 | } 465 | 466 | const addr = data[0].toLowerCase(); 467 | logVerbose(logLabel, `Getting smart contracts created by ${addr}`); 468 | if (addr === null || !validation.isAddress(addr)) { 469 | console.log('Invalid request'); 470 | throw new RPCError('Address size not appropriate', errorCodes.RPC_INVALID_ADDRESS_OR_KEY, null); 471 | } 472 | 473 | const stateLists = []; 474 | if (!createdContractsByUsers[addr]) { 475 | throw new RPCError('Address does not exist', errorCodes.RPC_INVALID_ADDRESS_OR_KEY, null); 476 | } 477 | // Addr found - proceed to append state to return list 478 | const contracts = createdContractsByUsers[addr]; 479 | 480 | contracts.forEach((contractId) => { 481 | const statePath = `${dataPath}${contractId.toLowerCase()}_state.json`; 482 | if (!fs.existsSync(statePath)) { 483 | console.log(`No state file found (Contract: ${contractId}`); 484 | throw new RPCError('Address does not exist', errorCodes.RPC_INVALID_ADDRESS_OR_KEY, null); 485 | } 486 | const retMsg = JSON.parse(fs.readFileSync(statePath, 'utf-8')); 487 | const contractStateObj = {}; 488 | contractStateObj.address = contractId; 489 | contractStateObj.state = retMsg; 490 | stateLists.push(contractStateObj); 491 | }); 492 | 493 | return stateLists; 494 | }, 495 | 496 | /** 497 | * Process Get Contract Address by Transaction ID 498 | * @method processGetContractAddressByTransactionID 499 | * @param { Object } data - data object of the payload which contrains transaction hash 500 | * @returns { String } contractAddress - 20 bytes string 501 | */ 502 | processGetContractAddressByTransactionID: (data) => { 503 | if ((typeof data === 'object' && data === null) || data[0].length !== 64) { 504 | throw new RPCError('Size not appropriate', errorCodes.RPC_INVALID_ADDRESS_OR_KEY, null); 505 | } 506 | const transId = data[0]; 507 | if (!transactions[transId]) { 508 | throw new Error('Txn Hash not Present'); 509 | } 510 | 511 | const contractAddr = contractAddressesByTransactionID[transId]; 512 | if (!contractAddr) { 513 | throw new Error('ID not a contract txn'); 514 | } else { 515 | return contractAddr; 516 | } 517 | }, 518 | }; 519 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------