Skip to content
Snippets Groups Projects
Unverified Commit 178d4acd authored by xx network's avatar xx network Committed by GitHub
Browse files

Merge pull request #13 from rntcruz23/master

Added polling website to 7th estate
parents 33355da6 10194098
No related branches found
No related tags found
No related merge requests found
Showing
with 16875 additions and 0 deletions
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
*/dist
*/tmp
*/out-tsc
# Only exists if Bazel was run
*/bazel-out
# dependencies
*/node_modules
# profiling files
chrome-profiler-events*.json
speed-measure-plugin*.json
# IDEs and editors
*/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
*/.sass-cache
*/connect.lock
*/coverage
*/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
*/typings
# System Files
.DS_Store
Thumbs.db
# XXN Config files
**/xxn_config.yaml
**/votes.csv
const yaml = require('js-yaml');
const fs = require('fs');
const Web3 = require('web3');
var Tx = require('ethereumjs-tx').Transaction;
const axios = require('axios');
exports.Blockchain = class Blockchain {
constructor(configfile) {
this.config = configfile;
this.doc = this.loadConfig(this.config);
this.web3 = new Web3(Web3.givenProvider || this.doc['node']);
this.account = this.web3.eth.accounts.privateKeyToAccount(this.doc['key']);
this.apikey = this.doc['apikey']
}
loadConfig(configfile) {
try {
return yaml.load(fs.readFileSync(configfile, 'utf8'));
} catch (e) {
console.log(e);
return null;
}
}
async postToBlockchain (data) {
try{
var data = this.web3.utils.toHex(data);
var gas = await this.web3.eth.estimateGas({
to: this.account.address,
data: data,
});
var txcount = await this.web3.eth.getTransactionCount(this.account.address);
var rawTx = {
to: this.account.address,
value: '0x00',
data: data,
nonce: txcount,
gas: gas,
gasLimit: this.web3.utils.toHex(314150),
gasPrice: this.web3.utils.toHex(this.web3.utils.toWei('10', 'gwei'))
}
var tx = new Tx(rawTx, { chain: this.doc['chain'] });
var pkeybuff = Buffer.from(this.account.privateKey.slice(2), 'hex');
tx.sign(pkeybuff);
tx = tx.serialize();
return new Promise(async (resolve, reject) => {
this.web3.eth
.sendSignedTransaction(this.web3.utils.toHex(tx))
.on("transactionHash", (hash) => {
resolve(hash);
})
.catch((err) => reject (err))
})
} catch(err) {
console.log(err);
throw(err)
}
}
async getData () {
var url = "https://api-ropsten.etherscan.io/api?"
var uri = url + `module=account&action=txlist&address=${this.account.address}&startblock=0&endblock=99999999&sort=asc&apikey=${this.apikey}`
var res = await axios.get(uri);
return res.data
}
async getDataTx(data) {
var datahex = this.web3.utils.toHex(data);
var dataposted = await this.getData();
for (var tx of dataposted['result']) {
if (tx.input == datahex)
return tx;
}
return null;
}
async checkReceipt(hash) {
return await this.web3.eth.getTransactionReceipt(hash);
}
}
{
"host": "localhost",
"port": 9098,
"apipath": "/vote"
}
\ No newline at end of file
const express = require('express')
const config = require('./config.json')
const helmet = require('helmet')
const csrf = require('csurf')
const csrfProtection = csrf({ cookie: true })
const cookieParser = require('cookie-parser')
const fs = require('fs');
const Blockchain = require('./blockchain.js').Blockchain
const compression = require('compression');
CONFIG = "xxn_config.yaml";
const chain = new Blockchain(CONFIG);
// To turn off stack traces, stop information leak
process.env.NODE_ENV = 'production';
const app = express();
app.use(helmet()); // Manage security headers
app.use(compression())
VOTE_CODE_GROUP_SIZE = 4;
VOTE_CODE_GROUP_SIZE_P = VOTE_CODE_GROUP_SIZE + 1;
VOTE_CODE_NUM_GROUPS = 4;
VOTE_CODE_LENGTH = VOTE_CODE_NUM_GROUPS + VOTE_CODE_GROUP_SIZE_P;
VOTES_FILE_PATH = "votes.csv";
fs.access(VOTES_FILE_PATH, fs.F_OK, (err) => {
if (err) {
fs.appendFile(VOTES_FILE_PATH, "votecode\n", (err) => {
return console.log(err);
});
}
})
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies
app.get(config.apipath + '/csrf', csrfProtection, (req, response) => {
response.send({ csrf: req.csrfToken() });
})
app.post(config.apipath, csrfProtection, (req, response) => {
console.log(req.body);
let votecode = req.body.votecode;
try{
if (!checkVotecode(votecode)) {
error(response, "Invalid votecode");
}
// Check if vote is in blockchain
voteInBlockchain(votecode)
.then(tx => {
if (tx) {
error(response, "Vote already in blockchain");
}
// Post vote
postVote(votecode)
.then((result => {
if (!result){
console.log("Error");
error(response, "Error posting in blockchain");
}
// Provide receipt
console.log("Hash sent: ", result)
sendResponse(response, {
hash: result,
status: "Validating your vote... You can check the status with the transaction hash"
});
fs.appendFile(VOTES_FILE_PATH, votecode + '\n', file_err);
// Provide proof that vote is on chain
// response.end();
}))
.catch((err) => {
error(response, err.message , err);
return;
})
})
}
catch(err) {
error(response, "Error processing request", err);
return;
}
})
app.get(config.apipath + '/status/:hash', (req, response) => {
var hash = req.params.hash;
checkReceipt(hash)
.then((status) => {
console.log(status);
sendResponse(response, {
receipt: status ? JSON.stringify(status) : null,
status: status? "Your vote was successfully posted to blockchain, here is the transaction receipt": null
});
})
.catch((err) => {
error(response, "Error getting tx status:" , err)
});
})
function error(response, message, err = null) {
console.log(message, err ? err.message : "");
sendError(response);
throw Error(message)
}
function file_err(err) {
if (err) return console.log(err);
console.log("Data written to file");
}
function checkVotecode(votecode) {
console.log("Checking votecode", votecode);
try{
let codegroups = votecode.split("-");
for (let i = 0; i < VOTE_CODE_NUM_GROUPS; i++){
if (!checkParity(codegroups[i]))
return false;
}
return true
}
catch(err) {
console.log(err);
return false;
}
}
function checkParity(code) {
if (code.length != VOTE_CODE_GROUP_SIZE_P)
return false;
try {
let parity = +code.slice(-1);
let code_sum = code.slice(0, -1)
.split('')
.map(c => +c)
.reduce((sum, cur) => {
return sum + cur
});
let code_parity = (10 * VOTE_CODE_NUM_GROUPS - code_sum) % 10;
return parity == code_parity;
}
catch(err) {
console.log(err.message);
return false;
}
}
function sendError(response) {
sendResponse(response, {errormessage: "There has been an error processing your vote"});
}
function sendResponse(response, messages) {
response.end(JSON.stringify(messages))
}
async function voteInBlockchain(votecode) {
console.log("Checking if votecode " + votecode + " is in blockchain");
var data = {votecode:votecode};
var tx = await chain.getDataTx(data);
console.log("Found ", tx)
return tx;
}
async function postVote(votecode) {
console.log("Vote submitted: " + votecode);
return await chain.postToBlockchain(JSON.stringify({votecode: votecode}));
}
async function checkReceipt(hash) {
console.log("Checking status of tx " + hash);
return await chain.checkReceipt(hash);
}
app.listen(config.port, config.host,() => console.log(`NodeServer started.`))
This diff is collapsed.
{
"name": "seven-vote_bckend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.21.1",
"compression": "^1.7.4",
"cookie-parser": "^1.4.5",
"csurf": "^1.11.0",
"ethereumjs-tx": "^2.1.2",
"express": "^4.17.1",
"helmet": "^4.4.1",
"js-yaml": "^4.0.0",
"web3": "^1.3.4"
}
}
#!/bin/bash
node index.js
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false
# SevenVote
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.3.20.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"seven-vote": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/seven-vote",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "seven-vote:build"
},
"configurations": {
"production": {
"browserTarget": "seven-vote:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "seven-vote:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "seven-vote:serve"
},
"configurations": {
"production": {
"devServerTarget": "seven-vote:serve:production"
}
}
}
}
}
},
"defaultProject": "seven-vote"
}
\ No newline at end of file
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# You can see what browsers were selected by your queries by running:
# npx browserslist
> 0.5%
last 2 versions
Firefox ESR
not dead
not IE 9-11 # For IE 9-11 support, remove 'not'.
\ No newline at end of file
// @ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
/**
* @type { import("protractor").Config }
*/
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
capabilities: {
browserName: 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};
\ No newline at end of file
import { AppPage } from './app.po';
import { browser, logging } from 'protractor';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('seven-vote app is running!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo() {
return browser.get(browser.baseUrl) as Promise<any>;
}
getTitleText() {
return element(by.css('app-root .content span')).getText() as Promise<string>;
}
}
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/e2e",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/seven-vote'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
This diff is collapsed.
{
"name": "seven-vote",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.js",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~8.2.14",
"@angular/common": "~8.2.14",
"@angular/compiler": "~8.2.14",
"@angular/core": "~8.2.14",
"@angular/forms": "~8.2.14",
"@angular/platform-browser": "~8.2.14",
"@angular/platform-browser-dynamic": "~8.2.14",
"@angular/router": "~8.2.14",
"@fortawesome/angular-fontawesome": "^0.8.2",
"@fortawesome/fontawesome-svg-core": "^1.2.36",
"@fortawesome/free-brands-svg-icons": "^5.15.4",
"@fortawesome/free-solid-svg-icons": "^5.15.4",
"bootstrap": "^4.5.2",
"rxjs": "~6.4.0",
"tslib": "^1.10.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.803.29",
"@angular/cli": "~8.3.20",
"@angular/compiler-cli": "~8.2.14",
"@angular/language-service": "~8.2.14",
"@types/jasmine": "~3.3.8",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "^5.0.0",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.15.0",
"typescript": "~3.5.3"
}
}
const PROXY_CONFIG = {
"/vote": {
"target": "http://localhost:9098/",
"secure": false,
"onProxyRes": function(proxyRes, req, res) {
delete proxyRes.headers['X-Powered-By'];
proxyRes.headers['Access-Control-Allow-Headers'] = 'Authorization';
},
}
}
module.exports = PROXY_CONFIG;
\ No newline at end of file
/* tslint:disable:no-unused-variable */
import { TestBed, async, inject } from '@angular/core/testing';
import { ValidateVotecodeService } from './ValidateVotecode.service';
describe('Service: ValidateVotecode', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ValidateVotecodeService]
});
});
it('should ...', inject([ValidateVotecodeService], (service: ValidateVotecodeService) => {
expect(service).toBeTruthy();
}));
});
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment