-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelection_voting_test.sol
executable file
·105 lines (89 loc) · 2.54 KB
/
election_voting_test.sol
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
pragma solidity ^0.4.0;
contract Votes {
address owner;
address public electionWinnerAddress;
uint public winnerVotes;
string public electionWinner;
Citizen[] public voters;
Candidate[] public candidates;
struct Citizen {
string name;
address citizenAddress;
address vote;
bool didVote;
}
struct Candidate {
string name;
address candidateAddress;
uint votes;
}
function Votes() {
owner = msg.sender;
}
modifier onlyOwner() {
if(owner == msg.sender) {
_;
} else {
revert();
}
}
modifier onlyCitizen() {
bool isCitizen = false;
for(uint i = 0; i < voters.length; i++) {
if(msg.sender == voters[i].citizenAddress) {
isCitizen = true;
}
}
if(isCitizen == true) {
_;
} else {
revert();
}
}
function Vote(address _candidateAddress) onlyCitizen {
uint amountOfVotes = 0;
for(uint i = 0; i < voters.length; i++) {
if(voters[i].citizenAddress == msg.sender && voters[i].didVote == false) {
voters[i].vote = _candidateAddress;
voters[i].didVote = true;
amountOfVotes += 1;
for(uint j = 0; j < candidates.length; j++) {
if(candidates[j].candidateAddress == _candidateAddress) {
candidates[j].votes += 1;
}
}
} else {
if(voters[i].didVote) {
amountOfVotes += 1;
}
}
}
if(amountOfVotes == voters.length) {
electionEnded();
}
}
function electionEnded() onlyOwner {
for(uint i = 0; i < candidates.length; i++) {
if(candidates[i].votes > winnerVotes) {
electionWinnerAddress = candidates[i].candidateAddress;
winnerVotes = candidates[i].votes;
electionWinner = candidates[i].name;
}
}
}
function addCandidate(address _address, string _name) onlyCitizen {
candidates.push(Candidate({
name: _name,
candidateAddress: _address,
votes: 0
}));
}
function addCitizen(address _citizenAddress, string _name) onlyOwner {
voters.push(Citizen({
name: _name,
citizenAddress: _citizenAddress,
vote: msg.sender,
didVote: false
}));
}
}