forked from Tribler/trustchain-superapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVotingActivity.kt
345 lines (295 loc) · 11.4 KB
/
VotingActivity.kt
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
package nl.tudelft.trustchain.voting
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.os.Bundle
import android.text.Html
import android.text.format.DateFormat
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.Switch
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main_voting.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import nl.tudelft.ipv8.android.IPv8Android
import nl.tudelft.ipv8.attestation.trustchain.TrustChainBlock
import nl.tudelft.ipv8.keyvault.PublicKey
import nl.tudelft.ipv8.keyvault.defaultCryptoProvider
import nl.tudelft.trustchain.common.util.TrustChainHelper
import nl.tudelft.trustchain.common.util.VotingHelper
import nl.tudelft.trustchain.common.util.VotingMode
import org.json.JSONException
import org.json.JSONObject
class VotingActivity : AppCompatActivity() {
private lateinit var vh: VotingHelper
private lateinit var community: VotingCommunity
private lateinit var adapter: BlockListAdapter
private lateinit var tch: TrustChainHelper
private var voteProposals: MutableList<TrustChainBlock> = mutableListOf()
private var displayAllVotes: Boolean = true
/**
* Setup method, binds functionality
*/
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_voting)
title = "TrustChain Voter"
initiateButton.setOnClickListener {
showNewVoteDialog()
}
uncastedToggle.setOnCheckedChangeListener { _, isChecked ->
displayAllVotes = if (isChecked) {
proposalOverViewTitle.text = "New Proposals"
printShortToast("Displaying proposals to cast on")
false
} else {
proposalOverViewTitle.text = "All Proposals"
printShortToast("Displaying all proposals")
true
}
}
// Initiate community and helpers
val ipv8 = IPv8Android.getInstance()
community = ipv8.getOverlay()!!
vh = VotingHelper(community)
tch = TrustChainHelper(community)
blockList.layoutManager = LinearLayoutManager(this)
adapter = BlockListAdapter(voteProposals, vh)
adapter.onItemClick = { block ->
try {
showNewCastVoteDialog(block)
showVoteCompletenessToast(block)
} catch (e: Exception) {
printShortToast(e.message.toString())
}
}
blockList.adapter = adapter
periodicUpdate()
}
/**
* Display a short message on the screen
*/
private fun printShortToast(s: String) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show()
}
/**
* Dialog for creating a new proposal
*/
@SuppressLint("InflateParams")
private fun showNewVoteDialog() {
val dialogView = LayoutInflater.from(this).inflate(R.layout.initiate_dialog, null)
val builder = AlertDialog.Builder(this)
.setView(dialogView)
.setTitle("Initiate vote on proposal")
val switch = dialogView.findViewById<Switch>(R.id.votingModeToggle)
val switchLabel = dialogView.findViewById<TextView>(R.id.votingMode)
switchLabel.text = getString(R.string.yes_no_mode)
var votingMode = VotingMode.YESNO
switch.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
switchLabel.text = getString(R.string.threshold_mode)
votingMode = VotingMode.THRESHOLD
} else {
switchLabel.text = getString(R.string.yes_no_mode)
votingMode = VotingMode.YESNO
}
}
builder.setPositiveButton("Create") { _, _ ->
val proposal = dialogView.findViewById<EditText>(R.id.proposalInput).text.toString()
// Create list of your peers and include yourself
val peers: MutableList<PublicKey> = ArrayList()
peers.addAll(community.getPeers().map { it.publicKey })
peers.add(community.myPeer.publicKey)
// Start voting procedure
vh.createProposal(proposal, peers, votingMode)
printShortToast("Proposal has been created")
}
// NeutralButton is always the leftmost button
builder.setNeutralButton("Cancel") { dialog, _ ->
dialog.cancel()
}
builder.show()
}
/**
* Make user aware of proposal status through toast message.
*/
private fun showVoteCompletenessToast(block: TrustChainBlock) {
val completed = vh.votingIsComplete(block, VotingCommunity.threshold)
if (completed) {
printShortToast("Voting has been completed.")
} else {
printShortToast("Voting still open.")
}
}
/**
* Show dialog from which the user can propose a vote
*/
private fun showNewCastVoteDialog(block: TrustChainBlock) {
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
// Parse the 'message' field as JSON.
var voteSubject = ""
var votingMode = VotingMode.YESNO
try {
val voteJSON = JSONObject(block.transaction["message"].toString())
voteSubject = voteJSON.get("VOTE_SUBJECT").toString()
votingMode = VotingMode.valueOf(voteJSON.get("VOTE_MODE").toString())
} catch (e: JSONException) {
"Block was a voting block but did not contain " +
"proper JSON in its message field: ${block.transaction["message"]}."
}
// Convert block date to simpler format
val date = DateFormat.format("EEE MMM d HH:mm", block.timestamp).toString()
val previouslyCastedVotes = vh.castedByPeer(block, community.myPeer.publicKey)
val hasCasted = when {
previouslyCastedVotes.first == 1 -> {
"Yes"
}
previouslyCastedVotes.second == 1 -> {
"No"
}
else -> {
null
}
}
val castedString = if (hasCasted != null) {
when (votingMode) {
VotingMode.YESNO -> {
"<br><br>" +
"<small><b>You have voted</b>: <i>" +
hasCasted +
"</i></small>"
}
VotingMode.THRESHOLD -> {
"<br><br><small><b>You have voted</b>: <i>Agree</i></small>"
}
}
} else {
""
}
// Get tally values
val tally = getTally(voteSubject, block)
// Show vote subject, proposer and current tally
builder.setMessage(
Html.fromHtml(
"<big>\"" + voteSubject + "\"</big>" +
"<br><br>" +
"<small><b>Proposed by</b>:" +
"<br>" +
"<i>" + defaultCryptoProvider.keyFromPublicBin(block.publicKey) + "</i></small>" +
"<br><br>" +
"<small><b>Date</b>: " +
"<i>" + date + "</i></small>" +
castedString +
"<br><br>" +
"<small><b>" + (if (vh.votingIsComplete(
block,
VotingCommunity.threshold
)
) "Final result" else "Current tally") + "</b>:" +
"<br>" +
when (votingMode) {
VotingMode.YESNO -> {
"Yes votes: " + tally.first +
" | No votes: " + tally.second
}
VotingMode.THRESHOLD -> {
tally.first.toString() + " in favour"
}
} + "</small></i>",
Html.FROM_HTML_MODE_LEGACY
)
)
// Display vote options is not previously casted a vote
if (hasCasted == null) {
builder.setTitle("Cast vote on proposal:")
when (votingMode) {
VotingMode.YESNO -> {
builder.setPositiveButton("YES") { _, _ ->
vh.respondToProposal(true, block)
printShortToast("You voted: YES")
}
builder.setNegativeButton("NO") { _, _ ->
vh.respondToProposal(false, block)
printShortToast("You voted: NO")
}
}
VotingMode.THRESHOLD -> {
builder.setPositiveButton("AGREE") { _, _ ->
vh.respondToProposal(true, block)
printShortToast("You voted: AGREE")
}
}
}
// NeutralButton is always the leftmost button
builder.setNeutralButton("CANCEL") { dialog, _ ->
printShortToast("No vote was cast")
dialog.cancel()
}
} else {
builder.setTitle("Inspect proposal:")
// NeutralButton is always the leftmost button
builder.setNeutralButton("Exit") { dialog, _ ->
dialog.cancel()
}
}
builder.setCancelable(true)
builder.show()
}
/**
* Count votes and return tally
*/
private fun getTally(voteSubject: String, block: TrustChainBlock): Pair<Int, Int> {
val peers: MutableList<PublicKey> = ArrayList()
peers.addAll(community.getPeers().map { it.publicKey })
peers.add(community.myPeer.publicKey)
return vh.countVotes(peers, voteSubject, block.publicKey)
}
/**
* Periodically update vote proposal set
*/
private fun periodicUpdate() {
lifecycleScope.launchWhenStarted {
while (isActive) {
proposalListUpdate()
delay(1000)
}
}
}
/**
* Update the list of proposals
*/
private fun proposalListUpdate() {
val currentProposals = tch.getBlocksByType("voting_block").filter {
// Only the original proposal blocks.
!JSONObject(it.transaction["message"].toString()).has("VOTE_REPLY") &&
// Only those that you are eligible for
vh.getVoters(it).any { key ->
key.pub().keyToBin()
.contentEquals(community.myPeer.publicKey.keyToBin())
} &&
// Take display mode into consideration
displayBlock(
it
)
}.asReversed()
// Update vote proposal set
if (voteProposals != currentProposals) {
voteProposals.clear()
voteProposals.addAll(currentProposals)
}
adapter.notifyDataSetChanged()
}
/**
* Check if proposal block should be displayed
*/
private fun displayBlock(block: TrustChainBlock): Boolean {
if (displayAllVotes) return true
val votePair = vh.castedByPeer(block, community.myPeer.publicKey)
return votePair == Pair(0, 0)
}
}