├── .dockerignore ├── .eslintignore ├── .eslintrc.json ├── .gitignore ├── .travis.yml ├── Dockerfile ├── Jenkinsfile ├── LICENSE ├── LICENSE_NOTICE ├── README.md ├── bundle ├── bundle_and_store.js ├── unix.sh └── windows.bat ├── docker-compose.test.yml ├── docker-compose.yml ├── docker └── README.md ├── docs ├── Plutus_runtime_and_interaction_model.md ├── README.md ├── contract_bundle.md └── images │ └── server_components_diagram.png ├── features ├── client_validation.feature ├── contract_interaction.feature ├── contract_loading.feature ├── contract_unloading.feature ├── list_loaded_contracts.feature └── signed_transaction_submission.feature ├── package-lock.json ├── package.json ├── puppeteer_evaluater.js ├── src ├── client │ ├── Client.ts │ ├── README.MD │ └── index.ts ├── core │ ├── Bundle.ts │ ├── Contract.ts │ ├── ContractCallInstruction.ts │ ├── ContractRepository.ts │ ├── Endpoint.ts │ ├── Engine.ts │ ├── EngineClient.ts │ ├── Events.ts │ ├── ExecutionEngines.ts │ ├── OperationMode.ts │ ├── PortAllocation.ts │ ├── PortAllocationRepository.ts │ ├── errors │ │ ├── AllPortsAllocated.ts │ │ ├── UnknownEntity.ts │ │ └── index.ts │ └── index.ts ├── execution_service │ ├── README.md │ ├── application │ │ ├── Api.ts │ │ ├── ExecutionEngine.ts │ │ ├── ExecutionEngineController.ts │ │ ├── ExecutionService.spec.ts │ │ ├── ExecutionService.ts │ │ └── index.ts │ ├── config.ts │ ├── errors │ │ ├── BadArgument.ts │ │ ├── ContainerFailedToStart.ts │ │ ├── ContractNotLoaded.ts │ │ ├── ExecutionFailure.ts │ │ ├── InvalidEndpoint.ts │ │ ├── MissingConfig.ts │ │ └── index.ts │ ├── index.ts │ ├── infrastructure │ │ ├── docker_client │ │ │ ├── DockerClient.spec.ts │ │ │ └── DockerClient.ts │ │ ├── execution_engines │ │ │ ├── DockerExecutionEngine.ts │ │ │ ├── NodeJsExecutionEngine.spec.ts │ │ │ ├── NodeJsExecutionEngine.ts │ │ │ ├── StubExecutionEngine.ts │ │ │ └── index.ts │ │ ├── index.ts │ │ └── node_js │ │ │ ├── execute.spec.ts │ │ │ └── execute.ts │ └── test │ │ ├── docker-integration.spec.ts │ │ ├── node-integration.spec.ts │ │ └── security │ │ └── node_js │ │ ├── isolation_from_nodejs.spec.ts │ │ ├── load_test.spec.ts │ │ ├── network_attacks.spec.ts │ │ ├── page_boundaries.spec.ts │ │ └── resource_consumption_attack.spec.ts ├── lib │ ├── Entity.ts │ ├── NetworkInterface.ts │ ├── NumberRange.ts │ ├── PortMapper.spec.ts │ ├── PortMapper.ts │ ├── Repository.ts │ ├── compileContractSchema.spec.ts │ ├── compileContractSchema.ts │ ├── createEndpoint.spec.ts │ ├── createEndpoint.ts │ ├── expressEventPromiseHandler.ts │ ├── fsPromises.ts │ ├── httpEventPromiseHandler.ts │ ├── index.ts │ ├── repositories │ │ ├── InMemoryRepository.spec.ts │ │ ├── InMemoryRepository.ts │ │ └── index.ts │ └── test │ │ ├── RogueService.ts │ │ ├── checkPortIsFree.ts │ │ ├── index.ts │ │ ├── populatedContractRepository.ts │ │ └── testContracts.ts ├── server │ ├── README.md │ ├── application │ │ ├── Api.spec.ts │ │ ├── Api.ts │ │ ├── ContractController.spec.ts │ │ ├── ContractController.ts │ │ ├── Server.spec.ts │ │ ├── Server.ts │ │ ├── errors │ │ │ ├── ContractNotLoaded.ts │ │ │ └── index.ts │ │ └── index.ts │ ├── index.ts │ └── infrastructure │ │ ├── engine_clients │ │ ├── StubEngineClient.ts │ │ ├── index.ts │ │ └── plutus │ │ │ ├── PlutusEngineClient.spec.ts │ │ │ └── PlutusEngineClient.ts │ │ ├── index.ts │ │ └── pubsub_clients │ │ ├── MemoryPubSubClient.ts │ │ ├── RedisPubSubClient.ts │ │ └── index.ts ├── single_process.ts └── test │ └── e2e │ ├── steps │ ├── contract_interactions.ts │ ├── contract_loading.ts │ └── list_contracts.ts │ └── support │ ├── hooks.ts │ └── world.ts ├── test ├── bundles │ ├── create_docker_tar │ │ ├── Dockerfile │ │ ├── README.md │ │ ├── index.js │ │ ├── package-lock.json │ │ └── package.json │ ├── docker │ │ ├── abcd │ │ └── plutusGuessingGame │ └── nodejs │ │ ├── abcd │ │ └── plutusGuessingGame └── mocha.opts ├── tsconfig.json ├── tsoa.json ├── wallaby.conf.js └── webpack.config.js /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | src/execution_service/routes.ts -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@typescript-eslint/parser", 3 | "parserOptions": { 4 | "project": "./tsconfig.json" 5 | }, 6 | "extends": [ 7 | "standard" 8 | ], 9 | "plugins": [ 10 | "@typescript-eslint", 11 | "chai-friendly" 12 | ], 13 | "globals": { 14 | "it": "readonly", 15 | "describe": "readonly", 16 | "beforeEach": "readonly", 17 | "afterEach": "readonly" 18 | }, 19 | "rules": { 20 | "linebreak-style": [ 21 | 2, 22 | "unix" 23 | ], 24 | "no-unused-vars": 0, 25 | "no-unused-expressions": 0, 26 | "chai-friendly/no-unused-expressions": 1 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *node_modules* 2 | /contract_dist 3 | /dist 4 | /.nyc_output 5 | /coverage 6 | /src/execution_service/routes.ts 7 | /test/e2e/dist 8 | docker/* 9 | !docker/README.md 10 | .idea 11 | *.tsbuildinfo 12 | build -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "10" 4 | os: 5 | - windows 6 | - linux 7 | - osx 8 | script: 9 | - npm run bundle -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:10.15.3-alpine as builder 2 | RUN apk add --update git python krb5 krb5-libs gcc make g++ krb5-dev 3 | RUN mkdir /application 4 | COPY package.json /application/package.json 5 | WORKDIR /application 6 | RUN npm i 7 | COPY . /application 8 | RUN npm run build 9 | 10 | FROM node:10.15.3-alpine as test 11 | COPY --from=builder /application /application 12 | WORKDIR /application 13 | CMD ["npm", "test"] 14 | 15 | FROM node:10.15.3-alpine as production_deps 16 | RUN apk add --update git python krb5 krb5-libs gcc make g++ krb5-dev 17 | RUN mkdir /application 18 | COPY package.json /application/package.json 19 | WORKDIR /application 20 | RUN npm i --production 21 | 22 | FROM node:10.15.3-alpine as server 23 | RUN mkdir /application 24 | COPY --from=builder /application/src /application/src 25 | COPY --from=builder /application/dist/core /application/dist/core 26 | COPY --from=builder /application/dist/lib /application/dist/lib 27 | COPY --from=builder /application/dist/execution_service /application/dist/execution_service 28 | COPY --from=builder /application/dist/server /application/dist/server 29 | COPY --from=builder /application/webpack.config.js /application/webpack.config.js 30 | COPY --from=builder /application/tsconfig.json /application/tsconfig.json 31 | COPY --from=builder /application/node_modules /application/node_modules 32 | WORKDIR /application 33 | CMD ["./node_modules/.bin/pm2", "--no-daemon", "start", "dist/server/index.js"] 34 | 35 | FROM node:10.15.3-alpine as execution_service 36 | RUN mkdir /application 37 | RUN mkdir /application/docker 38 | COPY --from=builder /application/src /application/src 39 | COPY --from=builder /application/dist/core /application/dist/core 40 | COPY --from=builder /application/dist/lib /application/dist/lib 41 | COPY --from=builder /application/dist/execution_service /application/dist/execution_service 42 | COPY --from=builder /application/puppeteer_evaluater.js /application/puppeteer_evaluater.js 43 | COPY --from=builder /application/dist/swagger.json /application/dist/swagger.json 44 | COPY --from=production_deps /application/node_modules /application/node_modules 45 | WORKDIR /application 46 | CMD ["./node_modules/.bin/pm2", "--no-daemon", "start", "dist/execution_service/index.js"] -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | pipeline { 2 | agent any 3 | 4 | tools {nodejs "Node 10"} 5 | 6 | // Lock concurrent builds due to the docker dependency 7 | options { 8 | lock resource: 'DockerJob' 9 | disableConcurrentBuilds() 10 | } 11 | 12 | stages { 13 | stage('Install') { 14 | steps { 15 | sh 'npm i' 16 | } 17 | } 18 | stage('Unit/Integration Test') { 19 | steps { 20 | sh 'npm test' 21 | } 22 | } 23 | stage('E2E Single Process Setup') { 24 | steps { 25 | sh 'npm start' 26 | } 27 | } 28 | stage('E2E Single Process Test') { 29 | steps { 30 | sh 'npm run e2e:nodejs' 31 | } 32 | post { 33 | always { 34 | sh 'npm stop || true' 35 | sh 'git add -A && git reset --hard || true' 36 | } 37 | } 38 | } 39 | stage('E2E Docker Setup') { 40 | steps { 41 | sh 'docker-compose build' 42 | sh 'docker-compose -p smart-contract-backend up -d' 43 | } 44 | } 45 | stage('E2E Docker Test') { 46 | steps { 47 | sh 'npm run e2e:docker' 48 | } 49 | post { 50 | always { 51 | sh 'docker kill $(docker ps -q) || true' 52 | sh 'docker-compose -p smart-contract-backend down' 53 | sh 'docker system prune -a -f' 54 | } 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /LICENSE_NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2019 IOHK 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License”). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt 4 | 5 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Smart Contract Backend 2 | 3 | [](http://13.238.211.79:8080/blue/organizations/jenkins/smart-contract-backend/) 4 | 5 | Run off-chain smart contract executables server-side in isolation, accessible via a GraphQL interface. The [server](src/server/README.md) exposes a GraphQL control API for loading contracts and subscribing to signing requests for transactions generated by the contracts. An [execution service](src/execution_service/README.md) isolates potentially untrusted code execution, enabling interaction with the contracts via a [Docker](src/execution_service/infrastructure/execution_engines/DockerExecutionEngine.ts) or [NodeJS](src/execution_service/infrastructure/execution_engines/NodeJsExecutionEngine.ts) engine. 6 | 7 | For TypeScript/JavaScript applications the provided [client](src/client/README.MD) will serve as a good starting point, and provides a lightweight approach for most applications. 8 | 9 | The primary goal for the project is to deliver [a runtime and interaction model for Plutus](docs/Plutus_runtime_and_interaction_model.md), however there is no fixed coupling to any particular Smart Contract language. 10 | 11 | - [Features](features) 12 | - [More documentation](docs) 13 | 14 | ## Project State: Alpha 15 | This system is a work in progress, and dependent on external tooling efforts. The Docker-based engine will likely be first to reach stability, but development on both engines is happening in parallel. 16 | 17 | ## Development 18 | 19 | ### Docker Compose 20 | 1. Uncomment the volumes for the service you are working on in `docker-compose.yml` 21 | 2. docker-compose up 22 | 3. Run a TypeScript file watcher for live reloading of development changes 23 | 24 | Swagger API documentation for docker execution engine available at `/docs` 25 | 26 | ### Testing 27 | Unit tests are placed inline within the `src` directory. Integration tests are located in the `test` directory for each service. 28 | 29 | Run the test suit with `npm test` 30 | 31 | A running Docker daemon is required for the tests to run. 32 | 33 | Depending on network speed, you may need to run `docker pull samjeston/smart_contract_server_mock` prior to running the test suite to avoid timeouts. 34 | -------------------------------------------------------------------------------- /bundle/bundle_and_store.js: -------------------------------------------------------------------------------- 1 | const os = require('os') 2 | const platform = os.platform() 3 | const { exec, execFile } = require('child_process') 4 | const { join } = require('path') 5 | const archiver = require('archiver') 6 | const AWS = require('aws-sdk') 7 | const fs = require('fs-extra') 8 | 9 | const S3_BUCKET = 'smart-contract-backend-builds' 10 | 11 | function commitHash() { 12 | return new Promise((resolve, reject) => { 13 | exec('git rev-parse HEAD', function (err, stdout) { 14 | if (err) return reject(err) 15 | resolve(stdout.split(/\r?\n/)[0]) 16 | }) 17 | }) 18 | } 19 | 20 | function createBundle() { 21 | return new Promise((resolve, reject) => { 22 | if (platform === 'win32') { 23 | execFile(join(process.cwd(), 'bundle', 'windows.bat'), function (err, stdout) { 24 | if (err) return reject(err) 25 | resolve(stdout) 26 | }) 27 | } else { 28 | execFile(join(process.cwd(), 'bundle', 'unix.sh'), function (err, stdout) { 29 | if (err) return reject(err) 30 | resolve(stdout) 31 | }) 32 | } 33 | }) 34 | } 35 | 36 | function createZip(bundlePath, zipPath, exeName, buildDeps) { 37 | return new Promise((resolve, reject) => { 38 | let output = fs.createWriteStream(zipPath) 39 | var archive = archiver('zip') 40 | 41 | output.on('close', resolve) 42 | 43 | archive.on('error', function (err) { 44 | return reject(err) 45 | }) 46 | 47 | archive.pipe(output) 48 | 49 | archive.file(join(bundlePath, exeName), { name: exeName }) 50 | 51 | buildDeps.forEach(dep => { 52 | const testExp = RegExp('.node*', 'g') 53 | 54 | if (testExp.test(dep)) { 55 | archive.file(join(bundlePath, dep), { name: dep }) 56 | } else { 57 | archive.directory(join(bundlePath, dep), dep) 58 | } 59 | }) 60 | 61 | archive.finalize() 62 | }) 63 | } 64 | 65 | function determineOsInfo(commitHash) { 66 | const winBuildPath = join(process.cwd(), 'build', 'Windows') 67 | const macOSBuildPath = join(process.cwd(), 'build', 'Darwin') 68 | const linuxBuildPath = join(process.cwd(), 'build', 'Linux') 69 | 70 | switch (platform) { 71 | case 'win32': 72 | return { bundlePath: winBuildPath, exeName: 'smart-contract-backend.exe', s3Path: `${commitHash}/Windows.zip` } 73 | case 'darwin': 74 | return { bundlePath: macOSBuildPath, exeName: 'smart-contract-backend', s3Path: `${commitHash}/Darwin.zip` } 75 | case 'linux': 76 | return { bundlePath: linuxBuildPath, exeName: 'smart-contract-backend', s3Path: `${commitHash}/Linux.zip` } 77 | default: 78 | throw new Error('Unsupported platform') 79 | } 80 | } 81 | 82 | async function uploadToS3(s3Path, zipPath) { 83 | const s3 = new AWS.S3() 84 | 85 | const deleteParams = { 86 | Bucket: S3_BUCKET, 87 | Key: s3Path 88 | } 89 | 90 | await s3.deleteObject(deleteParams).promise() 91 | 92 | const createParams = { 93 | Body: fs.readFileSync(zipPath), 94 | Bucket: S3_BUCKET, 95 | Key: s3Path 96 | } 97 | 98 | await s3.putObject(createParams).promise() 99 | } 100 | 101 | async function validateDependencies(buildOutput, bundlePath) { 102 | const testExpression = RegExp('path-to-executable*', 'g') 103 | const pkgDeclaredBuildDeps = buildOutput 104 | .split('\n') 105 | .filter(line => testExpression.test(line)) 106 | .map(filteredLine => filteredLine.split('path-to-executable/')[1]) 107 | 108 | const validatePaths = await Promise.all(pkgDeclaredBuildDeps.map(dep => { 109 | return fs.pathExists(join(bundlePath, dep)) 110 | })) 111 | 112 | if (new Set(validatePaths).has(false)) { 113 | throw new Error(`Missing dependencies. Ensure the build copies ${pkgDeclaredBuildDeps} from appropriate locations`) 114 | } 115 | 116 | return pkgDeclaredBuildDeps 117 | } 118 | 119 | async function main() { 120 | try { 121 | const hash = await commitHash() 122 | console.log(`Creating Build for commit: ${hash}`) 123 | const buildOutput = await createBundle() 124 | 125 | const { bundlePath, exeName, s3Path } = determineOsInfo(hash) 126 | 127 | // We use the output of the pkg and validate that all 128 | // of the native addons are included at the expected file 129 | // location before adding them to the zip 130 | const buildDeps = await validateDependencies(buildOutput, bundlePath) 131 | 132 | const zipPath = `${bundlePath}.zip` 133 | console.log(`Creating zip at ${zipPath}`) 134 | await createZip(bundlePath, zipPath, exeName, buildDeps) 135 | 136 | console.log('Uploading to S3...') 137 | await uploadToS3(s3Path, zipPath) 138 | } catch (e) { 139 | console.log('An error occurred while creating the bundle') 140 | console.log(e.message) 141 | throw e 142 | } 143 | } 144 | 145 | main() 146 | .then(() => console.log('Bundling complete')) 147 | .catch(() => process.exit(1)) 148 | -------------------------------------------------------------------------------- /bundle/unix.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "Install dependencies for building" 3 | npm i 4 | 5 | echo "Cleanup existing build dir" 6 | rm -rf build 7 | 8 | echo "Creating dist" 9 | npm run build 10 | 11 | echo "Make build dir" 12 | mkdir -p "build/$(uname)" 13 | 14 | echo "Copying deps" 15 | cp -r node_modules/puppeteer/.local-chromium "build/$(uname)/puppeteer" 16 | 17 | if [ "$(uname)" == "Linux" ] 18 | then 19 | echo "Creating Linux executable" 20 | npx pkg -t node10-linux . 21 | else 22 | echo "Creating macOS executable" 23 | npx pkg -t node10-macos . 24 | fi 25 | 26 | mv smart-contract-backend "build/$(uname)" -------------------------------------------------------------------------------- /bundle/windows.bat: -------------------------------------------------------------------------------- 1 | ECHO "Install dependencies for building" 2 | CALL npm i 3 | 4 | ECHO "Cleanup existing build dir" 5 | CALL npx rimraf build 6 | 7 | ECHO "Creating dist" 8 | CALL npm run build 9 | 10 | ECHO "Make build dir" 11 | MKDIR "build" 12 | MKDIR "build\Windows" 13 | 14 | ECHO "Copying deps" 15 | XCOPY node_modules\puppeteer\.local-chromium build\Windows\puppeteer /s/i 16 | 17 | ECHO "Creating Windows64 executable" 18 | CALL npx pkg -t node10-win . 19 | 20 | MOVE smart-contract-backend.exe build\Windows\smart-contract-backend.exe -------------------------------------------------------------------------------- /docker-compose.test.yml: -------------------------------------------------------------------------------- 1 | version: '3.7' 2 | services: 3 | smart_contract_backend_e2e_test: 4 | build: 5 | context: . 6 | target: test 7 | init: true 8 | environment: 9 | - APPLICATION_URI=http://server:8081 10 | - WS_URI=ws://server:8081/graphql -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.7' 2 | services: 3 | server: 4 | build: 5 | context: . 6 | target: server 7 | init: true 8 | environment: 9 | - API_PORT=8081 10 | - WALLET_SERVICE_URI=http://wallet:0000 11 | - EXECUTION_SERVICE_URI=http://execution_service:9000 12 | - CONTRACT_DIRECTORY=/application/bundles 13 | - REDIS_HOST=redis 14 | - REDIS_PORT=6379 15 | - OPERATION_MODE=distributed 16 | volumes: 17 | # - ./dist/server:/application/dist/server 18 | - ./test/bundles/docker:/application/bundles 19 | ports: 20 | - 8081:8081 21 | - 8082:8082 22 | depends_on: 23 | - execution_service 24 | execution_service: 25 | build: 26 | context: . 27 | target: execution_service 28 | init: true 29 | environment: 30 | - EXECUTION_API_PORT=9000 31 | - CONTAINER_LOWER_PORT_BOUND=11000 32 | - CONTAINER_UPPER_PORT_BOUND=12000 33 | - DOCKER_EXECUTION_ENGINE_CONTEXT=docker 34 | - EXECUTION_ENGINE=docker 35 | volumes: 36 | - /var/run/docker.sock:/var/run/docker.sock 37 | # - ./dist/swagger.json:/application/dist/swagger.json 38 | # - ./dist/execution_service:/application/dist/execution_service 39 | ports: 40 | - 9000:9000 41 | redis: 42 | image: redis:5.0.4 43 | ports: 44 | - 6379:6380 45 | -------------------------------------------------------------------------------- /docker/README.md: -------------------------------------------------------------------------------- 1 | This directory is the target location for auto-generated dockerfiles and decoded binaries. -------------------------------------------------------------------------------- /docs/Plutus_runtime_and_interaction_model.md: -------------------------------------------------------------------------------- 1 | # A _Plutus_ runtime and interaction model 2 | [_Plutus_](https://github.com/input-output-hk/plutus) presents a new paradigm for Smart Contracts by moving some of the execution out of the ledger. This changes how we think about implementing Smart Contracts as they can now be considered an application service, taking user input, and generating transactions which contain the lifted _Plutus_ core blocks. Read more about the [extended UTXO model](https://github.com/input-output-hk/plutus/tree/master/docs/extended-utxo) 3 | 4 | ## What are the requirements to run a _**Plutus**_ contract? 5 | ### Loading 6 | 1. The contract must be loaded from the file system. 7 | 2. Dynamic [bundle](./contract_bundle.md) generation. 8 | 3. It needs to be made available to the consumer to call it's endpoints 9 | ### Interaction 10 | 1. Transactions generated must be sent to the client for signing and submission 11 | 2. Any off-chain state persisted 12 | 3. Any triggers defined by the contract must be setup and managed with assurance they will fire 13 | 14 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | - [_Plutus_ Runtime and interaction model](Plutus_runtime_and_interaction_model.md) 2 | - [Contract Bundle](contract_bundle.md) 3 | - [Server](../src/server/README.md) 4 | - [Execution Service](../src/execution_service/README.md) -------------------------------------------------------------------------------- /docs/contract_bundle.md: -------------------------------------------------------------------------------- 1 | # Contract Bundle 2 | The bundle contains the compiled executable and JavaScript executable [endpoints](../src/lib/createEndpoint.ts). This bundle is dynamically generated when a contract is loaded, as Plutus contracts are self-descriptive with their `schema` endpoint. When a usecase arises, the bundle generation can be lifted to an external module to use outside of the Smart Contract Backend. 3 | 4 | View the TypeScript [model](../src/core/Bundle.ts) for reference. -------------------------------------------------------------------------------- /docs/images/server_components_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/input-output-hk/smart-contract-backend/ccef4dba46db20add0010c4267345c8e726fd0bd/docs/images/server_components_diagram.png -------------------------------------------------------------------------------- /features/client_validation.feature: -------------------------------------------------------------------------------- 1 | @Todo 2 | Feature: Client Validation 3 | As a client, to establish a connection to a smart contract 4 | A hash of the expected schema must be passed and verified 5 | To ensure the contract exposes the expected schema -------------------------------------------------------------------------------- /features/contract_interaction.feature: -------------------------------------------------------------------------------- 1 | Feature: Contract Interaction 2 | To interact with loaded Smart Contracts 3 | As a client of the platform 4 | I want to call the endpoints to access expressed behaviour 5 | 6 | Scenario Outline: contract interaction that generates a transaction 7 | 8 | When I load a contract by address
9 | And I subscribe by public key