-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
1308 lines (1166 loc) · 47.7 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
process.env.GOPATH = __dirname;
var hfc = require('hfc');
var util = require('util');
var fs = require('fs');
var Cloudant = require('cloudant');
const https = require('https');
var jwt = require('express-jwt');
var express = require('express');
var auth0 = require('auth0-js');
// cfenv provides access to your Cloud Foundry environment
var cfenv = require('cfenv');
//allows Cross Origin Resource Sharing [only during testing phase, TO BE REMOVED]
var cors = require('cors')
//for detecting memory leaks
var memwatch = require('memwatch-next');
// create a new express server
var app = express();
//help us with the scalibility problem
var queue = require('express-queue');
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
//to get post variables
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(cors()) //enable CORS
app.use(queue({ activeLimit: 1 })); //setting concurrency for each route to 1 to ENSURE it works (limitation of fabric 0.6)
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
//database variables
var cloudant;
var blockvoteDB;
var cloudantUsername;
var cloudantPassword;
//auth0 varialbles
var auth0Domain;
var auth0ClientSecret;
var auth0ClientID;
var authenticate;
var webAuth;
var vcap_app = { application_uris: [''] };
var ext_uri = '';
if (process.env.VCAP_APPLICATION) {
vcap_app = JSON.parse(process.env.VCAP_APPLICATION);
for (var i in vcap_app.application_uris) {
if (vcap_app.application_uris[i].indexOf(vcap_app.name) >= 0) {
ext_uri = vcap_app.application_uris[i];
}
}
}
if (process.env.VCAP_SERVICES) {
console.log('This app is running on Bluemix.');
if (process.env.cloudantUsername && process.env.cloudantUsername && process.env.auth0Domain && process.env.auth0ClientSecret && process.env.auth0ClientID) {
console.log("Cloudant and auth0 credentials detected in environment varaibles")
cloudantUsername = process.env.cloudantUsername;
cloudantPassword = process.env.cloudantPassword;
auth0Domain = process.env.auth0Domain;
auth0ClientSecret = process.env.auth0ClientSecret;
auth0ClientID = process.env.auth0ClientID;
authenticate = jwt({
secret: auth0ClientSecret,
audience: auth0ClientID
});
webAuth = new auth0.WebAuth({
domain: auth0Domain,
clientID: auth0ClientID
});
cloudant = Cloudant({ account: cloudantUsername, password: cloudantPassword });
}
else {
console.error("Please input the cloudant and auth0 credentials into the environment varaibles as cloudantUsername, cloudantPassword, auth0Domain, auth0ClientSecret, and auth0ClientID")
process.exit(-1);
}
exports.SERVER = {
HOST: process.env.VCAP_APP_HOST || '0.0.0.0',
PORT: process.env.VCAP_APP_PORT || process.env.PORT,
DESCRIPTION: 'Bluemix - Production',
EXTURI: ext_uri
};
} else {
console.log('Assuming this app is running on localhost.');
if (process.argv.length != 7) {
console.error("Please input the cloudant credentials as CLI arguments: node app.js <cloudantUsername> <cloudantPassword> <auth0Domain> <auth0ClientSecret> <auth0ClientID>")
process.exit(-1);
} else {
cloudantUsername = process.argv[2];
cloudantPassword = process.argv[3];
auth0Domain = process.argv[4];
auth0ClientSecret = process.argv[5];
auth0ClientID = process.argv[6];
cloudant = Cloudant({ account: cloudantUsername, password: cloudantPassword });
authenticate = jwt({
secret: auth0ClientSecret,
audience: auth0ClientID
});
webAuth = new auth0.WebAuth({
domain: auth0Domain,
clientID: auth0ClientID
});
}
exports.SERVER = {
HOST: 'localhost',
PORT: 3000,
DESCRIPTION: 'Localhost',
EXTURI: process.env.EXTURI || 'localhost:3000'
};
//do leak detection when running locally
memwatch.on('leak', function (info) {
console.log("****************************************** MEM-WATCH")
console.log("heap usage has increased for five consecutive garbage collections");
console.log(info);
console.log("****************************************** MEM-WATCH")
});
}
exports.SERVER.vcap_app = vcap_app;
exports.DEBUG = vcap_app;
// start server on the specified port and binding host
var port = process.env.PORT || process.env.VCAP_APP_PORT || 3000;
app.listen(port);
console.log('listening at:', port);
//******************************************************************************************CLOUDANT FUNCTIONS
var createDataBase = function (callback) {
cloudant.db.create('blockvote', function (err, data) {
if (err) {
if (err.error === "file_exists") {
blockvoteDB = cloudant.db.use('blockvote');
callback(null, null); //db already exists
} else {
callback(err, null); //creation error
}
}
else { //created successfully
blockvoteDB = cloudant.db.use('blockvote');
callback(null, data);
}
});
}
// create a document
var createDocument = function (id, val, callback) {
// we are specifying the id of the document so we can update and delete it later
blockvoteDB.insert({ _id: id, electionData: val }, function (err, data) {
callback(err, data);
});
};
// read a document
var readDocument = function (id, callback) {
blockvoteDB.get(id, function (err, data) {
callback(err, data);
});
};
//******************************************************************************************GLOBAL VARIABLES
var config;
var chain;
var network;
var certPath;
var peers;
var users;
var userObj;
var newUserName;
var chaincodeID;
var certFile = 'us.blockchain.ibm.com.cert';
var chaincodeIDPath = __dirname + "/chaincodeID";
var chaincodeIDKnown;
var districts = [];
var voteOptions = [];
var startDate;
var endDate;
var allowLiveResults;
var caUrl;
var peerUrls = [];
var EventUrls = [];
createDataBase(function (err, resp) {
if (err) { //creation error
console.log("fatal error creating database, please start up the server again. error: " + err);
process.exit();
} else {
if (!resp)
console.log("blockvote db already existed, ready to use")
else
console.log("blockvote db created, ready to use")
}
});
app.use('/init', authenticate);
app.use('/addRegistrar', authenticate);
app.use('/registerVoter', authenticate);
app.get('/authping', function (req, res) {
res.status(200).send("Server responding to ping");
});
//******************************************************************************************ROUTES-ADMIN ONLY
app.get('/init', function (req, res) { //NEEDS TO BE CALLED EVERYTIME THE SERVER IS RESTARTED
//REQUIRES: a proper config file, valid Authorization header and access token in header
//PROMISES: If deployment has already been done, an error mentioning this. If deployment is successful, returns election metadata.
var authToken = req.get("AccessToken");
console.log(authToken);
webAuth.client.userInfo(authToken, function (err, user) {
if (err) {
res.send(JSON.stringify({ error: err, response: null }));
} else {
if (user === null || user.app_metadata === null) {
err = new Error();
err.code = 401;
err.message = "Unauthorized";
console.log(err.message);
res.send(JSON.stringify({ error: err, response: null }));
} else {
if (user.app_metadata.isAdmin === "true") {
res.setHeader('Content-Type', 'application/json');
init(function (err, resp) { //actual initialization function
if (err) {
res.send(JSON.stringify({ error: err, response: null }));
}
else {
read("admin", "metadata", function (err, readRes) {
if (err) {
if (err.message.includes("No data exists for")) {
err.message = "init failed";
}
res.send(JSON.stringify({ error: err, response: null }));
}
else {
res.send(JSON.stringify({ response: readRes, error: null }));
}
});
}
});
} else {
res.send("Not authorized");
}
}
}
});
});
//locked by electon that has ended
app.post('/addRegistrar', function (req, res) {
//REQUIRES: valid Authorization header and valid access token in header, the name of a registrar, the registrar's key modulus, the registrar's key exponent, and their district
//PROMISES: if this registrar is a new registrar, and the key parts are encoded properly, and the district is valid, then this registrar will be added to the blockchain
res.setHeader('Content-Type', 'application/json');
var registrarName = req.body.registrarName //empty check+preExistance check
var registrarKeyModulus = req.body.registrarKeyModulus //empty check+encoding check
var registrarKeyExponent = req.body.registrarKeyExponent//empty check+encoding check
var registrarDistrict = req.body.registrarDistrict//empty check+existance check
var authToken = req.get("AccessToken");
console.log(authToken);
webAuth.client.userInfo(authToken, function (err, user) {
if (err) {
res.send(JSON.stringify({ error: err, response: null }));
} else {
if (user === null || user.app_metadata === null) {
err = new Error();
err.code = 401;
err.message = "Unauthorized";
console.log(err.message);
res.send(JSON.stringify({ error: err, response: null }));
} else {
if (user.app_metadata.isAdmin === "true") {
if (!registrarName || !registrarKeyModulus || !registrarKeyExponent || !registrarDistrict) {
err = new Error();
err.code = 400;
err.message = "you need to supply: a registrar name, their key modululus and exponent, and the name of their district ";
console.log(err.message);
res.send(JSON.stringify({ error: err, response: null }));
} else {
// Read chaincodeID and use this for sub sequent Invokes/Queries
readDocument(config.chainName, function (err, resp) { //not_found is the err.error if not found
if (err) {
err.code = 503;
err.message = "error reading election info from database";
res.send(JSON.stringify({ error: err, response: null }));
}
else {
chaincodeID = resp.electionData.chaincodeID;
districts = resp.electionData.districts;
voteOptions = resp.electionData.voteOptions;
startDate = resp.electionData.electionStart;
endDate = resp.electionData.electionEnd;
var iskeyExpValid = true;
var currDate = new Date();
if (currDate > endDate || currDate < startDate) {
err = new Error();
err.code = 400;
err.message = "The election is closed";
console.log(err.message);
res.send(JSON.stringify({ error: err, response: null }));
} else {
if (!iskeyExpValid) { //ADD CRYPTO CHECK
err = new Error();
err.code = 400;
err.message = registrarKeyModulus + " is not encoded properly";
console.log(err.message);
res.send(JSON.stringify({ error: err, response: null }));
} else {
chain.getUser("admin", function (err, user) {
if (err) {
err2 = new Error();
err2.code = 500;
err2.message = " Failed to register and enroll " + deployerName + ": " + err;
res.send(JSON.stringify({ error: err2, response: null }));
} else {
userObj = user;
//check if desired district exists!
read("admin", registrarDistrict, function (err, readResp) {
if (!readResp) {
if (err.message.includes("No data exists for")) {
err.message = registrarDistrict + " does not exist";
}
console.log(err.message);
delete err.stack;
res.send(JSON.stringify({ error: err, response: null }));
}
else {
//check that this registrar hasn't already been registered
read("admin", "registarInfo", function (err, readResp) {
if (readResp && JSON.parse(readResp).hasOwnProperty(registrarName)) {
err2 = new Error();
err2.code = 500;
err2.message = " The registrar " + registrarName + " is already registered ";
delete err2.stack;
res.send(JSON.stringify({ error: err2, response: null }));
} else {
//can now invoke, query, etc
var args2 = [];
args2.push(registrarName);
args2.push(registrarKeyModulus);
args2.push(registrarKeyExponent);
args2.push(registrarDistrict);
try {
invoke(args2, "writeRegistar", function (err, resp) {
res.send(JSON.stringify({ response: { code: 200, disclaimer: "This registration needs to be double checked" }, error: null }));
});
} catch (err2) {
console.log("invoke threw an error in: add registrar");
err3 = new Error();
err3.code = 503;
err3.message = "Oops the blockchain is overloaded, please try again.";
callback(err3, null);
}
}
});
}
});
}
});
}
}
}
});
}
} else {
res.send("User is not admin");
}
}
}
});
});
//******************************************************************************************ROUTES-REGISTRAR ONLY
//locked by electon that has ended
app.post('/registerVoter', function (req, res) {
//REQUIRES: the government ID of the voter, the name of the registrar who is doing the registration, the JWT token for the registrar
//PROMISES: if this voter has not yet been registered, and the registrar is registered, the voter will be have a registration record created for them.
res.setHeader('Content-Type', 'application/json');
var govID = req.body.govID;
var registrarName = req.body.registrarName;
if (!govID || !registrarName) {
err = new Error();
err.code = 400;
err.message = "you need to supply: the voter's govID and the registrar name";
console.log(err.message);
res.send(JSON.stringify({ error: err, response: null }));
} else {
// Read chaincodeID and use this for sub sequent Invokes/Queries
readDocument(config.chainName, function (err, resp) { //not_found is the err.error if not found
if (err) {
err.code = 503;
err.message = "error reading election data from database";
res.send(JSON.stringify({ error: err, response: null }));
}
else {
chaincodeID = resp.electionData.chaincodeID;
districts = resp.electionData.districts;
voteOptions = resp.electionData.voteOptions;
startDate = resp.electionData.electionStart;
endDate = resp.electionData.electionEnd;
chain.getUser("admin", function (err, user) {
if (err) {
err2 = new Error();
err2.code = 500;
err2.message = " Failed to register and enroll admin: " + err;
res.send(JSON.stringify({ error: err2, response: null }));
} else {
userObj = user;
var currDate = new Date();
if (currDate > endDate || currDate < startDate) {
err = new Error();
err.code = 400;
err.message = "The election is closed";
console.log(err.message);
res.send(JSON.stringify({ error: err, response: null }));
} else {
//check if this person has already registered
read("admin", govID, function (err, readResp) {
if (readResp) {
err2 = new Error();
err2.code = 400;
err2.message = "User with govID " + govID + " is already registered";
delete err2.stack;
console.log(err2.message);
res.send(JSON.stringify({ error: err2, response: null }));
}
else {
//check if this registar is registered
read("admin", "registarInfo", function (err, readResp) {
if (!readResp) {
err2 = new Error();
err2.code = 500;
err2.message = "There are no registrars registered";
delete err2.stack;
res.send(JSON.stringify({ error: err2, response: null }));
} else if (!JSON.parse(readResp).hasOwnProperty(registrarName)) {
err2 = new Error();
err2.code = 500;
err2.message = " The registrar " + registrarName + " is not registered ";
delete err2.stack;
res.send(JSON.stringify({ error: err2, response: null }));
} else {
var args2 = [];
args2.push(govID);
args2.push(registrarName);
try {
invoke(args2, "register", function (err, resp) {
res.send(JSON.stringify({ response: { code: 200, disclaimer: "This registration needs to be double checked" }, error: null }));
});
} catch (err2) {
console.log("invoke threw an error in: registerVoter");
err3 = new Error();
err3.code = 503;
err3.message = "Oops the blockchain is overloaded, please try again.";
callback(err3, null);
}
}
});
}
});
}
}
});
}
});
}
});
//******************************************************************************************ROUTES-OPEN ROUTES
app.post('/VoterRegRecord', function (req, res) {
//REQUIRES:
//POST username: govID of A registered voter
//PROMISES: the registration record of the voter if they have one
res.setHeader('Content-Type', 'application/json');
var govID = req.body.govID;
read("admin", govID, function (err, readRes) {
if (err) {
if (err.message.includes("No data exists for")) {
err.message = "voter with govID " + govID + " has not yet registered to vote";
}
res.send(JSON.stringify({ error: err, response: null }));
}
else {
res.send(JSON.stringify({ response: readRes, error: null }));
}
});
});
//locked when live results are not allowed and election is running
app.post('/readDistrict', function (req, res) {
/*REQUIRES:
POST district: name of district you want to get information about
PROMISES: data about the district, if valid
*/
res.setHeader('Content-Type', 'application/json');
var district = req.body.district;
function readDistrictCallback(err, readRes) {
if (err) {
if (err.message.includes("No data exists for")) {
err.message = district + " is not a valid district";
}
res.send(JSON.stringify({ error: err, response: null }));
}
else {
res.send(JSON.stringify({ response: readRes, error: null }));
}
}
readDocument(config.chainName, function (err, resp) {
if (err) {
err.code = 503;
err.message = "error reading election info from database";
res.send(JSON.stringify({ error: err, response: null }));
}
else {
chaincodeID = resp.electionData.chaincodeID;
districts = resp.electionData.districts;
voteOptions = resp.electionData.voteOptions;
startDate = resp.electionData.electionStart;
endDate = resp.electionData.electionEnd;
allowLiveResults = resp.electionData.liveResults;
var currDate = Date.now();
if (currDate < endDate) {
//election open
console.log("allowLiveResults: " + allowLiveResults)
if (allowLiveResults === "no") {
err = new Error();
err.code = 400;
err.message = "Live results not allowed for this election, please wait for it to finish";
delete err.stack;
res.send(JSON.stringify({ error: err, response: null }));
} else {
read("admin", district, function (err, readRes) {
readDistrictCallback(err, readRes);
});
}
} else {
//election closed
read("admin", district, function (err, readRes) {
readDistrictCallback(err, readRes);
});
}
}
});
});
app.post('/readVote', function (req, res) {
/*REQUIRES: a signedToken ID and and signedToken Signature for a voter that has already voted
PROMISES: if a vote has been registered with the signedToken, the vote will be returned.
*/
res.setHeader('Content-Type', 'application/json');
var signedTokenID = req.body.signedTokenID
var signedTokenSig = req.body.signedTokenSig
read("admin", signedTokenID + signedTokenSig, function (err, readRes) {
if (err) {
if (err.message.includes("No data exists for")) {
err.message = "No vote exists for a voter with signed token: " + signedTokenID + signedTokenSig;
}
res.send(JSON.stringify({ error: err, response: null }));
}
else {
res.send(JSON.stringify({ response: readRes, error: null }));
}
});
});
app.get('/getElectionInfo', function (req, res) {
//REQUIRES: for an election to have been deployed from the config file
//PROMISES: name of election, districts inside of it, and the options for voting*/
res.setHeader('Content-Type', 'application/json');
readDocument(config.chainName, function (err, resp) { //not_found is the err.error if not found
if (err) {
err.code = 503;
err.message = "error reading election info from database databse";
res.send(JSON.stringify({ error: err, response: null }));
}
else {
delete resp.electionData.chaincodeID;
delete resp._rev;
resp.electionData.electionStart = (new Date(resp.electionData.electionStart));
resp.electionData.electionEnd = (new Date(resp.electionData.electionEnd));
console.log(resp);
res.send(JSON.stringify({ response: resp, error: null }));
}
});
});
//locked when live results are not allowed and election is running
app.get('/results', function (req, res) {
//REQUIRES: for an election to have been deployed from the config file
//PROMISES: get overall results of election, plus number of districts and the name of the eleciton
res.setHeader('Content-Type', 'application/json');
function resultReadCallback(err, readRes) {
if (err) {
if (err.message.includes("No data exists for")) {
err.message = "election has not yet been initializied properly";
}
res.send(JSON.stringify({ error: err, response: null }));
} else {
res.send(JSON.stringify({ response: readRes, error: null }));
}
}
readDocument(config.chainName, function (err, resp) {
if (err) {
err.code = 503;
err.message = "error reading election info from database";
res.send(JSON.stringify({ error: err, response: null }));
}
else {
chaincodeID = resp.electionData.chaincodeID;
districts = resp.electionData.districts;
voteOptions = resp.electionData.voteOptions;
startDate = resp.electionData.electionStart;
endDate = resp.electionData.electionEnd;
allowLiveResults = resp.electionData.liveResults;
var currDate = Date.now();
if (currDate < endDate) {
//election open
console.log("allowLiveResults: " + allowLiveResults)
if (allowLiveResults === "no") {
err = new Error();
err.code = 400;
err.message = "Live results not allowed for this election, please wait for it to finish";
delete err.stack;
res.send(JSON.stringify({ error: err, response: null }));
} else {
read("admin", "metadata", function (err, readRes) {
resultReadCallback(err, readRes);
});
}
} else {
//election closed
read("admin", "metadata", function (err, readRes) {
resultReadCallback(err, readRes);
});
}
}
});
});
app.get('/getRegistrarInfo', function (req, res) {
//REQUIRES: for an election to have been deployed from the config file
//PROMISES: get information about the registrars in the system
res.setHeader('Content-Type', 'application/json');
read("admin", "registarInfo", function (err, readRes) {
if (err) {
if (err.message.includes("No data exists for")) {
err.message = "no registrars have been added yet";
}
res.send(JSON.stringify({ error: err, response: null }));
} else {
var readResJSON = JSON.parse(readRes);
var registrars = [];
for (var i in readResJSON) {
var reg = readResJSON[i];
var registrar = {
"Registrar": {
"RegistrarName": i,
"KeyModulus": reg.KeyModulus,
"KeyExponent": reg.KeyExponent,
"RegistrationDistrict": reg.RegistrationDistrict
},
};
registrars.push(registrar);
}
var registrarsJSON = JSON.stringify(registrars);
res.send(JSON.stringify({ response: registrarsJSON, error: null }));
}
});
});
//locked by electon that has ended
app.post('/writeVote', function (req, res) {
res.setHeader('Content-Type', 'application/json');
var signedTokenID = req.body.signedTokenID
var signedTokenSig = req.body.signedTokenSig
var vote = req.body.vote
var registrarName = req.body.registrarName
if (!signedTokenID || !signedTokenSig || !vote || !registrarName) {
err = new Error();
err.code = 400;
err.message = "you need to supply: a voter's signedTokenID and signedTokenSig , a vote, and the name of the registrar who authorized the user";
console.log(err.message);
res.send(JSON.stringify({ error: err, response: null }));
}
else {
// Read chaincodeID and use this for sub sequent Invokes/Queries
readDocument(config.chainName, function (err, resp) { //not_found is the err.error if not found
if (err) {
err.code = 503;
err.message = "error reading election info from database";
res.send(JSON.stringify({ error: err, response: null }));
}
else {
chaincodeID = resp.electionData.chaincodeID;
districts = resp.electionData.districts;
voteOptions = resp.electionData.voteOptions;
startDate = resp.electionData.electionStart;
endDate = resp.electionData.electionEnd;
var currDate = new Date();
if (currDate > endDate || currDate < startDate) {
err = new Error();
err.code = 400;
err.message = "The election is closed";
delete err.stack;
console.log(err.message);
res.send(JSON.stringify({ error: err, response: null }));
} else {
if (voteOptions.indexOf(vote) === -1) {
err = new Error();
err.code = 400;
err.message = vote + " is an invalid vote";
console.log(err.message);
res.send(JSON.stringify({ error: err, response: null }));
}
else {
chain.getUser("admin", function (err, user) {
if (err) {
err2 = new Error();
err2.code = 500;
err2.message = " Failed to register and enroll admin"
res.send(JSON.stringify({ error: err2, response: null }));
} else {
userObj = user;
//check if this registar is registered
read("admin", "registarInfo", function (err, readResp) {
if (!readResp) {
err2 = new Error();
err2.code = 500;
err2.message = "There are no registrars registered";
delete err2.stack;
res.send(JSON.stringify({ error: err2, response: null }));
} else if (!JSON.parse(readResp).hasOwnProperty(registrarName)) {
err2 = new Error();
err2.code = 500;
err2.message = " The registrar " + registrarName + " is not registered ";
delete err2.stack;
res.send(JSON.stringify({ error: err2, response: null }));
}
else {
//check if this person has already voted
read("admin", signedTokenID + signedTokenSig, function (err, readResp) {
if (readResp) { //record found
err2 = new Error();
err2.code = 500;
err2.message = "user with signedToken" + signedTokenID + signedTokenSig + " has already voted"
delete err2.stack;
res.send(JSON.stringify({ error: err2, response: null }));
}
else { // no record found
if (!err.message.includes("No data exists for")) { //read error apart from no document found
res.send(JSON.stringify({ error: err, response: null }));
} else {
var CRYPTOVERIFIED = true
if (!CRYPTOVERIFIED) { //need actual crypto solution in nodeJS
err2 = new Error();
err2.code = 500;
err2.message = "user with signedToken" + signedTokenID + signedTokenSig + " is not authorized to vote by " + registrarName
delete err2.stack;
res.send(JSON.stringify({ error: err2, response: null }));
} else {
//can now invoke, query, etc
var args2 = [];
args2.push(signedTokenID);
args2.push(signedTokenSig);
args2.push(vote);
args2.push(registrarName);
try {
invoke(args2, "writeVote", function (err, resp) {
res.send(JSON.stringify({ response: { code: 200, disclaimer: "This vote needs to be double checked" }, error: null }));
});
} catch (err2) {
console.log("invoke threw an error in: writevote");
err3 = new Error();
err3.code = 503;
err3.message = "Oops the blockchain is overloaded, please try again.";
callback(err3, null);
}
}
}
}
});
}
});
}
});
}
}
}
});
}
});
//******************************************************************************************HFC FUNCTIONS
function init(callback) { //INITIALIZATION
console.log("Initializing chaincode from config.json");
try {
config = JSON.parse(fs.readFileSync(__dirname + '/config.json', 'utf8')); //TURN CONFIG.JSON INTO CONFIG OBJECT
} catch (err) {
err.message = "config.json is missing or invalid file, Rerun the program with right file";
err.code = 500;
console.log(err.message)
callback(err, null)
}
if (config.deployRequest.args.length < 16) {
err = new Error();
err.code = 500;
err.message = "Incorrect number of arguments for init. Check config file";
console.log(err.message);
callback(err, null);
} else { //only continue if we have the min amount of args
//new user that this whole process creates
newUserName = config.user.username;
// Create a client blockchin.
if (!chain)
chain = hfc.newChain(config.chainName); //USE THE GIVEN CHAIN NAME TO CREATE A CHAIN OBJECT
certPath = __dirname + "/src/" + config.deployRequest.chaincodePath + "/certificate.pem"; //CREATE PATH TO ADD THE CERTIFICATE
// Read and process the credentials.json
try {
network = JSON.parse(fs.readFileSync(__dirname + '/ServiceCredentials.json', 'utf8')); //TURN SERVICECREDENTIALS.JSON INTO NETWORK OBJECT
if (network.credentials) network = network.credentials;
} catch (err) {
err.code = 500;
err.message = "ServiceCredentials.json is missing or invalid file, Rerun the program with right file";
console.log(err.message);
callback(err, null)
}
peers = network.peers; // EXTRACT PEERS FROM NETWORK OBJECT
users = network.users; // EXTRACT USERS FROM NETWORK OBJECT
setup(); //CALL SET UP: ADDS PEERS FROM SERVICE CREDENTIALS TO BLOCKCHAIN. ALSO GETS THE USERNAME FOR THE NEW USER IN CONFIG
printNetworkDetails();
console.log("attempting to read election meta-data from DB");
readDocument(config.chainName, function (err, resp) { //not_found is the err.error if not found
if (!err) {
console.log("the election data for " + config.chainName + " was found on the DB");
chaincodeIDKnown = true;
chaincodeID = resp.electionData.chaincodeID;
districts = resp.electionData.districts;
voteOptions = resp.electionData.voteOptions;
}
else if (err.error === "not_found") {
console.log("the election meta-data for " + config.chainName + " was not found on the DB");
chaincodeIDKnown = false;
} else if (err.error !== "not_found") {
console.log("some other error happened: " + err);
err.message = "unknown error happened on the database"
err.code = 503;
callback(err, null);
}
if (chaincodeIDKnown) {
console.log("Chaincode was already deployed and users are ready! You can now invoke and query");
console.log("election districts: " + districts);
err = new Error();
err.code = 202;
err.message = "deployment: chaincode already deployed. Ready to invoke and query"
delete err.stack;
callback(err, null);
} else {
enrollAndRegisterUsers(callback); //ENROLL THE PRE-REGISTERED ADMIN (FROM membersrvc.YAML) AND SERVICECREDENTIALS, CALL deployChaincode!
}
});
}
}
function setup() {
// Determining if we are running on a startup or HSBN network based on the url
// of the discovery host name. The HSBN will contain the string zone.
var isHSBN = peers[0].discovery_host.indexOf('secure') >= 0 ? true : false;
var network_id = Object.keys(network.ca);
caUrl = "grpcs://" + network.ca[network_id].discovery_host + ":" + network.ca[network_id].discovery_port;
// Configure the KeyValStore which is used to store sensitive keys.
// This data needs to be located or accessible any time the users enrollmentID
// perform any functions on the blockchain. The users are not usable without
// This data.
var uuid = network_id[0].substring(0, 8);
chain.setKeyValStore(hfc.newFileKeyValStore(__dirname + '/keyValStore-' + uuid));
if (isHSBN) {
console.log("we are running on a HSBN Network");
certFile = '0.secure.blockchain.ibm.com.cert';
}
else {
console.log("we are running on a startup Network");
}
fs.createReadStream(certFile).pipe(fs.createWriteStream(certPath));
var cert = fs.readFileSync(certFile);
chain.setMemberServicesUrl(caUrl, {
pem: cert
});
peerUrls = [];
eventUrls = [];
// Adding all the peers to blockchain
// this adds high availability for the client
for (var i = 0; i < peers.length; i++) {
// Peers on Bluemix require secured connections, hence 'grpcs://'
peerUrls.push("grpcs://" + peers[i].discovery_host + ":" + peers[i].discovery_port);
chain.addPeer(peerUrls[i], {
pem: cert
});
eventUrls.push("grpcs://" + peers[i].event_host + ":" + peers[i].event_port);
/*
chain.eventHubConnect(eventUrls[0], {
pem: cert
});
*/
}
// Make sure disconnect the eventhub on exit
/*
process.on('exit', function () {
chain.eventHubDisconnect();
});
*/
}
function enrollAndRegisterUsers(callback) { //enrolls admin
// Enroll a 'admin' who is already registered because it is
// listed in fabric/membersrvc/membersrvc.yaml with it's one time password.
chain.enroll(users[0].enrollId, users[0].enrollSecret, function (err, admin) {
if (err) {
err = new Error();
err.code = 500;
err.message = "failed to enroll admin : " + err;
callback(err, null)
}
console.log("\nEnrolled admin sucecssfully");
// Set this user as the chain's registrar which is authorized to register other users.
chain.setRegistrar(admin);
//register and enroll our custom user (would be nice to refactor this out)
//creating a new user