├── .editorconfig ├── .github └── workflows │ └── automerge.yaml ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── bin ├── load.ts └── www.ts ├── config └── default.js ├── ecosystem.config.js ├── jest.config.js ├── knexfile.js ├── migrations └── 00000000000000_keys.js ├── package.json ├── seeds └── keys.js ├── src ├── __test__ │ └── ping.spec.ts ├── app.ts ├── models │ └── key.ts └── routes │ ├── api.ts │ └── ping.ts ├── tsconfig.json ├── tslint.json └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | charset = utf-8 6 | insert_final_newline = true 7 | 8 | [*.yml] 9 | indent_style = space 10 | indent_size = 2 11 | 12 | [*.{ts,json,js}] 13 | trim_trailing_whitespace = true 14 | indent_style = space 15 | indent_size = 4 16 | 17 | # npm inserts a final newline. 18 | [package.json] 19 | trim_trailing_whitespace = false 20 | -------------------------------------------------------------------------------- /.github/workflows/automerge.yaml: -------------------------------------------------------------------------------- 1 | name: automerge 2 | on: 3 | pull_request: 4 | types: 5 | - labeled 6 | - unlabeled 7 | - synchronize 8 | - opened 9 | - edited 10 | - ready_for_review 11 | - reopened 12 | - unlocked 13 | pull_request_review: 14 | types: 15 | - submitted 16 | status: {} 17 | jobs: 18 | automerge: 19 | runs-on: ubuntu-latest 20 | steps: 21 | - name: automerge 22 | uses: "pascalgn/automerge-action@v0.6.1" 23 | env: 24 | GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" 25 | MERGE_METHOD: rebase 26 | UPDATE_METHOD: rebase 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.vscode/ 2 | /dist/ 3 | node_modules/ 4 | /public/stylesheets/*.css 5 | /public/stylesheets/*.css.map 6 | .DS_Store 7 | /config/local*.js 8 | /config/local*.json 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "10" 4 | - "8" 5 | before_install: 6 | - yarn install 7 | script: 8 | - yarn test 9 | cache: yarn 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | CodeChain keystore server [![Build Status](https://travis-ci.org/CodeChain-io/codechain-keystore-server.svg?branch=master)](https://travis-ci.org/CodeChain-io/codechain-keystore-server) 2 | ========================== 3 | 4 | CodeChain keystore server is a private key management server. It saves CodeChain's asset transfer address safely in a database. You should use this keystore server to save your private key safely in CodeChain SDK. 5 | 6 | ## Installation 7 | 8 | ### Prerequisite 9 | 10 | 1. Install PostgreSQL 11 | 12 | ### Initial Configuration 13 | 14 | 1. Install dependencies with `yarn install` 15 | 1. Execute the following SQL queries 16 | ```sql 17 | CREATE DATABASE "codechain-keystore"; 18 | CREATE USER "codechain" WITH ENCRYPTED PASSWORD 'DATABASE_PASSWORD'; 19 | GRANT ALL PRIVILEGES ON DATABASE "codechain-keystore" TO "codechain"; 20 | ``` 21 | 1. Create `config/local.json` with the following data 22 | ```json 23 | { 24 | "knex": { 25 | "connection": { 26 | "password": "DATABASE_PASSWORD" 27 | } 28 | } 29 | } 30 | ``` 31 | 1. Update the database with `yarn migrate` 32 | 1. Seed the database with `yarn seed` 33 | 34 | ## Usage 35 | 36 | - `yarn start` to start a server 37 | - `yarn load` to load local keystore to database 38 | - `yarn lint` to lint the entire source code 39 | - `yarn fmt` to apply formatters 40 | - `yarn migrate` to migrate the database 41 | - `yarn rollback` to rollback the database 42 | - `yarn seed` to reset and seed the database 43 | 44 | ### Check if the server is alive 45 | 46 | You can send a ping to the server to check if it's up and running. 47 | 48 | ``` 49 | curl http://localhost:7007/ping 50 | ``` 51 | -------------------------------------------------------------------------------- /bin/load.ts: -------------------------------------------------------------------------------- 1 | import * as program from "commander"; 2 | import * as config from "config"; 3 | import * as knex from "knex"; 4 | import { Model, transaction } from "objection"; 5 | import * as path from "path"; 6 | 7 | import KeyModel from "../src/models/key"; 8 | 9 | let dbPath: string; 10 | 11 | program.arguments("").action(dbPathValue => { 12 | dbPath = path.join(__dirname, "..", dbPathValue); 13 | }); 14 | 15 | program.parse(process.argv); 16 | 17 | Model.knex(knex(config.get("knex"))); 18 | 19 | async function main() { 20 | const tx = await transaction.start(Model.knex()); 21 | try { 22 | if (dbPath === undefined) { 23 | console.error("no db_path given!"); 24 | process.exit(1); 25 | } 26 | 27 | const keystore = require(dbPath); 28 | 29 | for (const addr of keystore.platform) { 30 | const row = await KeyModel.query().findById([ 31 | "platform", 32 | addr.address 33 | ]); 34 | if (row != null) { 35 | throw new Error(`Platform key ${addr.address} already exists!`); 36 | } 37 | await KeyModel.query(tx).insert({ 38 | type: "platform", 39 | address: addr.address, 40 | version: addr.version, 41 | 42 | kdf: addr.crypto.kdf, 43 | kdfparams: addr.crypto.kdfparams, 44 | mac: addr.crypto.mac, 45 | 46 | cipher: addr.crypto.cipher, 47 | cipherparams: addr.crypto.cipherparams, 48 | ciphertext: addr.crypto.ciphertext, 49 | 50 | meta: addr.meta 51 | }); 52 | } 53 | 54 | for (const addr of keystore.asset) { 55 | const row = await KeyModel.query().findById([ 56 | "asset", 57 | addr.address 58 | ]); 59 | if (row != null) { 60 | throw new Error(`Asset key ${addr.address} already exists!`); 61 | } 62 | await KeyModel.query(tx).insert({ 63 | type: "asset", 64 | address: addr.address, 65 | version: addr.version, 66 | 67 | kdf: addr.crypto.kdf, 68 | kdfparams: addr.crypto.kdfparams, 69 | mac: addr.crypto.mac, 70 | 71 | cipher: addr.crypto.cipher, 72 | cipherparams: addr.crypto.cipherparams, 73 | ciphertext: addr.crypto.ciphertext, 74 | 75 | meta: addr.meta 76 | }); 77 | } 78 | await tx.commit(); 79 | } catch (e) { 80 | console.error(`Unexpected error found!: ${e}`); 81 | await tx.rollback(); 82 | } 83 | process.exit(0); 84 | } 85 | 86 | main().catch(console.error); 87 | -------------------------------------------------------------------------------- /bin/www.ts: -------------------------------------------------------------------------------- 1 | import * as program from "commander"; 2 | import * as debugModule from "debug"; 3 | import * as http from "http"; 4 | import { createApp } from "../src/app"; 5 | 6 | const debug = debugModule("www"); 7 | 8 | program.option("--port ", "port number", "7007").parse(process.argv); 9 | 10 | main().catch(console.error); 11 | 12 | async function main() { 13 | const app = await createApp(); 14 | const port = normalizePort(program.port); 15 | app.set("port", port); 16 | 17 | const server = http.createServer(app); 18 | 19 | server.listen(port); 20 | server.on("error", onError(port)); 21 | server.on("listening", onListening(server)); 22 | 23 | process.on("SIGINT", async () => { 24 | console.log("Closing server..."); 25 | 26 | try { 27 | await new Promise((resolve, reject) => { 28 | server.close((err: any) => { 29 | if (err) { 30 | reject(err); 31 | return; 32 | } 33 | resolve(); 34 | }); 35 | }); 36 | } catch (err) { 37 | console.error(`Error at closing ${err}`); 38 | } finally { 39 | process.exit(); 40 | } 41 | }); 42 | } 43 | 44 | function normalizePort(val: string) { 45 | const parsedPort = parseInt(val, 10); 46 | 47 | if (isNaN(parsedPort)) { 48 | return val; 49 | } 50 | 51 | if (parsedPort >= 0) { 52 | return parsedPort; 53 | } 54 | 55 | return false; 56 | } 57 | 58 | function onError(port: any): (error: any) => void { 59 | return (error: any) => { 60 | if (error.syscall !== "listen") { 61 | throw error; 62 | } 63 | 64 | const bind = typeof port === "string" ? "Pipe " + port : "Port " + port; 65 | 66 | switch (error.code) { 67 | case "EACCES": 68 | console.error(bind + " requires elevated privileges"); 69 | process.exit(1); 70 | break; 71 | case "EADDRINUSE": 72 | console.error(bind + " is already in use"); 73 | process.exit(1); 74 | break; 75 | default: 76 | throw error; 77 | } 78 | }; 79 | } 80 | 81 | function onListening(server: any): () => void { 82 | return () => { 83 | const addr = server.address(); 84 | const bind = 85 | typeof addr === "string" ? "pipe " + addr : "port " + addr.port; 86 | debug("Listening on " + bind); 87 | }; 88 | } 89 | -------------------------------------------------------------------------------- /config/default.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | 3 | module.exports = { 4 | knex: { 5 | client: "pg", 6 | connection: { 7 | host: "localhost", 8 | port: 5432, 9 | database: "codechain-keystore", 10 | user: "codechain" 11 | }, 12 | migrations: { 13 | directory: path.resolve(__dirname, "..", "migrations"), 14 | tableName: "knex" 15 | }, 16 | seeds: { 17 | directory: path.resolve(__dirname, "..", "seeds") 18 | } 19 | }, 20 | }; 21 | -------------------------------------------------------------------------------- /ecosystem.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | /** 3 | * Application configuration section 4 | * http://pm2.keymetrics.io/docs/usage/application-declaration/ 5 | */ 6 | apps: [ 7 | 8 | // First application 9 | { 10 | name: 'codechain-keystore', 11 | script: 'bin/www.ts', 12 | env: { 13 | COMMON_VARIABLE: 'true' 14 | }, 15 | env_production: { 16 | NODE_ENV: 'production' 17 | } 18 | } 19 | ] 20 | }; 21 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "roots": [ 3 | "/src" 4 | ], 5 | "transform": { 6 | "^.+\\.tsx?$": "ts-jest" 7 | }, 8 | "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$", 9 | "moduleFileExtensions": [ 10 | "ts", 11 | "tsx", 12 | "js", 13 | "jsx", 14 | "json", 15 | "node" 16 | ], 17 | } 18 | -------------------------------------------------------------------------------- /knexfile.js: -------------------------------------------------------------------------------- 1 | module.exports = require("config").get("knex"); 2 | -------------------------------------------------------------------------------- /migrations/00000000000000_keys.js: -------------------------------------------------------------------------------- 1 | const table = "keys"; 2 | 3 | exports.up = async (knex) => { 4 | const hasTable = await knex.schema.hasTable(table); 5 | if (!hasTable) { 6 | return knex.schema.createTable(table, (t) => { 7 | t.string("type").notNullable(); 8 | t.string("address").notNullable(); 9 | t.integer("version").notNullable(); 10 | t.string("kdf").notNullable(); 11 | t.json("kdfparams"); 12 | t.string("mac").notNullable(); 13 | t.string("cipher").notNullable(); 14 | t.json("cipherparams"); 15 | t.string("ciphertext").notNullable(); 16 | t.json("meta"); 17 | 18 | t.primary(["type", "address"]); 19 | }); 20 | } 21 | else { 22 | // TODO: Add detailed error message 23 | throw Error(); 24 | } 25 | }; 26 | 27 | exports.down = async (knex) => { 28 | const hasTable = await knex.schema.hasTable(table); 29 | if (hasTable) { 30 | return knex.schema.dropTable(table); 31 | } 32 | else { 33 | // TODO: Add detailed error message 34 | throw Error(); 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "codechain-keystore-server", 3 | "version": "0.3.0", 4 | "author": "CodeChain Team ", 5 | "license": "Apache-2.0", 6 | "scripts": { 7 | "start": "ts-node ./bin/www.ts", 8 | "load": "ts-node ./bin/load.ts", 9 | "test": "yarn lint && jest --env node", 10 | "lint": "tslint -p . && prettier '**/*.ts' -l", 11 | "fmt": "tslint -p . --fix && prettier '**/*ts' --write", 12 | "migrate": "knex migrate:latest --knexfile ./knexfile.js", 13 | "rollback": "knex migrate:rollback --knexfile ./knexfile.js", 14 | "seed": "knex seed:run --knexfile ./knexfile.js" 15 | }, 16 | "dependencies": { 17 | "codechain-keystore": "^0.6.1", 18 | "codechain-primitives": "^1.0.1", 19 | "commander": "^4.0.1", 20 | "config": "^3.1.0", 21 | "debug": "~2.6.9", 22 | "express": "~4.16.0", 23 | "http-errors": "~1.6.2", 24 | "knex": "^0.19.5", 25 | "morgan": "~1.9.1", 26 | "morgan-body": "^2.4.5", 27 | "objection": "^1.6.8", 28 | "pg": "^7.10.0", 29 | "request": "^2.88.0", 30 | "request-promise": "^4.2.2" 31 | }, 32 | "devDependencies": { 33 | "@types/commander": "^2.12.2", 34 | "@types/config": "^0.0.34", 35 | "@types/debug": "^0.0.30", 36 | "@types/express": "^4.16.0", 37 | "@types/http-errors": "^1.6.1", 38 | "@types/jest": "^23.3.1", 39 | "@types/lodash": "^4.14.116", 40 | "@types/morgan": "^1.7.35", 41 | "@types/node-sass-middleware": "^0.0.30", 42 | "@types/request-promise": "^4.1.42", 43 | "@types/supertest": "^2.0.5", 44 | "jest": "^24.8.0", 45 | "prettier": "1.14.2", 46 | "superagent": "^3.8.3", 47 | "supertest": "^3.1.0", 48 | "ts-jest": "^23.1.3", 49 | "ts-node": "^7.0.0", 50 | "tsc": "^1.20150623.0", 51 | "tslint": "^5.11.0", 52 | "tslint-config-prettier": "^1.14.0", 53 | "typescript": "^3.7.2" 54 | }, 55 | "resolutions": { 56 | "merge": "^1.2.1" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /seeds/keys.js: -------------------------------------------------------------------------------- 1 | const table = "keys"; 2 | 3 | exports.seed = async (knex) => { 4 | await knex(table).del(); 5 | return knex(table).insert([]); 6 | }; 7 | -------------------------------------------------------------------------------- /src/__test__/ping.spec.ts: -------------------------------------------------------------------------------- 1 | import { Application } from "express"; 2 | import * as request from "supertest"; 3 | import { createApp } from "../app"; 4 | 5 | let app: Application; 6 | 7 | beforeEach(async () => { 8 | app = await createApp(); 9 | }); 10 | 11 | test("ping", async () => { 12 | const response = await request(app).get("/ping"); 13 | expect(response.status).toBe(200); 14 | }); 15 | -------------------------------------------------------------------------------- /src/app.ts: -------------------------------------------------------------------------------- 1 | import * as config from "config"; 2 | import * as express from "express"; 3 | import * as createError from "http-errors"; 4 | import * as knex from "knex"; 5 | import * as logger from "morgan"; 6 | import { Model } from "objection"; 7 | const morganBody = require("morgan-body"); 8 | 9 | import { createRouter as createApiRouter } from "./routes/api"; 10 | import { createRouter as createPingRouter } from "./routes/ping"; 11 | 12 | export async function createApp(): Promise { 13 | Model.knex(knex(config.get("knex"))); 14 | const app = express(); 15 | 16 | app.use(logger("dev")); 17 | app.use(express.json()); 18 | morganBody(app); 19 | 20 | app.use("/api", createApiRouter()); 21 | app.use("/ping", createPingRouter()); 22 | 23 | // catch 404 and forward to error handler 24 | app.use((req, res, next) => { 25 | next(createError(404)); 26 | }); 27 | 28 | // error handler 29 | app.use((err: any, req: express.Request, res: express.Response) => { 30 | // set locals, only providing error in development 31 | res.locals.message = err.message; 32 | res.locals.error = req.app.get("env") === "development" ? err : {}; 33 | console.error(err); 34 | 35 | // render the error page 36 | res.status(err.status || 500); 37 | res.render("error"); 38 | }); 39 | return app; 40 | } 41 | -------------------------------------------------------------------------------- /src/models/key.ts: -------------------------------------------------------------------------------- 1 | import { SecretStorage } from "codechain-keystore"; 2 | import { Model, snakeCaseMappers } from "objection"; 3 | 4 | export default class KeyModel extends Model { 5 | public static columnNameMappers = snakeCaseMappers(); 6 | 7 | public static tableName = "keys"; 8 | public static idColumn = ["type", "address"]; 9 | public readonly type!: "asset" | "platform"; 10 | public readonly address!: string; 11 | public readonly version!: number; 12 | 13 | public readonly kdf!: string; 14 | public readonly kdfparams?: any; 15 | public readonly mac!: string; 16 | 17 | public readonly cipher!: string; 18 | public readonly cipherparams?: any; 19 | public readonly ciphertext!: string; 20 | 21 | public readonly meta!: any; 22 | 23 | public toJSON(): SecretStorage { 24 | return { 25 | crypto: { 26 | ciphertext: this.ciphertext, 27 | cipherparams: this.cipherparams, 28 | cipher: this.cipher, 29 | kdf: this.kdf, 30 | kdfparams: this.kdfparams, 31 | mac: this.mac 32 | }, 33 | id: this.address, 34 | version: this.version, 35 | address: this.address, 36 | meta: this.meta 37 | }; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/routes/api.ts: -------------------------------------------------------------------------------- 1 | import * as storage from "codechain-keystore/lib/logic/storage"; 2 | import { KeyType as KeyTypeId } from "codechain-keystore/lib/model/keytypes"; 3 | import { 4 | generatePrivateKey, 5 | getAccountIdFromPublic, 6 | getPublicFromPrivate, 7 | signEcdsa 8 | } from "codechain-primitives"; 9 | import * as express from "express"; 10 | import KeyModel from "../models/key"; 11 | 12 | type KeyType = "asset" | "platform"; 13 | 14 | function findKey( 15 | type: KeyType, 16 | address: string 17 | ): Promise { 18 | return KeyModel.query().findById([type, address]) as any; 19 | } 20 | 21 | export function createRouter() { 22 | const router = express.Router(); 23 | 24 | router.get("/keys", async (req, res) => { 25 | const keyType: KeyType = req.body.keyType; 26 | res.json({ 27 | success: true, 28 | result: await KeyModel.query().where({ type: keyType }) 29 | }); 30 | }); 31 | 32 | router.get("/keys/:key/publicKey", async (req, res) => { 33 | const { key } = req.params; 34 | const keyType: KeyType = req.body.keyType; 35 | 36 | const row = await findKey(keyType, key); 37 | if (row == null) { 38 | res.json({ 39 | success: false, 40 | error: "Not found" 41 | }); 42 | } else { 43 | const priv = await storage.decode(row.toJSON(), ""); 44 | const pub = getPublicFromPrivate(priv); 45 | res.json({ 46 | success: true, 47 | result: pub 48 | }); 49 | } 50 | }); 51 | 52 | router.get("/keys/:key/rawKey", async (req, res) => { 53 | const { key } = req.params; 54 | const { passphrase } = req.body; 55 | const keyType: KeyType = req.body.keyType; 56 | 57 | const row = await findKey(keyType, key); 58 | if (row == null) { 59 | res.json({ 60 | success: false, 61 | error: "Not found" 62 | }); 63 | } else { 64 | try { 65 | const priv = await storage.decode(row.toJSON(), passphrase); 66 | res.json({ 67 | success: true, 68 | result: priv 69 | }); 70 | } catch (e) { 71 | res.json({ 72 | success: false, 73 | error: "Invalid passphrase" 74 | }); 75 | } 76 | } 77 | }); 78 | 79 | router.post("/keys", async (req, res) => { 80 | const { passphrase } = req.body; 81 | const keyType: KeyType = req.body.keyType; 82 | 83 | while (true) { 84 | const priv = generatePrivateKey(); 85 | const pub = getPublicFromPrivate(priv); 86 | const address = getAccountIdFromPublic(pub); 87 | 88 | // Check duplication 89 | if ((await findKey(keyType, address)) != null) { 90 | continue; 91 | } 92 | 93 | let typeId: KeyTypeId | undefined; 94 | switch (keyType) { 95 | case "asset": { 96 | typeId = KeyTypeId.Asset; 97 | break; 98 | } 99 | case "platform": { 100 | typeId = KeyTypeId.Platform; 101 | break; 102 | } 103 | } 104 | 105 | const secret = await storage.encode( 106 | priv, 107 | typeId!, 108 | passphrase, 109 | JSON.stringify({}) 110 | ); 111 | await KeyModel.query().insert({ 112 | type: keyType, 113 | address: secret.address, 114 | version: secret.version, 115 | 116 | kdf: secret.crypto.kdf, 117 | kdfparams: secret.crypto.kdfparams, 118 | mac: secret.crypto.mac, 119 | 120 | cipher: secret.crypto.cipher, 121 | cipherparams: secret.crypto.cipherparams, 122 | ciphertext: secret.crypto.ciphertext, 123 | 124 | meta: secret.meta 125 | }); 126 | 127 | res.json({ 128 | success: true, 129 | result: secret.address 130 | }); 131 | return; 132 | } 133 | }); 134 | 135 | router.delete("/keys/:key", async (req, res) => { 136 | const { key } = req.params; 137 | const keyType: KeyType = req.body.keyType; 138 | 139 | const row = await findKey(keyType, key); 140 | 141 | if (row == null) { 142 | res.json({ 143 | success: false, 144 | error: "Not found" 145 | }); 146 | } else { 147 | try { 148 | // Check if the passphrase is correct 149 | await storage.decode(row.toJSON(), ""); 150 | await KeyModel.query() 151 | .del() 152 | .findById([keyType, key]); 153 | res.json({ 154 | success: true, 155 | result: true 156 | }); 157 | } catch (e) { 158 | res.json({ 159 | success: true, 160 | result: false 161 | }); 162 | } 163 | } 164 | }); 165 | 166 | router.post("/keys/:key/sign", async (req, res) => { 167 | const { key } = req.params; 168 | const { message, passphrase = "" } = req.body; 169 | const keyType: KeyType = req.body.keyType; 170 | 171 | const row = await findKey(keyType, key); 172 | 173 | if (row == null) { 174 | res.json({ 175 | success: false, 176 | error: "Not found" 177 | }); 178 | } else { 179 | try { 180 | const priv = await storage.decode(row.toJSON(), passphrase); 181 | res.json({ 182 | success: true, 183 | result: signEcdsa(message, priv) 184 | }); 185 | } catch (e) { 186 | res.json({ 187 | success: false, 188 | error: e 189 | }); 190 | } 191 | } 192 | }); 193 | 194 | return router; 195 | } 196 | -------------------------------------------------------------------------------- /src/routes/ping.ts: -------------------------------------------------------------------------------- 1 | import * as express from "express"; 2 | 3 | export function createRouter() { 4 | const router = express.Router(); 5 | 6 | router.get("/", async (req, res) => { 7 | res.json({ 8 | success: true 9 | }); 10 | }); 11 | 12 | return router; 13 | } 14 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "dist", 4 | "module": "commonjs", 5 | "target": "es5", 6 | "lib": [ 7 | "es6", 8 | "dom" 9 | ], 10 | "baseUrl": ".", 11 | "sourceMap": true, 12 | "allowJs": true, 13 | "moduleResolution": "node", 14 | "rootDir": ".", 15 | "forceConsistentCasingInFileNames": true, 16 | "noImplicitReturns": true, 17 | "noImplicitThis": true, 18 | "noImplicitAny": true, 19 | "strictNullChecks": true, 20 | "suppressImplicitAnyIndexErrors": true, 21 | "noUnusedLocals": true 22 | }, 23 | "exclude": [ 24 | "node_modules", 25 | "dist" 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint:recommended", 4 | "tslint-config-prettier" 5 | ], 6 | "rules": { 7 | "interface-name": false, 8 | "no-console": false, 9 | "object-literal-sort-keys": false, 10 | "no-var-requires": false, 11 | "array-type": false 12 | }, 13 | "jsRules": { 14 | "no-console": false, 15 | "object-literal-sort-keys": false 16 | }, 17 | "linterOptions": { 18 | "exclude": [ 19 | "dist/**/*.js", 20 | "node_modules/**/*.ts", 21 | "public/javascripts/lib/*.js" 22 | ] 23 | } 24 | } 25 | --------------------------------------------------------------------------------