forked from Tribler/kotlin-ipv8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FrostCommunity.kt
318 lines (280 loc) · 10.6 KB
/
FrostCommunity.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
package me.rahimklaber.frosttestapp.ipv8
import FIleLogger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import me.rahimklaber.frosttestapp.ipv8.message.*
import nl.tudelft.ipv8.Community
import nl.tudelft.ipv8.Peer
import nl.tudelft.ipv8.messaging.Packet
import nl.tudelft.ipv8.messaging.eva.takeInRange
import nl.tudelft.ipv8.messaging.payload.IntroductionResponsePayload
import java.util.*
import kotlin.random.Random
data class FrostMemberInfo(
val peer : String, //use mid instead of peer. if the peer is offline, then `Peer` wont wor
val index: Int, // index in FROST scheme
)
//enum class FrostState(val id: Long){
// NotReady,
// ReadyForKeyGen,
// RequestedToJoin(,
// KeyGenStep1,
// KeyGenStep2,
// KeyGenStep3,
// ReadyForSign
//}
data class FrostGroup(
// members is without us
val members: List<FrostMemberInfo>,
val myIndex: Int,
val threshold: Int
){
val amount : Int
get() = members.size + 1 // we are not included here
}
//typealias OnJoinRequestCallBack = (Peer, RequestToJoinMessage) -> Unit
//typealias onJoinRequestResponseCallback = (Peer, RequestToJoinResponseMessage) -> Unit
class FrostCommunity: Community() {
override val serviceId: String
// get() = "5ce0aab9123b60537030b1312783a0ebcf5fd92f"
get() = "3ce0aab9123b60537030b1312783a0ebcf5fd92f"
private val _channel = MutableSharedFlow<Pair<Peer,FrostMessage>>(extraBufferCapacity = 10) //todo check this
private val _filteredChannel = MutableSharedFlow<Pair<Peer,FrostMessage>>(extraBufferCapacity = 10)
val channel = _filteredChannel.asSharedFlow()
//todo this should be a mutable flow
// fun getMsgChannel(): Flow<Pair<Peer, FrostMessage>> {
// return _channel.filter {(peer, msg) ->
// val contains = received.containsKey(peer.mid to msg.hashCode())
// if (!contains){
// Log.d("FROST", "Does not contain $msg")
// received[peer.mid to msg.hashCode()]=true
// true
// }else{false}
// }
// }
val lastResponseFrom = mutableMapOf<String,Date>()
override fun onIntroductionResponse(peer: Peer, payload: IntroductionResponsePayload) {
super.onIntroductionResponse(peer, payload)
lastResponseFrom[peer.mid] = Date()
}
var onAckCbId = 0;
val onAckCallbacks= mutableMapOf<Int,suspend (peer: Peer,ack:Ack)->Unit>()
private val ackCbMutex = Mutex()
//todo, check if we need to lock
suspend fun addOnAck(cb: suspend (peer: Peer,ack:Ack)->Unit) : Int{
ackCbMutex.withLock {
val id = onAckCbId++;
onAckCallbacks[id] = cb
return id
}
}
suspend fun removeOnAck(id: Int){
ackCbMutex.withLock {
onAckCallbacks.remove(id)
}
}
init {
messageHandlers[StartKeyGenMsg.MESSAGE_ID] = {packet ->
val pair = packet.getAuthPayload(StartKeyGenMsg.Deserializer)
scope.launch(Dispatchers.Default) {
_channel.emit(pair)
}
}
//todo maybe deserialize
messageHandlers[RequestToJoinMessage.MESSAGE_ID] = {packet ->
val pair = packet.getAuthPayload(RequestToJoinMessage.Deserializer)
// error("received ${pair.second}")
//todo check this
scope.launch(Dispatchers.Default) {
_channel.emit(pair)
}
}
messageHandlers[RequestToJoinResponseMessage.MESSAGE_ID] = {packet ->
val pair = packet.getAuthPayload(RequestToJoinResponseMessage.Deserializer)
//todo check this
scope.launch(Dispatchers.Default) {
_channel.emit(pair)
}
}
messageHandlers[KeyGenCommitments.MESSAGE_ID] = { packet ->
val pair = packet.getAuthPayload(KeyGenCommitments.Deserializer)
//todo check this
scope.launch(Dispatchers.Default) {
_channel.emit(pair)
}
}
messageHandlers[KeyGenShare.MESSAGE_ID] = { packet ->
val pair = packet.getAuthPayload(KeyGenShare.Deserializer)
//todo check this
scope.launch(Dispatchers.Default) {
_channel.emit(pair)
}
}
messageHandlers[Preprocess.MESSAGE_ID] = { packet ->
val pair = packet.getAuthPayload(Preprocess.Deserializer)
//todo check this
scope.launch(Dispatchers.Default) {
_channel.emit(pair)
}
}
messageHandlers[SignShare.MESSAGE_ID] = { packet ->
val pair = packet.getAuthPayload(SignShare.Deserializer)
//todo check this
scope.launch(Dispatchers.Default) {
_channel.emit(pair)
}
}
messageHandlers[SignRequest.MESSAGE_ID] = { packet ->
val pair = packet.getAuthPayload(SignRequest.Deserializer)
//todo check this
scope.launch(Dispatchers.Default) {
_channel.emit(pair)
}
}
messageHandlers[SignRequestResponse.MESSAGE_ID] = { packet ->
val pair = packet.getAuthPayload(SignRequestResponse.Deserializer)
//todo check this
scope.launch(Dispatchers.Default) {
_channel.emit(pair)
}
}
messageHandlers[GossipRequest.MESSAGE_ID] = { packet ->
val (peer,msg) = packet.getAuthPayload(GossipRequest.Deserializer)
//todo check this
scope.launch(Dispatchers.Default) {
}
}
messageHandlers[GossipResponse.MESSAGE_ID] = {packet ->
val (peer,msg) = packet.getAuthPayload(GossipResponse.Deserializer)
getPeers().find{
it.mid == msg.originallyFromMid
}// so if we know the peer, then we should do something. Otherwise it probably doesn't matter
?.also {originalPeer ->
scope.launch(Dispatchers.Default) {
_channel.emit(originalPeer to msg.payload)
}
}
}
messageHandlers[Ack.MESSAGE_ID] = {packet ->
val (peer,msg) = packet.getAuthPayload(Ack.Deserializer)
scope.launch(Dispatchers.Default) {
ackCbMutex.withLock {
onAckCallbacks.forEach { (i, callback) -> scope.launch(Dispatchers.Default){ callback(peer,msg) }}
}
}
}
evaProtocolEnabled = true
}
override fun load() {
super.load()
setOnEVAErrorCallback{ peer, exception ->
scope.launch {
FIleLogger("eva error: $exception")
}
}
setOnEVAReceiveCompleteCallback { peer, info, id, data ->
scope.launch {
FIleLogger("received eva stuff")
}
if (data == null){
return@setOnEVAReceiveCompleteCallback
}
if (info!= EVA_FROST_DAO_attachment)
return@setOnEVAReceiveCompleteCallback
data.let {
val packet = Packet(peer.address,data.takeInRange(1,data.size))
messageHandlers[data[0].toInt()]?.let { it1 -> it1(packet) }
}
}
scope.launch(Dispatchers.Default) {
_channel.collect {(peer, msg) ->
val contains = received.containsKey(peer.mid to msg.hashCode())
if (!contains){
received[peer.mid to msg.hashCode()]=true
_filteredChannel.emit(peer to msg)
}
}
}
scope.launch(Dispatchers.Default){
_channel.collect{(peer,msg)->
FIleLogger("Sending ack for $msg")
sendAck(peer, Ack(msg.hashCode()))
}
}
scope.launch(Dispatchers.Default) {
var afterDate = Date().time / 1000
while (true) {
delay(delayAmount + 600_000)
//after 2 min ( so everything loads), as send gossiprequest
val request = GossipRequest(afterDate)
val packet = serializePacket(GossipRequest.MESSAGE_ID, request)
for (peer in getPeers()) {
scope.launch(Dispatchers.Default) {
send(peer, packet)
}
sent[peer.mid to request.hashCode()] = true
}
}
}
}
fun sendEva (peer: Peer, msg: FrostMessage){
val id = messageIdFromMsg(msg)
val packet = listOf(id.toByte()) + serializePacket(id,msg).toList()
evaSendBinary(peer, EVA_FROST_DAO_attachment,"${msg.id}$id",packet.toByteArray())
}
fun broadcastEva(msg : FrostMessage){
val id = messageIdFromMsg(msg)
val packet = listOf(id.toByte()) + serializePacket(id,msg).toList()
for (peer in getPeers()) {
evaSendBinary(peer, EVA_FROST_DAO_attachment,"${msg.id}$id",packet.toByteArray())
}
}
// store that we received a msg.
// (mid,hash) -> Boolean
val sent = mutableMapOf<Pair<String,Int>,Boolean>()
val received = mutableMapOf<Pair<String,Int>,Boolean>()
// better name lol
suspend fun sendForPublic(peer: Peer, msg: FrostMessage) {
// Log.d("FROST", "sending msg $msg in community")
val id = messageIdFromMsg(msg)
val packet = serializePacket(id,msg)
// scope.launch(Dispatchers.Default) {
// repeat(10){
//
// }
// }
if(msg.serialize().size < 1000){
send(peer,packet)
}else{
FIleLogger("sending eva")
sendEva(peer,msg)
}
sent[peer.mid to msg.hashCode()] = true
}
fun sendProposalStatusRequest(peer: Peer ,request: ProposalStatusRequest){
val packet = serializePacket(ProposalStatusRequest.MESSAGE_ID,request)
send(peer,packet)
}
fun sendAck(peer: Peer,ack: Ack){
val packet = serializePacket(Ack.MESSAGE_ID,ack)
send(peer,packet)
}
fun broadcast(msg : FrostMessage){
//todo fix this
val packet = serializePacket(messageIdFromMsg(msg),msg)
for (peer in getPeers()) {
scope.launch(Dispatchers.Default) {
send(peer,packet)
}
sent[peer.mid to msg.hashCode()] = true
}
}
companion object {
const val EVA_FROST_DAO_attachment = "eva_frost_attachment"
const val delayAmount = /*5 * 60 * 1000L*/ 1000L
}
}