├── .gitignore ├── README.md ├── bitagora-booth ├── LICENSE ├── README.md ├── booth.js ├── package-lock.json ├── package.json └── protobuf_bundle.json ├── bitagora-certifier ├── .gitignore ├── README.md ├── certifier.js ├── context.json ├── event_sources.json ├── index.js ├── package-lock.json ├── package.json ├── tests │ ├── event_close.json │ ├── event_create.json │ └── event_register.json └── validators │ └── validator-es.js ├── bitagora-library ├── LICENSE ├── README.md ├── constants.js ├── functions.js ├── index.js ├── package-lock.json ├── package.json ├── state.js └── validate.js ├── bitagora-node ├── .gitignore ├── LICENSE ├── README.md ├── bitagora-node.sh ├── docker-compose.yaml ├── src │ ├── Dockerfile │ ├── ballots-tp │ │ ├── Dockerfile │ │ ├── ballots-handler.js │ │ ├── ballots.js │ │ ├── package-lock.json │ │ └── package.json │ ├── polls-tp │ │ ├── Dockerfile │ │ ├── package-lock.json │ │ ├── package.json │ │ ├── polls-handler.js │ │ └── polls.js │ ├── shell │ │ ├── Dockerfile │ │ ├── package-lock.json │ │ ├── package.json │ │ └── shell.js │ └── update-lib.sh └── validator.toml └── bitagora-pollster ├── LICENSE ├── README.md ├── package-lock.json ├── package.json └── pollster.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [Bitagora White Paper](https://github.com/bitagora/bitagora-web/blob/master/assets/docs/Bitagora_WP.pdf) 2 | -------------------------------------------------------------------------------- /bitagora-booth/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 | -------------------------------------------------------------------------------- /bitagora-booth/README.md: -------------------------------------------------------------------------------- 1 | ![Bitagora](https://bitagora.cc/assets/img/bitagora-name-blue.png) 2 | 3 | ## Bitagora Booth 4 | 5 | ![version](https://img.shields.io/badge/version-1.0.178-green.svg) 6 | ![Hex.pm](https://img.shields.io/hexpm/l/plug.svg) 7 | 8 | Source code for the JS client used to process and send ballots to the Bitagora blockchain. 9 | This code is used in both the web and mobile UIs freely distributed by Bitagora. To learn more 10 | about Bitagora, please visit [Bitagora website](https://www.bitagora.cc). 11 | 12 | ## License 13 | 14 | Bitagora Booth is licensed under the [Apache License Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) 15 | software license. -------------------------------------------------------------------------------- /bitagora-booth/booth.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BITAGORA BOOTH 3 | * booth.js 4 | * Vote, check and count ballots in the Bitagora Platform voting system 5 | * Developed by Ignasi Ribó, 2018 6 | * Repo: https://github.com/bitagora/bitagora-core 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * ------------------------------------------------------------------------------ 20 | */ 21 | 22 | 'use strict' 23 | const { 24 | BITAGORA_URL, BITAGORA_PREFIX, BITAGORA_FAMILY, BITAGORA_VERSION, 25 | getPollAddress, getPrechecksumVote, requestState, getNodeList, _hash, requestURL, getBallot, getVoteAddress, 26 | validateVote } = require('bitagora-library'); 27 | const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; 28 | const Bs58 = require('base-x')(BASE58); 29 | 30 | const { createContext, CryptoFactory } = require('sawtooth-sdk/signing'); 31 | const { Secp256k1PrivateKey } = require('sawtooth-sdk/signing/secp256k1'); 32 | 33 | const protobuf = require('protobufjs'); 34 | const root = protobuf.Root.fromJSON(require('./protobuf_bundle.json')); 35 | const TransactionHeader = root.lookup('TransactionHeader'); 36 | const Transaction = root.lookup('Transaction'); 37 | const Batch = root.lookup('Batch'); 38 | const BatchHeader = root.lookup('BatchHeader'); 39 | const BatchList = root.lookup('BatchList'); 40 | 41 | class Vote { 42 | constructor(data, poll) { 43 | this.prefix = BITAGORA_PREFIX, 44 | this.id = data.id, 45 | this.date = data.date, 46 | this.poll = poll.id, 47 | this.ballot = getBallot(data.ballot, poll, Bs58.decode(data.privkey).toString('hex')), 48 | this.checksum = _hash('sha256',getPrechecksumVote(this)).substr(0,4), 49 | this.certsig = data.certsig 50 | this.timestamp = '' 51 | } 52 | } 53 | 54 | function postVote(voteBytes,url) { 55 | return new Promise(function(resolve, reject) { 56 | const request = require('request'); 57 | request.post({ 58 | url: url+'/batches', 59 | body: voteBytes, 60 | headers: { 61 | 'Content-Type': 'application/octet-stream' 62 | }, 63 | timeout: 2000 64 | }, 65 | (err, response) => { 66 | try { 67 | if (err) { 68 | console.log(err); 69 | reject(err); 70 | } else { 71 | if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 202) { 72 | let link = JSON.parse(response.body)['link']; 73 | requestURL(link).then((result) => { 74 | if (Boolean(result) && Boolean(result.data)) { 75 | resolve(result.data[0]); 76 | } else { 77 | reject(false); 78 | } 79 | }).catch((e) => { 80 | reject(e); 81 | }); 82 | } else { 83 | reject(response.body); 84 | } 85 | } 86 | } catch(e) { 87 | console.log(e); 88 | reject(e); 89 | } 90 | }); 91 | }); 92 | } 93 | 94 | function getVoteBytes(vote, signer, poll) { 95 | return new Promise((resolve) => { 96 | try { 97 | vote.timestamp = new Date().getTime().toString(); 98 | var payloadBytes = Buffer.from(JSON.stringify(vote)); 99 | const transactionHeaderBytes = TransactionHeader.encode({ 100 | familyName: BITAGORA_FAMILY, 101 | familyVersion: BITAGORA_VERSION, 102 | inputs: [getVoteAddress(poll.id, vote.id), getPollAddress(poll.id)], 103 | outputs: [getVoteAddress(poll.id, vote.id), getPollAddress(poll.id)], 104 | signerPublicKey: vote.id, 105 | batcherPublicKey: vote.id, 106 | dependencies: [], 107 | payloadSha512: _hash('sha512', payloadBytes) 108 | }).finish(); 109 | const signature = signer.sign(transactionHeaderBytes); 110 | const transaction = Transaction.create({ 111 | header: transactionHeaderBytes, 112 | headerSignature: signature, 113 | payload: payloadBytes 114 | }); 115 | const transactions = [transaction]; 116 | const batchHeaderBytes = BatchHeader.encode({ 117 | signerPublicKey: vote.id, 118 | transactionIds: transactions.map((txn) => txn.headerSignature) 119 | }).finish(); 120 | const batchSignature = signer.sign(batchHeaderBytes); 121 | const batch = Batch.create({ 122 | header: batchHeaderBytes, 123 | headerSignature: batchSignature, 124 | transactions: transactions 125 | }); 126 | const batchListBytes = BatchList.encode({ 127 | batches: [batch] 128 | }).finish(); 129 | resolve(batchListBytes); 130 | } catch(e) { 131 | console.log(e); 132 | resolve(false); 133 | } 134 | }); 135 | } 136 | 137 | function fetchVote(data) { 138 | return new Promise((resolve) => { 139 | try { 140 | if (!Boolean(data['id'])) { 141 | if (Boolean(data['privkey'])) { 142 | const privkey_hex = Bs58.decode(data['privkey']).toString('hex'); 143 | const privateKey = Secp256k1PrivateKey.fromHex(privkey_hex); 144 | const signerContext = createContext('secp256k1'); 145 | data['id'] = signerContext.getPublicKey(privateKey).asHex(); 146 | } 147 | } 148 | if (!Boolean(data['poll']) || !Boolean(data['id'])) throw 'No data'; 149 | requestState(BITAGORA_URL, 'ballot', data['poll'], data['id'], null, null).then((result) => { 150 | resolve(result); 151 | }).catch((e) => { 152 | console.log(e); 153 | resolve({status: 'UNKNOWN' }); 154 | }); 155 | } catch(e) { 156 | console.log(e); 157 | resolve({status: 'UNKNOWN' }); 158 | } 159 | }); 160 | } 161 | 162 | function wait(ms){ 163 | var start = new Date().getTime(); 164 | var end = start; 165 | while(end < start + ms) { 166 | end = new Date().getTime(); 167 | } 168 | } 169 | 170 | 171 | async function confirmSubmission(link) { 172 | try { 173 | let attempts = 0; 174 | var response; 175 | while (attempts < 3) { 176 | response = await requestURL(link); 177 | if (response.data[0].status == "COMMITTED" || response.data[0].status == "INVALID") break; 178 | wait(2000 + attempts * 1000); 179 | attempts = attempts + 1; 180 | } 181 | return(response); 182 | } catch(e) { 183 | return { status: 'UNKNOWN' }; 184 | } 185 | } 186 | 187 | async function sendVoteToAPIs(bytes, apis) { 188 | try { 189 | let response = { status: 'ERROR', code: '', message: '' }; 190 | var link; 191 | for (var i=0; i { 193 | console.log(e); 194 | try { 195 | let error = JSON.parse(e); 196 | if (Boolean(error['error']) && Boolean(error['error']['code'])) { 197 | response['code'] = error['error']['code']; 198 | response['message'] = error['error']['message']; 199 | } 200 | } catch(err) { console.log(err); } 201 | return false; 202 | }); 203 | if (result) { 204 | if ( result.status == 'COMMITTED' ) { 205 | response = result; 206 | break; 207 | } else if ( result.status == 'PENDING' ) { 208 | link = apis[i] + "/batch_statuses?id=" + result.id; 209 | response = await confirmSubmission(link).catch((e) => { return { status: 'ERROR', code: '', message: e } }); 210 | if (Boolean(response) && Boolean(response.status)) { 211 | if (response.status == 'COMMITTED') break; 212 | if (response.status == 'INVALID') throw response; 213 | } 214 | } else if (result.status == 'INVALID' ) { 215 | throw result; 216 | } 217 | } 218 | } 219 | return response; 220 | } catch(e) { 221 | console.log(e); 222 | if (Boolean(e.status) && e.status == 'INVALID') { 223 | return e; 224 | } else { 225 | return { status: 'ERROR', code: '', message: e }; 226 | } 227 | } 228 | } 229 | 230 | function vote(ballot, context) { 231 | return new Promise((resolve) => { 232 | try { 233 | if (!Boolean(ballot) || !Boolean(context)) throw 'No data'; 234 | var newVote = new Vote(ballot, context.poll); 235 | if (!newVote.ballot) throw 'Ballot is not valid'; 236 | var privkey_hex = Bs58.decode(ballot.privkey).toString('hex'); 237 | const privateKey = Secp256k1PrivateKey.fromHex(privkey_hex); 238 | const signerContext = createContext('secp256k1'); 239 | const factory = new CryptoFactory(signerContext); 240 | const signer = factory.newSigner(privateKey); 241 | const pubkey_hex = signerContext.getPublicKey(privateKey).asHex(); 242 | if (pubkey_hex != newVote.id) throw 'Vote is not valid'; 243 | validateVote(newVote, context.poll).then((valid) => { 244 | try { 245 | if (!valid) throw 'Vote is not valid'; 246 | requestState(BITAGORA_URL, 'poll', context.poll.id, null, null).then((respState) => { 247 | try { 248 | if (!Boolean(respState) || respState.status != "FOUND" ) throw 'No state'; 249 | getNodeList(BITAGORA_URL).then((APIs) => { 250 | try { 251 | if (!Boolean(APIs)) APIs = []; 252 | if (Boolean(context.nodeSeed)) APIs.concat(context.nodeSeed); 253 | let uniqueAPIs = APIs.filter(function(value, index, self) { return self.indexOf(value) === index; }); 254 | if (!Boolean(uniqueAPIs) || uniqueAPIs.length == 0) throw 'No APIs'; 255 | getVoteBytes(newVote, signer, context.poll).then((bytes) => { 256 | try { 257 | if (!bytes) throw 'No bytes to send'; 258 | sendVoteToAPIs(bytes, uniqueAPIs).then((result) => { 259 | resolve(result); 260 | }).catch((e) => { 261 | console.log(e); 262 | resolve({ status: 'ERROR' }); 263 | }); 264 | } catch(e) { 265 | console.log(e); 266 | resolve({ status: 'ERROR' }); 267 | } 268 | }).catch((e) => { 269 | console.log(e); 270 | resolve({ status: 'ERROR' }); 271 | }); 272 | } catch(e) { 273 | console.log(e); 274 | resolve({ status: 'ERROR' }); 275 | } 276 | }).catch((e) => { 277 | console.log(e); 278 | resolve({ status: 'ERROR' }); 279 | }); 280 | } catch(e) { 281 | console.log(e); 282 | resolve({ status: 'ERROR' }); 283 | } 284 | }).catch((e) => { 285 | console.log(e); 286 | resolve({ status: 'ERROR' }); 287 | }); 288 | } catch(e) { 289 | console.log(e); 290 | resolve({ status: 'ERROR' }); 291 | } 292 | }).catch((e) => { 293 | console.log(e); 294 | resolve({ status: 'ERROR' }); 295 | }); 296 | } catch(e) { 297 | console.log(e); 298 | resolve({ status: 'ERROR' }); 299 | } 300 | }); 301 | } 302 | 303 | function check(data) { 304 | return new Promise((resolve) => { 305 | try { 306 | if (!Boolean(data)) throw 'No data'; 307 | if (!Boolean(data.poll)) throw 'No poll'; 308 | if (!Boolean(data.id) && !Boolean(data.privkey)) throw 'No privkey'; 309 | fetchVote(data).then((result) => { 310 | resolve(result); 311 | }).catch((e) => { 312 | console.log(e); 313 | resolve(false); 314 | }); 315 | } catch(e) { 316 | console.log(e); 317 | resolve(false); 318 | } 319 | }); 320 | }; 321 | 322 | function recount(pollId) { 323 | return new Promise((resolve) => { 324 | try { 325 | if (!Boolean(pollId)) throw 'No poll id'; 326 | requestState(BITAGORA_URL, 'poll', pollId, null, null).then((result) => { 327 | resolve(result); 328 | }).catch((e) => { 329 | console.log(e); 330 | resolve({status: 'ERROR' }); 331 | }); 332 | } catch(e) { 333 | console.log(e); 334 | resolve({status: 'ERROR' }); 335 | } 336 | }); 337 | }; 338 | 339 | module.exports = { 340 | vote, 341 | check, 342 | recount 343 | } 344 | 345 | -------------------------------------------------------------------------------- /bitagora-booth/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bitagora-booth", 3 | "version": "1.1.1", 4 | "license": "Apache-2.0", 5 | "author": "Ignasi Ribó, 2018", 6 | "description": "Bitagora Booth functions for submitting, counting and checking ballots from a client application", 7 | "main": "booth.js", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/bitagora/bitagora-core.git" 11 | }, 12 | "scripts": { 13 | "build:local": "ionic-app-scripts build", 14 | "build": "true" 15 | }, 16 | "dependencies": { 17 | "bitagora-library": "0.1.1", 18 | "async": "2.6.0", 19 | "atob": "2.1.1", 20 | "base-x": "3.0.4", 21 | "btoa": "1.2.1", 22 | "cbor": "4.0.0", 23 | "protobufjs": "^6.8.6", 24 | "request": "2.87.0", 25 | "sawtooth-sdk": "^1.0.4" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /bitagora-certifier/.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | deploy.env 3 | event.json 4 | .lambda 5 | -------------------------------------------------------------------------------- /bitagora-certifier/README.md: -------------------------------------------------------------------------------- 1 | ![Bitagora](https://bitagora.cc/assets/img/bitagora-name-blue.png) 2 | 3 | # Bitagora Certifier 4 | 5 | WARNING: This module is still being developed and is not ready for production. 6 | 7 | ![version](https://img.shields.io/badge/version-0.1.0-green.svg) 8 | ![Hex.pm](https://img.shields.io/hexpm/l/plug.svg) 9 | 10 | Source code for Certifier instance to be deployed as an AWS lambda. It acts as an opaque registration instance 11 | in the Bitagora Platform voting system. 12 | 13 | For more information, visit 14 | 15 | [https://bitagora.cc](https://bitagora.cc) 16 | 17 | ## License 18 | 19 | Bitagora Certifier is licensed under the [Apache License Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) 20 | software license. 21 | ``` -------------------------------------------------------------------------------- /bitagora-certifier/certifier.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BITAGORA CERTIFIER 3 | * certifier.js 4 | * Functions run by the AWS lambda handler in the Bitagora Certifier implementation of the voter registration system 5 | * Developed by Ignasi Ribó, 2018 6 | * Repo: https://github.com/bitagora/bitagora-core 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * ------------------------------------------------------------------------------ 20 | */ 21 | 22 | 'use strict' 23 | const { create, close } = require('bitagora-pollster'); 24 | const BITAGORA_PREFIX = 'cc0110'; 25 | const crypto = require('crypto'); 26 | const EC = require('elliptic').ec; 27 | var ec = new EC('secp256k1'); 28 | const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; 29 | const Bs58 = require('base-x')(BASE58); 30 | 31 | const _hash = (sha, x) => crypto.createHash(sha).update(x).digest('hex').toLowerCase(); 32 | 33 | function getPollToken(poll) { 34 | try { 35 | return JSON.stringify({ 36 | id: poll.id, 37 | certkey: poll.certkey, 38 | starts: poll.starts, 39 | ends: poll.ends, 40 | question: poll.question, 41 | values: poll.values, 42 | open: poll.open, 43 | adminkey: poll.adminkey 44 | }); 45 | } catch(e) { 46 | return null; 47 | } 48 | } 49 | 50 | function getVoteToken(vote) { 51 | try { 52 | return JSON.stringify({ 53 | prefix: vote.prefix, 54 | id: vote.id, 55 | date: vote.date, 56 | poll: vote.poll, 57 | checksum: vote.checksum 58 | }); 59 | } catch(e) { 60 | return null; 61 | } 62 | } 63 | 64 | function getPrechecksumVote(vote) { 65 | return vote.prefix + vote.id + vote.date + vote.poll; 66 | } 67 | 68 | function generateKeys(context) { 69 | try { 70 | let certKey = ec.genKeyPair(); 71 | context['privkey'] = certKey.getPrivate('hex'); 72 | context['poll']['certkey'] = certKey.getPublic().encodeCompressed('hex'); 73 | context['poll']['id'] = context['poll']['certkey'].substr(context['poll']['certkey'].length - 8); 74 | context['secret'] = crypto.randomBytes(32).toString('hex'); 75 | if (!Boolean(context['poll']['certkey'])) throw 'Unable to generate certkey'; 76 | if (!Boolean(context['privkey'])) throw 'Unable to generate privkey'; 77 | if (!Boolean(context['secret'])) throw 'Unable to generate secret'; 78 | if (!Boolean(context['poll']['id'])) throw 'Unable to generate id'; 79 | return(context); 80 | } catch(e) { 81 | reject(false); 82 | } 83 | } 84 | 85 | function approvePoll(adminPrivkeyHex, context) { 86 | try { 87 | if (!Boolean(adminPrivkeyHex)) throw 'No admin key'; 88 | let token = _hash('sha256',_hash('sha256', getPollToken(context['poll']))); 89 | let adminKey = ec.keyFromPrivate(adminPrivkeyHex); 90 | let signature = adminKey.sign(token); 91 | context['poll']['approval'] = signature.toDER('hex'); 92 | return context; 93 | } catch(e) { 94 | reject(false); 95 | } 96 | } 97 | 98 | 99 | function processVoter(idcode, context) { 100 | return new Promise((resolve, reject) => { 101 | try { 102 | if (!Boolean(context['privkey']) || !Boolean(context['secret'])) throw 'No private key or secret'; 103 | let certKey = ec.keyFromPrivate(context['privkey']); 104 | let voterPrivkeyHex = context['privkey'] + context['poll']['id']+ idcode + context['secret']; 105 | for (var i=0; i<11; i++) { 106 | voterPrivkeyHex = _hash('sha256', voterPrivkeyHex); 107 | } 108 | let voterKey = ec.keyFromPrivate(voterPrivkeyHex); 109 | let d = new Date(); 110 | let vote = { 111 | prefix: BITAGORA_PREFIX, 112 | id: voterKey.getPublic().encodeCompressed('hex'), 113 | date: d.getFullYear().toString() + ("0"+(d.getMonth()+1)).slice(-2).toString() + ("0" + d.getDate()).slice(-2).toString(), 114 | poll: context['poll']['id'] 115 | } 116 | vote['checksum'] = _hash('sha256',getPrechecksumVote(vote)).substr(0,4); 117 | let registration = { 118 | privkey: Bs58.encode(Buffer.from(voterPrivkeyHex, 'hex')), 119 | id: vote.id, 120 | certsig: certKey.sign(getVoteToken(vote)).toDER('hex'), 121 | date: vote.date 122 | } 123 | resolve(registration); 124 | } catch(e) { 125 | reject(e); 126 | } 127 | }); 128 | } 129 | 130 | function registerVoter(pollId, id, context, validator) { 131 | return new Promise((resolve) => { 132 | try { 133 | const { validId } = require('./validators/'+validator); 134 | if (!Boolean(id)) throw 'No id'; 135 | if (!Boolean(pollId)) throw 'No poll id'; 136 | if (context['poll']['id'] !== pollId) throw 'Wrong poll id'; 137 | if (!validId) throw 'Id is not valid'; 138 | processVoter(id, context).then((voter) => { 139 | try { 140 | if (Boolean(voter) && 141 | Boolean(voter.privkey) && 142 | Boolean(voter.certsig) && 143 | Boolean(voter.certsig) && 144 | Boolean(voter.id) && 145 | Boolean(voter.date)) 146 | { 147 | resolve(voter); 148 | } else { 149 | throw 'Error'; 150 | } 151 | } catch(e) { 152 | resolve(null); 153 | } 154 | }).catch((e) => { 155 | resolve(null); 156 | }); 157 | } catch(e) { 158 | resolve(null); 159 | } 160 | }); 161 | } 162 | 163 | function closePoll(adminPrivkey, context) { 164 | return new Promise((resolve) => { 165 | try { 166 | if (!Boolean(adminPrivkey)) throw 'No admin key'; 167 | if (!Boolean(context) || !Boolean(context['privkey'])) throw 'Poll has not been set'; 168 | let adminKey = ec.keyFromPrivate(adminPrivkey); 169 | if (adminKey.getPublic().encodeCompressed('hex') !== context['poll']['adminkey'] ) throw 'Wrong admin key'; 170 | close(context['poll'], context['privkey']).then((closed) => { 171 | let privkey = context['privkey']; 172 | if (closed.status == 'COMMITTED') { 173 | context['privkey'] = null; 174 | context['secret'] = null; 175 | } 176 | resolve({ status: closed.status, context: context, response: privkey }); 177 | }).catch((e) => { 178 | resolve({ status: 'ERROR', response: 'Failed to close poll' }); 179 | }); 180 | } catch(e) { 181 | resolve({ status: 'ERROR', response: 'Failed to close poll' }); 182 | } 183 | }); 184 | } 185 | 186 | function createPoll(adminPrivkey, context) { 187 | return new Promise((resolve) => { 188 | try { 189 | if (!Boolean(adminPrivkey)) throw 'No admin key'; 190 | if (Boolean(context['privkey'])) throw 'Poll already exists'; 191 | let adminKey = ec.keyFromPrivate(adminPrivkey); 192 | if (adminKey.getPublic().encodeCompressed('hex') !== context['poll']['adminkey'] ) throw 'Wrong admin key'; 193 | context = generateKeys(context); 194 | if (!Boolean(context)) throw 'Poll data not registered'; 195 | context = approvePoll(adminPrivkey, context) 196 | if (!Boolean(context)) throw 'Unable to approve'; 197 | create(context['poll'], context['privkey']).then((created) => { 198 | resolve({ status: created.status, context: context, response: context['poll'] }); 199 | }).catch((e) => { 200 | resolve({ status: 'ERROR', response: 'Failed to create poll' }); 201 | }); 202 | } catch(e) { 203 | resolve({ status: 'ERROR', response: 'Failed to create poll' }); 204 | } 205 | }); 206 | } 207 | 208 | module.exports = { 209 | createPoll, 210 | closePoll, 211 | registerVoter 212 | } -------------------------------------------------------------------------------- /bitagora-certifier/context.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /bitagora-certifier/event_sources.json: -------------------------------------------------------------------------------- 1 | { 2 | "EventSourceMappings": [ 3 | { 4 | "EventSourceArn": "your event source arn", 5 | "StartingPosition": "LATEST", 6 | "BatchSize": 100, 7 | "Enabled": true 8 | } 9 | ], 10 | "ScheduleEvents": [ 11 | { 12 | "ScheduleName": "node-lambda-test-schedule", 13 | "ScheduleState": "ENABLED", 14 | "ScheduleExpression": "rate(1 hour)" 15 | } 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /bitagora-certifier/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BITAGORA CERTIFIER 3 | * index.js 4 | * Handlers for AWS lambda Certifier instance. Work in progress. 5 | * Repo: https://github.com/bitagora/bitagora-core 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * ------------------------------------------------------------------------------ 19 | */ 20 | 21 | 'use strict' 22 | const crypto = require('crypto'); 23 | const {createPoll, closePoll, registerVoter } = require('./certifier.js'); 24 | var AWS = require("aws-sdk"); 25 | var awsConfig = new AWS.Config(); 26 | 27 | /// CERTIFIER SETTINGS 28 | /// These settings need to be adjusted for each Certifier instance 29 | const S3bucket = 'bitagora-polls'; // AWS S3 bucket name 30 | awsConfig.update({ region: 'eu-central-1' }); // AWS region 31 | const certifierId = 'abd88b149c12ed6f'; // Certifier id 8 bytes hex string 32 | const certifierKey = '6dc7e4849eb951e2f5df3949c129940855ee1dc5e8133a1d34e0d767cd4f7c25'; // Certifier key 32 bytes hex string 33 | const validator = 'validator-es.js'; // name of the validator file in the /validators directory 34 | 35 | // The initial_context object is partially set with the information of the poll that the certifier will be 36 | // employed for. The values of privkey, secret, id, certkey and approval are left as null. They are 37 | // only set by the Certifier instance at runtime. 38 | const initial_context = { 39 | "privkey":null, // Leave null - Needs to be set by certifier instance 40 | "secret":null, // Leave null - Needs to be set by certifier instance 41 | "poll": 42 | { 43 | "id":null, // Leave null - Needs to be set by certifier instance 44 | "certkey":null, // Leave null - Needs to be set by certifier instance 45 | "starts":"1535734800000", // JS time value 46 | "ends":"1543597200000", // JS time value 47 | "question":"Some question?", // String 48 | "values":{"00":"Option 1","01":"Option 2"}, // JSON object with values and options 49 | "open": true, // Boolean true/false 50 | "adminkey":"025cc23ab1d64668e54acbfcf911806666a553968ee3322ca1829037e40b46c0e9", // Hex string. Administrator public key 51 | "approval":null // Leave null - Needs to be set by certifier instance 52 | } 53 | } 54 | ///// End of settings 55 | 56 | 57 | function encrypt(data) { 58 | const cipher = crypto.createCipher('aes192', certifierKey); 59 | var encrypted = cipher.update(data, 'utf8', 'hex'); 60 | encrypted += cipher.final('hex'); 61 | return encrypted; 62 | } 63 | 64 | function decrypt(ciphertext) { 65 | const decipher = crypto.createDecipher('aes192', certifierKey); 66 | var decrypted = decipher.update(ciphertext, 'hex', 'utf8'); 67 | decrypted += decipher.final('utf8'); 68 | return decrypted; 69 | } 70 | 71 | function putObjectToS3(key, data){ 72 | return new Promise((resolve, reject) => { 73 | try { 74 | var s3 = new AWS.S3(); 75 | var params = { 76 | Bucket: S3bucket, 77 | Key: key, 78 | Body: encrypt(JSON.stringify(data)) 79 | }; 80 | s3.putObject(params, function(err, respo) { 81 | if (err) { 82 | reject(err); 83 | } else { 84 | resolve(respo); 85 | } 86 | }); 87 | } catch(e) { 88 | reject(e); 89 | } 90 | }); 91 | } 92 | 93 | function getObjectFromS3(key) { 94 | return new Promise((resolve, reject) => { 95 | try { 96 | var s3 = new AWS.S3(); 97 | var params = { 98 | Bucket : S3bucket, 99 | Key : key 100 | } 101 | s3.getObject(params, function(err, respo) { 102 | if (err){ 103 | reject(err); 104 | } else { 105 | let encrypted = Buffer.from(respo['Body']).toString(); 106 | let decrypted = decrypt(encrypted); 107 | resolve(JSON.parse(decrypted)); 108 | } 109 | }); 110 | } catch(e) { 111 | reject(e); 112 | } 113 | }); 114 | } 115 | 116 | exports.handler = (event, context, callback) => { 117 | 118 | const done = (err, res) => callback(null, { 119 | statusCode: err ? '400' : '200', 120 | body: err ? err : JSON.stringify(res), 121 | headers: { 'Content-Type': 'application/json' }, 122 | }); 123 | 124 | function createNewPoll(privkey) { 125 | createPoll(privkey, initial_context).then((result) => { 126 | if (Boolean(result) && result.status == 'COMMITTED') { 127 | putObjectToS3(certifierId, result.context).then((stored) => { 128 | if (stored) { 129 | done(null, result.response); 130 | } else { 131 | done('Poll has been created, but could not be stored in S3 bucket.'); 132 | } 133 | }).catch((e) => { 134 | done('Poll has been created, but could not be stored in S3 bucket.'); 135 | }); 136 | } else { 137 | done(result.response); 138 | } 139 | }).catch((e) => { 140 | done('Failed to create poll'); 141 | }); 142 | } 143 | let data = event.body; 144 | //let data = JSON.parse(event.body); 145 | switch (event.httpMethod) { 146 | case 'GET': 147 | getObjectFromS3(certifierId).then((context) => { 148 | try { 149 | if (Boolean(context.poll)) { 150 | registerVoter(data.poll, data.id, context, validator).then((result) => { 151 | if (result) { 152 | done(null, result); 153 | } else { 154 | done('Invalid request'); 155 | } 156 | }).catch((e) => { 157 | done(e); 158 | }); 159 | } else { 160 | done('Internal error'); 161 | } 162 | } catch(e) { 163 | done('Internal error'); 164 | } 165 | }).catch((e) => { 166 | done('Internal error'); 167 | }); 168 | break; 169 | case 'POST': 170 | if (data.action == 'create') { 171 | getObjectFromS3(certifierId).then((context) => { 172 | if (Boolean(context.poll) && Boolean(context.privkey)) { 173 | done('Poll already exists. Nothing done.'); 174 | } else { 175 | createNewPoll(data.privkey); 176 | } 177 | }).catch((e) => { 178 | if (e.code == 'NoSuchKey') { 179 | createNewPoll(data.privkey); 180 | } else { 181 | done('Failed to create poll. Invalid request to S3.'); 182 | } 183 | }); 184 | } else if (data.action == 'close' ) { 185 | getObjectFromS3(certifierId).then((context) => { 186 | try { 187 | if (Boolean(context) && Boolean(context['poll'])) { 188 | closePoll(data.privkey, context).then((result) => { 189 | if (Boolean(result) && result.status == 'COMMITTED') { 190 | putObjectToS3(certifierId, result.context).then((stored) => { 191 | if (stored) { 192 | done(null, result.response); 193 | } else { 194 | done('Poll has been closed, but context could not be stored.'); 195 | } 196 | }).catch((e) => { 197 | done('Poll has been closed, but context could not be stored.'); 198 | }); 199 | } else { 200 | done(result.response); 201 | } 202 | }).catch((e) => { 203 | done('Failed to close poll. Error while closing.'); 204 | }); 205 | } else { 206 | done('Failed to close poll. No context retrieved from S3.'); 207 | } 208 | } catch(e) { 209 | done('Failed to close poll. Error while retrieving context.'); 210 | } 211 | }).catch((e) => { 212 | done('Failed to close poll. Invalid request to S3.'); 213 | }); 214 | } else { 215 | done(new Error('Unsupported action')); 216 | } 217 | break; 218 | default: 219 | done(new Error(`Unsupported method "${event.httpMethod}"`)); 220 | } 221 | }; 222 | -------------------------------------------------------------------------------- /bitagora-certifier/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bitagora-certifier", 3 | "version": "0.1.0", 4 | "description": "Acts as a locked and opaque register for voters in Bitagora Platform polls", 5 | "license": "Apache-2.0", 6 | "main": "index.js", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/bitagora/bitagora-core.git" 10 | }, 11 | "scripts": { 12 | "setup": "./node_modules/.bin/node-lambda setup", 13 | "test": "./node_modules/.bin/node-lambda run", 14 | "package": "./node_modules/.bin/node-lambda package", 15 | "deploy": "./node_modules/.bin/node-lambda deploy" 16 | }, 17 | "dependencies": { 18 | "bitagora-pollster": "0.1.0", 19 | "base-x": "^3.0.4", 20 | "elliptic": "^6.4.0", 21 | "request": "^2.8.1" 22 | }, 23 | "devDependencies": { 24 | "node-lambda": "^0.9.0" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /bitagora-certifier/tests/event_close.json: -------------------------------------------------------------------------------- 1 | { 2 | "httpMethod": "POST", 3 | "body": { 4 | "action": "close", 5 | "privkey": "admin_private_key" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /bitagora-certifier/tests/event_create.json: -------------------------------------------------------------------------------- 1 | { 2 | "httpMethod": "POST", 3 | "body": { 4 | "action": "create", 5 | "privkey": "admin_private_key" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /bitagora-certifier/tests/event_register.json: -------------------------------------------------------------------------------- 1 | { 2 | "httpMethod": "GET", 3 | "body": 4 | { 5 | "poll": "poll_id", 6 | "id": "voter_id_to_register" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /bitagora-certifier/validators/validator-es.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BITAGORA CERTIFIER 3 | * validator-es.js 4 | * Example of validator file. This validator is used to validate Spanish ESP ID codes. 5 | * Validator files need to export a function: 6 | * function validId(id) { ... } 7 | * This function takes a single parameter (id) and returns true or false 8 | * 9 | * Repo: https://github.com/bitagora/bitagora-core 10 | * 11 | * ------------------------------------------------------------------------------ 12 | */ 13 | 14 | function validId(id) { 15 | if (id.length != 90) return false; 16 | let idtype = id.substr(0,2); 17 | let idstate = id.substr(2,3); 18 | let nserie = id.substr(5,9); 19 | let control1 = id.substr(14,1); 20 | let idnum = id.substr(15,8); 21 | let idletter = id.substr(23,1); 22 | let pad1 = id.substr(24,6); 23 | let birthdate = id.substr(30,6); 24 | let control2 = id.substr(36,1); 25 | let sex = id.substr(37,1); 26 | let expdate = id.substr(38,6); 27 | let control3 = id.substr(44,1); 28 | let nationality = id.substr(45,3); 29 | let pad2 = id.substr(48,11); 30 | let control4 = id.substr(59,1); 31 | let lastline = id.substr(60,30).split("*") 32 | let surname1 = lastline[0] 33 | let surname2 = lastline[1] 34 | let firstname = lastline[3] 35 | if (lastline[4]) { firstname = firstname + "-" + lastline[4] } 36 | let namelength = surname1.length + surname2.length + firstname.length + 3; 37 | if (30-namelength > 0) { 38 | pad3 = id.substr(60 + namelength, -1); 39 | } else { 40 | pad3 = ""; 41 | } 42 | if (idtype != "ID") return false; 43 | if (idstate != "ESP") return false; 44 | if ((sex != "M") && (sex != "F")) return false; 45 | if (nationality != "ESP") return false; 46 | let letters_dni = "TRWAGMYFPDXBNJZSQVHLCKE"; 47 | let resto = parseInt(idnum) % 23; 48 | let letter = letters_dni.substr(resto,1); 49 | if (idletter != letter) return false; 50 | if (checkControl(control1, nserie) == 0) return false; 51 | if (checkControl(control2, birthdate) == 0) return false; 52 | if (checkControl(control3, expdate) == 0) return false; 53 | let concat = nserie + control1 + idnum + idletter + birthdate + control2 + expdate + control3; 54 | if (checkControl(control4, concat) == 0) return false; 55 | let eyear = "20"+expdate.substr(0,2) 56 | let emonth = (parseInt(expdate.substr(2,2)) - 1).toString(); 57 | let eday = expdate.substr(4,2); 58 | let expiration = Date(eyear, emonth, eday); 59 | if (expiration eighteen) return false; 72 | if (birthday > today) return false; 73 | return true; 74 | } 75 | 76 | function checkControl(control, string) { 77 | const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 78 | let array = []; 79 | var index; 80 | for (var i=0; i crypto.createHash(sha).update(x).digest('hex').toLowerCase(); 33 | 34 | function getPrechecksumVote(vote) { 35 | return vote.prefix + vote.id + vote.date + vote.poll; 36 | } 37 | 38 | function getPollToken(poll) { 39 | try { 40 | return JSON.stringify({ 41 | id: poll.id, 42 | certkey: poll.certkey, 43 | starts: poll.starts, 44 | ends: poll.ends, 45 | question: poll.question, 46 | values: poll.values, 47 | open: poll.open, 48 | adminkey: poll.adminkey 49 | }); 50 | } catch(e) { 51 | return null; 52 | } 53 | } 54 | 55 | function getVoteToken(vote) { 56 | try { 57 | return JSON.stringify({ 58 | prefix: vote.prefix, 59 | id: vote.id, 60 | date: vote.date, 61 | poll: vote.poll, 62 | checksum: vote.checksum 63 | }); 64 | } catch(e) { 65 | return null; 66 | } 67 | } 68 | 69 | function getPollAddress(pollId) { 70 | return BITAGORA_PREFIX + 'bbbb' + pollId + 'bbbb' + _hash('sha512', pollId).substr(0,48); 71 | } 72 | 73 | function getVoteAddress(pollId, voteId) { 74 | return BITAGORA_PREFIX + pollId + voteId.substr(0,56); 75 | } 76 | 77 | function getSettingAddress(string) { 78 | let values = string.split("."); 79 | if (!Boolean(values)) return undefined; 80 | if (!Boolean(values[3])) values[3] = ""; 81 | return '000000' + _hash('sha256', values[0]).substr(0,16) + _hash('sha256', values[1]).substr(0,16) + _hash('sha256', values[2]).substr(0,16) + _hash('sha256', values[3]).substr(0,16); 82 | } 83 | 84 | function requestURL(url) { 85 | return new Promise((resolve) => { 86 | const request = require('request'); 87 | request.get({ url: url }, 88 | (err, response) => { 89 | try { 90 | if (err) throw 'Error'; 91 | if (!Boolean(response.body)) throw 'No response'; 92 | let parsed = JSON.parse(response.body); 93 | resolve(parsed); 94 | } catch(e) { 95 | resolve(false); 96 | } 97 | }); 98 | }); 99 | } 100 | 101 | function getLocation(href) { 102 | var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/); 103 | return match && { 104 | href: href, 105 | protocol: match[1], 106 | host: match[2], 107 | hostname: match[3], 108 | port: match[4], 109 | pathname: match[5], 110 | search: match[6], 111 | hash: match[7] 112 | } 113 | } 114 | 115 | function getNodeList(nodeListHost) { 116 | return new Promise((resolve) => { 117 | try { 118 | const location = getLocation(nodeListHost).host; 119 | const request = require('request'); 120 | request.get({ url: nodeListHost + '/nodes/list.json'}, 121 | (err, response) => { 122 | try { 123 | if (err) throw 'Error'; 124 | if (!Boolean(response.body)) throw 'No response'; 125 | const nodes = JSON.parse(response.body); 126 | if (!Boolean(nodes)) throw 'No data'; 127 | var currentHost; 128 | if (typeof window !== 'undefined') currentHost = window.location.hostname; 129 | if (Boolean(currentHost)) nodes.unshift(currentHost); 130 | const apis = nodes.map(function(api) { 131 | return 'http://' + api + ':8008'; 132 | }); 133 | if (Boolean(process.env.API_URL)) apis.unshift(process.env.API_URL); 134 | let uniqueAPIs = apis.filter(function(value, index, self) { return self.indexOf(value) === index; }); 135 | uniqueAPIs.sort(function() { return .5 - Math.random(); }); 136 | resolve(uniqueAPIs); 137 | } catch(e) { 138 | resolve([]); 139 | } 140 | }); 141 | } catch(e) { 142 | resolve([]); 143 | } 144 | }); 145 | } 146 | 147 | function count(counted, boxes, ballots, privkey) { 148 | try { 149 | let sum = 0; 150 | var ballot, vote; 151 | ballots.forEach(function(x) { 152 | ballot = x.address; 153 | vote = cbor.decode(Buffer.from(x.data, 'base64')); 154 | if (Boolean(privkey) && vote.substr(0,2) == 'xx') vote = decryptBallot(privkey, ballot, vote); 155 | if (vote.substr(0,2) != 'xx') { 156 | counted[vote] = (counted[vote] || 0) + 1; 157 | if (Boolean(boxes[vote])) { 158 | boxes[vote].push(ballot); 159 | } else { 160 | boxes[vote] = [ ballot ]; 161 | } 162 | } 163 | sum++; 164 | }); 165 | return { 'counted': counted, 'boxes': boxes, 'sum': sum }; 166 | } catch(e){ 167 | return false; 168 | } 169 | } 170 | 171 | 172 | async function parseBallots(api, pollId, privkey, boxed) { 173 | try { 174 | let counted = {}; 175 | let boxes = {}; 176 | let parsed = 0; 177 | var result, recount; 178 | let url = api + '/state?address=' + BITAGORA_PREFIX + pollId + '&limit=1000'; 179 | while (url) { 180 | result = await requestURL(url); 181 | if (!Boolean(result)) throw 'Uncountable'; 182 | recount = count(counted, boxes, result.data, privkey); 183 | if (!recount) throw 'Error'; 184 | counted = recount['counted']; 185 | if (boxed) boxes = recount['boxes']; 186 | parsed = parsed + recount['sum']; 187 | if (Boolean(result.paging.next)) { 188 | url = result.paging.next + "&limit=1000"; 189 | } else { 190 | url = null; 191 | } 192 | } 193 | return({ 'counted': counted, 'boxes': boxes, 'sum': parsed }); 194 | } catch(e) { 195 | return false ; 196 | } 197 | } 198 | 199 | async function parsePolls(api) { 200 | try { 201 | let polls = []; 202 | var poll, result, decoded; 203 | let url = api + '/state?address=' + BITAGORA_PREFIX + 'bbbb' + '&limit=1000'; 204 | while (url) { 205 | result = await requestURL(url); 206 | if (!Boolean(result)) throw 'Uncountable'; 207 | for (var i=0; i { 234 | const request = require('request'); 235 | var url = `${api}/state`; 236 | if (Boolean(address)) url = url + "/" + address; 237 | if (Boolean(opt) && Boolean(opt['filter'])) url = url +opt['filter']; 238 | if (type == 'ballots') { 239 | let givePrivkey = null; 240 | if (Boolean(opt.privkey)) givePrivkey = opt.privkey; 241 | parseBallots(api, opt.id, givePrivkey, true).then((parsed) => { 242 | if (parsed) { 243 | let obj = { 'ballots': parsed['counted'], 'votes': parsed['sum'], 'boxes': parsed['boxes'] }; 244 | resolve({ 'status': 'FOUND', 'data': obj }); 245 | } else { 246 | resolve({ 'status': 'UNKNOWN', 'data': null }); 247 | } 248 | }).catch((e) => { 249 | resolve({ 'status': 'ERROR' }); 250 | }); 251 | } else if (type == 'polls') { 252 | let polls = []; 253 | parsePolls(api).then((parsed) => { 254 | if (parsed) { 255 | resolve({ 'status': 'FOUND', 'polls': parsed }); 256 | } else { 257 | resolve({ 'status': 'UNKNOWN' }); 258 | } 259 | }).catch((e) => { 260 | resolve({ 'status': 'ERROR' }); 261 | }); 262 | } else { 263 | request.get({ url: url }, 264 | (err, response) => { 265 | try { 266 | if (err) throw 'Error'; 267 | if (!Boolean(response.body)) throw 'No response'; 268 | let json = JSON.parse(response.body); 269 | if (!Boolean(json.data)) throw 'No data'; 270 | if (type == 'setting') { 271 | resolve({ 'status': 'FOUND', 'data': json.data }); 272 | } else if (type == 'poll') { 273 | let data = cbor.decode(Buffer.from(json.data, 'base64')); 274 | if (!Boolean(data) || !Boolean(data.poll)) throw 'No data'; 275 | let poll = JSON.parse(data.poll); 276 | if (poll.open || (!poll.open && !Boolean(poll.privkey)) || (!poll.open && !opt['unbox']) ) { 277 | resolve({'status': 'FOUND', 'data': data }); 278 | } else { 279 | console.log(" This poll is encrypted and contains "+ data['votes'].toLocaleString() + " ballots."); 280 | console.log(" Ballots need to be opened and decrypted one by one with the private key."); 281 | console.log(" Please be aware that this process will take some time."); 282 | console.log(" Opening ballot boxes..."); 283 | parseBallots(api, poll.id, poll.privkey, true).then((parsed) => { 284 | let obj = { 'poll': JSON.stringify(poll), 'ballots': parsed['counted'], 'votes': parsed['sum'], 'boxes': parsed['boxes'] }; 285 | resolve({ 'status': 'FOUND', 'data': obj }); 286 | }).catch((e) => { 287 | resolve({ 'status': 'ERROR' }); 288 | }); 289 | } 290 | } else if (type == 'ballot') { 291 | let data = cbor.decode(Buffer.from(json.data, 'base64')); 292 | if (Boolean(opt) && Boolean(opt.privkey) && data.substr(0,2) == 'xx') { 293 | let decrypted = decryptBallot(opt.privkey, address, data); 294 | if (decrypted) { 295 | resolve({ 'status': 'FOUND', 'data': decrypted }); 296 | } else { 297 | resolve({ 'status': 'FOUND', 'data': data }); 298 | } 299 | } else { 300 | resolve({ 'status': 'FOUND', 'data': data }); 301 | } 302 | } else { 303 | throw 'Unknown request'; 304 | } 305 | } catch(e) { 306 | resolve({ 'status': 'ERROR' }); 307 | } 308 | }); 309 | } 310 | }); 311 | } 312 | 313 | async function requestStateFromAPIs(apis, address, type, opt) { 314 | try { 315 | var number = apis.length; 316 | if (number > 10) number = 10; 317 | let response = { status: 'UNKNOWN' }; 318 | for (var i=0; i { 345 | try { 346 | var address = ''; 347 | var opt = null; 348 | if (!Boolean(type)) throw 'No type'; 349 | if (unbox === undefined) unbox = true; 350 | if (type == 'setting' && Boolean(settingString)) address = getSettingAddress(settingString); 351 | if (type == 'poll' && Boolean(pollId)) { 352 | opt = { 'unbox': unbox }; 353 | address = getPollAddress(pollId); 354 | } 355 | if (type == 'ballots' && Boolean(pollId)) opt = {'id' : pollId, 'privkey': pollkey } 356 | if (type == 'ballot' && Boolean(voteId)) { 357 | if (voteId.substr(0,6) == BITAGORA_PREFIX) { 358 | address = voteId; 359 | } else { 360 | address = getVoteAddress(pollId, voteId); 361 | } 362 | if (Boolean(pollkey)) opt = { 'privkey': pollkey }; 363 | } 364 | if (type != 'polls' && type != 'ballots' && !Boolean(address)) throw 'No address'; 365 | getNodeList(nodeHost).then((apis) => { 366 | if (apis.length > 0) { 367 | requestStateFromAPIs(apis, address, type, opt).then((result)=> { 368 | resolve(result); 369 | }); 370 | } else { 371 | resolve({ 'status': 'UNKNOWN' }); 372 | } 373 | }); 374 | } catch(e) { 375 | resolve({'status': 'ERROR'}); 376 | } 377 | }); 378 | } 379 | 380 | const AES256CbcEncrypt = (iv, key, plaintext) => { 381 | const cipher = crypto.createCipheriv("aes-256-cbc", key, iv); 382 | const firstChunk = cipher.update(plaintext); 383 | const secondChunk = cipher.final(); 384 | return Buffer.concat([firstChunk, secondChunk]); 385 | } 386 | 387 | const AES256CbcDecrypt = (iv, key, ciphertext) => { 388 | const cipher = crypto.createDecipheriv("aes-256-cbc", key, iv); 389 | const firstChunk = cipher.update(ciphertext); 390 | const secondChunk = cipher.final(); 391 | return Buffer.concat([firstChunk, secondChunk]); 392 | } 393 | 394 | function encryptBallot(ballot, pollPubkey, voterPrivkey) { 395 | try { 396 | const plaintext = Buffer.from(ballot, 'hex'); 397 | const pubPoint = ec.keyFromPublic(pollPubkey, 'hex').getPublic(); 398 | const pubkey_hex = pubPoint.encode('hex'); 399 | const pubKey = Buffer.from(pubkey_hex, 'hex'); 400 | const ephemPrivKey = ec.keyFromPrivate(voterPrivkey); 401 | const ephemPubKey = ephemPrivKey.getPublic(); 402 | const ephemPubKeyEncoded = Buffer.from(ephemPubKey.encode()); 403 | const px = ephemPrivKey.derive(ec.keyFromPublic(pubKey).getPublic()); 404 | const hash = crypto.createHash("sha512").update(px.toArrayLike(Buffer)).digest(); 405 | const iv = crypto.randomBytes(16); 406 | const encryptionKey = hash.slice(0, 32); 407 | const ciphertext = AES256CbcEncrypt(iv, encryptionKey, plaintext); 408 | const serializedCiphertext = Buffer.concat([ iv, ciphertext ]); 409 | const voterPubkey = ephemPubKey.encodeCompressed('hex'); 410 | return "xx" + voterPubkey.substr(voterPubkey.length - 10) + serializedCiphertext.toString('base64'); 411 | } catch(e) { 412 | return false; 413 | } 414 | } 415 | 416 | function decryptBallot(pollPrivkey, address, encryptedString) { 417 | try { 418 | const voterPubkey = address.substr(14) + encryptedString.substr(2,10); 419 | const encrypted = Buffer.from(encryptedString.substr(12), 'base64'); 420 | const privKey = Buffer.from(pollPrivkey, 'hex'); 421 | const voterKey = ec.keyFromPublic(voterPubkey, 'hex'); 422 | const ephemPubKey = voterKey.getPublic(); 423 | const iv = encrypted.slice(0, 16); 424 | const ciphertext = encrypted.slice(16); 425 | const px = ec.keyFromPrivate(privKey).derive(ephemPubKey); 426 | const hash = crypto.createHash("sha512").update(px.toArrayLike(Buffer)).digest(); 427 | const encryptionKey = hash.slice(0, 32); 428 | const plaintext = AES256CbcDecrypt(iv, encryptionKey, ciphertext); 429 | return plaintext.toString('hex'); 430 | } catch(e) { 431 | return false; 432 | } 433 | } 434 | 435 | function decryptBallots(ballots, pollPrivkey) { 436 | return new Promise((resolve, reject) => { 437 | try { 438 | if (!Boolean(ballots)) throw 'No data to decrypt'; 439 | let decrypted = []; 440 | let decVote = ''; 441 | for (var i=0; i { 40 | try { 41 | let address = getSettingAddress(string); 42 | this.context.getState([address], this.timeout) 43 | .then((data) => { 44 | try { 45 | var getResponse = TpStateGetResponse.decode(data[address]); 46 | var results = {}; 47 | getResponse.entries.forEach(entry => { 48 | results[entry.address] = entry.data; 49 | }); 50 | resolve(Buffer.from(results[string], 'base64').toString()); 51 | } catch(e) { 52 | reject(e); 53 | } 54 | }).catch((e) => { 55 | reject(e); 56 | }); 57 | } catch(e) { 58 | reject(e); 59 | } 60 | }); 61 | } 62 | 63 | _encodePollData(ballots, pollAddress, ballot, voteAddress) { 64 | try { 65 | var entries; 66 | let pollData = cbor.encode(ballots); 67 | if (Boolean(voteAddress) && Boolean(ballot)) { 68 | let voteData = cbor.encode(ballot); 69 | entries = { 70 | [pollAddress]: pollData, 71 | [voteAddress]: voteData 72 | } 73 | } else { 74 | entries = { 75 | [pollAddress]: pollData 76 | } 77 | } 78 | return entries; 79 | } catch(e) { 80 | return undefined; 81 | } 82 | } 83 | 84 | getPoll(pollId) { 85 | try { 86 | let pollAddress = getPollAddress(pollId); 87 | return this._loadPoll(pollAddress).then((state) => { 88 | if (!Boolean(state)) throw 'No poll in state'; 89 | try { 90 | let pollInState = JSON.parse(state['poll']); 91 | return pollInState; 92 | } catch(e) { 93 | return undefined; 94 | } 95 | }).catch((e) => { 96 | return undefined; 97 | }); 98 | } catch(e) { 99 | return undefined; 100 | } 101 | } 102 | 103 | setPoll(poll) { 104 | try { 105 | let pollAddress = getPollAddress(poll.id); 106 | return this._loadPoll(pollAddress).then((state) => { 107 | if (Boolean(state)) return undefined; 108 | let k = Object.keys(poll.values); 109 | let ballots = {}; 110 | for (var i=0; i { 115 | if (!Boolean(pollToSet)) return undefined; 116 | try { 117 | return this.context.setState(this._encodePollData(pollToSet, pollAddress, null, null), this.timeout); 118 | } catch(e) { 119 | return undefined; 120 | } 121 | }).catch((e) => { 122 | return undefined; 123 | }); 124 | } catch(e) { 125 | return undefined; 126 | } 127 | } 128 | 129 | closePoll(poll) { 130 | try { 131 | let pollAddress = getPollAddress(poll.id); 132 | return this._loadPoll(pollAddress).then((state) => { 133 | try { 134 | if (!Boolean(state)) return undefined; 135 | if (!Boolean(poll.privkey)) return undefined; 136 | let pollData = JSON.parse(state['poll']); 137 | pollData['privkey'] = poll.privkey; 138 | return {'poll': JSON.stringify(pollData), 'ballots' : state['ballots'], 'votes': state['votes'] }; 139 | } catch(e) { 140 | return undefined; 141 | } 142 | }).then((pollToClose) => { 143 | if (!Boolean(pollToClose)) return undefined; 144 | try { 145 | return this.context.setState(this._encodePollData(pollToClose, pollAddress, null, null), this.timeout); 146 | } catch(e) { 147 | return undefined; 148 | } 149 | }).catch((e) => { 150 | return undefined; 151 | }); 152 | } catch(e) { 153 | return undefined; 154 | } 155 | } 156 | 157 | getBallot(poll, vote) { 158 | try { 159 | return this._loadBallot(getVoteAddress(poll.id, vote.id)); 160 | } catch(e) { 161 | return undefined; 162 | } 163 | } 164 | 165 | getBallots(poll) { 166 | try { 167 | return this._loadBallot(getVoteAddress(poll.id, vote.id)); 168 | } catch(e) { 169 | return undefined; 170 | } 171 | } 172 | 173 | setBallot(poll, vote) { 174 | try { 175 | let voteAddress = getVoteAddress(poll.id, vote.id); 176 | let pollAddress = getPollAddress(poll.id); 177 | return this._loadPoll(pollAddress).then((state) => { 178 | try { 179 | if (!Boolean(state) || !Boolean(state['poll'] || Boolean(state['privkey']))) throw 'No data'; 180 | if (poll.open) { 181 | let option = vote.ballot; 182 | if (!Boolean(state['ballots'][option]) && state['ballots'][option] != 0) throw 'No data'; 183 | state['ballots'][option] = state['ballots'][option] + 1; 184 | } 185 | state['votes'] = state['votes'] + 1; 186 | return state; 187 | } catch(e) { 188 | return undefined; 189 | } 190 | }).then((ballotsToSet) => { 191 | try { 192 | if (!Boolean(ballotsToSet)) throw 'No ballot to set'; 193 | return this.context.setState(this._encodePollData(ballotsToSet, pollAddress, vote.ballot, voteAddress), this.timeout); 194 | } catch(e) { 195 | return undefined; 196 | } 197 | }).catch((e) => { 198 | return undefined; 199 | }); 200 | } catch(e) { 201 | return undefined; 202 | } 203 | } 204 | 205 | _loadPoll(pollAddress) { 206 | return this.context.getState([pollAddress], this.timeout).then((data) => { 207 | try { 208 | if (!Boolean(data) || !Boolean(data[pollAddress]) || data[pollAddress].length == 0) throw 'No data'; 209 | return cbor.decode(data[pollAddress], 'base64'); 210 | } catch(e) { 211 | return undefined; 212 | } 213 | }); 214 | } 215 | 216 | _loadBallot(ballotAddress) { 217 | return this.context.getState([ballotAddress], this.timeout).then((data) => { 218 | try { 219 | if (!Boolean(data) || !Boolean(data[ballotAddress]) || data[ballotAddress].length == 0) throw 'No data'; 220 | return cbor.decode(data[ballotAddress], 'base64'); 221 | } catch(e) { 222 | return undefined; 223 | } 224 | }); 225 | } 226 | } 227 | 228 | module.exports = { 229 | PollState 230 | } -------------------------------------------------------------------------------- /bitagora-library/validate.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BITAGORA LIBRARY 3 | * validate.js 4 | * Shared validation functions for Bitagora Platform JS modules 5 | * Developed by Ignasi Ribó, 2018 6 | * Repo: https://github.com/bitagora/bitagora-core 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * ------------------------------------------------------------------------------ 20 | */ 21 | 22 | 'use strict'; 23 | const { BITAGORA_PREFIX } = require('./constants'); 24 | const { _hash, getVoteToken, getPollToken, getPrechecksumVote } = require('./functions'); 25 | const EC = require('elliptic').ec; 26 | var ec = new EC('secp256k1'); 27 | const today = new Date(); 28 | 29 | function validatePoll(poll) { 30 | return new Promise((resolve) => { 31 | try { 32 | if (poll.id.length != 8) throw 'Wrong poll id'; 33 | if (Boolean(poll.privkey)) { 34 | var pubPoint = ec.keyFromPrivate(poll.privkey, 'hex').getPublic(); 35 | var x = pubPoint.encodeCompressed('hex'); 36 | if ( x.substr(x.length - 8) != poll.id) throw 'Wrong privkey'; 37 | resolve(true); 38 | } else { 39 | if (!Boolean(poll.question)) throw 'No question'; 40 | if (!Boolean(poll.values)) throw 'No values'; 41 | if (!Boolean(Object.keys(poll.values))) throw 'Wrong value keys'; 42 | if (!Boolean(Object.values(poll.values))) throw 'Wrong values'; 43 | if (Object.keys(poll.values).length != Object.values(poll.values).length) throw 'Wrong values'; 44 | if (parseInt(poll.starts) < today.valueOf() || parseInt(poll.ends) < today.valueOf() || parseInt(poll.starts) > parseInt(poll.ends) ) throw 'Wrong dates'; 45 | if (!Boolean(poll.certkey)) throw 'No certkey'; 46 | if (!Boolean(poll.approval)) throw 'No approval'; 47 | if (!Boolean(poll.adminkey)) throw 'No adminkey'; 48 | var key = ec.keyFromPublic(poll.adminkey, 'hex'); 49 | var certScript = _hash('sha256',_hash('sha256', getPollToken(poll))); 50 | var verification = key.verify(certScript, poll.approval); 51 | resolve(verification); 52 | } 53 | } catch(e) { 54 | console.log(e); 55 | resolve(false); 56 | } 57 | }); 58 | } 59 | 60 | function validateCertSig(vote, certKey) { 61 | try { 62 | if (!Boolean(certKey)) throw 'No key'; 63 | var key = ec.keyFromPublic(certKey, 'hex'); 64 | var payload = getVoteToken(vote); 65 | var certScript = _hash('sha256',_hash('sha256',payload)); 66 | return key.verify(certScript, vote.certsig); 67 | } catch(e) { 68 | console.log(e); 69 | return false; 70 | } 71 | } 72 | 73 | function validateVote (vote, poll) { 74 | return new Promise((resolve) => { 75 | try { 76 | 77 | if (vote.prefix != BITAGORA_PREFIX) throw 'Wrong prefix'; 78 | let date = new Date(vote.date.substr(0,4)+"/"+vote.date.substr(4,2)+"/"+vote.date.substr(6,2)).valueOf(); 79 | if ( date < parseInt(poll.starts)) throw 'Poll has not started'; 80 | if ( parseInt(vote.timestamp) < parseInt(poll.starts)) throw 'Poll has not started'; 81 | if ( date > parseInt(poll.ends)) throw 'Poll has finished'; 82 | if ( parseInt(vote.timestamp) > parseInt(poll.ends)) throw 'Poll has finished'; 83 | if (vote.poll != poll.id) throw 'Poll id is wrong'; 84 | if (poll.open && Object.keys(poll.values).indexOf(vote.ballot) == -1 ) throw 'Ballot value is incorrect'; 85 | if (!poll.open && vote.ballot.substr(0,2) != 'xx' ) throw 'Ballot value is incorrect'; 86 | var checksum = _hash('sha256', getPrechecksumVote(vote)).substr(0,4); 87 | if (checksum != vote.checksum) throw 'Ballot checksum is incorrect'; 88 | if (!validateCertSig(vote, poll.certkey)) throw 'Ballot is not certified'; 89 | resolve(true); 90 | } catch(e) { 91 | console.log(e); 92 | resolve(false); 93 | } 94 | }); 95 | } 96 | 97 | module.exports = { 98 | validateVote, 99 | validatePoll 100 | } 101 | -------------------------------------------------------------------------------- /bitagora-node/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitagora/bitagora-core/f119b52d0dff784b1659270fbb74e2e10679fe34/bitagora-node/.gitignore -------------------------------------------------------------------------------- /bitagora-node/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 | -------------------------------------------------------------------------------- /bitagora-node/README.md: -------------------------------------------------------------------------------- 1 | ![Bitagora](https://bitagora.cc/assets/img/bitagora-name-blue.png) 2 | 3 | # Bitagora Node 4 | 5 | ![version](https://img.shields.io/badge/version-0.1.0-green.svg) 6 | ![Hex.pm](https://img.shields.io/hexpm/l/plug.svg) 7 | 8 | Repository of source code and configuration scripts for Bitagora Node. 9 | 10 | For more information, visit 11 | 12 | [https://bitagora.cc](https://bitagora.cc) 13 | 14 | ## License 15 | 16 | Bitagora Node is licensed under the [Apache License Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) 17 | software license. -------------------------------------------------------------------------------- /bitagora-node/bitagora-node.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # 4 | # BITAGORA NODE 5 | # bitagora-node.sh 6 | # Installation and monitoring script for Bitagora validator nodes 7 | # Developed by Ignasi Ribó, 2018 8 | # Repo: https://github.com/bitagora/bitagora-core 9 | # 10 | # Licensed under the Apache License, Version 2.0 (the "License"); 11 | # you may not use this file except in compliance with the License. 12 | # You may obtain a copy of the License at 13 | # 14 | # http://www.apache.org/licenses/LICENSE-2.0 15 | # 16 | # Unless required by applicable law or agreed to in writing, software 17 | # distributed under the License is distributed on an "AS IS" BASIS, 18 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | # See the License for the specific language governing permissions and 20 | # limitations under the License. 21 | # ------------------------------------------------------------------------------ 22 | # 23 | 24 | # Constants 25 | current_dir=`pwd` 26 | cl=$(( $(tput cols) / 3 )) 27 | option_row=0 28 | QUITMSG="Thank you for supporting democracy. Goodbye." 29 | normal="\\033[0;39m" 30 | green="\\033[1;32m" 31 | cyan="\\033[1;36m" 32 | bwhite="\\033[1;37m" 33 | bblack="\\033[40m" 34 | bred="\\033[41m" 35 | bgreen="\\033[42m" 36 | bblue="\\033[44m" 37 | bcyan="\\033[46m" 38 | 39 | # UI functions 40 | 41 | function printline { 42 | c=$1 43 | printf "%$(tput cols)s\n" "" | sed s/' '/"${c:=_}"/g 44 | } 45 | 46 | function printTitle { 47 | cols=$(tput cols) 48 | line1=$MUI_TITLE 49 | line2=`echo $1 | tr '[:lower:]' '[:upper:]'` 50 | printf "\\033[44m""%$(tput cols)s" "" 51 | tput cup 0 0; echo -e "$bcyan"" + ""$bblue" 52 | tput cup 0 $(($cols-3)); echo -e "$bcyan"" + ""$bblue" 53 | tput cup 0 $((($cols-${#line1})/2)) 54 | echo -e "$cyan""$line1"$normal 55 | printf "$bblue""$bwhite""%$(tput cols)s" "" 56 | tput cup 1 $((($cols-${#line2})/2)) 57 | echo -e "$line2""$normal" 58 | echo 59 | } 60 | 61 | function printOption { 62 | cols=$(tput cols) 63 | case "$1" in 64 | "desc" ) 65 | col1="$2 ""$green""$3""$normal" 66 | echo -ne " $col1" 67 | if [[ "x$4" != "x" ]]; then 68 | # Affiche la description 69 | tput cuf $((39-${#col1})) 70 | echo -e " $4" 71 | else 72 | echo 73 | fi 74 | echo -e "\\033[34m"`printline —`"$normal" 75 | return 76 | break;; 77 | "result" ) 78 | if [[ $option_row -eq 0 ]]; then 79 | row_color="" 80 | option_row=1 81 | else 82 | row_color="$bblue" 83 | option_row=0 84 | fi 85 | col1=" $2" 86 | result="$3 " 87 | tput sc 88 | printf "$row_color""%$(tput cols)s" "" 89 | tput rc 90 | echo -ne "$row_color""$col1" 91 | tput cuf $(($cols-${#col1}-${#result})) 92 | echo -e "$cyan""$result""$normal" 93 | return 94 | break;; 95 | * ) return ;; 96 | esac 97 | } 98 | 99 | function input { 100 | echo -ne " ""$bgreen"" ? ""$normal"" $1 \n > " 101 | read -p "" rep 102 | } 103 | 104 | function clearscreen { 105 | lignes=$((`tput lines`-3)) 106 | cols=$(tput cols) 107 | tput cup 2 0 108 | for i in $(seq 1 $lignes) 109 | do 110 | printf "$bblack""%$(tput cols)s" "" 111 | done 112 | tput cup 3 0 113 | } 114 | 115 | function resultscreen { 116 | clearscreen 117 | cols=$(tput cols) 118 | title=" $1 " 119 | line1=" $2 " 120 | line2=" $3 " 121 | line3=" $4 " 122 | line4=" $5 " 123 | line5=" $6 " 124 | tput cup 3 2 125 | printf "$bblue""$bwhite""%$(($cols-4))s" 126 | for i in 4 5 6 7 8 9 10; do 127 | tput cup $i 2 128 | printf "$bblue""$bwhite""%$(($cols-4))s" 129 | done 130 | tput cup 3 $((($cols-${#title})/2)) 131 | echo -e $bblue"$cyan""$title"$normal; #titre 132 | tput cup 5 $((($cols-${#line1})/2)); #line1 133 | echo -e $bblue"$line1"$normal 134 | tput cup 6 $((($cols-${#line2})/2)); #line2 135 | echo -e $bblue"$line2"$normal 136 | tput cup 7 $((($cols-${#line3})/2)); #line3 137 | echo -e $bblue"$line3"$normal 138 | tput cup 8 $((($cols-${#line4})/2)); #line4 139 | echo -e $bblue"$line4"$normal 140 | tput cup 9 $((($cols-${#line5})/2)); #line5 141 | echo -e $bblue"$line5"$normal 142 | tput cup 12 1 143 | echo -ne "\n $bgreen" 144 | read -p "$BACKMSG Press any key to return to the main menu " -n1 145 | echo -e "$normal" 146 | $BACKMSG = '' 147 | menu_root 148 | } 149 | 150 | function returnmainmenu { 151 | echo -ne "\n $bred" 152 | read -p "$BACKMSG Press any key to return to the main menu " -n1 153 | echo -e "$normal" 154 | $BACKMSG='' 155 | menu_root 156 | } 157 | 158 | function returnshellmenu { 159 | echo -ne "\n $bblue" 160 | read -p "$BACKMSG Press any key to return to the shell menu " -n1 161 | echo -e "$normal" 162 | $BACKMSG='' 163 | menu_shell 164 | } 165 | 166 | function exitscript { 167 | clear 168 | echo 169 | echo $QUITMSG 170 | echo 171 | exit 0 172 | } 173 | 174 | # Script functions 175 | 176 | function checkSudo { 177 | if [ "$EUID" -ne 0 ] 178 | then 179 | echo 180 | echo "You need to run the script as root. Try with: 'sudo bash $0'" 181 | echo 182 | exit 0 183 | fi 184 | } 185 | 186 | function checkIP { 187 | echo 188 | if [[ $1 == "IP" ]] 189 | then 190 | IP=$2 191 | fi 192 | if [ -z "$IP" ] 193 | then 194 | echo -ne " ""$bgreen"" ? ""$normal"" Please enter the external IP of your system (0=quit) \n > " 195 | read -p "" IP 196 | fi 197 | if [[ $IP == "0" ]] 198 | then 199 | QUITMSG="Quitting..." 200 | exitscript 201 | fi 202 | if [[ ! $IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] 203 | then 204 | echo 205 | echo "IP is not valid." 206 | IP= 207 | checkIP 208 | fi 209 | } 210 | 211 | function installNode { 212 | printTitle "Install node" 213 | sudo docker -v > /dev/null 2>&1 214 | if [ $? -ne 0 ] 215 | then 216 | BACKMSG="Docker is not installed. Installation cannot continue." 217 | returnmainmenu 218 | fi 219 | echo 220 | echo " By accepting to proceed, you acknowledge and accept Bitagora's terms of service and privacy policy." 221 | echo " If you haven't done so, please read this information before installing a node: " 222 | echo " https://bitagora.cc/static/en/terms" 223 | echo " https://bitagora.cc/static/en/privacy" 224 | echo 225 | input "Are you sure you want to install a Bitagora validator node? (yes/no) " 226 | if [ $rep == 'yes' ] 227 | then 228 | echo 229 | input "Your external IP appears to be ${IP}. Do you want to install the node on this IP? (yes/no)" 230 | if [ $rep == 'no' ] 231 | then 232 | IP= 233 | checkIP 234 | fi 235 | echo 236 | echo " Checking that there are no Bitagora containers already installed..." 237 | sudo docker-compose down >/dev/null 2>&1 238 | echo 239 | containers="$(sudo docker ps -a -q --filter='name=bitagora*')" 240 | if [[ -z $containers ]] 241 | then 242 | echo 243 | echo " No Bitagora installation detected in the system." 244 | echo 245 | else 246 | echo 247 | input " There are Bitagora containers in the system. Do you want to remove them? (yes/no) " 248 | if [ $rep == 'no' ] 249 | then 250 | BACKMSG="Installation cannot continue." 251 | returnmainmenu 252 | else 253 | echo 254 | echo " Removing Bitagora containers..." 255 | sudo docker stop $containers && sudo docker rm $containers 256 | echo 257 | if [ "$?" -ne "0" ] 258 | then 259 | BACKMSG="Failed to remove containers. Please remove them manually. Installation cannot continue." 260 | returnmainmenu 261 | fi 262 | fi 263 | fi 264 | echo " Downloading configuration files..." 265 | echo 266 | if [ -f docker-compose.yaml ] 267 | then 268 | sudo rm docker-compose.yaml 269 | fi 270 | if [ -f validator.toml ] 271 | then 272 | sudo rm validator.toml 273 | fi 274 | ## Temporary 275 | wget -q https://bitbucket.org/bitagora/bitagora-public/downloads/docker-compose.yaml > /dev/null 276 | ## wget -q https://raw.githubusercontent.com/bitagora/bitagora-node/master/docker-compose.yaml > /dev/null 277 | if [ "$?" -ne 0 ] 278 | then 279 | BACKMSG="Failed to download docker-compose.yaml from Bitagora repo. Installation cannot continue." 280 | returnmainmenu 281 | fi 282 | ## Temporary 283 | wget -q https://bitbucket.org/bitagora/bitagora-public/downloads/validator.toml > /dev/null 284 | ## wget -q https://raw.githubusercontent.com/bitagora/bitagora-node/master/validator.toml > /dev/null 285 | if [ "$?" -ne 0 ] 286 | then 287 | BACKMSG="Failed to download validator.toml from Bitagora repo. Installation cannot continue." 288 | returnmainmenu 289 | fi 290 | sed -i "s/NIP/$IP/g" validator.toml 291 | sed -i "s/NIP/$IP/g" docker-compose.yaml 292 | 293 | echo 294 | echo " Looking for list of seed nodes..." 295 | seeds="" 296 | nodes=($(echo $(curl -o- -s https://bitagora.cc/nodes/list.json))) 297 | i=1 298 | let length=${#nodes[@]}-1 299 | count=0 300 | while [ $i -lt $length ]; do 301 | if [[ ${nodes[$i]} ]] && [[ ${nodes[$i]} != *"]"* ]] && [[ ${nodes[$i]} != *"["* ]] 302 | then 303 | nodes[$i]="${nodes[$i]//\"/}" 304 | nodes[$i]="${nodes[$i]//\,/}" 305 | nodes[$i]="\"tcp://${nodes[$i]}:8801\"" 306 | let comp=length-1 307 | if [ $i -lt $comp ] 308 | then 309 | nodes[$i]="${nodes[$i]}," 310 | fi 311 | let count=count+1 312 | fi 313 | seeds="${seeds}${nodes[$i]}" 314 | let i=i+1 315 | done 316 | seeds="[${seeds}]" 317 | if [ $count -gt 0 ] 318 | then 319 | sed -i "s#SEEDS#$seeds#g" validator.toml 320 | echo " Found $count seed nodes: $seeds" 321 | echo 322 | echo " Checking ports..." 323 | echo 324 | open8801="$(nc -z -v -w 3 $IP 8801 &> /dev/null; echo $?)" 325 | open8008="$(nc -z -v -w 3 $IP 8008 &> /dev/null; echo $?)" 326 | if [[ open8801 -eq 0 ]] || [[ open8008 -eq 0 ]] 327 | then 328 | BACKMSG="Ports 8801 and/or 8008 are not available. Installation cannot continue." 329 | returnmainmenu 330 | else 331 | sudo ufw status | grep -qw active 332 | if [[ $? -eq 0 ]] 333 | then 334 | echo 335 | echo " Found ufw firewall active" 336 | echo 337 | input "Allow external connections on ports 8801 and 8008 through ufw firewall? (yes/no)" 338 | if [[ $rep == "yes" ]] 339 | then 340 | echo 341 | sudo ufw allow 8801/tcp > /dev/null 2>&1 342 | sudo ufw allow 8008/tcp > /dev/null 2>&1 343 | else 344 | BACKMSG="Ports need to be open to install a node. Installation cannot continue." 345 | returnmainmenu 346 | fi 347 | else 348 | echo 349 | echo " No firewall detected." 350 | echo 351 | input "Are you sure that ports 8801 and 8008 are allowed? (yes/no)" 352 | if [[ $rep != "yes" ]] 353 | then 354 | BACKMSG="Ports need to be open to install a node. Installation cannot continue." 355 | returnmainmenu 356 | fi 357 | fi 358 | echo 359 | echo " Building new node..." 360 | echo 361 | input "Do you want to run the node in the background [recommended]? (yes/no)" 362 | if [[ $rep == "no" ]] 363 | then 364 | echo 365 | echo " Once started, the node will begin to produce output messages, as it connects with other peers." 366 | echo " When you close the terminal or press 'Ctrl+C', the node will stop and be disconnect from the network." 367 | echo 368 | input "Do you want to continue with the installation? (yes/no)" 369 | echo 370 | if [[ $rep == "yes" ]] 371 | then 372 | sudo docker-compose up 373 | else 374 | menu_root 375 | fi 376 | else 377 | echo 378 | echo " Downloading images and starting node. This might take a few minutes..." 379 | echo 380 | sudo docker-compose up -d 381 | if [ $? -eq 0 ]; then 382 | resultscreen "Installation successfully completed" "Your node is now up and running. Enter the shell from the script menu or by typing in your terminal: " "docker exec -it bitagora-shell bash" " " "Please consider adding your node to the seed list of validator nodes available at the Bitagora website." "Send an email to mail@bitagora.cc with the Subject 'Add node' and your IP as the body of the message." 383 | else 384 | sudo docker-compose down 385 | BACKMSG="Installation failed. Node has not been set up." 386 | returnmainmenu 387 | fi 388 | fi 389 | fi 390 | else 391 | BACKMSG="No seed nodes found. Installation cannot continue." 392 | returnmainmenu 393 | fi 394 | else 395 | BACKMSG="Installation cannot continue." 396 | returnmainmenu 397 | fi 398 | } 399 | 400 | function uninstallNode { 401 | printTitle "Uninstall node" 402 | echo 403 | echo " This operation will completely remove the validator node containers and images from your system. This cannot be undone." 404 | echo " After uninstalling, if you wish, you will be able to reinstall a new node from scratch." 405 | echo 406 | input "Are you sure you want to remove the validator node? (yes/no)" 407 | echo 408 | if [[ $rep == "yes" ]] 409 | then 410 | error=0 411 | declare -a ERRORS 412 | containers="$(sudo docker ps -a -q --filter='name=bitagora*')" 413 | if [[ -z $containers ]] 414 | then 415 | echo " No node containers found in the system." 416 | else 417 | echo 418 | echo " Stopping containers..." 419 | echo 420 | sudo docker-compose down 421 | if [ "$?" -ne "0" ] 422 | then 423 | echo " Containers already stopped." 424 | fi 425 | echo 426 | echo " Removing containers..." 427 | echo 428 | containers="$(sudo docker ps -a -q --filter='name=bitagora*')" 429 | sudo docker stop $containers && sudo docker rm $containers 430 | if [ "$?" -ne "0" ] 431 | then 432 | ERRORS[0]=" Node containers could not be removed. Please remove them manually:" 433 | ERRORS[1]=" -->$ sudo docker stop $(sudo docker ps -a -q --filter='name=bitagora*')" 434 | ERRORS[2]=" -->$ sudo docker rm $(sudo docker ps -a -q --filter='name=bitagora*')" 435 | let error=2 436 | fi 437 | fi 438 | echo 439 | echo " Removing images..." 440 | echo 441 | images="$(sudo docker images --filter=reference='bitagora/*' --format '{{.ID}}')" 442 | sudo docker rmi $images 443 | if [ "$?" -ne "0" ] 444 | then 445 | let error=error+1 446 | ERRORS[$error]=" Node images could not be removed. Please remove them manually:" 447 | let error=error+1 448 | ERRORS[$error]=" -->$ sudo docker rmi $(sudo docker images --filter=reference='bitagora/*' --format '{{.ID}}')" 449 | fi 450 | echo 451 | echo " Removing configuration files..." 452 | echo 453 | rm docker-compose.yaml && rm validator.toml 454 | if [ "$?" -ne "0" ] 455 | then 456 | let error=error+1 457 | ERRORS[$error]=" Configuration files could not be removed. Please remove them manually:" 458 | let error=error+1 459 | ERRORS[$error]=" -->$ rm docker-compose.yaml && rm validator.toml" 460 | fi 461 | if [[ $error -eq 0 ]] 462 | then 463 | resultscreen "Node succesfully removed" "Bitagora Node has been completely removed from your system." "All docker images and containers have been deleted." "Only this script remains in your computer." "You can remove it by typing: 'rm bitagora-node-ubuntu.sh'" 464 | else 465 | echo 466 | echo " Errors were encountered during the process of uninstalling the node." 467 | echo " These errors might be due to the fact that you don't have a node installed." 468 | echo " If you have one, you will need to use the manual instructions provided to uninstall it." 469 | echo " -----------------------" 470 | for i in "${ERRORS[@]}" 471 | do 472 | echo $i 473 | done 474 | echo " ----------------------" 475 | echo 476 | input "Do you want to stop the script and run these instructions now? (yes/no)" 477 | echo 478 | if [[ $rep == "yes" ]] 479 | then 480 | echo 481 | exit 0 482 | else 483 | menu_root 484 | fi 485 | fi 486 | else 487 | BACKMSG="Nothing was done." 488 | returnmainmenu 489 | fi 490 | } 491 | 492 | function statusNode { 493 | printTitle "Node status" 494 | echo 495 | sudo docker ps --filter="name=bitagora*" --format "table {{.Names}}\t{{.ID}}\t{{.RunningFor}}\t{{.Ports}}\t{{.Status}}" 496 | BACKMSG="" 497 | returnmainmenu 498 | } 499 | 500 | function stopNode { 501 | printTitle "Stop node" 502 | echo 503 | input "Are you sure you want to stop the validator node? (yes/no)" 504 | if [[ $rep == "yes" ]] 505 | then 506 | echo " Stopping node..." 507 | sudo docker-compose down 508 | if [ "$?" -ne "0" ] 509 | then 510 | BACKMSG="Node cannot be stopped. Please check its status. Maybe it's not running." 511 | returnmainmenu 512 | fi 513 | containers="$(sudo docker ps -a -q --filter='name=bitagora*')" 514 | if [[ -z "$containers" ]] 515 | then 516 | echo " Node has already stopped" 517 | else 518 | echo " Stopping node containers..." 519 | sudo docker stop $containers 520 | if [ "$?" -ne "0" ] 521 | then 522 | BACKMSG="An error was encountered while stopping the containers. Please check node status." 523 | returnmainmenu 524 | fi 525 | fi 526 | resultscreen "Node succesfully stopped" "The containers running your node have been stopped but not removed." "To restart them, use the main menu of this script." 527 | else 528 | BACKMSG="Nothing was done." 529 | returnmainmenu 530 | fi 531 | } 532 | 533 | function restartNode { 534 | printTitle "Restart node" 535 | echo 536 | input "Are you sure you want to stop the validator node? (yes/no)" 537 | if [[ $rep == "yes" ]] 538 | then 539 | input "Do you want to run the node in the background [recommended]? (yes/no)" 540 | if [[ $rep == "no" ]] 541 | then 542 | echo 543 | echo " Once started, the node will begin to produce output messages, as it connects with other peers." 544 | echo " When you close the terminal or press 'Ctrl+C', the node will stop and be disconnected from the network." 545 | echo 546 | input "Do you want to restart the node now? (yes/no)" 547 | if [[ $rep == "yes" ]] 548 | then 549 | sudo docker-compose up 550 | if [ "$?" -ne "0" ] 551 | then 552 | sudo docker-compose down 553 | BACKMSG="Node cannot be started." 554 | returnmainmenu 555 | fi 556 | else 557 | menu_root 558 | fi 559 | else 560 | sudo docker-compose up -d 561 | if [ $? -eq 0 ]; then 562 | resultscreen "Node succesfully restarted" "Your node has been restarted and is now back up and running." "Enter shell by typing:" "docker exec -it bitagora-shell bash" 563 | else 564 | sudo docker-compose down 565 | BACKMSG="Could not restart node. If error persists, please uninstall and reinstall the node." 566 | returnmainmenu 567 | fi 568 | fi 569 | else 570 | BACKMSG="Nothing was done." 571 | returnmainmenu 572 | fi 573 | } 574 | 575 | # Shell functions 576 | 577 | function list { 578 | clearscreen 579 | printTitle "Listing $1 $2" 580 | echo 581 | sudo docker exec -it bitagora-shell node shell.js list $1 $2 582 | returnshellmenu 583 | } 584 | 585 | function show { 586 | clearscreen 587 | printTitle "Showing $1" 588 | echo 589 | sudo docker exec -it bitagora-shell node shell.js show $1 $2 $3 590 | returnshellmenu 591 | } 592 | 593 | function get_keys { 594 | clearscreen 595 | printTitle "Node keys" 596 | echo 597 | echo "Private key: " 598 | sudo docker exec -it bitagora-shell cat /etc/sawtooth/keys/validator.priv 599 | echo 600 | echo "Public key: " 601 | sudo docker exec -it bitagora-shell cat /etc/sawtooth/keys/validator.pub 602 | echo 603 | returnshellmenu 604 | } 605 | 606 | function viewConsole { 607 | clearscreen 608 | printTitle "Node console $1" 609 | printOption "result" "" "Press Ctrl + C to go back to menu" 610 | echo 611 | echo 612 | trap menu_console SIGINT 613 | sudo docker logs -f $1 614 | } 615 | 616 | # Menus 617 | 618 | function menu_root { 619 | while true; do 620 | clear 621 | printTitle "Bitagora Node script" 622 | printOption "result" "DATE" "`date +'%a %d %B %Y'`" 623 | printOption "result" "IP" "$IP" 624 | echo 625 | printOption "desc" "1" "INSTALL" "Install a node in your system" 626 | printOption "desc" "2" "UNINSTALL" "Uninstall node from your system" 627 | printOption "desc" "3" "STATUS" "View status of your node" 628 | printOption "desc" "4" "STOP" "Stop your node" 629 | printOption "desc" "5" "RESTART" "Restart your node" 630 | printOption "desc" "6" "SHELL" "Enter node shell" 631 | printOption "desc" "7" "CONSOLE" "View node console output" 632 | printOption "desc" "Q" "QUIT" "Quit script" 633 | echo 634 | read -p " What do you want to do? " -n1 rep 635 | case $rep in 636 | [1]* ) 637 | clearscreen 638 | installNode 639 | break;; 640 | [2]* ) 641 | clearscreen 642 | uninstallNode 643 | break;; 644 | [3]* ) 645 | clearscreen 646 | statusNode 647 | break;; 648 | [4]* ) 649 | clearscreen 650 | stopNode 651 | break;; 652 | [5]* ) 653 | clearscreen 654 | restartNode 655 | break;; 656 | [6]* ) 657 | clearscreen 658 | menu_shell 659 | break;; 660 | [7]* ) 661 | clearscreen 662 | menu_console 663 | break;; 664 | [qQ]* ) 665 | exitscript; 666 | break;; 667 | * ) returnhome;; 668 | esac 669 | done 670 | returnmainmenu 671 | } 672 | 673 | function menu_shell { 674 | while true; do 675 | clear 676 | printTitle "Node Shell" 677 | printOption "result" "DATE" "`date +'%a %d %B %Y'`" 678 | printOption "result" "IP" "$IP" 679 | echo 680 | 681 | printOption "desc" "1" "POLLS" "List or show polls" 682 | printOption "desc" "2" "BALLOTS" "List or show ballots" 683 | printOption "desc" "3" "BLOCKS" "List or show blocks" 684 | printOption "desc" "4" "STATE" "List or show state addresses" 685 | printOption "desc" "5" "PEERS" "List or compare with peers" 686 | printOption "desc" "6" "SETTINGS" "List settings" 687 | printOption "desc" "7" "KEYS" "Show node keys" 688 | printOption "desc" "Q" "MENU" "Back to main menu" 689 | echo 690 | read -p " Choose an option : " -n1 rep 691 | echo 692 | case $rep in 693 | [1]* ) 694 | echo 695 | echo " (L)ist all available polls " 696 | echo " (S)how a poll with id" 697 | echo 698 | read -p " What do you want to do? " -n1 rep 699 | case $rep in 700 | [lL]* ) 701 | list "polls" 702 | break;; 703 | [sS]*) 704 | echo 705 | echo 706 | input "Enter the poll 8-digit alphanumerical id" 707 | show "poll" $rep 708 | break;; 709 | * ) 710 | menu_shell 711 | break;; 712 | esac 713 | break;; 714 | [2]* ) 715 | echo 716 | echo 717 | echo " (L)ist all ballots for a poll" 718 | echo " (S)how information of a ballot with id or private key" 719 | echo 720 | read -p " What do you want to do? " -n1 rep 721 | case $rep in 722 | [lL]* ) 723 | echo 724 | echo 725 | input "Enter the poll 8-digit alphanumerical id (0 to cancel)" 726 | poll=$rep 727 | if [[ $poll == "0" ]] 728 | then 729 | menu_shell 730 | else 731 | list "ballots" $poll 732 | fi 733 | break;; 734 | [sS]*) 735 | echo 736 | echo 737 | input "Enter the poll 8-digit alphanumerical id (0 to cancel)" 738 | poll=$rep 739 | if [[ $poll == "0" ]] 740 | then 741 | menu_shell 742 | fi 743 | echo 744 | input "Enter the vote id number or a voter private key (0 to cancel)" 745 | id=$rep 746 | if [[ $id == "0" ]] 747 | then 748 | menu_shell 749 | fi 750 | show "ballot" $poll $id 751 | break;; 752 | * ) 753 | menu_shell 754 | break;; 755 | esac 756 | break;; 757 | [3]* ) 758 | echo 759 | echo " (L)ist all blocks in the chain " 760 | echo " (S)how a block with id" 761 | echo 762 | read -p " What do you want to do? " -n1 rep 763 | case $rep in 764 | [lL]* ) 765 | list "blocks" 766 | break;; 767 | [sS]*) 768 | echo 769 | echo 770 | input "Enter the block alphanumerical id" 771 | show "block" $rep 772 | break;; 773 | * ) 774 | menu_shell 775 | break;; 776 | esac 777 | break;; 778 | [4]* ) 779 | echo 780 | echo " (L)ist current state of blockchain " 781 | echo " (S)how state of an address with id" 782 | echo 783 | read -p " What do you want to do? " -n1 rep 784 | case $rep in 785 | [lL]* ) 786 | list "state" 787 | break;; 788 | [sS]*) 789 | echo 790 | echo 791 | input "Enter the address alphanumerical id" 792 | show "state" $rep 793 | break;; 794 | * ) 795 | menu_shell 796 | break;; 797 | esac 798 | break;; 799 | [5]* ) 800 | list "peers" 801 | break;; 802 | [6]* ) 803 | list "settings" 804 | break;; 805 | [7]* ) 806 | get_keys 807 | break;; 808 | [qQ]* ) 809 | menu_root 810 | break;; 811 | * ) menu_shell; break;; 812 | esac 813 | done 814 | } 815 | 816 | function menu_console { 817 | while true; do 818 | clear 819 | printTitle "Node Console" 820 | printOption "result" "DATE" "`date +'%a %d %B %Y'`" 821 | printOption "result" "IP" "$IP" 822 | echo 823 | 824 | printOption "desc" "1" "VALIDATOR" "View validator console" 825 | printOption "desc" "2" "POLLS" "View polls transaction processor console" 826 | printOption "desc" "3" "BALLOTS" "View ballots transaction processor console" 827 | printOption "desc" "4" "SETTINGS" "View settings transaction processor console" 828 | printOption "desc" "Q" "MENU" "Back to main menu" 829 | echo 830 | read -p " Choose an option : " -n1 rep 831 | echo 832 | case $rep in 833 | [1]* ) 834 | viewConsole "bitagora-validator" 835 | break;; 836 | [2]* ) 837 | viewConsole "bitagora-polls-tp" 838 | break;; 839 | [3]* ) 840 | viewConsole "bitagora-ballots-tp" 841 | break;; 842 | [4]* ) 843 | viewConsole "bitagora-settings-tp" 844 | break;; 845 | [qQ]* ) 846 | menu_root 847 | break;; 848 | * ) menu_console; break;; 849 | esac 850 | done 851 | } 852 | 853 | ### Runtime 854 | checkSudo 855 | IP=$(ifconfig eth0 | perl -ne 'print $1 if /inet\s.*?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/') 856 | clearscreen 857 | checkIP 858 | menu_root 859 | -------------------------------------------------------------------------------- /bitagora-node/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: "2.1" 2 | 3 | services: 4 | 5 | shell: 6 | image: bitagora/shell:0.1.0 7 | container_name: bitagora-shell 8 | environment: 9 | - VALIDATOR_URL=tcp://validator:4004 10 | - API_URL=http://NIP:8008 11 | restart: always 12 | command: | 13 | bash -c " 14 | if [ ! -f /etc/sawtooth/keys/validator.priv ]; then 15 | sawtooth keygen --key-dir /etc/sawtooth/keys validator 16 | fi; 17 | export API_URL 18 | tail -f /dev/null 19 | " 20 | stop_signal: SIGKILL 21 | 22 | polls-tp: 23 | image: bitagora/polls-tp:0.1.0 24 | container_name: bitagora-polls-tp 25 | restart: always 26 | depends_on: 27 | - validator 28 | entrypoint: | 29 | /usr/bin/node polls.js tcp://validator:4004 30 | stop_signal: SIGKILL 31 | 32 | ballots-tp: 33 | image: bitagora/ballots-tp:0.1.0 34 | container_name: bitagora-ballots-tp 35 | restart: always 36 | depends_on: 37 | - validator 38 | entrypoint: | 39 | /usr/bin/node ballots.js tcp://validator:4004 40 | stop_signal: SIGKILL 41 | 42 | settings-tp: 43 | image: hyperledger/sawtooth-settings-tp:1.0.4 44 | container_name: bitagora-settings-tp 45 | restart: always 46 | depends_on: 47 | - validator 48 | entrypoint: settings-tp -vv -C tcp://validator:4004 49 | stop_signal: SIGKILL 50 | 51 | poet-validator-registry-tp: 52 | image: hyperledger/sawtooth-poet-validator-registry-tp:1.0.4 53 | container_name: bitagora-poet-validator-registry-tp 54 | restart: always 55 | expose: 56 | - 4004 57 | command: poet-validator-registry-tp -C tcp://validator:4004 58 | environment: 59 | PYTHONPATH: /project/sawtooth-core/consensus/poet/common 60 | stop_signal: SIGKILL 61 | 62 | validator: 63 | image: hyperledger/sawtooth-validator:1.0.4 64 | container_name: bitagora-validator 65 | restart: always 66 | expose: 67 | - 4004 68 | - 8801 69 | ports: 70 | - '8801:8801' 71 | volumes: 72 | - ./validator.toml:/etc/sawtooth/validator.toml 73 | entrypoint: | 74 | bash -c " 75 | if [ ! -f /etc/sawtooth/keys/validator.priv ]; then 76 | sawadm keygen --force 77 | fi; 78 | sawtooth-validator -vv 79 | " 80 | environment: 81 | PYTHONPATH: "/project/sawtooth-core/consensus/poet/common:\ 82 | /project/sawtooth-core/consensus/poet/simulator:\ 83 | /project/sawtooth-core/consensus/poet/core" 84 | stop_signal: SIGKILL 85 | 86 | rest-api: 87 | image: bitagora/rest-api:0.1.0 88 | container_name: bitagora-rest-api 89 | restart: always 90 | expose: 91 | - 8008 92 | - 4004 93 | ports: 94 | - '8008:8008' 95 | depends_on: 96 | - validator 97 | entrypoint: | 98 | sawtooth-rest-api -vv 99 | --connect tcp://validator:4004 100 | --bind rest-api:8008 101 | stop_signal: SIGKILL -------------------------------------------------------------------------------- /bitagora-node/src/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM hyperledger/sawtooth-rest-api:1.0.4 2 | 3 | WORKDIR ~ 4 | 5 | LABEL "install-type"="mounted" 6 | 7 | # Install Node and Ubuntu dependencies 8 | RUN apt-get update && apt-get install -y -q --no-install-recommends \ 9 | curl \ 10 | ca-certificates \ 11 | pkg-config \ 12 | build-essential \ 13 | libzmq3-dev \ 14 | && curl -s -S -o /tmp/setup-node.sh https://deb.nodesource.com/setup_8.x \ 15 | && chmod 755 /tmp/setup-node.sh \ 16 | && /tmp/setup-node.sh \ 17 | && apt-get install nodejs -y -q \ 18 | && rm /tmp/setup-node.sh \ 19 | && apt-get clean \ 20 | && rm -rf /var/lib/apt/lists/* \ 21 | && npm install -g prebuild-install 22 | 23 | WORKDIR /bitagora-rest-api 24 | 25 | ADD . /bitagora-rest-api 26 | 27 | RUN \ 28 | if [ ! -z $HTTP_PROXY ] && [ -z $http_proxy ]; then \ 29 | http_proxy=$HTTP_PROXY; \ 30 | fi; \ 31 | if [ ! -z $HTTPS_PROXY ] && [ -z $https_proxy ]; then \ 32 | https_proxy=$HTTPS_PROXY; \ 33 | fi; \ 34 | if [ ! -z $http_proxy ]; then \ 35 | npm config set proxy $http_proxy; \ 36 | fi; \ 37 | if [ ! -z $https_proxy ]; then \ 38 | npm config set https-proxy $https_proxy; \ 39 | fi 40 | 41 | CMD ["/usr/bin/node", "./rest-api.js"] 42 | -------------------------------------------------------------------------------- /bitagora-node/src/ballots-tp/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:xenial 2 | 3 | LABEL "install-type"="mounted" 4 | 5 | # Install Node and Ubuntu dependencies 6 | RUN apt-get update && apt-get install -y -q --no-install-recommends \ 7 | curl \ 8 | ca-certificates \ 9 | pkg-config \ 10 | build-essential \ 11 | libzmq3-dev \ 12 | && curl -s -S -o /tmp/setup-node.sh https://deb.nodesource.com/setup_8.x \ 13 | && chmod 755 /tmp/setup-node.sh \ 14 | && /tmp/setup-node.sh \ 15 | && apt-get install nodejs -y -q \ 16 | && rm /tmp/setup-node.sh \ 17 | && apt-get clean \ 18 | && rm -rf /var/lib/apt/lists/* \ 19 | && npm install -g prebuild-install 20 | 21 | WORKDIR /bitagora-ballots 22 | 23 | ADD . /bitagora-ballots 24 | 25 | RUN \ 26 | if [ ! -z $HTTP_PROXY ] && [ -z $http_proxy ]; then \ 27 | http_proxy=$HTTP_PROXY; \ 28 | fi; \ 29 | if [ ! -z $HTTPS_PROXY ] && [ -z $https_proxy ]; then \ 30 | https_proxy=$HTTPS_PROXY; \ 31 | fi; \ 32 | if [ ! -z $http_proxy ]; then \ 33 | npm config set proxy $http_proxy; \ 34 | fi; \ 35 | if [ ! -z $https_proxy ]; then \ 36 | npm config set https-proxy $https_proxy; \ 37 | fi 38 | 39 | EXPOSE 4004/tcp 40 | 41 | CMD ["/usr/bin/node", "./ballots.js", "tcp://validator:4004"] 42 | -------------------------------------------------------------------------------- /bitagora-node/src/ballots-tp/ballots-handler.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BITAGORA NODE 3 | * ballots-handler.js 4 | * Handler for ballot transactions in Bitagora Platform voting system 5 | * Developed by Ignasi Ribó, 2018 6 | * Repo: https://github.com/bitagora/bitagora-core 7 | * 8 | * Based on Hyperledger/Sawtooth 9 | * Copyright 2018 Intel Corporation 10 | * https://github.com/hyperledger/sawtooth-core 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | * ------------------------------------------------------------------------------ 24 | */ 25 | 26 | 'use strict' 27 | const { BITAGORA_PREFIX, BITAGORA_FAMILY, BITAGORA_VERSION, PollState, validateVote } = require('bitagora-library'); 28 | const { TransactionHandler } = require('sawtooth-sdk/processor/handler'); 29 | const { InvalidTransaction } = require('sawtooth-sdk/processor/exceptions'); 30 | 31 | const _parseVote = (buffer, pollState) => 32 | new Promise(function(resolve, reject) { 33 | try { 34 | let vote = JSON.parse(buffer); 35 | if (vote === undefined || vote.poll === undefined) throw "Failed to parse vote"; 36 | pollState.getPoll(vote.poll).then( 37 | (poll) => { 38 | if (poll === undefined) throw 'Invalid Action: Poll not found'; 39 | if (Boolean(poll.privkey)) throw 'Invalid Action: Poll already closed'; 40 | validateVote(vote, poll).then((result) => { 41 | if (result) { 42 | resolve([poll, vote]); 43 | } else { 44 | reject('Invalid Action: Vote is not valid'); 45 | } 46 | }).catch((e) => { 47 | reject(e); 48 | }); 49 | }).catch((e) => { 50 | reject(e); 51 | }); 52 | } catch(e) { 53 | reject(e); 54 | } 55 | }); 56 | 57 | class BallotsHandler extends TransactionHandler { 58 | 59 | constructor () { 60 | super(BITAGORA_FAMILY, [BITAGORA_VERSION], [BITAGORA_PREFIX], 'application/protobuf'); 61 | } 62 | 63 | apply (transactionProcessRequest, context) { 64 | let pollState = new PollState(context); 65 | return _parseVote(transactionProcessRequest.payload, pollState) 66 | .then((response) => { 67 | try { 68 | let poll = response[0]; 69 | let vote = response[1]; 70 | let header = transactionProcessRequest.header; 71 | let voter = header.signerPublicKey; 72 | if (vote.id != voter) throw 'Invalid Action: Vote id does not correspond to voter'; 73 | return pollState.getBallot(poll, vote) 74 | .then((ballot) => { 75 | try { 76 | if (ballot !== undefined) throw 'Invalid Action: Vote already cast'; 77 | console.log("Setting ballot: " + JSON.stringify(vote)); 78 | return pollState.setBallot(poll, vote); 79 | } catch(e) { 80 | console.log(e); 81 | return Promise.resolve().then(() => { 82 | throw new InvalidTransaction(e); 83 | }); 84 | } 85 | }).catch((e) => { 86 | console.log(e); 87 | return Promise.resolve().then(() => { 88 | throw new InvalidTransaction(e); 89 | }); 90 | }); 91 | } catch(e) { 92 | console.log(e); 93 | return Promise.resolve().then(() => { 94 | throw new InvalidTransaction(e); 95 | }); 96 | } 97 | }).catch((e) => { 98 | console.log(e); 99 | return Promise.resolve().then(() => { 100 | throw new InvalidTransaction(e); 101 | }); 102 | }); 103 | } 104 | } 105 | 106 | module.exports = { 107 | BallotsHandler 108 | } -------------------------------------------------------------------------------- /bitagora-node/src/ballots-tp/ballots.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BITAGORA NODE 3 | * ballots.js 4 | * Entrypoint for Ballot Transaction Processor in Bitagora Platform voting system 5 | * Developed by Ignasi Ribó, 2018 6 | * Repo: https://github.com/bitagora/bitagora-core 7 | * 8 | * Based on Hyperledger/Sawtooth 9 | * Copyright 2018 Intel Corporation 10 | * https://github.com/hyperledger/sawtooth-core 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | * ------------------------------------------------------------------------------ 24 | */ 25 | 26 | 'use strict' 27 | const { TransactionProcessor } = require('sawtooth-sdk/processor'); 28 | const { BallotsHandler } = require('./ballots-handler'); 29 | if (process.argv.length < 3) { 30 | console.log('Missing a validator address'); 31 | process.exit(1); 32 | } 33 | const ValidatorAddress = process.argv[2]; 34 | const transactionProcessor = new TransactionProcessor(ValidatorAddress); 35 | transactionProcessor.addHandler(new BallotsHandler()); 36 | transactionProcessor.start(); 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /bitagora-node/src/ballots-tp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ballots-tp", 3 | "version": "0.1.0", 4 | "author": "Ignasi Ribó, 2018", 5 | "license": "Apache-2.0", 6 | "description": "Transaction processor for ballots using the Bitagora Platform", 7 | "main": "ballots.js", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/bitagora/bitagora-core.git" 11 | }, 12 | "dependencies": { 13 | "bitagora-library": "0.1.0", 14 | "atob": "^2.1.0", 15 | "btoa": "^1.2.1", 16 | "cbor": "^4.0.0", 17 | "request": "^2.87.0", 18 | "elliptic": "^6.4.0", 19 | "protobufjs": "^6.8.6", 20 | "sawtooth-sdk": "^1.0.4" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /bitagora-node/src/polls-tp/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:xenial 2 | 3 | LABEL "install-type"="mounted" 4 | 5 | RUN apt-get update && apt-get install -y -q --no-install-recommends \ 6 | curl \ 7 | ca-certificates \ 8 | pkg-config \ 9 | build-essential \ 10 | libzmq3-dev \ 11 | && curl -s -S -o /tmp/setup-node.sh https://deb.nodesource.com/setup_8.x \ 12 | && chmod 755 /tmp/setup-node.sh \ 13 | && /tmp/setup-node.sh \ 14 | && apt-get install nodejs -y -q \ 15 | && rm /tmp/setup-node.sh \ 16 | && apt-get clean \ 17 | && rm -rf /var/lib/apt/lists/* \ 18 | && npm install -g prebuild-install 19 | 20 | WORKDIR /bitagora-polls 21 | 22 | ADD . /bitagora-polls 23 | 24 | RUN \ 25 | if [ ! -z $HTTP_PROXY ] && [ -z $http_proxy ]; then \ 26 | http_proxy=$HTTP_PROXY; \ 27 | fi; \ 28 | if [ ! -z $HTTPS_PROXY ] && [ -z $https_proxy ]; then \ 29 | https_proxy=$HTTPS_PROXY; \ 30 | fi; \ 31 | if [ ! -z $http_proxy ]; then \ 32 | npm config set proxy $http_proxy; \ 33 | fi; \ 34 | if [ ! -z $https_proxy ]; then \ 35 | npm config set https-proxy $https_proxy; \ 36 | fi 37 | 38 | RUN npm install 39 | 40 | EXPOSE 4004/tcp 41 | 42 | CMD ["/usr/bin/node", "./polls.js", "tcp://validator:4004"] 43 | -------------------------------------------------------------------------------- /bitagora-node/src/polls-tp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "polls-tp", 3 | "version": "0.1.0", 4 | "author": "Ignasi Ribó, 2018", 5 | "license": "Apache-2.0", 6 | "description": "Transaction processor for polls using the Bitagora Platform", 7 | "main": "polls.js", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/bitagora/bitagora-core.git" 11 | }, 12 | "dependencies": { 13 | "bitagora-library": "0.1.0", 14 | "atob": "^2.1.0", 15 | "btoa": "^1.2.1", 16 | "cbor": "^4.0.0", 17 | "request": "^2.87.0", 18 | "elliptic": "^6.4.0", 19 | "protobufjs": "^6.8.6", 20 | "sawtooth-sdk": "^1.0.4" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /bitagora-node/src/polls-tp/polls-handler.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BITAGORA NODE 3 | * polls-handler.js 4 | * Handler for poll transactions in Bitagora Platform voting system 5 | * Developed by Ignasi Ribó, 2018 6 | * Repo: https://github.com/bitagora/bitagora-core 7 | * 8 | * Based on Hyperledger/Sawtooth 9 | * Copyright 2018 Intel Corporation 10 | * https://github.com/hyperledger/sawtooth-core 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | * ------------------------------------------------------------------------------ 24 | */ 25 | 26 | 'use strict' 27 | const { BITAGORA_PREFIX, BITAGORA_POLL_FAMILY, BITAGORA_VERSION, PollState, validatePoll } = require('bitagora-library'); 28 | const { TransactionHandler } = require('sawtooth-sdk/processor/handler'); 29 | const { InvalidTransaction } = require('sawtooth-sdk/processor/exceptions'); 30 | 31 | const _parsePoll = (buffer, pollState, signerPubkey) => 32 | new Promise(function(resolve, reject) { 33 | try { 34 | let poll = JSON.parse(buffer); 35 | if (!Boolean(poll)) throw 'Failed to parse vote'; 36 | validatePoll(poll) 37 | .then((valid) => { 38 | try { 39 | if (!valid) throw 'Invalid Poll: Poll is not valid'; 40 | if ( signerPubkey != poll.certkey ) throw 'Invalid Signer: Pollster is not authorized'; 41 | pollState.getSetting('sawtooth.settings.vote.authorized_keys') 42 | .then((authorized) => { 43 | try { 44 | if (Boolean(poll.privkey)) { 45 | resolve(poll); 46 | } else { 47 | let authorizedArray = authorized.split(","); 48 | if (authorizedArray.indexOf(poll.adminkey) === -1) throw 'Invalid Poll: Admin is not authorized'; 49 | resolve(poll); 50 | } 51 | } catch(e) { 52 | reject(e); 53 | } 54 | }).catch((e) => { 55 | reject(e); 56 | }); 57 | } catch(e) { 58 | reject(e); 59 | } 60 | }).catch((e) => { 61 | reject(e); 62 | }); 63 | } catch(e) { 64 | reject(e); 65 | } 66 | }); 67 | 68 | class PollsHandler extends TransactionHandler { 69 | constructor () { 70 | super(BITAGORA_POLL_FAMILY, [BITAGORA_VERSION], [BITAGORA_PREFIX], 'application/protobuf'); 71 | } 72 | 73 | apply (transactionProcessRequest, context) { 74 | try { 75 | let pollState = new PollState(context); 76 | let header = transactionProcessRequest.header; 77 | let signer = header.signerPublicKey; 78 | return _parsePoll(transactionProcessRequest.payload, pollState, signer) 79 | .then((poll) => { 80 | try { 81 | return pollState.getPoll(poll.id) 82 | .then((pollInState) => { 83 | try { 84 | if (Boolean(pollInState) && Boolean(pollInState.privkey)) throw 'Invalid Action: Poll already closed'; 85 | if (!Boolean(poll.privkey) && Boolean(pollInState)) throw 'Invalid Action: Poll already exists'; 86 | if (Boolean(poll.privkey) && !Boolean(pollInState)) throw 'Invalid Action: Poll does not exist'; 87 | if (Boolean(poll.privkey)) { 88 | console.log("Closing poll: "); 89 | console.log(poll); 90 | return pollState.closePoll(poll); 91 | } else { 92 | console.log("Creating poll: "); 93 | console.log(poll); 94 | return pollState.setPoll(poll); 95 | } 96 | } catch(e) { 97 | console.log(e); 98 | return Promise.resolve().then(() => { 99 | throw new InvalidTransaction(e); 100 | }); 101 | } 102 | }).catch((e) => { 103 | console.log(e); 104 | return Promise.resolve().then(() => { 105 | throw new InvalidTransaction(e); 106 | }); 107 | }); 108 | } catch(e) { 109 | console.log(e); 110 | return Promise.resolve().then(() => { 111 | throw new InvalidTransaction(e); 112 | }); 113 | } 114 | }).catch((e) => { 115 | console.log(e); 116 | return Promise.resolve().then(() => { 117 | throw new InvalidTransaction(e); 118 | }); 119 | }); 120 | } catch(e) { 121 | console.log(e); 122 | return Promise.resolve().then(() => { 123 | throw new InvalidTransaction(e); 124 | }); 125 | } 126 | } 127 | } 128 | 129 | module.exports = { 130 | PollsHandler 131 | } -------------------------------------------------------------------------------- /bitagora-node/src/polls-tp/polls.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BITAGORA NODE 3 | * polls.js 4 | * Entrypoint for Polls Transaction Processor in Bitagora Platform voting system 5 | * Developed by Ignasi Ribó, 2018 6 | * Repo: https://github.com/bitagora/bitagora-core 7 | * 8 | * Based on Hyperledger/Sawtooth 9 | * Copyright 2018 Intel Corporation 10 | * https://github.com/hyperledger/sawtooth-core 11 | * 12 | * Licensed under the Apache License, Version 2.0 (the "License"); 13 | * you may not use this file except in compliance with the License. 14 | * You may obtain a copy of the License at 15 | * 16 | * http://www.apache.org/licenses/LICENSE-2.0 17 | * 18 | * Unless required by applicable law or agreed to in writing, software 19 | * distributed under the License is distributed on an "AS IS" BASIS, 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 21 | * See the License for the specific language governing permissions and 22 | * limitations under the License. 23 | * ------------------------------------------------------------------------------ 24 | */ 25 | 26 | 'use strict' 27 | const { TransactionProcessor } = require('sawtooth-sdk/processor'); 28 | const { PollsHandler } = require('./polls-handler'); 29 | if (process.argv.length < 3) { 30 | console.log('Missing a validator address'); 31 | process.exit(1); 32 | } 33 | const ValidatorAddress = process.argv[2]; 34 | const transactionProcessor = new TransactionProcessor(ValidatorAddress); 35 | transactionProcessor.addHandler(new PollsHandler()); 36 | transactionProcessor.start(); 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /bitagora-node/src/shell/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM hyperledger/sawtooth-shell:1.0.4 2 | 3 | RUN apt-get update && apt-get install -y -q --no-install-recommends \ 4 | curl \ 5 | ca-certificates \ 6 | pkg-config \ 7 | build-essential \ 8 | libzmq3-dev \ 9 | vim \ 10 | && curl -s -S -o /tmp/setup-node.sh https://deb.nodesource.com/setup_8.x \ 11 | && chmod 755 /tmp/setup-node.sh \ 12 | && /tmp/setup-node.sh \ 13 | && apt-get install nodejs -y -q \ 14 | && rm /tmp/setup-node.sh \ 15 | && apt-get clean \ 16 | && rm -rf /var/lib/apt/lists/* \ 17 | && npm install -g prebuild-install 18 | 19 | WORKDIR /bitagora-shell 20 | 21 | ADD . /bitagora-shell 22 | 23 | RUN \ 24 | if [ ! -z $HTTP_PROXY ] && [ -z $http_proxy ]; then \ 25 | http_proxy=$HTTP_PROXY; \ 26 | fi; \ 27 | if [ ! -z $HTTPS_PROXY ] && [ -z $https_proxy ]; then \ 28 | https_proxy=$HTTPS_PROXY; \ 29 | fi; \ 30 | if [ ! -z $http_proxy ]; then \ 31 | npm config set proxy $http_proxy; \ 32 | fi; \ 33 | if [ ! -z $https_proxy ]; then \ 34 | npm config set https-proxy $https_proxy; \ 35 | fi 36 | 37 | ENV PATH $PATH:/bitagora-shell/bin 38 | 39 | CMD ["tail", "-f", "/dev/null"] -------------------------------------------------------------------------------- /bitagora-node/src/shell/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "shell", 3 | "version": "0.1.0", 4 | "author": "Ignasi Ribó, 2018", 5 | "license": "Apache-2.0", 6 | "description": "Shell JS functions for nodes in the Bitagora Platform", 7 | "main": "shell.js", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/bitagora/bitagora-core.git" 11 | }, 12 | "dependencies": { 13 | "bitagora-library": "0.1.1", 14 | "atob": "^2.1.0", 15 | "base-x": "^3.0.4", 16 | "btoa": "^1.2.0", 17 | "cbor": "^4.0.0", 18 | "elliptic": "^6.4.0", 19 | "request": "^2.8.1", 20 | "protobufjs": "^6.8.6", 21 | "sawtooth-sdk": "^1.0.4", 22 | "shelljs": "^0.8.1", 23 | "console.table": "^0.10.0" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /bitagora-node/src/shell/shell.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BITAGORA NODE 3 | * shell.js 4 | * Shell functions for Bitagora Platform voting system 5 | * Developed by Ignasi Ribó, 2018 6 | * Repo: https://github.com/bitagora/bitagora-core 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * ------------------------------------------------------------------------------ 20 | */ 21 | 22 | 'use strict' 23 | const { BITAGORA_URL, BITAGORA_PREFIX, requestState } = require('bitagora-library'); 24 | const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; 25 | const Bs58 = require('base-x')(BASE58); 26 | const { Secp256k1PrivateKey } = require('sawtooth-sdk/signing/secp256k1'); 27 | const { createContext } = require('sawtooth-sdk/signing'); 28 | const cTable = require('console.table'); 29 | const shell = require('shelljs'); 30 | const today = new Date(); 31 | 32 | function Vote(option, ballots) { 33 | this.option = option; 34 | this.ballots = ballots; 35 | } 36 | 37 | function fetchVote(data) { 38 | return new Promise((resolve) => { 39 | try { 40 | if (!Boolean(data.id)) { 41 | if (Boolean(data.privkey)) { 42 | const privkey_hex = Bs58.decode(data.privkey).toString('hex'); 43 | const privateKey = Secp256k1PrivateKey.fromHex(privkey_hex); 44 | const signerContext = createContext('secp256k1'); 45 | data['id'] = signerContext.getPublicKey(privateKey).asHex(); 46 | } 47 | } 48 | if (!Boolean(data.poll) || !Boolean(data.id)) throw 'No data'; 49 | requestState(BITAGORA_URL, 'poll', data.poll, null, null, null, false).then((pollResult) => { 50 | try { 51 | if (pollResult.status != 'FOUND') throw 'Poll not found'; 52 | let poll = JSON.parse(pollResult.data.poll); 53 | var pollkey; 54 | if (!poll.open && Boolean(poll.privkey)) pollkey = poll.privkey; 55 | requestState(BITAGORA_URL, 'ballot', data.poll, data.id, null, pollkey).then((result) => { 56 | resolve(result); 57 | }).catch((e) => { 58 | resolve({status: 'UNKNOWN' }); 59 | }); 60 | } catch(e) { 61 | resolve({status: 'UNKNOWN' }); 62 | } 63 | }).catch((e) => { 64 | resolve({status: 'UNKNOWN' }); 65 | }); 66 | } catch(e) { 67 | resolve({status: 'UNKNOWN' }); 68 | } 69 | }); 70 | } 71 | 72 | function check(data) { 73 | return new Promise((resolve) => { 74 | /* Takes as data an object with params (poll id) 'poll' and either (vote) 'id' or (voter) 'privkey' */ 75 | if (!Boolean(data)) resolve(false); 76 | if (!Boolean(data.poll)) resolve(false); 77 | if (!Boolean(data.id) && !Boolean(data.privkey)) resolve(false); 78 | fetchVote(data).then((result) => { 79 | resolve(result); 80 | }); 81 | }); 82 | }; 83 | 84 | function recount(pollId) { 85 | return new Promise((resolve) => { 86 | /* Takes a single param 'pollId' */ 87 | if (!Boolean(pollId)) return false; 88 | try { 89 | requestState(BITAGORA_URL, 'poll', pollId, null, null).then((result) => { 90 | resolve(result); 91 | }); 92 | } catch(e) { 93 | console.log(e); 94 | resolve({status: 'ERROR' }); 95 | } 96 | }); 97 | }; 98 | 99 | function listPolls() { 100 | return new Promise((resolve) => { 101 | try { 102 | requestState(BITAGORA_URL, 'polls').then((result) => { 103 | resolve(result); 104 | }).catch((e) => { 105 | resolve({ status: 'ERROR' }); 106 | }); 107 | } catch(e) { 108 | resolve({ status: 'ERROR' }); 109 | } 110 | }); 111 | } 112 | 113 | function getNodeLocation(href) { 114 | var match = href.match(/^(tcp?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/); 115 | return match && { 116 | href: href, 117 | protocol: match[1], 118 | host: match[2], 119 | hostname: match[3], 120 | port: match[4], 121 | pathname: match[5], 122 | search: match[6], 123 | hash: match[7] 124 | } 125 | } 126 | 127 | function listBallots(pollId) { 128 | return new Promise((resolve) => { 129 | try { 130 | requestState(BITAGORA_URL, 'poll', pollId).then((result) => { 131 | try { 132 | if (!Boolean(result)) throw 'No data'; 133 | if (result.status != 'FOUND') throw 'Poll not found'; 134 | let poll = JSON.parse(result.data.poll); 135 | var pollkey; 136 | if (!poll.open && Boolean(poll.privkey)) { 137 | resolve(result); 138 | } else { 139 | if (!poll.open) { 140 | resolve({ status: 'UNKNOWN', votes: result.data.votes }); 141 | } else { 142 | if (result.data.votes > 5000) { 143 | console.log("This poll contains "+ result.data.votes.toLocaleString() + " ballots."); 144 | console.log("Please be aware that the process of parsing so many ballots will take some time."); 145 | console.log("Opening ballot boxes..."); 146 | console.log("\r"); 147 | } 148 | requestState(BITAGORA_URL, 'ballots', pollId, null, null, poll.privkey).then((response) => { 149 | resolve(response); 150 | }).catch((e) => { 151 | resolve({ status: 'ERROR' }); 152 | }); 153 | } 154 | } 155 | } catch(e) { 156 | resolve({ status: 'ERROR' }); 157 | } 158 | }).catch((e) => { 159 | resolve({ status: 'ERROR' }); 160 | }); 161 | } catch(e) { 162 | resolve({ status: 'ERROR' }); 163 | } 164 | }); 165 | } 166 | 167 | try { 168 | shell.config.silent = true; 169 | let api = process.env.API_URL; 170 | var args = process.argv.slice(2); 171 | if (args[0] === undefined || args[1] === undefined) throw ' Empty command'; 172 | if (args[0] == 'list') { 173 | if (args[1] == 'polls') { 174 | listPolls().then((result) => { 175 | console.group(); 176 | if (Boolean(result) && result.status == 'FOUND') { 177 | let polls = result.polls; 178 | if (polls.length == 0) { 179 | console.log("No polls found"); 180 | } else if (polls.length == 1) { 181 | console.log("Found 1 poll:"); 182 | } else { 183 | console.log("Found "+polls.length.toLocaleString()+" polls:"); 184 | polls.sort((a, b) => parseInt(a.votes) - parseInt(b.votes)).reverse(); 185 | } 186 | console.log('\r'); 187 | if (polls.length > 20) { 188 | console.log("Listing only active and pending polls:"); 189 | console.log('\r'); 190 | let list = []; 191 | let unlisted = []; 192 | polls.forEach(function(obj) { 193 | if (obj['votes'] > 0 || new Date(obj['ends']) > today ) { 194 | obj['votes'] = obj['votes'].toLocaleString(); 195 | list.push(obj); 196 | } else { 197 | unlisted.push(obj['id']); 198 | } 199 | }); 200 | console.table(list); 201 | if (unlisted.length > 0) console.log("Unlisted poll IDs: "+unlisted.join(", ")); 202 | } else { 203 | polls.forEach(function(obj){ obj['votes'] = obj['votes'].toLocaleString(); }); 204 | console.table(polls); 205 | } 206 | console.log('\r'); 207 | } else { 208 | console.log("No polls found"); 209 | } 210 | console.groupEnd(); 211 | }).catch((e) => { 212 | console.log("No polls found"); 213 | }); 214 | } else if (args[1] == 'ballots') { 215 | if (!Boolean(args[2])) throw ' Argument [pollId] missing'; 216 | let pollId = args[2]; 217 | listBallots(pollId).then((result) => { 218 | console.group(); 219 | if (Boolean(result.status) && result.status == "FOUND") { 220 | console.log(result.data.boxes['00']) 221 | if (result.data.votes == 0) { 222 | console.log("\r"); 223 | console.log("No ballots found for poll "+pollId+"\n"); 224 | console.log("\n"); 225 | } else if (result.data.votes < 100) { 226 | console.log("\r"); 227 | console.log("Found "+result.data.votes.toLocaleString() +" ballots for poll "+pollId+":"); 228 | console.log("\r"); 229 | console.log(result.data.boxes); 230 | console.log("\n"); 231 | } else { 232 | console.log("\r"); 233 | console.log("Found "+ result.data.votes.toLocaleString()+" ballots for poll "+pollId+"."); 234 | var fs = require('fs'); 235 | fs.writeFile("ballots-"+pollId+".json", JSON.stringify(result), function(err) { 236 | if (err) { 237 | return console.log(err); 238 | } else { 239 | console.log("The full list of ballots has been saved to file. You can view it by typing: cat ballots-"+ pollId+".json from the shell container. \n"); 240 | } 241 | }); 242 | console.log("\n"); 243 | } 244 | } else if (Boolean(result.status) && result.status == "UNKNOWN") { 245 | if ( Boolean(result.data.votes) && result.data.votes > 0 ) { 246 | console.log("\r"); 247 | console.log("Found "+ result.votes.toLocaleString() +" ballots for poll "+ pollId + "."); 248 | console.log("This poll is encrypted and ballots cannot be parsed until the poll secret key has been published."); 249 | console.log("\n"); 250 | } else if ( Boolean(result.data.votes) && result.data.votes == 0 ) { 251 | console.log("\r"); 252 | console.log("No ballots cast yet."); 253 | console.log("\n"); 254 | } else { 255 | console.log("Nothing found\n"); 256 | } 257 | } else { 258 | console.log("Nothing found\n"); 259 | } 260 | console.groupEnd(); 261 | }).catch((e) => { 262 | console.log(e); 263 | console.log("\r"); 264 | }); 265 | } else if (args[1] == 'blocks') { 266 | shell.exec("sawtooth block list --url "+api, function(code, stdout, stderr) { 267 | console.group(); 268 | if (code == 0) { 269 | console.table(stdout); 270 | console.log('\r'); 271 | } else { 272 | console.log('Command could not be executed\n'); 273 | } 274 | console.groupEnd(); 275 | }); 276 | } else if (args[1] == 'peers') { 277 | shell.exec("sawtooth peer list --url "+api, function(code, stdout, stderr) { 278 | console.group(); 279 | if (code == 0) { 280 | let peers = stdout.split(","); 281 | if (peers.length == 0) { 282 | console.log("Your node seems to have no peers. Try uninstalling and reinstalling the node again."); 283 | console.log('\r'); 284 | } else { 285 | console.log("Your node [0] is peered with the following validators: "); 286 | console.log("\r"); 287 | for (var i=0; i { 350 | console.group(); 351 | if (Boolean(result.status) && result.status == "FOUND") { 352 | let ballotTable = { 353 | 'poll': data.poll, 354 | 'voter': data.id, 355 | 'ballot': result.data 356 | } 357 | console.log("\r"); 358 | console.log("Ballot found:"); 359 | console.log("\r"); 360 | console.table(ballotTable); 361 | console.log("\r"); 362 | } else { 363 | console.log("Ballot not found\n"); 364 | } 365 | console.groupEnd(); 366 | }); 367 | } else if (args[1] == 'poll') { 368 | if (!Boolean(args[2])) throw ' Argument [pollId] missing'; 369 | let pollId = args[2]; 370 | recount(pollId).then((result) => { 371 | console.group(); 372 | if (Boolean(result) && Boolean(result.data.poll) && (result.status == "FOUND" || result.status == "UNKNOWN")) { 373 | console.log('\r'); 374 | let poll = JSON.parse(result.data.poll); 375 | poll.values = JSON.stringify(poll.values); 376 | poll.starts = new Date(parseInt(poll.starts)).toDateString(); 377 | poll.ends = new Date(parseInt(poll.ends)).toDateString(); 378 | console.table(poll); 379 | console.group(); 380 | console.log("--------------------------------------------------------------------------------------------------------------------------------"); 381 | console.log("RESULTS:"); 382 | console.log("Total ballots cast: "+result.data.votes.toLocaleString()); 383 | let showResults = true; 384 | if (!poll.open && !Boolean(poll.privkey)) showResults = false; 385 | if (showResults && Boolean(result.data.ballots) && Object.keys(result.data.ballots).length > 0) { 386 | let val = JSON.parse(poll.values); 387 | let bal = result.data.ballots; 388 | Object.keys(bal).forEach(function(k){ bal[k] = bal[k].toLocaleString(); }); 389 | console.table(bal); 390 | } else { 391 | console.log("No results available"); 392 | } 393 | console.log("--------------------------------------------------------------------------------------------------------------------------------"); 394 | console.log("\r"); 395 | console.groupEnd(); 396 | } else { 397 | console.log("Nothing found\n"); 398 | } 399 | console.groupEnd(); 400 | }); 401 | } else if (args[1] == 'block') { 402 | if (!Boolean(args[2])) throw ' Argument [blockId] missing'; 403 | shell.exec("sawtooth block show "+args[2]+" --url "+api, function(code, stdout, stderr) { 404 | console.group(); 405 | if (code == 0) { 406 | console.table(stdout); 407 | console.log("\n"); 408 | } else { 409 | console.log("Command could not be executed\n"); 410 | } 411 | console.groupEnd(); 412 | }); 413 | } else if (args[1] == 'state') { 414 | if (!Boolean(args[2])) throw ' Argument [address] missing'; 415 | shell.exec("sawtooth state show "+args[2]+" --url "+api, function(code, stdout, stderr) { 416 | console.group(); 417 | if (code== 0) { 418 | console.table(stdout); 419 | console.log('\r'); 420 | } else { 421 | console.log("Command could not be executed\n"); 422 | } 423 | console.groupEnd(); 424 | }); 425 | } else { 426 | throw ' Wrong command'; 427 | } 428 | } 429 | } catch(e) { 430 | console.group(); 431 | console.log('\r'); 432 | console.log(' Bitagora Shell - Usage:'); 433 | console.log(' bitagora list [ polls | blocks | state | peers | settings ]'); 434 | console.log(' bitagora list ballots < poll_id >'); 435 | console.log(' bitagora show [ poll | ballot | block | state ] < argument > < argument >'); 436 | console.log(' bitagora show ballot < poll_id > < voter_private_key | vote_id >'); 437 | console.log(' bitagora show poll < poll_id >'); 438 | console.log(' bitagora show block < block_id >'); 439 | console.log(' bitagora show state < address >'); 440 | console.log('\r'); 441 | console.groupEnd(); 442 | } 443 | -------------------------------------------------------------------------------- /bitagora-node/src/update-lib.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | cd ./ballots-tp 3 | sudo docker build -t bitagora/ballots-tp:0.1.0 . && sudo docker push bitagora/ballots-tp:0.1.0 4 | cd ../polls-tp 5 | sudo docker build -t bitagora/polls-tp:0.1.0 . && sudo docker push bitagora/polls-tp:0.1.0 6 | cd ../shell 7 | sudo docker build -t bitagora/shell:0.1.0 . && sudo docker push bitagora/shell:0.1.0 8 | cd ../../../sawtooth-core 9 | sudo docker build -f rest_api/Dockerfile-installed -t bitagora/rest-api:0.1.0 . && sudo docker push bitagora/rest-api:0.1.0 -------------------------------------------------------------------------------- /bitagora-node/validator.toml: -------------------------------------------------------------------------------- 1 | endpoint = 'tcp://NIP:8801' 2 | bind = [ 'network:tcp://eth0:8801', 'component:tcp://eth0:4004' ] 3 | peering = 'dynamic' 4 | scheduler = 'parallel' 5 | seeds = SEEDS 6 | network_public_key = NETWORK_PUBLIC_KEY 7 | network_private_key = NETWORK_PRIVATE_KEY 8 | minimum_peer_connectivity = 3 9 | maximum_peer_connectivity = 10 10 | [roles] 11 | network = 'trust' -------------------------------------------------------------------------------- /bitagora-pollster/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 | -------------------------------------------------------------------------------- /bitagora-pollster/README.md: -------------------------------------------------------------------------------- 1 | ![Bitagora](https://bitagora.cc/assets/img/bitagora-name-blue.png) 2 | 3 | # Bitagora Pollster 4 | 5 | ![version](https://img.shields.io/badge/version-0.1.0-green.svg) 6 | ![Hex.pm](https://img.shields.io/hexpm/l/plug.svg) 7 | 8 | Source code for the JS functions necessary to create, close and approve polls in the 9 | Bitagora Platform voting system. 10 | 11 | For more information, visit 12 | 13 | [https://bitagora.cc](https://bitagora.cc) 14 | 15 | ## License 16 | 17 | Bitagora Pollster is licensed under the [Apache License Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) 18 | software license. -------------------------------------------------------------------------------- /bitagora-pollster/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bitagora-pollster", 3 | "version": "0.1.0", 4 | "description": "Functions for opening and closing polls in the Bitagora Platform", 5 | "author": "Ignasi Ribó", 6 | "license": "Apache-2.0", 7 | "main": "pollster.js", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/bitagora/bitagora-core.git" 11 | }, 12 | "dependencies": { 13 | "bitagora-library": "0.1.0", 14 | "elliptic": "^6.4.0", 15 | "request": "^2.8.1", 16 | "sawtooth-sdk": "^1.0.4" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /bitagora-pollster/pollster.js: -------------------------------------------------------------------------------- 1 | /** 2 | * BITAGORA POLLSTER 3 | * pollster.js 4 | * Functions to create, close and approve polls in the Bitagora Platform voting system 5 | * Developed by Ignasi Ribó, 2018 6 | * Repo: https://github.com/bitagora/bitagora-core 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | * ------------------------------------------------------------------------------ 20 | */ 21 | 22 | 'use strict' 23 | const { 24 | BITAGORA_URL, BITAGORA_POLL_FAMILY, BITAGORA_VERSION, 25 | getPollAddress, requestURL, _hash, getNodeList, getSettingAddress, validatePoll } = require('bitagora-library'); 26 | const EC = require('elliptic').ec; 27 | var ec = new EC('secp256k1'); 28 | const { Secp256k1PrivateKey } = require('sawtooth-sdk/signing/secp256k1') 29 | const { protobuf } = require('sawtooth-sdk'); 30 | const { createContext, CryptoFactory } = require('sawtooth-sdk/signing'); 31 | const signerContext = createContext('secp256k1'); 32 | 33 | function createPoll(api, poll, signer) { 34 | return new Promise((resolve) => { 35 | try { 36 | poll.timestamp = new Date().getTime().toString(); 37 | var payloadBytes = Buffer.from(JSON.stringify(poll)); 38 | const transactionHeaderBytes = protobuf.TransactionHeader.encode({ 39 | familyName: BITAGORA_POLL_FAMILY, 40 | familyVersion: BITAGORA_VERSION, 41 | inputs: [getPollAddress(poll.id), getSettingAddress('sawtooth.settings.vote.authorized_keys')], 42 | outputs: [getPollAddress(poll.id)], 43 | signerPublicKey: signer.getPublicKey().asHex(), 44 | batcherPublicKey: signer.getPublicKey().asHex(), 45 | dependencies: [], 46 | payloadSha512: _hash('sha512', payloadBytes) 47 | }).finish(); 48 | const signature = signer.sign(transactionHeaderBytes); 49 | const transaction = protobuf.Transaction.create({ 50 | header: transactionHeaderBytes, 51 | headerSignature: signature, 52 | payload: payloadBytes 53 | }); 54 | const transactions = [transaction]; 55 | const batchHeaderBytes = protobuf.BatchHeader.encode({ 56 | signerPublicKey: signer.getPublicKey().asHex(), 57 | transactionIds: transactions.map((txn) => txn.headerSignature) 58 | }).finish(); 59 | const batchSignature = signer.sign(batchHeaderBytes); 60 | const batch = protobuf.Batch.create({ 61 | header: batchHeaderBytes, 62 | headerSignature: batchSignature, 63 | transactions: transactions 64 | }); 65 | const batchListBytes = protobuf.BatchList.encode({ 66 | batches: [batch] 67 | }).finish() 68 | const request = require('request'); 69 | request.post({ 70 | url: `${api}/batches`, 71 | body: batchListBytes, 72 | headers: { 73 | 'Content-Type': 'application/octet-stream' 74 | } 75 | }, 76 | (err, response) => { 77 | try { 78 | if (err) throw err; 79 | if (!Boolean(response.body)) throw 'No response'; 80 | if (response.statusCode != 200 && response.statusCode != 201 && response.statusCode != 202) throw 'Failed request'; 81 | let link = JSON.parse(response.body)['link']; 82 | requestURL(link).then((result) => { 83 | if (Boolean(result) && Boolean(result.data)) { 84 | resolve(result.data[0]); 85 | } else { 86 | resolve({ status: "ERROR" }); 87 | } 88 | }).catch((e) => { 89 | console.log(e); 90 | resolve({ status: "ERROR" }); 91 | }); 92 | } catch(e) { 93 | console.log(e); 94 | resolve({ status: "ERROR" }); 95 | } 96 | }); 97 | } catch(e) { 98 | console.log(e); 99 | resolve({ status: "ERROR" }); 100 | } 101 | }); 102 | } 103 | 104 | function closePoll(api, poll, signer, privkey) { 105 | return new Promise((resolve) => { 106 | try { 107 | let obj = { 108 | 'id': poll.id, 109 | 'privkey': privkey, 110 | 'certkey': poll.certkey, 111 | 'timestamp': new Date().getTime().toString() 112 | } 113 | var payloadBytes = Buffer.from(JSON.stringify(obj)); 114 | const transactionHeaderBytes = protobuf.TransactionHeader.encode({ 115 | familyName: BITAGORA_POLL_FAMILY, 116 | familyVersion: BITAGORA_VERSION, 117 | inputs: [getPollAddress(poll.id), getSettingAddress('sawtooth.settings.vote.authorized_keys')], 118 | outputs: [getPollAddress(poll.id)], 119 | signerPublicKey: signer.getPublicKey().asHex(), 120 | batcherPublicKey: signer.getPublicKey().asHex(), 121 | dependencies: [], 122 | payloadSha512: _hash('sha512', payloadBytes) 123 | }).finish(); 124 | const signature = signer.sign(transactionHeaderBytes); 125 | const transaction = protobuf.Transaction.create({ 126 | header: transactionHeaderBytes, 127 | headerSignature: signature, 128 | payload: payloadBytes 129 | }); 130 | const transactions = [transaction]; 131 | const batchHeaderBytes = protobuf.BatchHeader.encode({ 132 | signerPublicKey: signer.getPublicKey().asHex(), 133 | transactionIds: transactions.map((txn) => txn.headerSignature) 134 | }).finish(); 135 | const batchSignature = signer.sign(batchHeaderBytes); 136 | const batch = protobuf.Batch.create({ 137 | header: batchHeaderBytes, 138 | headerSignature: batchSignature, 139 | transactions: transactions 140 | }); 141 | const batchListBytes = protobuf.BatchList.encode({ 142 | batches: [batch] 143 | }).finish() 144 | const request = require('request'); 145 | request.post({ 146 | url: `${api}/batches`, 147 | body: batchListBytes, 148 | headers: { 149 | 'Content-Type': 'application/octet-stream', 150 | } 151 | }, 152 | (err, response) => { 153 | try { 154 | if (err) throw err; 155 | if (!Boolean(response.body)) throw 'No response'; 156 | if (response.statusCode != 200 && response.statusCode != 201 && response.statusCode != 202) throw 'Failed request'; 157 | let link = JSON.parse(response.body)['link']; 158 | requestURL(link).then((result) => { 159 | if (Boolean(result) && Boolean(result.data)) { 160 | resolve(result.data[0]); 161 | } else { 162 | resolve({ status: "ERROR" }); 163 | } 164 | }).catch((e) => { 165 | console.log(e); 166 | resolve({ status: "ERROR" }); 167 | }); 168 | } catch(e) { 169 | console.log(e); 170 | resolve({ status: "ERROR" }); 171 | } 172 | }); 173 | } catch(e) { 174 | console.log(e); 175 | resolve({ status: "ERROR" }); 176 | } 177 | }); 178 | } 179 | 180 | async function submitPolltoAPIs(apis, poll, signer, action, key) { 181 | try { 182 | if (action != 'create' && action != 'close') return false; 183 | var number = 10; 184 | if (apis.length < 10) number = apis.length; 185 | var link; 186 | let response = { status: 'UNKNOWN' }; 187 | for (var i=0; i { 255 | try { 256 | if (!Boolean(poll)) throw 'No poll'; 257 | if (!Boolean(pollsterPrivkey)) throw 'No pollster key'; 258 | if (poll.certkey.substr(poll.certkey.length-8) !== poll.id) throw 'Poll id is incorrect'; 259 | const privateKey = Secp256k1PrivateKey.fromHex(pollsterPrivkey); 260 | const signerContext = createContext('secp256k1'); 261 | const factory = new CryptoFactory(signerContext); 262 | const signer = factory.newSigner(privateKey); 263 | const pubkeyHex = signerContext.getPublicKey(privateKey).asHex(); 264 | if (poll.certkey !== pubkeyHex) throw 'Pollster key is not valid'; 265 | validatePoll(poll).then((valid) => { 266 | try { 267 | if (!valid) throw 'Poll is not valid'; 268 | getNodeList(BITAGORA_URL).then((APIs) => { 269 | try { 270 | if (!Boolean(APIs) || APIs.length == 0) throw 'No APIs'; 271 | submitPolltoAPIs(APIs, poll, signer, 'create', pollsterPrivkey).then((result) => { 272 | if (result.status == 'COMMITTED' || result.status == 'INVALID') { 273 | resolve(result); 274 | } else { 275 | reject(result); 276 | } 277 | }).catch((e) => { 278 | console.log(e); 279 | reject(e); 280 | }); 281 | } catch(e) { 282 | console.log(e); 283 | reject(e); 284 | } 285 | }).catch((e) => { 286 | console.log(e); 287 | reject(e); 288 | }); 289 | } catch(e) { 290 | console.log(e); 291 | reject(e); 292 | } 293 | }).catch((e) => { 294 | console.log(e); 295 | reject(e); 296 | }); 297 | } catch(e) { 298 | console.log(e); 299 | reject(e); 300 | } 301 | }); 302 | } 303 | 304 | function close(poll, pollsterPrivkey) { 305 | return new Promise((resolve, reject) => { 306 | try { 307 | if (!Boolean(poll)) throw 'No poll'; 308 | if (!Boolean(pollsterPrivkey)) throw 'No pollster privkey'; 309 | const signerContext = createContext('secp256k1'); 310 | const factory = new CryptoFactory(signerContext); 311 | const privateKey = Secp256k1PrivateKey.fromHex(pollsterPrivkey); 312 | const signer = factory.newSigner(privateKey); 313 | const pubkeyHex = signerContext.getPublicKey(privateKey).asHex(); 314 | if (pubkeyHex !==poll.certkey) throw 'Invalid keys'; 315 | getNodeList(BITAGORA_URL).then((APIs) => { 316 | try { 317 | if (!Boolean(APIs) || APIs.length == 0) throw 'No APIs'; 318 | submitPolltoAPIs(APIs, poll, signer, 'close', pollsterPrivkey).then((result) => { 319 | if (result.status == 'COMMITTED' || result.status == 'INVALID') { 320 | resolve(result); 321 | } else { 322 | reject(result); 323 | } 324 | }).catch((e) => { 325 | console.log(e); 326 | reject(e); 327 | }); 328 | } catch(e) { 329 | console.log(e); 330 | reject(e); 331 | } 332 | }).catch((e) => { 333 | console.log(e); 334 | reject(e); 335 | }); 336 | } catch(e) { 337 | console.log(e); 338 | reject(e); 339 | } 340 | }); 341 | } 342 | 343 | function approve(poll, adminPrivkeyHex) { 344 | return new Promise((resolve, reject) => { 345 | try { 346 | if (!Boolean(poll.certkey)) throw 'No certkey'; 347 | let token = _hash('sha256',_hash('sha256', getPollToken(poll))); 348 | let adminKey = ec.keyFromPrivate(adminPrivkeyHex); 349 | let signature = adminKey.sign(token); 350 | let approval = signature.toDER('hex'); 351 | resolve(approval); 352 | } catch(e) { 353 | console.log(e); 354 | reject(false); 355 | } 356 | }); 357 | } 358 | 359 | module.exports = { 360 | create, 361 | close, 362 | approve 363 | } 364 | --------------------------------------------------------------------------------