-
Notifications
You must be signed in to change notification settings - Fork 2
/
message.go
1217 lines (1042 loc) · 52.6 KB
/
message.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 routes
import (
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/btcsuite/btcd/btcec"
"github.com/deso-smart/deso-core/v2/lib"
"github.com/pkg/errors"
"io"
"net/http"
"reflect"
"sort"
"time"
)
// GetMessagesStatelessRequest ...
type GetMessagesStatelessRequest struct {
PublicKeyBase58Check string `safeForLogging:"true"`
// FetchAfterPublicKeyBase58Check specifies where to start
// in the messages to begin fetching new messages. If set empty,
// we start fetching threads from the most recent message.
FetchAfterPublicKeyBase58Check string `safeForLogging:"true"`
// NumToFetch specifies the number of message threads to return. Defaults to 20
// unless otherwise specified.
NumToFetch uint64 `safeForLogging:"true"`
// There are four filters: HoldersOnly, HoldingsOnly, FollowersOnly, FollowedOnly
// If all filters are false, we return all messages. Otherwise we include
// messages from the sets set true.
// HoldersOnly when set true includes messages from holders.
HoldersOnly bool `safeForLogging:"true"`
// HoldingsOnly when set true includes messages from the user's holdings.
HoldingsOnly bool `safeForLogging:"true"`
// FollowersOnly when set true includes messages from the user's followers.
FollowersOnly bool `safeForLogging:"true"`
// FollowedOnly when set true includes messages from who the user follows.
FollowingOnly bool `safeForLogging:"true"`
// SortAlgorithm determines how the messages should be returned. Currently
// it support time, deso, and followers based sorting.
SortAlgorithm string `safeForLogging:"true"`
}
// GetMessagesResponse ...
type GetMessagesResponse struct {
// PublicKeyToProfileEntry is a map of profile entries of the message parties. Keys are base58check public keys.
PublicKeyToProfileEntry map[string]*ProfileEntryResponse
// OrderedContactsWithMessages is a list of message contacts. Each entry in the list corresponds to a messaging
// thread and contains the public key and profile entry of the other party in the thread. Entries also contain a
// list of encrypted messages for the threads.
OrderedContactsWithMessages []*MessageContactResponse
// UnreadStateByContact is a map indexed by public key base58check of contacts and with boolean values corresponding
// to whether the thread has any unread messages. True means there are unread messages.
UnreadStateByContact map[string]bool
// NumberOfUnreadThreads is a counter of how many unread threads are there.
NumberOfUnreadThreads int
// MessagingGroups are all user's registered messaging keys and group chats that the user is a member of.
MessagingGroups []*MessagingGroupEntryResponse
}
func (fes *APIServer) getMessagesStateless(publicKeyBytes []byte,
fetchAfterPublicKeyBytes []byte, numToFetch uint64, holdersOnly bool,
holdingsOnly bool, followersOnly bool, followingOnly bool, sortAlgorithm string) (
_publicKeyToProfileEntry map[string]*ProfileEntryResponse,
_orderedContactsWithMessages []*MessageContactResponse,
_unreadMessagesByContact map[string]bool,
_numOfUnreadThreads int,
_messagingGroups []*MessagingGroupEntryResponse,
_err error) {
// Get mempool augmented UtxoView so we can fetch message threads.
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUtxoViewForPublicKey(publicKeyBytes, nil)
if err != nil {
return nil, nil, nil, 0, nil, errors.Wrapf(
err, "getMessagesStateless: Error calling GetAugmentedUtxoViewForPublicKey: %v", err)
}
// On a high level this function fetches all user's messages and messaging groups and creates a MessageEntryResponse
// for each one. At the end, sort the MessageEntries by their timestamp.
//
// TODO: The timestamp is spoofable, but it's not a big deal. See comment on MessageEntry
// for more insight on this.
// Get user's messaging groups and up to lib.MessagesToFetchPerInboxCall messages.
messageEntries, messagingGroups, err := utxoView.GetLimitedMessagesForUser(publicKeyBytes, uint64(lib.MessagesToFetchPerInboxCall))
if err != nil {
return nil, nil, nil, 0, nil, errors.Wrapf(
err, "getMessagesStateless: Problem fetching MessageEntries and MessagingGroupEntries from augmented UtxoView: ")
}
// We sort the messages to be sure they're in the correct order for filtering out selected threads.
// There could be a faster way to do this, but it preserves pagination properly.
publicKeyToDESO := make(map[string]uint64)
publicKeyToNumberOfFollowers := make(map[string]uint64)
publicKeyToNanosUserHeld := make(map[string]uint64)
if sortAlgorithm == "deso" {
for _, messageEntry := range messageEntries {
otherPartyPublicKeyBytes, otherPartyPublicKeyBase58Check := fes.getOtherPartyInThread(messageEntry, publicKeyBytes)
if _, alreadySeen := publicKeyToDESO[otherPartyPublicKeyBase58Check]; !alreadySeen {
otherPartyProfileEntry := utxoView.GetProfileEntryForPublicKey(otherPartyPublicKeyBytes)
if otherPartyProfileEntry != nil {
publicKeyToDESO[otherPartyPublicKeyBase58Check] = otherPartyProfileEntry.CreatorCoinEntry.DeSoLockedNanos
} else {
publicKeyToDESO[otherPartyPublicKeyBase58Check] = 0
}
}
}
sort.Slice(messageEntries, func(ii, jj int) bool {
_, otherPartyPublicKeyiiBase58Check := fes.getOtherPartyInThread(messageEntries[ii], publicKeyBytes)
_, otherPartyPublicKeyjjBase58Check := fes.getOtherPartyInThread(messageEntries[jj], publicKeyBytes)
return publicKeyToDESO[otherPartyPublicKeyiiBase58Check] > publicKeyToDESO[otherPartyPublicKeyjjBase58Check]
})
} else if sortAlgorithm == "followers" {
for _, messageEntry := range messageEntries {
otherPartyPublicKeyBytes, otherPartyPublicKeyBase58Check := fes.getOtherPartyInThread(messageEntry, publicKeyBytes)
if _, alreadySeen := publicKeyToNumberOfFollowers[otherPartyPublicKeyBase58Check]; !alreadySeen {
// TODO: Make an index to quickly lookup how many followers a user has
otherPartyFollowers, err := lib.DbGetPKIDsFollowingYou(utxoView.Handle, lib.PublicKeyToPKID(otherPartyPublicKeyBytes))
if err != nil {
return nil, nil, nil, 0, nil, errors.Wrapf(
err, "getMessagesStateless: Problem getting follows for public key")
}
publicKeyToNumberOfFollowers[otherPartyPublicKeyBase58Check] = uint64(len(otherPartyFollowers))
}
}
sort.Slice(messageEntries, func(ii, jj int) bool {
_, otherPartyPublicKeyiiBase58Check := fes.getOtherPartyInThread(messageEntries[ii], publicKeyBytes)
_, otherPartyPublicKeyjjBase58Check := fes.getOtherPartyInThread(messageEntries[jj], publicKeyBytes)
return publicKeyToNumberOfFollowers[otherPartyPublicKeyiiBase58Check] > publicKeyToNumberOfFollowers[otherPartyPublicKeyjjBase58Check]
})
} else if sortAlgorithm == "holders" {
for _, messageEntry := range messageEntries {
otherPartyPublicKeyBytes, otherPartyPublicKeyBase58Check := fes.getOtherPartyInThread(messageEntry, publicKeyBytes)
if _, alreadySeen := publicKeyToNanosUserHeld[otherPartyPublicKeyBase58Check]; !alreadySeen {
otherPartyBalanceEntry, err := lib.GetSingleBalanceEntryFromPublicKeys(
otherPartyPublicKeyBytes, publicKeyBytes, utxoView, false)
if err != nil {
return nil, nil, nil, 0, nil, errors.Wrapf(
err, "getMessagesStateless: Problem getting balance entry for public key")
}
if otherPartyBalanceEntry != nil {
// CreatorCoins never exceed uint64
publicKeyToNanosUserHeld[otherPartyPublicKeyBase58Check] = otherPartyBalanceEntry.BalanceNanos.Uint64()
} else {
publicKeyToNanosUserHeld[otherPartyPublicKeyBase58Check] = 0
}
}
}
sort.Slice(messageEntries, func(ii, jj int) bool {
_, otherPartyPublicKeyiiBase58Check := fes.getOtherPartyInThread(messageEntries[ii], publicKeyBytes)
_, otherPartyPublicKeyjjBase58Check := fes.getOtherPartyInThread(messageEntries[jj], publicKeyBytes)
return publicKeyToNanosUserHeld[otherPartyPublicKeyiiBase58Check] > publicKeyToNanosUserHeld[otherPartyPublicKeyjjBase58Check]
})
} else {
sort.Slice(messageEntries, func(ii, jj int) bool {
return messageEntries[ii].TstampNanos > messageEntries[jj].TstampNanos
})
}
// Setup fetch boolean used for determining if we've already hit the fetchAfterPublicKeyBytes.
hitFetchAfterPublicKey := len(fetchAfterPublicKeyBytes) == 0
// Check if we're filtering results, setup maps if so
filterResults := holdersOnly || holdingsOnly || followersOnly || followingOnly
// Create maps for checking specific filters
publicKeyHoldsUser := make(map[string]bool)
userHoldsPublicKey := make(map[string]bool)
publicKeyFollowsUser := make(map[string]bool)
userFollowsPublicKey := make(map[string]bool)
publicKeyPassedFilters := make(map[string]bool)
// Filter out paginated messages from messageEntries
publicKeyInPaginatedSet := make(map[string]bool)
publicKeyToProfileEntry := make(map[string]*ProfileEntryResponse)
contactMap := make(map[string]*MessageContactResponse)
newContactEntries := []*MessageContactResponse{}
uniqueProfilesInPaginatedSetSeen := uint64(0)
blockedPubKeysForUser, err := fes.GetBlockedPubKeysForUser(publicKeyBytes)
if err != nil {
return nil, nil, nil, 0, nil, errors.Wrapf(
err, "getMessagesStateless: Problem getting blocked users for public key")
}
for _, messageEntry := range messageEntries {
// Check who the other party in the message is
otherPartyPublicKeyBytes, otherPartyPublicKeyBase58Check := fes.getOtherPartyInThread(messageEntry, publicKeyBytes)
// Check if the other party has been seen before and if it needs to be included in the response message
inPageSet, alreadySeen := publicKeyInPaginatedSet[otherPartyPublicKeyBase58Check]
// Skip it if it's already been processed
if alreadySeen && !inPageSet {
continue
}
// Skip if it's a blocked user
if _, blocked := blockedPubKeysForUser[otherPartyPublicKeyBase58Check]; blocked {
continue
}
// Filter out messages if requested by user
passedFilters, checkedFilters := publicKeyPassedFilters[otherPartyPublicKeyBase58Check]
if checkedFilters && !passedFilters {
continue
}
if filterResults && !checkedFilters {
publicKeyWithinFilters := false
// Check if the messenger passes the holder check
if holdersOnly {
holdsUser, balanceChecked := publicKeyHoldsUser[otherPartyPublicKeyBase58Check]
if !balanceChecked {
balanceEntry, err := lib.GetSingleBalanceEntryFromPublicKeys(
otherPartyPublicKeyBytes, publicKeyBytes, utxoView, false)
if err != nil {
return nil, nil, nil, 0, nil, errors.Wrapf(
err, "getMessagesStateless: Problem getting balance entry for holder public key %v", otherPartyPublicKeyBase58Check)
}
// CreatorCoins never exceed Uint64
holdsUser = balanceEntry != nil && balanceEntry.BalanceNanos.Uint64() > 0
publicKeyHoldsUser[otherPartyPublicKeyBase58Check] = holdsUser
}
if holdsUser {
publicKeyWithinFilters = true
}
}
// Check if the messenger passes the holding check
if !publicKeyWithinFilters && holdingsOnly {
holdsPublicKey, balanceChecked := userHoldsPublicKey[otherPartyPublicKeyBase58Check]
if !balanceChecked {
balanceEntry, err := lib.GetSingleBalanceEntryFromPublicKeys(
publicKeyBytes, otherPartyPublicKeyBytes, utxoView, false)
if err != nil {
return nil, nil, nil, 0, nil, errors.Wrapf(
err, "getMessagesStateless: Problem getting balance entry for holder public key %v", otherPartyPublicKeyBase58Check)
}
// CreatorCoins never exceed Uint64
holdsPublicKey = balanceEntry != nil && balanceEntry.BalanceNanos.Uint64() > 0
userHoldsPublicKey[otherPartyPublicKeyBase58Check] = holdsPublicKey
}
if holdsPublicKey {
publicKeyWithinFilters = true
}
}
// Check if the messenger passes the followers check
if !publicKeyWithinFilters && followersOnly {
followsUser, followChecked := publicKeyFollowsUser[otherPartyPublicKeyBase58Check]
if !followChecked {
followEntry := lib.DbGetFollowerToFollowedMapping(utxoView.Handle,
lib.PublicKeyToPKID(otherPartyPublicKeyBytes),
lib.PublicKeyToPKID(publicKeyBytes))
followsUser = followEntry != nil
publicKeyFollowsUser[otherPartyPublicKeyBase58Check] = followsUser
}
if followsUser {
publicKeyWithinFilters = true
}
}
// Check if the messenger passes the following check
if !publicKeyWithinFilters && followingOnly {
followsPublicKey, followChecked := userFollowsPublicKey[otherPartyPublicKeyBase58Check]
if !followChecked {
followEntry := lib.DbGetFollowerToFollowedMapping(utxoView.Handle,
lib.PublicKeyToPKID(publicKeyBytes),
lib.PublicKeyToPKID(otherPartyPublicKeyBytes))
followsPublicKey = followEntry != nil
userFollowsPublicKey[otherPartyPublicKeyBase58Check] = followsPublicKey
}
if followsPublicKey {
publicKeyWithinFilters = true
}
}
// Skip if the user failed the tests and update the map for faster lookup
publicKeyPassedFilters[otherPartyPublicKeyBase58Check] = publicKeyWithinFilters
if !publicKeyWithinFilters {
continue
}
}
// If this passed all the filter's requested by the user, we now check if it's within the requested
// page parameters.
if !alreadySeen {
if hitFetchAfterPublicKey && uniqueProfilesInPaginatedSetSeen < numToFetch {
inPageSet = true
publicKeyInPaginatedSet[otherPartyPublicKeyBase58Check] = true
// We now know the other user's messages are set to be returned for the first time.
otherProfileEntry := fes._profileEntryToResponse(utxoView.GetProfileEntryForPublicKey(otherPartyPublicKeyBytes), utxoView)
publicKeyToProfileEntry[otherPartyPublicKeyBase58Check] = otherProfileEntry
contactEntry := &MessageContactResponse{
PublicKeyBase58Check: otherPartyPublicKeyBase58Check,
ProfileEntryResponse: otherProfileEntry,
Messages: []*MessageEntryResponse{},
}
contactMap[otherPartyPublicKeyBase58Check] = contactEntry
newContactEntries = append(newContactEntries, contactEntry)
// Increment the number of profiles in the paginated set to prevent fetching too many profiles.
uniqueProfilesInPaginatedSetSeen++
} else {
publicKeyInPaginatedSet[otherPartyPublicKeyBase58Check] = false
// Check if we've hit the fetchAfterPublicKey and update accordingly.
// This means the next unique public key which fits our filter parameters will
// be put in the paginated set.
hitFetchAfterPublicKey = reflect.DeepEqual(otherPartyPublicKeyBytes, fetchAfterPublicKeyBytes)
continue
}
}
// The deprecated V2 field will be true if message version is 2, and the version field in MessageEntryResponse
// will reflect the real message version.
V2 := false
if messageEntry.Version == lib.MessagesVersion2 {
V2 = true
}
// By now we know this messageEntry is meant to be included in the response.
messageEntryRes := &MessageEntryResponse{
SenderPublicKeyBase58Check: lib.PkToString(messageEntry.SenderPublicKey[:], fes.Params),
RecipientPublicKeyBase58Check: lib.PkToString(messageEntry.RecipientPublicKey[:], fes.Params),
EncryptedText: hex.EncodeToString(messageEntry.EncryptedText),
TstampNanos: messageEntry.TstampNanos,
IsSender: !reflect.DeepEqual(messageEntry.RecipientPublicKey[:], publicKeyBytes),
V2: V2, /* DEPRECATED */
Version: uint32(messageEntry.Version),
SenderMessagingPublicKey: lib.PkToString(messageEntry.SenderMessagingPublicKey[:], fes.Params),
SenderMessagingGroupKeyName: string(lib.MessagingKeyNameDecode(messageEntry.SenderMessagingGroupKeyName)),
RecipientMessagingPublicKey: lib.PkToString(messageEntry.RecipientMessagingPublicKey[:], fes.Params),
RecipientMessagingGroupKeyName: string(lib.MessagingKeyNameDecode(messageEntry.RecipientMessagingGroupKeyName)),
ExtraData: extraDataToResponse(messageEntry.ExtraData),
}
contactEntry, _ := contactMap[lib.PkToString(otherPartyPublicKeyBytes, fes.Params)]
contactEntry.Messages = append(contactEntry.Messages, messageEntryRes)
}
// Go through the messages to ensure proper ordering between participant messages.
for _, contact := range newContactEntries {
sort.Slice(contact.Messages, func(ii, jj int) bool {
return contact.Messages[ii].TstampNanos < contact.Messages[jj].TstampNanos
})
}
// Order the messages in the inbox based on the selected sort algorithm.
if sortAlgorithm == "deso" {
sort.Slice(newContactEntries, func(ii, jj int) bool {
return publicKeyToDESO[newContactEntries[ii].PublicKeyBase58Check] >
publicKeyToDESO[newContactEntries[jj].PublicKeyBase58Check]
})
} else if sortAlgorithm == "followers" {
sort.Slice(newContactEntries, func(ii, jj int) bool {
return publicKeyToNumberOfFollowers[newContactEntries[ii].PublicKeyBase58Check] >
publicKeyToNumberOfFollowers[newContactEntries[jj].PublicKeyBase58Check]
})
} else if sortAlgorithm == "holders" {
sort.Slice(newContactEntries, func(ii, jj int) bool {
return publicKeyToNanosUserHeld[newContactEntries[ii].PublicKeyBase58Check] >
publicKeyToNanosUserHeld[newContactEntries[jj].PublicKeyBase58Check]
})
} else {
sort.Slice(newContactEntries, func(ii, jj int) bool {
return newContactEntries[ii].Messages[len(newContactEntries[ii].Messages)-1].TstampNanos >
newContactEntries[jj].Messages[len(newContactEntries[jj].Messages)-1].TstampNanos
})
}
// We now check if a messages are unread. unreadMessagesBycontact returns true
// if the contact has new messages for the user.
unreadMessagesBycontact := make(map[string]bool)
numOfUnreadThreads := 0
for _, entry := range newContactEntries {
otherUserPublicKeyBytes, _, err := lib.Base58CheckDecode(entry.PublicKeyBase58Check)
if err != nil {
return nil, nil, nil, 0, nil, errors.Wrapf(err, "getMessagesStateless: Problem decoding "+
"contact's public key.")
}
mostRecentReadTstampNanos, err := fes.getUserContactMostRecentReadTime(publicKeyBytes, otherUserPublicKeyBytes)
if err != nil {
return nil, nil, nil, 0, nil, errors.Wrapf(err, "getMessagesStateless: Problem getting "+
"contact's most recent read state.")
}
for ii, msg := range entry.Messages {
// Check if this is an unread message.
if !msg.IsSender {
if msg.TstampNanos > mostRecentReadTstampNanos {
unreadMessagesBycontact[entry.PublicKeyBase58Check] = true
numOfUnreadThreads++
break
}
}
// If we've gone through all the messages and they're all ready, we mark this thread as read.
if ii == len(entry.Messages)-1 {
unreadMessagesBycontact[entry.PublicKeyBase58Check] = false
}
}
}
var userMessagingKeys []*MessagingGroupEntryResponse
userMessagingKeys = fes.ParseMessagingGroupEntries(publicKeyBytes, messagingGroups)
return publicKeyToProfileEntry, newContactEntries, unreadMessagesBycontact, numOfUnreadThreads, userMessagingKeys, nil
}
// ParseMessagingGroupEntries parses a core type []*lib.MessagingGroupEntry to the backend type []*MessagingGroupEntryResponse.
func (fes *APIServer) ParseMessagingGroupEntries(memberPublicKeyBytes []byte, messagingGroupEntries []*lib.MessagingGroupEntry) []*MessagingGroupEntryResponse {
var userMessagingGroupEntries []*MessagingGroupEntryResponse
// Iterate through all messaging group entries.
for _, key := range messagingGroupEntries {
// Create an initial MessagingGroupEntryResponse that we will push to our userMessagingGroupEntries list.
userMessagingGroup := MessagingGroupEntryResponse{
GroupOwnerPublicKeyBase58Check: lib.PkToString(key.GroupOwnerPublicKey[:], fes.Params),
MessagingPublicKeyBase58Check: lib.PkToString(key.MessagingPublicKey[:], fes.Params),
MessagingGroupKeyName: string(lib.MessagingKeyNameDecode(key.MessagingGroupKeyName)),
EncryptedKey: "",
ExtraData: extraDataToResponse(key.ExtraData),
}
// Add all messaging group recipients from the messagingGroupEntries parameter.
for _, groupMember := range key.MessagingGroupMembers {
encryptedKey := hex.EncodeToString(groupMember.EncryptedKey)
if reflect.DeepEqual(groupMember.GroupMemberPublicKey[:], memberPublicKeyBytes) {
userMessagingGroup.EncryptedKey = encryptedKey
}
// Create a MessagingGroupMemberResponse to add to our userMessagingGroup.
messagingRecipient := &MessagingGroupMemberResponse{
GroupMemberPublicKeyBase58Check: lib.PkToString(groupMember.GroupMemberPublicKey[:], fes.Params),
GroupMemberKeyName: string(lib.MessagingKeyNameDecode(groupMember.GroupMemberKeyName)),
EncryptedKey: hex.EncodeToString(groupMember.EncryptedKey),
}
userMessagingGroup.MessagingGroupMembers = append(userMessagingGroup.MessagingGroupMembers, messagingRecipient)
}
userMessagingGroupEntries = append(userMessagingGroupEntries, &userMessagingGroup)
}
return userMessagingGroupEntries
}
func (fes *APIServer) getOtherPartyInThread(messageEntry *lib.MessageEntry,
readerPublicKeyBytes []byte) (otherPartyPublicKeyBytes []byte, otherPartyPublicKeyBase58Check string) {
if reflect.DeepEqual(messageEntry.RecipientPublicKey[:], readerPublicKeyBytes) {
otherPartyPublicKeyBytes = messageEntry.SenderPublicKey[:]
} else {
otherPartyPublicKeyBytes = messageEntry.RecipientPublicKey[:]
}
otherPartyPublicKeyBase58Check = lib.PkToString(otherPartyPublicKeyBytes, fes.Params)
return
}
// GetMessagesStateless ...
func (fes *APIServer) GetMessagesStateless(ww http.ResponseWriter, rr *http.Request) {
decoder := json.NewDecoder(io.LimitReader(rr.Body, MaxRequestBodySizeBytes))
getMessagesRequest := GetMessagesStatelessRequest{}
if err := decoder.Decode(&getMessagesRequest); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetMessagesStateless: Error parsing request body: %v", err))
return
}
// Decode the public key into bytes.
publicKeyBytes, _, err := lib.Base58CheckDecode(getMessagesRequest.PublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetMessagesStateless: Problem decoding user public key: %v", err))
return
}
var fetchAfterPublicKeyBytes []byte
if getMessagesRequest.FetchAfterPublicKeyBase58Check != "" {
fetchAfterPublicKeyBytes, _, err = lib.Base58CheckDecode(getMessagesRequest.FetchAfterPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetMessagesStateless: Problem decoding fetch after public key: %v", err))
return
}
}
// Get all contacts profile entries, messages, and group messaging keys.
publicKeyToProfileEntry, orderedContactsWithMessages,
unreadStateByContact, numOfUnreadThreads, messagingGroups, err := fes.getMessagesStateless(publicKeyBytes, fetchAfterPublicKeyBytes,
getMessagesRequest.NumToFetch, getMessagesRequest.HoldersOnly, getMessagesRequest.HoldingsOnly,
getMessagesRequest.FollowersOnly, getMessagesRequest.FollowingOnly, getMessagesRequest.SortAlgorithm)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetMessagesStateless: Problem fetching and decrypting messages: %v", err))
return
}
// =====================================================================================
// Now assemble the response.
res := GetMessagesResponse{
PublicKeyToProfileEntry: publicKeyToProfileEntry,
OrderedContactsWithMessages: orderedContactsWithMessages,
UnreadStateByContact: unreadStateByContact,
NumberOfUnreadThreads: numOfUnreadThreads,
MessagingGroups: messagingGroups,
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetMessages: Problem serializing object to JSON: %v", err))
return
}
}
// SendMessageStatelessRequest ...
type SendMessageStatelessRequest struct {
// SenderPublicKeyBase58Check is the public key in base58check of the message sender.
SenderPublicKeyBase58Check string `safeForLogging:"true"`
// RecipientPublicKeyBase58Check is the public key in base58check of the messaging recipient.
RecipientPublicKeyBase58Check string `safeForLogging:"true"`
MessageText string // Deprecated
// EncryptedMessageText is the intended message content. It is recommended to pass actual encrypted message here,
// although unencrypted message can be passed as well.
EncryptedMessageText string
MinFeeRateNanosPerKB uint64 `safeForLogging:"true"`
// No need to specify ProfileEntryResponse in each TransactionFee
TransactionFees []TransactionFee `safeForLogging:"true"`
// ---------------------------------------------------------
// DeSo V3 Messages Fields
// ---------------------------------------------------------
// SenderMessagingGroupKeyName is the messaging group key name of the sender. If left empty, this endpoint
// will replace it with the base messaging key. If both SenderMessagingGroupKeyName and
// RecipientMessagingGroupKeyName are left empty, a V2 message will be constructed.
SenderMessagingGroupKeyName string `safeForLogging:"true"`
// RecipientMessagingGroupKeyName is the messaging group key name of the recipient. If left empty, this endpoint
// will replace it with the base messaging key. If both SenderMessagingGroupKeyName and
// RecipientMessagingGroupKeyName are left empty, a V2 message will be constructed.
RecipientMessagingGroupKeyName string `safeForLogging:"true"`
// ExtraData is an arbitrary key value map
ExtraData map[string]string
}
// SendMessageStatelessResponse ...
type SendMessageStatelessResponse struct {
TstampNanos uint64
TotalInputNanos uint64
ChangeAmountNanos uint64
FeeNanos uint64
Transaction *lib.MsgDeSoTxn
TransactionHex string
}
// SendMessageStateless ...
func (fes *APIServer) SendMessageStateless(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := SendMessageStatelessRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem parsing request body: %v", err))
return
}
// Decode the sender public key.
senderPkBytes, _, err := lib.Base58CheckDecode(requestData.SenderPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem decoding sender "+
"base58 public key %s: %v", requestData.SenderPublicKeyBase58Check, err))
return
}
// Parse sender public key to lib.PublicKey
senderPublicKey := lib.NewPublicKey(senderPkBytes)
// If recipient messaging group key name is passed, we will validate it. Otherwise, just validate sender public key.
// We will treat empty group messaging keys as lib.BaseGroupKeyName(), which is an empty string key name.
senderMessagingGroupKeyNameBytes := []byte(requestData.SenderMessagingGroupKeyName)
if len(requestData.SenderMessagingGroupKeyName) > 0 {
if err = lib.ValidateGroupPublicKeyAndName(senderPkBytes, senderMessagingGroupKeyNameBytes); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem validating sender "+
"public key and group messaging key name %s: %v", requestData.SenderMessagingGroupKeyName, err))
return
}
} else {
if err = lib.IsByteArrayValidPublicKey(senderPkBytes); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem validating sender "+
"public key %s: %v", senderPkBytes, err))
return
}
}
// Decode the recipient's public key.
recipientPkBytes, _, err := lib.Base58CheckDecode(requestData.RecipientPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem decoding recipient "+
"base58 public key %s: %v", requestData.RecipientPublicKeyBase58Check, err))
return
}
// Parse recipient public key to lib.PublicKey
recipientPublicKey := lib.NewPublicKey(recipientPkBytes)
// If recipient messaging group key name is passed, we will validate it. Otherwise, just validate sender public key.
// We will treat empty group messaging keys as lib.BaseGroupKeyName(), which is an empty string key name.
recipientMessagingGroupKeyNameBytes := []byte(requestData.RecipientMessagingGroupKeyName)
if len(requestData.RecipientMessagingGroupKeyName) > 0 {
if err = lib.ValidateGroupPublicKeyAndName(recipientPkBytes, recipientMessagingGroupKeyNameBytes); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem validating recipient "+
"public key and group messaging key name %s: %v", requestData.RecipientMessagingGroupKeyName, err))
return
}
} else {
if err = lib.IsByteArrayValidPublicKey(recipientPkBytes); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem validating recipient "+
"public key %s: %v", senderPkBytes, err))
return
}
}
// Validate sender and recipient group messaging keys with UtxoView.
checkPartyMessagingKeysResponse, err := fes.CreateCheckPartyMessagingKeysResponse(senderPublicKey, lib.NewGroupKeyName(senderMessagingGroupKeyNameBytes),
recipientPublicKey, lib.NewGroupKeyName(recipientMessagingGroupKeyNameBytes))
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem checking party keys sender (public key: %v, key name: %v), recipient "+
"(public key: %v, key name: %v), error: %v", senderPublicKey, lib.NewGroupKeyName(senderMessagingGroupKeyNameBytes),
recipientPkBytes, lib.NewGroupKeyName(recipientMessagingGroupKeyNameBytes), err))
return
}
// Error if sender group messaging key doesn't exist, because we can't send the intended message.
if !checkPartyMessagingKeysResponse.IsSenderMessagingKey {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem checking party keys; sender messaging key doesn't exist "+
"(public key: %v, key name: %v)", senderPublicKey, lib.NewGroupKeyName(senderMessagingGroupKeyNameBytes)))
return
}
// Error if recipient group messaging key doesn't exist, because we can't send the intended message.
if !checkPartyMessagingKeysResponse.IsRecipientMessagingKey {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem checking party keys recipient messaging key doesn't exist "+
"(public key: %v, key name: %v)", recipientPkBytes, lib.NewGroupKeyName(recipientMessagingGroupKeyNameBytes)))
return
}
// Get messaging public key for the sender. If sender group key name is empty, that means we're intending to send
// a V2 message, so we'll leave the messaging public key empty.
senderMessagingPublicKey := []byte{}
if len(requestData.SenderMessagingGroupKeyName) > 0 {
senderMessagingPublicKey, _, err = lib.Base58CheckDecode(checkPartyMessagingKeysResponse.SenderMessagingPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem decoding sender messaging public key "+
"(public key: %v, key name: %v)", checkPartyMessagingKeysResponse.SenderMessagingPublicKeyBase58Check,
senderMessagingGroupKeyNameBytes))
return
}
}
// Get messaging public key for the recipient. If recipient group key name is empty, that means we're intending to
// send a V2 message, so we'll leave the messaging public key empty.
recipientMessagingPublicKey := []byte{}
if len(requestData.RecipientMessagingGroupKeyName) > 0 {
recipientMessagingPublicKey, _, err = lib.Base58CheckDecode(checkPartyMessagingKeysResponse.RecipientMessagingPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem decoding recipient messaging public key "+
"(public key: %v, key name: %v)", checkPartyMessagingKeysResponse.RecipientMessagingPublicKeyBase58Check,
recipientMessagingGroupKeyNameBytes))
return
}
}
// Compute the additional transaction fees as specified by the request body and the node-level fees.
additionalOutputs, err := fes.getTransactionFee(lib.TxnTypePrivateMessage, senderPkBytes, requestData.TransactionFees)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: TransactionFees specified in Request body are invalid: %v", err))
return
}
// Try and create the message for the user.
tstamp := uint64(time.Now().UnixNano())
txn, totalInput, changeAmount, fees, err := fes.blockchain.CreatePrivateMessageTxn(
senderPkBytes, recipientPkBytes,
requestData.MessageText, requestData.EncryptedMessageText,
senderMessagingPublicKey, senderMessagingGroupKeyNameBytes,
recipientMessagingPublicKey, recipientMessagingGroupKeyNameBytes,
tstamp, preprocessExtraData(requestData.ExtraData),
requestData.MinFeeRateNanosPerKB, fes.backendServer.GetMempool(), additionalOutputs)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem creating transaction: %v", err))
return
}
// Add node source to txn metadata
fes.AddNodeSourceToTxnMetadata(txn)
txnBytes, err := txn.ToBytes(true)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem serializing transaction: %v", err))
return
}
// Return all the data associated with the transaction in the response
res := SendMessageStatelessResponse{
TstampNanos: tstamp,
TotalInputNanos: totalInput,
ChangeAmountNanos: changeAmount,
FeeNanos: fees,
Transaction: txn,
TransactionHex: hex.EncodeToString(txnBytes),
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessageStateless: Problem encoding response as JSON: %v", err))
return
}
}
type MarkContactMessagesReadRequest struct {
JWT string
UserPublicKeyBase58Check string
ContactPublicKeyBase58Check string
}
func (fes *APIServer) MarkContactMessagesRead(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := MarkContactMessagesReadRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("MarkUserContactMessagesRead: Problem parsing request body: %v", err))
return
}
isValid, err := fes.ValidateJWT(requestData.UserPublicKeyBase58Check, requestData.JWT)
if !isValid {
_AddBadRequestError(ww, fmt.Sprintf("MarkUserContactMessagesRead: Invalid token: %v", err))
return
}
userPublicKeyBytes, _, err := lib.Base58CheckDecode(requestData.UserPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("MarkUserContactMessagesRead: Problem decoding user public key: %v", err))
return
}
contactPublicKeyBytes, _, err := lib.Base58CheckDecode(requestData.ContactPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("MarkUserContactMessagesRead: Problem decoding contact public key: %v", err))
return
}
err = fes.markContactMessagesRead(userPublicKeyBytes, contactPublicKeyBytes)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("MarkUserContactMessagesRead: Problem marking thread as read: %v", err))
return
}
}
type MarkAllMessagesReadRequest struct {
JWT string
UserPublicKeyBase58Check string
}
func (fes *APIServer) MarkAllMessagesRead(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := MarkAllMessagesReadRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("MarkUserContactMessagesRead: Problem parsing request body: %v", err))
return
}
isValid, err := fes.ValidateJWT(requestData.UserPublicKeyBase58Check, requestData.JWT)
if !isValid {
_AddBadRequestError(ww, fmt.Sprintf("MarkUserContactMessagesRead: Invalid token: %v", err))
return
}
userPublicKeyBytes, _, err := lib.Base58CheckDecode(requestData.UserPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("MarkUserContactMessagesRead: Problem decoding user public key: %v", err))
return
}
err = fes.markAllMessagesRead(userPublicKeyBytes)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("MarkUserContactMessagesRead: Problem marking threads as read: %v", err))
return
}
}
// markAllMessagesRead...
func (fes *APIServer) markAllMessagesRead(publicKeyBytes []byte) error {
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUtxoViewForPublicKey(publicKeyBytes, nil)
if err != nil {
return errors.Wrapf(err, "markAllMessagesRead: Error calling GetAugmentedUtxoViewForPublicKey: %v", err)
}
messageEntries, _, err := utxoView.GetMessagesForUser(publicKeyBytes)
if err != nil {
return errors.Wrapf(err, "markAllMessagesRead: Problem fetching MessageEntries from augmented UtxoView: ")
}
alreadySeenContactMap := make(map[string]struct{})
for _, messageEntry := range messageEntries {
otherPartyPublicKeyBytes, otherPartyPublicKeyBase58Check := fes.getOtherPartyInThread(messageEntry, publicKeyBytes)
// Check if we've seen this contact before
_, alreadySeenContact := alreadySeenContactMap[otherPartyPublicKeyBase58Check]
// Mark messages if this is the first time seeing the contact
if !alreadySeenContact {
alreadySeenContactMap[otherPartyPublicKeyBase58Check] = struct{}{}
err = fes.markContactMessagesRead(publicKeyBytes, otherPartyPublicKeyBytes)
if err != nil {
return errors.Wrapf(err, "markAllMessagesRead: Problem marking public key as read: ")
}
}
}
return nil
}
// markContactMessagesRead...
func (fes *APIServer) markContactMessagesRead(userPublicKeyBytes []byte, contactPublicKeyBytes []byte) (_err error) {
dbKey := GlobalStateKeyForUserPkContactPkToMostRecentReadTstampNanos(userPublicKeyBytes, contactPublicKeyBytes)
tStampNanos := uint64(time.Now().UnixNano())
tStampNanosBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(tStampNanosBytes, tStampNanos)
err := fes.GlobalState.Put(dbKey, tStampNanosBytes)
if err != nil {
return errors.Wrap(fmt.Errorf(
"putUserContactMostRecentReadTime: Problem putting updated tStampNanosBytes: %v", err), "")
}
return nil
}
// getUserContactMostRecentReadTime...
func (fes *APIServer) getUserContactMostRecentReadTime(userPublicKeyBytes []byte, contactPublicKeyBytes []byte) (uint64, error) {
dbKey := GlobalStateKeyForUserPkContactPkToMostRecentReadTstampNanos(userPublicKeyBytes, contactPublicKeyBytes)
tStampNanosBytes, err := fes.GlobalState.Get(dbKey)
if err != nil {
// If the key errors, we return 0.
return 0, nil
}
var tStampNanos uint64
if len(tStampNanosBytes) != 0 {
tStampNanos = binary.LittleEndian.Uint64(tStampNanosBytes)
}
return tStampNanos, nil
}
// RegisterMessagingGroupKeyRequest ...
type RegisterMessagingGroupKeyRequest struct {
// OwnerPublicKeyBase58Check is the public key in base58check of the account we want to register the messaging key for.
OwnerPublicKeyBase58Check string
// MessagingPublicKeyBase58Check is the public key in base58check of the messaging group we want to register.
MessagingPublicKeyBase58Check string
// MessagingGroupKeyName is the name of the group key.
MessagingGroupKeyName string
// MessagingKeySignatureHex is the signature of sha256x2(MessagingPublicKey + MessagingGroupKeyName). Currently,
// the signature is only needed to register the default key.
MessagingKeySignatureHex string
// ExtraData is an arbitrary key value map
ExtraData map[string]string
MinFeeRateNanosPerKB uint64 `safeForLogging:"true"`
// No need to specify ProfileEntryResponse in each TransactionFee
TransactionFees []TransactionFee `safeForLogging:"true"`
}
// RegisterMessagingGroupKeyResponse ...
type RegisterMessagingGroupKeyResponse struct {
TotalInputNanos uint64
ChangeAmountNanos uint64
FeeNanos uint64
Transaction *lib.MsgDeSoTxn
TransactionHex string
TxnHashHex string
}
// RegisterMessagingGroupKey ...
func (fes *APIServer) RegisterMessagingGroupKey(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := RegisterMessagingGroupKeyRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("RegisterMessagingGroupKey: Problem parsing request body: %v", err))
return
}
// Decode the owner public key.
ownerPkBytes, _, err := lib.Base58CheckDecode(requestData.OwnerPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("RegisterMessagingGroupKey: Problem decoding sender "+
"base58 public key %s: %v", requestData.OwnerPublicKeyBase58Check, err))
return
}
// Decode the group messaging public key
messagingPkBytes, _, err := lib.Base58CheckDecode(requestData.MessagingPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("RegisterMessagingGroupKey: Problem decoding messaging "+
"base58 public key %s: %v", requestData.MessagingPublicKeyBase58Check, err))
return
}
// Parse the messaging group key name from string to bytes
messagingKeyNameBytes := []byte(requestData.MessagingGroupKeyName)
// Validate that the group messaging public key and key name have the correct format.
err = lib.ValidateGroupPublicKeyAndName(messagingPkBytes, messagingKeyNameBytes)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("RegisterMessagingGroupKey: Problem validating messaging public key and name %v", err))
return
}
// Decode the messaging key signature.
messagingKeySignature, _ := hex.DecodeString(requestData.MessagingKeySignatureHex)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("RegisterMessagingGroupKey: Problem decoding messaging public key signature %v", err))
return
}
// If the messaging key name is the default key name, then we will sanity-check that the signature is valid.
if lib.EqualGroupKeyName(lib.DefaultGroupKeyName(), lib.NewGroupKeyName(messagingKeyNameBytes)) {
msgBytes := append(messagingPkBytes, messagingKeyNameBytes...)
if err := VerifyBytesSignature(ownerPkBytes, msgBytes, messagingKeySignature); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("RegisterMessagingGroupKey: Problem verifying transaction signature: %v", err))
return
}
}
// Compute the additional transaction fees as specified by the request body and the node-level fees.
additionalOutputs, err := fes.getTransactionFee(lib.TxnTypeMessagingGroup, ownerPkBytes, requestData.TransactionFees)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("RegisterMessagingGroupKey: TransactionFees specified in Request body are invalid: %v", err))
return
}
txn, totalInput, changeAmount, fees, err := fes.blockchain.CreateMessagingKeyTxn(
ownerPkBytes, messagingPkBytes, messagingKeyNameBytes, messagingKeySignature,
[]*lib.MessagingGroupMember{}, preprocessExtraData(requestData.ExtraData),
requestData.MinFeeRateNanosPerKB, fes.backendServer.GetMempool(), additionalOutputs)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("RegisterMessagingGroupKey: Problem creating transaction: %v", err))
return
}
// Add node source to txn metadata
fes.AddNodeSourceToTxnMetadata(txn)
txnBytes, err := txn.ToBytes(true)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("RegisterMessagingGroupKey: Problem serializing transaction: %v", err))
return
}
// Assemble and encode the response.
res := RegisterMessagingGroupKeyResponse{
TotalInputNanos: totalInput,
ChangeAmountNanos: changeAmount,
FeeNanos: fees,
Transaction: txn,
TransactionHex: hex.EncodeToString(txnBytes),
TxnHashHex: txn.Hash().String(),
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("RegisterMessagingGroupKey: Problem encoding response as JSON: %v", err))
return
}
}
// VerifyBytesSignature checks if signatureBytes is a correct DER signature of data made by signerPk.
func VerifyBytesSignature(signerPk, data, signatureBytes []byte) error {