-
Notifications
You must be signed in to change notification settings - Fork 1
/
multilogue.go
1363 lines (1128 loc) · 37.4 KB
/
multilogue.go
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
package main
import (
"bufio"
"context"
"encoding/json"
"io/ioutil"
"log"
"os"
"reflect"
"sync"
"time"
p2p "github.com/assemblaj/Multilogue/pb"
"github.com/gogo/protobuf/proto"
protobufCodec "github.com/multiformats/go-multicodec/protobuf"
uuid "github.com/google/uuid"
inet "github.com/libp2p/go-libp2p-net"
peer "github.com/libp2p/go-libp2p-peer"
)
// pattern: /protocol-name/request-or-response-message/version
const clientJoinChannel = "/multilogue/clientjoinchannel/0.0.1"
const clientLeaveChannel = "/multilogue/clientleavechannel/0.0.1"
const clientSendMessage = "/multilogue/clientsendmessage/0.0.1"
const clientTransmissionStart = "/multilogue/clienttransmissionstart/0.0.1"
const clientTransmissionEnd = "/multilogue/clienttransmissionend/0.0.1"
const hostAcceptClient = "/multilogue/hostacceptclient/0.0.1"
const hostDenyClient = "/multilogue/hostdenyclient/0.0.1"
const hostAcceptTransmission = "/multilogue/hostaccepttransmission/0.0.1"
const hostDenyTransmission = "/multilogue/hostdenytransmission/0.0.1"
const hostBroadcastMessage = "/multilogue/hostbroadcastmessage/0.0.1"
// might add more data for statistics later
// join timestamp
// total messages
// etc etc
type Peer struct {
peerID peer.ID
username string
lastMessage time.Time // unix timestamp of last message
lastTransmission time.Time // unix timestamp of last transmission
}
type Message struct {
peer *Peer
timestamp time.Time
text string
}
func NewMessage(peer *Peer, message string) *Message {
return &Message{
peer: peer,
timestamp: time.Now(),
text: message}
}
type SyncedMap struct {
lock sync.RWMutex
values map[string]interface{}
valueType reflect.Type
}
func newSyncedMap(v interface{}) *SyncedMap {
return &SyncedMap{
values: make(map[string]interface{}),
valueType: reflect.TypeOf(v)}
}
func (t *SyncedMap) Get(key string) (interface{}, bool) {
t.lock.RLock()
defer t.lock.RUnlock()
value, found := t.values[key]
return value, found
}
func (t *SyncedMap) Size() int {
t.lock.RLock()
defer t.lock.RUnlock()
return len(t.values)
}
func (t *SyncedMap) Delete(key string) {
t.lock.Lock()
defer t.lock.Unlock()
delete(t.values, key)
}
func (t *SyncedMap) Put(key string, value interface{}) {
if reflect.TypeOf(value) == t.valueType {
t.lock.Lock()
defer t.lock.Unlock()
t.values[key] = value
}
}
func (t *SyncedMap) Range(f func(key, value interface{})) {
t.lock.RLock()
defer t.lock.RUnlock()
for k, v := range t.values {
t.lock.RUnlock()
f(k, v)
t.lock.RLock()
}
}
type OutputSession struct {
messageQueue chan *Message
queueSize int
}
func NewOutputSession(queueSize int) *OutputSession {
os := new(OutputSession)
os.queueSize = queueSize
os.messageQueue = make(chan *Message, os.queueSize)
return os
}
type Transmission struct {
channelId string
peer *Peer
totalMsgs int
startTime time.Time
done chan bool // notifies timer when transmission is ended
timeEnded bool
sync.RWMutex
}
type Channel struct {
channelId string
history []string // peer Ids of users who last spoke
peers *SyncedMap // slice of peer objects
// probably need a map of peerId to cooldown
currentTransmission *Transmission
output *OutputSession
config *ChannelConfig
sync.RWMutex
}
func NewChannel(channelId string, config *ChannelConfig) *Channel {
if config == nil {
config = DefaultChannelConfig()
}
c := &Channel{
channelId: channelId,
history: []string{},
peers: newSyncedMap(&Peer{}),
output: NewOutputSession(1), //TODO: Replace with some default/config
config: config}
return c
}
// Protocol Error States
type ProtocolErrorState int32
const (
NoError ProtocolErrorState = 100
GenericError ProtocolErrorState = 200
MessageLimitError ProtocolErrorState = 210
TimeLimitError ProtocolErrorState = 220
CooldownError ProtocolErrorState = 230
HistoryError ProtocolErrorState = 240
RatioError ProtocolErrorState = 250
)
// Prorbably want useful statistics in this eventually too
type Response struct {
errorCode ProtocolErrorState
}
func NewResponse(errorCode ProtocolErrorState) *Response {
return &Response{
errorCode: errorCode}
}
type Request struct {
success chan *Response
fail chan *Response
}
func NewRequest() *Request {
return &Request{
success: make(chan *Response),
fail: make(chan *Response)}
}
// MultilogueProtocol type
type MultilogueProtocol struct {
node *Node // local host
channels *SyncedMap // channelId : *Channel
requests *SyncedMap // used to access request data from response handlers
debug bool
logger *log.Logger
}
// NewMultilogueProtocol Create instance of protocol
// Might want a data object
func NewMultilogueProtocol(node *Node) *MultilogueProtocol {
p := &MultilogueProtocol{
node: node,
channels: newSyncedMap(&Channel{}),
requests: newSyncedMap(&Request{}),
debug: true,
logger: initDebugLogger()}
// Server functions
node.SetStreamHandler(clientJoinChannel, p.onClientJoinChannel)
node.SetStreamHandler(clientLeaveChannel, p.onClientLeaveChannel)
node.SetStreamHandler(clientSendMessage, p.onClientSendMessage)
node.SetStreamHandler(clientTransmissionStart, p.onClientTransmissionStart)
node.SetStreamHandler(clientTransmissionEnd, p.onClientTransmissionEnd)
// Client functions
node.SetStreamHandler(hostAcceptClient, p.onHostAcceptClient)
node.SetStreamHandler(hostDenyClient, p.onHostDenyClient)
node.SetStreamHandler(hostAcceptTransmission, p.onHostAcceptTransmission)
node.SetStreamHandler(hostDenyTransmission, p.onHostDenyTransmission)
node.SetStreamHandler(hostBroadcastMessage, p.onHostBroadcastMessage)
return p
}
func initDebugLogger() *log.Logger {
timeStirng := time.Now().Format("1-2_2006_15-04")
f, err := os.OpenFile("./log/log_"+timeStirng+".log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
//defer f.Close() // lets leave this to the os
logger := log.New(f, "Debug:", log.Lshortfile)
return logger
}
func (p *MultilogueProtocol) debugPrintln(v ...interface{}) {
if p.debug {
p.logger.Println(v...)
}
}
func ProtocolErrorName(errorCode ProtocolErrorState) string {
var errorName string
switch errorCode {
case NoError:
errorName = "NoError"
case GenericError:
errorName = "GenericError"
case MessageLimitError:
errorName = "MessageLimitError"
case TimeLimitError:
errorName = "TimeLimitError"
case CooldownError:
errorName = "CooldownError"
case HistoryError:
errorName = "HistoryError"
case RatioError:
errorName = "RatioError"
default:
errorName = "UnknownError"
}
return errorName
}
type ChannelConfig struct {
MessageLimit int
CooldownPeriod int
TimeLimit int
MaxMessageRatio float64
HistorySize int
}
func ReadChannelConfigs(fname string, config *ChannelConfig) {
b, err := ioutil.ReadFile(fname)
if err != nil {
log.Println("Error reading data from file. ")
}
err = json.Unmarshal(b, config)
if err != nil {
log.Println("Error loading data. ")
}
}
func DefaultChannelConfig() *ChannelConfig {
defaultChannelConfig := &ChannelConfig{
MessageLimit: 5,
CooldownPeriod: 200, // Seconds
TimeLimit: 180, // Minutes
MaxMessageRatio: 8, // for now
HistorySize: 2}
return defaultChannelConfig
}
// Handled when hosting
// Validate and broadcast this message to all peers
// deny if necesary
func (p *MultilogueProtocol) onClientSendMessage(s inet.Stream) {
p.debugPrintln("In onClientSendMessage: Message accepted.")
// get request data
data := &p2p.ClientSendMessage{}
decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
err := decoder.Decode(data)
if err != nil {
p.debugPrintln(err)
return
}
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
p.debugPrintln("Failed to authenticate message")
return
}
clientPeerID, err := peer.IDFromBytes(data.ClientData.PeerId)
clientPeerIDString := clientPeerID.String()
if err != nil {
p.debugPrintln("Failed to obtain Client Peer ID")
return
}
// Protocol Logic
accepted := false
errorCode := GenericError
var hasPeer bool
var channel *Channel
var currentChannelClient string
var givenChannelClient string
var remoteRequester string
var sessionLength time.Duration
var messageRatio float64
value, exists := p.channels.Get(data.HostData.ChannelId)
if !exists {
p.debugPrintln("In onClientSendMessage: Denied because channel not found.")
goto Response
}
channel = value.(*Channel)
channel.currentTransmission.RLock()
_, hasPeer = channel.peers.Get(clientPeerIDString)
if !hasPeer {
p.debugPrintln("In onClientSendMessage: Denied because peer not found.")
goto Response
}
if channel.currentTransmission == nil {
p.debugPrintln("In onClientSendMessage: Denied because transmission doesn't exist.")
goto Response
}
// valid peer id
currentChannelClient = channel.currentTransmission.peer.peerID.String()
givenChannelClient = clientPeerIDString
remoteRequester = s.Conn().RemotePeer().String()
if !(currentChannelClient == givenChannelClient && currentChannelClient == remoteRequester) {
p.debugPrintln("In onClientSendMessage: Denied because transmisison peer id, given peer id and remote peer id are not equal.")
p.debugPrintln(currentChannelClient, " ", givenChannelClient, " ", remoteRequester)
goto Response
}
if channel.currentTransmission.totalMsgs+1 > channel.config.MessageLimit {
p.debugPrintln("In onClientSendMessage: Denied because meessage limit reached.")
errorCode = MessageLimitError
goto Response
}
sessionLength = time.Now().Sub(channel.currentTransmission.startTime)
messageRatio = float64(channel.currentTransmission.totalMsgs) / sessionLength.Seconds()
if messageRatio > channel.config.MaxMessageRatio {
p.debugPrintln("In onClientSendMessage: Denied because message ratio passed.")
errorCode = RatioError
goto Response
}
if channel.currentTransmission.timeEnded {
p.debugPrintln("In onClientSendMessage: Denied time limit for transmission passed.")
errorCode = TimeLimitError
goto Response
}
channel.currentTransmission.RUnlock()
accepted = true
Response:
// generate response message
// Returning separate messages based on accepted or not
var resp proto.Message
var respErr error
if accepted {
// Updating increment messages
channel.currentTransmission.Lock()
channel.currentTransmission.totalMsgs = channel.currentTransmission.totalMsgs + 1
channel.currentTransmission.Unlock()
//for peerID, currentPeer := range channel.peers {
channel.peers.Range(func(key, value interface{}) {
peerID := key
currentPeer := value.(*Peer)
resp = &p2p.HostBroadcastMessage{MessageData: p.node.NewMessageData(data.MessageData.Id, false),
ClientData: data.ClientData,
HostData: data.HostData,
Message: data.Message}
// sign the data
signature, err := p.node.signProtoMessage(resp)
if err != nil {
p.debugPrintln("failed to sign response")
return
}
// Cannot take the above code outside of the if because I need to do the following
broadcastResp := resp.(*p2p.HostBroadcastMessage)
// add the signature to the message
broadcastResp.MessageData.Sign = signature
// Have to use the constant for the protocol message name string because reasons
// So that had to be done within this if
s, respErr = p.node.NewStream(context.Background(), currentPeer.peerID, hostBroadcastMessage)
if respErr != nil {
p.debugPrintln(respErr)
return
}
// send the response
ok := p.node.sendProtoMessage(resp, s)
if ok {
p.debugPrintln("%s: Message from %s recieved.", s.Conn().LocalPeer().String(), peerID)
}
})
} else {
//peer := channel.peers[clientPeerIDString]
// ending transmission
channel.currentTransmission.done <- true
channel.Lock()
channel.currentTransmission = nil
channel.Unlock()
p.debugPrintln("In onClientSendMessage: Ending transmission because of denial. ")
resp = &p2p.HostDenyClient{MessageData: p.node.NewMessageData(data.MessageData.Id, false),
ClientData: data.ClientData,
HostData: data.HostData,
ErrorCode: int32(errorCode)}
// sign the data
signature, err := p.node.signProtoMessage(resp)
if err != nil {
p.debugPrintln("failed to sign response")
return
}
denyClientResp := resp.(*p2p.HostDenyClient)
// add the signature to the message
denyClientResp.MessageData.Sign = signature
s, respErr = p.node.NewStream(context.Background(), s.Conn().RemotePeer(), hostDenyClient)
if respErr != nil {
p.debugPrintln(respErr)
return
}
// send the response
ok := p.node.sendProtoMessage(resp, s)
if ok {
p.debugPrintln("%s: Denying Message from %s.", s.Conn().LocalPeer().String(), s.Conn().RemotePeer().String())
}
}
}
// verify this and set new transmission
// deny if necesary
func (p *MultilogueProtocol) onClientTransmissionStart(s inet.Stream) {
// get request data
data := &p2p.ClientTransmissionStart{}
decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
err := decoder.Decode(data)
if err != nil {
p.debugPrintln(err)
return
}
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
p.debugPrintln("Failed to authenticate message")
return
}
clientPeerID, err := peer.IDFromBytes(data.ClientData.PeerId)
clientPeerIDString := clientPeerID.String()
if err != nil {
p.debugPrintln("Failed to obtain Client Peer ID")
return
}
errorCode := GenericError
// Protocol Logic
accepted := true
var channel *Channel
value, exists := p.channels.Get(data.HostData.ChannelId)
if exists {
channel = value.(*Channel)
value, hasPeer := channel.peers.Get(clientPeerIDString)
var peer *Peer
if !hasPeer {
accepted = false
p.debugPrintln("Transmission denied, peer not found on channel.")
goto Response
} else {
peer = value.(*Peer)
}
if channel.currentTransmission != nil {
p.debugPrintln("Transmission denied, current transmission exists.")
accepted = false
goto Response
}
if len(channel.history) > 0 {
lastPeer := channel.history[len(channel.history)-1]
if peer.peerID.String() == lastPeer {
time.Sleep(time.Duration(channel.config.CooldownPeriod) * time.Millisecond)
channel.Lock()
if channel.currentTransmission != nil {
p.debugPrintln("Transmission denied, other request recieved during cooldown period.")
accepted = false
errorCode = CooldownError
}
channel.Unlock()
goto Response
}
}
} else {
p.debugPrintln("Transmission denied, channel doesn't exist.")
accepted = false
goto Response
}
Response:
// generate response message
// Returning separate messages based on accepted or not
var resp proto.Message
var respErr error
if accepted {
channel.history = append(channel.history, clientPeerIDString)
value, _ := channel.peers.Get(clientPeerIDString)
peer := value.(*Peer)
peer.lastTransmission = time.Now()
// Create new transmission
channel.currentTransmission = &Transmission{
channelId: data.HostData.ChannelId,
peer: peer,
startTime: time.Now(),
done: make(chan bool)}
// Time limit handling
go func() {
timeLimit := time.Duration(channel.config.TimeLimit) * time.Second
transmissionTimer := time.NewTimer(timeLimit)
select {
case <-channel.currentTransmission.done:
p.debugPrintln("timer returning, transmission done")
return
case <-transmissionTimer.C:
channel.currentTransmission.Lock()
channel.currentTransmission.timeEnded = true
channel.currentTransmission.Unlock()
}
}()
resp = &p2p.HostAcceptTransmission{MessageData: p.node.NewMessageData(data.MessageData.Id, false),
ClientData: data.ClientData,
HostData: data.HostData}
// sign the data
signature, err := p.node.signProtoMessage(resp)
if err != nil {
p.debugPrintln("failed to sign response")
return
}
// Cannot take the above code outside of the if because I need to do the following
acceptClientResp := resp.(*p2p.HostAcceptTransmission)
// add the signature to the message
acceptClientResp.MessageData.Sign = signature
// Have to use the constant for the protocol message name string because reasons
// So that had to be done within this if
s, respErr = p.node.NewStream(context.Background(), s.Conn().RemotePeer(), hostAcceptTransmission)
} else {
resp = &p2p.HostDenyClient{MessageData: p.node.NewMessageData(data.MessageData.Id, false),
ClientData: data.ClientData,
HostData: data.HostData,
ErrorCode: int32(errorCode)}
// sign the data
signature, err := p.node.signProtoMessage(resp)
if err != nil {
p.debugPrintln("failed to sign response")
return
}
denyClientResp := resp.(*p2p.HostDenyClient)
// add the signature to the message
denyClientResp.MessageData.Sign = signature
s, respErr = p.node.NewStream(context.Background(), s.Conn().RemotePeer(), hostDenyClient)
}
if respErr != nil {
p.debugPrintln(respErr)
return
}
// send the response
ok := p.node.sendProtoMessage(resp, s)
if ok {
p.debugPrintln("%s: Transmisison attempted from %s.", s.Conn().LocalPeer().String(), s.Conn().RemotePeer().String())
}
}
// verify this and delete transmission
func (p *MultilogueProtocol) onClientTransmissionEnd(s inet.Stream) {
// get request data
data := &p2p.ClientTransmissionEnd{}
decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
err := decoder.Decode(data)
if err != nil {
p.debugPrintln(err)
return
}
p.debugPrintln("%s: User: %s (%s) ending transmission. ", s.Conn().LocalPeer(), data.ClientData.Username, s.Conn().RemotePeer())
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
p.debugPrintln("Failed to authenticate message")
return
}
clientPeerID, err := peer.IDFromBytes(data.ClientData.PeerId)
clientPeerIDString := clientPeerID.String()
if err != nil {
p.debugPrintln("Failed to obtain Client Peer ID")
return
}
// Protocol Logic
// Leaving channel
val, exists := p.channels.Get(data.HostData.ChannelId)
if exists {
channel := val.(*Channel)
// remove request from map as we have processed it here
_, hasPeer := channel.peers.Get(clientPeerIDString)
if hasPeer {
if channel.currentTransmission == nil {
p.debugPrintln("In onClientTransmissionEnd: Transmisison doesn't exist.")
return
}
currentChannelClient := channel.currentTransmission.peer.peerID.String()
givenChannelClient := clientPeerIDString
remoteRequester := s.Conn().RemotePeer().String()
if currentChannelClient == givenChannelClient && currentChannelClient == remoteRequester {
channel.currentTransmission.Lock()
channel.currentTransmission.done <- true
channel.currentTransmission.Unlock()
channel.Lock()
channel.currentTransmission = nil
channel.Unlock()
p.debugPrintln("In onClientTransmissionEnd: Ending transmission. ")
} else {
p.debugPrintln("In onClientTransmissionEnd: currentChannelClient, givenChannelClient , remoteRequester Not the same.")
p.debugPrintln("In onClientTransmissionEnd: ", currentChannelClient, " ", givenChannelClient, " ", remoteRequester)
}
} else {
p.debugPrintln("In onClientTransmissionEnd: Peer not found .")
}
} else {
p.debugPrintln("In onClientTransmissionEnd: Channel not found .")
}
p.debugPrintln("%s: User: %s (%s) ended transmission. ", s.Conn().LocalPeer(), data.ClientData.Username, s.Conn().RemotePeer())
}
// add to channel
// deny if necesary
func (p *MultilogueProtocol) onClientJoinChannel(s inet.Stream) {
// get request data
data := &p2p.ClientJoinChannel{}
decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
err := decoder.Decode(data)
if err != nil {
p.debugPrintln(err)
return
}
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
p.debugPrintln("Failed to authenticate message")
return
}
clientPeerID, err := peer.IDFromBytes(data.ClientData.PeerId)
clientPeerIDString := clientPeerID.String()
if err != nil {
p.debugPrintln("Failed to obtain Client Peer ID")
return
}
// Protocol Logic
// Adding to channel
accepted := false
val, exists := p.channels.Get(data.HostData.ChannelId)
if exists {
channel := val.(*Channel)
// Accept if the peerId and username aren't already in the channel
_, hasPeer := channel.peers.Get(clientPeerIDString)
if !hasPeer {
accepted = true
channel.peers.Range(func(key, value interface{}) {
peer := value.(*Peer)
//for _, peer := range channel.peers {
if data.ClientData.Username == peer.username {
accepted = false
}
})
}
if accepted {
channel.peers.Put(clientPeerIDString, &Peer{
peerID: clientPeerID,
username: data.ClientData.Username,
})
}
}
// generate response message
// Returning separate messages based on accepted or not
var resp proto.Message
var respErr error
if accepted {
resp = &p2p.HostAcceptClient{MessageData: p.node.NewMessageData(data.MessageData.Id, false),
ClientData: data.ClientData,
HostData: data.HostData}
// sign the data
signature, err := p.node.signProtoMessage(resp)
if err != nil {
p.debugPrintln("failed to sign response")
return
}
// Cannot take the above code outside of the if because I need to do the following
acceptClientResp := resp.(*p2p.HostAcceptClient)
// add the signature to the message
acceptClientResp.MessageData.Sign = signature
// Have to use the constant for the protocol message name string because reasons
// So that had to be done within this if
s, respErr = p.node.NewStream(context.Background(), s.Conn().RemotePeer(), hostAcceptClient)
} else {
resp = &p2p.HostDenyClient{MessageData: p.node.NewMessageData(data.MessageData.Id, false),
ClientData: data.ClientData,
HostData: data.HostData}
// sign the data
signature, err := p.node.signProtoMessage(resp)
if err != nil {
p.debugPrintln("failed to sign response")
return
}
denyClientResp := resp.(*p2p.HostDenyClient)
// add the signature to the message
denyClientResp.MessageData.Sign = signature
s, respErr = p.node.NewStream(context.Background(), s.Conn().RemotePeer(), hostDenyClient)
}
if respErr != nil {
p.debugPrintln(respErr)
return
}
// send the response
ok := p.node.sendProtoMessage(resp, s)
if ok {
p.debugPrintln("%s: Join Channel response to %s sent.", s.Conn().LocalPeer().String(), s.Conn().RemotePeer().String())
}
}
// delete form channel
func (p *MultilogueProtocol) onClientLeaveChannel(s inet.Stream) {
// get request data
data := &p2p.ClientLeaveChannel{}
decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
err := decoder.Decode(data)
if err != nil {
p.debugPrintln(err)
return
}
p.debugPrintln("%s: User: %s (%s) Leaving Channel %s. (Client)", s.Conn().LocalPeer(), data.ClientData.Username, s.Conn().RemotePeer(), data.HostData.ChannelId)
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
p.debugPrintln("Failed to authenticate message")
return
}
clientPeerID, err := peer.IDFromBytes(data.ClientData.PeerId)
clientPeerIDString := clientPeerID.String()
if err != nil {
p.debugPrintln("Failed to obtain Client Peer ID")
return
}
// Protocol Logic
// Leaving channel
val, exists := p.channels.Get(data.HostData.ChannelId)
if exists {
channel := val.(*Channel)
// remove request from map as we have processed it here
_, hasPeer := channel.peers.Get(clientPeerIDString)
if hasPeer {
channel.peers.Delete(clientPeerIDString)
}
}
p.debugPrintln("%s: User: %s (%s) Left channel %s ", s.Conn().LocalPeer(), data.ClientData.Username, s.Conn().RemotePeer(), data.HostData.ChannelId)
}
// Handled when Client
// Start sending messages
func (p *MultilogueProtocol) onHostAcceptTransmission(s inet.Stream) {
// get request data
data := &p2p.HostAcceptTransmission{}
decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
err := decoder.Decode(data)
if err != nil {
p.debugPrintln(err)
return
}
p.debugPrintln("%s: User: %s (%s) Transmission Accepted from host on channel %s. ", s.Conn().LocalPeer(), data.ClientData.Username, s.Conn().RemotePeer(), data.HostData.ChannelId)
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
p.debugPrintln("Failed to authenticate message")
return
}
clientPeerID, err := peer.IDFromBytes(data.ClientData.PeerId)
clientPeerIDString := clientPeerID.String()
if err != nil {
p.debugPrintln("Failed to obtain Client Peer ID")
return
}
// If there's no request, then simply print an error and return
val, requestExists := p.requests.Get(data.MessageData.Id)
if !requestExists {
p.debugPrintln("Request not found ")
return
}
request := val.(*Request)
// Protocol Logic
// Leaving channel
val, channelExists := p.channels.Get(data.HostData.ChannelId)
if !channelExists {
p.debugPrintln("In onHostAcceptTransmission: Denied because channel doesn't exist")
request.fail <- NewResponse(GenericError)
return
}
channel := val.(*Channel)
_, hasPeer := channel.peers.Get(clientPeerIDString)
if !hasPeer {
p.debugPrintln("In onHostAcceptTransmission: Denied because peer doesn't exist: ", data.ClientData.PeerId)
request.fail <- NewResponse(GenericError)
return
}
p.debugPrintln("In onHostAcceptTransmission: Success")
request.success <- NewResponse(NoError)
// remove request from map as we have processed it here
if channel.currentTransmission == nil {
channel.currentTransmission = &Transmission{}
}
p.debugPrintln("%s: User: %s (%s) attempting transmission on channel %s ", s.Conn().LocalPeer(), data.ClientData.Username, s.Conn().RemotePeer(), data.HostData.ChannelId)
}
func (p *MultilogueProtocol) onHostDenyTransmission(s inet.Stream) {
// get request data
data := &p2p.HostDenyTransmission{}
decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
err := decoder.Decode(data)
if err != nil {
p.debugPrintln(err)
return
}
p.debugPrintln("%s: User: %s (%s) Transmision denied on channel %s. ", s.Conn().LocalPeer(), data.ClientData.Username, s.Conn().RemotePeer(), data.HostData.ChannelId)
valid := p.node.authenticateMessage(data, data.MessageData)
if !valid {
p.debugPrintln("Failed to authenticate message")
return
}
clientPeerID, err := peer.IDFromBytes(data.ClientData.PeerId)
clientPeerIDString := clientPeerID.String()
if err != nil {
p.debugPrintln("Failed to obtain Client Peer ID")
return
}
// If there's no request, then simply print an error and return
val, requestExists := p.requests.Get(data.MessageData.Id)
if !requestExists {
p.debugPrintln("Request not found ")
return
}
request := val.(*Request)
val, channelExists := p.channels.Get(data.HostData.ChannelId)
if !channelExists {
request.fail <- NewResponse(GenericError)
return
}
channel := val.(*Channel)
_, hasPeer := channel.peers.Get(clientPeerIDString)
if !hasPeer {
request.fail <- NewResponse(GenericError)
return
}
request.fail <- NewResponse(ProtocolErrorState(data.ErrorCode))
p.channels.Delete(data.HostData.ChannelId)
p.debugPrintln("%s: User: %s (%s) denied on channel at peerID %s ", s.Conn().LocalPeer(), data.ClientData.Username, s.Conn().RemotePeer(), data.HostData.ChannelId)
}
// Start reading messages
func (p *MultilogueProtocol) onHostBroadcastMessage(s inet.Stream) {
// get request data
data := &p2p.HostBroadcastMessage{}
decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
err := decoder.Decode(data)
if err != nil {
p.debugPrintln(err)
return
}
clientPeerId := p.node.ID().String()
p.debugPrintln("%s: User: %s (%s) Message being broadcasted on channel %s. ", s.Conn().LocalPeer(), data.ClientData.Username, s.Conn().RemotePeer(), data.HostData.ChannelId)