-
Notifications
You must be signed in to change notification settings - Fork 2
/
user.go
3295 lines (2907 loc) · 126 KB
/
user.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 (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/holiman/uint256"
"io"
"net/http"
"reflect"
"sort"
"strconv"
"strings"
"github.com/btcsuite/btcd/btcec"
"github.com/dgraph-io/badger/v3"
"github.com/gorilla/mux"
"github.com/deso-smart/deso-core/v2/lib"
"github.com/golang/glog"
"github.com/pkg/errors"
)
// GetUsersRequest ...
type GetUsersStatelessRequest struct {
PublicKeysBase58Check []string `safeForLogging:"true"`
SkipForLeaderboard bool `safeForLogging:"true"`
IncludeBalance bool `safeForLogging:"true"`
GetUnminedBalance bool `safeForLogging:"true"`
}
// GetUsersResponse ...
type GetUsersResponse struct {
UserList []*User
DefaultFeeRateNanosPerKB uint64
ParamUpdaters map[string]bool
}
// GetUsersStateless ...
func (fes *APIServer) GetUsersStateless(ww http.ResponseWriter, rr *http.Request) {
decoder := json.NewDecoder(io.LimitReader(rr.Body, MaxRequestBodySizeBytes))
getUsersRequest := GetUsersStatelessRequest{}
if err := decoder.Decode(&getUsersRequest); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetUsersStateless: Error parsing request body: %v", err))
return
}
userList := []*User{}
for ii := range getUsersRequest.PublicKeysBase58Check {
currentUser := &User{
PublicKeyBase58Check: getUsersRequest.PublicKeysBase58Check[ii],
// All the other fields will be set in the call to UpdateUsers below.
}
userList = append(userList, currentUser)
}
globalParams, err := fes.updateUsersStateless(userList, getUsersRequest.SkipForLeaderboard,
getUsersRequest.GetUnminedBalance, getUsersRequest.IncludeBalance)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetUsersStateless: Error fetching data for user: %v", err))
return
}
// Compute a default fee rate.
defaultFeeRateNanosPerKB := fes.MinFeeRateNanosPerKB
if globalParams != nil && globalParams.MinimumNetworkFeeNanosPerKB > 0 {
defaultFeeRateNanosPerKB = globalParams.MinimumNetworkFeeNanosPerKB
}
paramUpdaters := make(map[string]bool)
for kk := range fes.Params.ParamUpdaterPublicKeys {
paramUpdaters[lib.PkToString(kk[:], fes.Params)] = true
}
// Update all user information before returning.
res := GetUsersResponse{
UserList: userList,
DefaultFeeRateNanosPerKB: defaultFeeRateNanosPerKB,
ParamUpdaters: paramUpdaters,
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetUsers: Problem serializing object to Error: %v", err))
return
}
}
func (fes *APIServer) updateUsersStateless(userList []*User, skipForLeaderboard bool, getUnminedBalance bool,
includeBalance bool) (
*lib.GlobalParamsEntry, error) {
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
return nil, fmt.Errorf("updateUserFields: Error calling GetAugmentedUtxoViewForPublicKey: %v", err)
}
globalParams := utxoView.GlobalParamsEntry
for _, user := range userList {
// If we get an error updating the user, log it but don't stop the show.
if err = fes.updateUserFieldsStateless(
user, utxoView, skipForLeaderboard, getUnminedBalance, includeBalance); err != nil {
glog.Errorf(fmt.Sprintf("updateUsers: Problem updating user with pk %s: %v", user.PublicKeyBase58Check, err))
}
}
return globalParams, nil
}
func (fes *APIServer) updateUserFieldsStateless(user *User, utxoView *lib.UtxoView, skipForLeaderboard bool,
getUnminedBalance bool, includeBalance bool) error {
// If there's no public key, then return an error. We need a public key on
// the user object in order to be able to update the fields.
if user.PublicKeyBase58Check == "" {
return fmt.Errorf("updateUserFields: Missing PublicKeyBase58Check")
}
// Decode the public key into bytes.
publicKeyBytes, _, err := lib.Base58CheckDecode(user.PublicKeyBase58Check)
if err != nil {
return errors.Wrapf(err, "updateUserFields: Problem decoding user public key: ")
}
// Get the ProfileEntry corresponding to this user's public key from the view.
profileEntryy := utxoView.GetProfileEntryForPublicKey(publicKeyBytes)
var profileEntryResponse *ProfileEntryResponse
if profileEntryy != nil {
// Convert it to a response since that sanitizes the inputs.
profileEntryResponse = fes._profileEntryToResponse(profileEntryy, utxoView)
user.ProfileEntryResponse = profileEntryResponse
}
// We do not need a user's balance for the leaderboard
if !skipForLeaderboard || includeBalance {
if getUnminedBalance {
// Get the UtxoEntries from the augmented view
utxoEntries, err := fes.blockchain.GetSpendableUtxosForPublicKey(
publicKeyBytes, fes.backendServer.GetMempool(), utxoView)
if err != nil {
return errors.Wrapf(err, "updateUserFields: Problem getting utxos from view: ")
}
totalBalanceNanos := uint64(0)
unminedBalanceNanos := uint64(0)
for _, utxoEntry := range utxoEntries {
totalBalanceNanos += utxoEntry.AmountNanos
if utxoEntry.BlockHeight > fes.blockchain.BlockTip().Height {
unminedBalanceNanos += utxoEntry.AmountNanos
}
}
// Set the user's balance.
user.BalanceNanos = totalBalanceNanos
user.UnminedBalanceNanos = unminedBalanceNanos
} else {
balanceNanos, err := utxoView.GetDeSoBalanceNanosForPublicKey(publicKeyBytes)
if err != nil {
glog.Errorf("updateUserFields: Error getting balance nanos for public key: %v", err)
}
user.BalanceNanos = balanceNanos
}
}
// We do not need follows for the leaderboard
if !skipForLeaderboard {
// Get the people who the user is following
// Note: we may want to revisit this in the future. This might be inefficient if we're obtaining
// a lot of users and all their followers.
// Set NumToFetch to 0 and fetchAll to true to retrieve all followed public keys.
publicKeyToProfileEntry, _, err := fes.getPublicKeyToProfileEntryMapForFollows(
publicKeyBytes, false, utxoView, nil, 0, false, true)
if err != nil {
return errors.Wrapf(err, "GetFollowsStateless: Problem fetching and decrypting follows:")
}
publicKeysBase58CheckFollowedByUser := make([]string, 0, len(publicKeyToProfileEntry))
for k := range publicKeyToProfileEntry {
publicKeysBase58CheckFollowedByUser = append(publicKeysBase58CheckFollowedByUser, k)
}
// Ensure that these show up in the frontend in a consistent order
// The frontend needs consistent ordering since app.component.ts does the following
// to determine whether any user fields are changed:
// (JSON.stringify(this.appData.loggedInUser) !== JSON.stringify(loggedInUserFound))
sort.Strings(publicKeysBase58CheckFollowedByUser)
user.PublicKeysBase58CheckFollowedByUser = publicKeysBase58CheckFollowedByUser
}
pkid := utxoView.GetPKIDForPublicKey(publicKeyBytes)
// We don't need hodlings for the leaderboard
if !skipForLeaderboard {
var youHodlMap map[string]*BalanceEntryResponse
// Get the users that the user hodls
youHodlMap, err = fes.GetYouHodlMap(pkid, true, false, utxoView)
if err != nil {
return errors.Errorf("updateUserFieldsStateless: Problem with canUserCreateProfile: %v", err)
}
youHodlList := []*BalanceEntryResponse{}
for _, entryRes := range youHodlMap {
youHodlList = append(youHodlList, entryRes)
}
// Note we sort the youHodl list by the creator pk
sort.Slice(youHodlList, func(ii, jj int) bool {
return youHodlList[ii].CreatorPublicKeyBase58Check > youHodlList[jj].CreatorPublicKeyBase58Check
})
var hodlYouMap map[string]*BalanceEntryResponse
hodlYouMap, err = fes.GetHodlYouMap(pkid, false, false, utxoView)
// Assign the new hodl lists to the user object
user.UsersYouHODL = youHodlList
user.UsersWhoHODLYouCount = len(hodlYouMap)
}
// We don't need user metadata from global state for the leaderboard.
if !skipForLeaderboard {
// Populate fields from userMetadata global state
var userMetadata *UserMetadata
userMetadata, err = fes.getUserMetadataFromGlobalState(user.PublicKeyBase58Check)
if err != nil {
return errors.Wrap(fmt.Errorf(
"updateUserFieldsStateless: Problem with getUserMetadataFromGlobalState: %v", err), "")
}
// HasPhoneNumber is a computed boolean so we can avoid returning the phone number in the
// API response, since phone numbers are sensitive PII. Same for emails.
user.HasPhoneNumber = userMetadata.PhoneNumber != ""
user.HasEmail = userMetadata.Email != ""
user.EmailVerified = userMetadata.EmailVerified
user.JumioVerified = userMetadata.JumioVerified
user.JumioReturned = userMetadata.JumioReturned
user.JumioFinishedTime = userMetadata.JumioFinishedTime
user.TutorialStatus = userMetadata.TutorialStatus
user.MustCompleteTutorial = userMetadata.MustCompleteTutorial
// We only need to fetch the creator purchased in the tutorial if the user is still in the tutorial
if user.TutorialStatus != COMPLETE && user.TutorialStatus != SKIPPED && userMetadata.CreatorPurchasedInTutorialPKID != nil {
tutorialCreatorProfileEntry := utxoView.GetProfileEntryForPKID(userMetadata.CreatorPurchasedInTutorialPKID)
if tutorialCreatorProfileEntry == nil {
return fmt.Errorf("updateUserFieldsStateless: Did not find profile entry for PKID for creator purchased in tutorial")
}
username := string(tutorialCreatorProfileEntry.Username)
user.CreatorPurchasedInTutorialUsername = &username
user.CreatorCoinsPurchasedInTutorial = userMetadata.CreatorCoinsPurchasedInTutorial
}
if profileEntryy != nil {
user.ProfileEntryResponse.IsFeaturedTutorialUpAndComingCreator = userMetadata.IsFeaturedTutorialUpAndComingCreator
user.ProfileEntryResponse.IsFeaturedTutorialWellKnownCreator = userMetadata.IsFeaturedTutorialWellKnownCreator
}
if user.CanCreateProfile, err = fes.canUserCreateProfile(userMetadata, utxoView); err != nil {
return errors.Wrap(fmt.Errorf("updateUserFieldsStateless: Problem with canUserCreateProfile: %v", err), "")
}
// Get map of public keys user has blocked
if user.BlockedPubKeys, err = fes.GetBlockedPubKeysForUser(publicKeyBytes); err != nil {
return errors.Wrap(fmt.Errorf("updateUserFieldsStateless: Problem with GetBlockedPubKeysForUser: %v", err), "")
}
}
// Check if the user is blacklisted/graylisted
user.IsBlacklisted = fes.IsUserBlacklisted(pkid.PKID)
user.IsGraylisted = fes.IsUserGraylisted(pkid.PKID)
// Only set User.IsAdmin in GetUsersStateless
// We don't want or need to set this on every endpoint that generates a ProfileEntryResponse
isAdmin, isSuperAdmin := fes.UserAdminStatus(user.PublicKeyBase58Check)
user.IsAdmin = isAdmin
user.IsSuperAdmin = isSuperAdmin
return nil
}
func (fes *APIServer) UserAdminStatus(publicKeyBase58Check string) (_isAdmin bool, _isSuperAdmin bool) {
for _, k := range fes.Config.SuperAdminPublicKeys {
if k == publicKeyBase58Check || k == "*" {
return true, true
}
}
for _, k := range fes.Config.AdminPublicKeys {
if k == publicKeyBase58Check || k == "*" {
return true, false
}
}
return false, false
}
// Get map of creators you hodl.
func (fes *APIServer) GetYouHodlMap(pkid *lib.PKIDEntry, fetchProfiles bool, isDAOCoin bool, utxoView *lib.UtxoView) (
_youHodlMap map[string]*BalanceEntryResponse, _err error) {
// Get all the hodlings for this user from the db
entriesYouHodl, profilesYouHodl, err := utxoView.GetHoldings(pkid.PKID, fetchProfiles, isDAOCoin)
if err != nil {
return nil, fmt.Errorf(
"GetHodlingsForPublicKey: Error looking up balance entries in db: %v", err)
}
// Map hodler pk -> their entry
youHodlMap := fes.getMapFromEntries(entriesYouHodl, profilesYouHodl, true, utxoView)
// Iterate over the view and use the entries to update our maps.
//
// TODO: We need to screen out zero balances in the view. Right now we only screen them
// out from the DB query.
for _, balanceEntry := range utxoView.GetHODLerPKIDCreatorPKIDToBalanceEntryMap(isDAOCoin) {
dbBalanceEntryResponse := &BalanceEntryResponse{}
if reflect.DeepEqual(balanceEntry.HODLerPKID, pkid.PKID) {
// In this case the user is the HODLer.
// Optionally look up the profile of the creator.
var profileEntry *lib.ProfileEntry
if fetchProfiles {
profileEntry = utxoView.GetProfileEntryForPKID(balanceEntry.CreatorPKID)
}
if _, ok := youHodlMap[lib.PkToString(balanceEntry.CreatorPKID[:], fes.Params)]; ok {
// If we made it here, we found both a mempool and a db balanceEntry.
// We update the dbBalanceEntry so it can be used in order to get net mempool data.
dbBalanceEntryResponse = youHodlMap[lib.PkToString(balanceEntry.CreatorPKID[:], fes.Params)]
}
youHodlMap[lib.PkToString(balanceEntry.CreatorPKID[:], fes.Params)] = fes._balanceEntryToResponse(
balanceEntry, dbBalanceEntryResponse.BalanceNanos, profileEntry, utxoView)
}
}
return youHodlMap, nil
}
// Convert list of BalanceEntries to a map of hodler / creator PKID to balance entry response.
func (fes *APIServer) getMapFromEntries(entries []*lib.BalanceEntry, profiles []*lib.ProfileEntry, useCreatorPKIDAsKey bool, utxoView *lib.UtxoView) map[string]*BalanceEntryResponse {
mapYouHodl := map[string]*BalanceEntryResponse{}
for ii, entry := range entries {
var currentProfile *lib.ProfileEntry
if len(profiles) != 0 {
currentProfile = profiles[ii]
}
// Creator coins can't exceed uint64
if useCreatorPKIDAsKey {
mapYouHodl[lib.PkToString(entry.CreatorPKID[:], fes.Params)] =
fes._balanceEntryToResponse(entry, entry.BalanceNanos.Uint64() /*dbBalanceNanos*/, currentProfile, utxoView)
} else {
mapYouHodl[lib.PkToString(entry.HODLerPKID[:], fes.Params)] =
fes._balanceEntryToResponse(entry, entry.BalanceNanos.Uint64() /*dbBalanceNanos*/, currentProfile, utxoView)
}
}
return mapYouHodl
}
func (fes *APIServer) _balanceEntryToResponse(
balanceEntry *lib.BalanceEntry, dbBalanceNanos uint64, profileEntry *lib.ProfileEntry, utxoView *lib.UtxoView) *BalanceEntryResponse {
if balanceEntry == nil {
return nil
}
// Convert the PKIDs to public keys.
hodlerPk := utxoView.GetPublicKeyForPKID(balanceEntry.HODLerPKID)
creatorPk := utxoView.GetPublicKeyForPKID(balanceEntry.CreatorPKID)
return &BalanceEntryResponse{
HODLerPublicKeyBase58Check: lib.PkToString(hodlerPk, fes.Params),
CreatorPublicKeyBase58Check: lib.PkToString(creatorPk, fes.Params),
HasPurchased: balanceEntry.HasPurchased,
// CreatorCoins can't exceed uint64
BalanceNanos: balanceEntry.BalanceNanos.Uint64(),
// Use this value for DAO Coins balances
BalanceNanosUint256: balanceEntry.BalanceNanos,
NetBalanceInMempool: int64(balanceEntry.BalanceNanos.Uint64()) - int64(dbBalanceNanos),
// If the profile is nil, this will be nil
ProfileEntryResponse: fes._profileEntryToResponse(profileEntry, utxoView),
}
}
// GetHodlingsForPublicKey ...
func (fes *APIServer) GetHodlingsForPublicKey(
pkid *lib.PKIDEntry, fetchProfiles bool, isDAOCoin bool, referenceUtxoView *lib.UtxoView) (
_youHodlMap map[string]*BalanceEntryResponse,
_hodlYouMap map[string]*BalanceEntryResponse, _err error) {
// Get a view that considers all of this user's transactions.
var utxoView *lib.UtxoView
if referenceUtxoView != nil {
utxoView = referenceUtxoView
} else {
var err error
utxoView, err = fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
return nil, nil, fmt.Errorf(
"GetHodlingsForPublicKey: Error calling GetAugmentedUtxoViewForPublicKey: %v", err)
}
}
// Get the map of entries this PKID hodls.
youHodlMap, err := fes.GetYouHodlMap(pkid, fetchProfiles, isDAOCoin, utxoView)
if err != nil {
return nil, nil, err
}
// Get the map of the entries hodlings this PKID
hodlYouMap, err := fes.GetHodlYouMap(pkid, fetchProfiles, isDAOCoin, utxoView)
if err != nil {
return nil, nil, err
}
// At this point, the maps should reflect all the creators the user HODLs
// and all the people who HODL the user.
return youHodlMap, hodlYouMap, nil
}
// Get map of public keys hodling your coin.
func (fes *APIServer) GetHodlYouMap(pkid *lib.PKIDEntry, fetchProfiles bool, isDAOCoin bool, utxoView *lib.UtxoView) (
_youHodlMap map[string]*BalanceEntryResponse, _err error) {
// Get all the hodlings for this user from the db
entriesHodlingYou, profileHodlingYou, err := utxoView.GetHolders(pkid.PKID, fetchProfiles, isDAOCoin)
if err != nil {
return nil, fmt.Errorf(
"GetHodlingsForPublicKey: Error looking up balance entries in db: %v", err)
}
// Map hodler pk -> their entry
hodlYouMap := fes.getMapFromEntries(entriesHodlingYou, profileHodlingYou, false, utxoView)
// Iterate over the view and use the entries to update our maps.
//
// TODO: We need to screen out zero balances in the view. Right now we only screen them
// out from the DB query.
for _, balanceEntry := range utxoView.GetHODLerPKIDCreatorPKIDToBalanceEntryMap(isDAOCoin) {
dbBalanceEntryResponse := &BalanceEntryResponse{}
if reflect.DeepEqual(balanceEntry.CreatorPKID, pkid.PKID) {
// In this case the user is the one *being* HODL'ed.
// Optionally ook up the profile of the person who is HODL'ing the user.
var profileEntry *lib.ProfileEntry
if fetchProfiles {
profileEntry = utxoView.GetProfileEntryForPKID(balanceEntry.HODLerPKID)
}
if _, ok := hodlYouMap[lib.PkToString(balanceEntry.HODLerPKID[:], fes.Params)]; ok {
// If we made it here, we found both a mempool and a db balanceEntry.
// We update the dbBalanceEntry so it can be used in order to get net mempool data.
dbBalanceEntryResponse = hodlYouMap[lib.PkToString(balanceEntry.HODLerPKID[:], fes.Params)]
}
hodlYouMap[lib.PkToString(balanceEntry.HODLerPKID[:], fes.Params)] = fes._balanceEntryToResponse(
balanceEntry, dbBalanceEntryResponse.BalanceNanos, profileEntry, utxoView)
}
}
return hodlYouMap, nil
}
type GetUserMetadataRequest struct {
PublicKeyBase58Check string
}
type GetUserMetadataResponse struct {
HasPhoneNumber bool
CanCreateProfile bool
BlockedPubKeys map[string]struct{}
HasEmail bool
EmailVerified bool
// JumioFinishedTime = Time user completed flow in Jumio
JumioFinishedTime uint64
// JumioVerified = user was verified from Jumio flow
JumioVerified bool
// JumioReturned = jumio webhook called
JumioReturned bool
}
// GetUserMetadata ...
func (fes *APIServer) GetUserMetadata(ww http.ResponseWriter, req *http.Request) {
if !fes.Config.ExposeGlobalState {
_AddNotFoundError(ww, fmt.Sprintf("Global state not exposed"))
return
}
vars := mux.Vars(req)
publicKeyBase58Check, publicKeyBase58CheckExists := vars["publicKeyBase58Check"]
if !publicKeyBase58CheckExists {
_AddBadRequestError(ww, fmt.Sprintf("GetUserMetadata: Missing public key base 58 check"))
return
}
// Decode the public key into bytes.
publicKeyBytes, _, err := lib.Base58CheckDecode(publicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetUserMetadata: error decoding public key: %v", err))
return
}
userMetadata, err := fes.getUserMetadataFromGlobalStateByPublicKeyBytes(publicKeyBytes)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetUserMetadata: error getting user metadata from global state: %v", err))
return
}
res := GetUserMetadataResponse{}
res.HasPhoneNumber = userMetadata.PhoneNumber != ""
res.HasEmail = userMetadata.Email != ""
res.EmailVerified = userMetadata.EmailVerified
res.JumioVerified = userMetadata.JumioVerified
res.JumioReturned = userMetadata.JumioReturned
res.JumioFinishedTime = userMetadata.JumioFinishedTime
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetUserMetadata: error getting utxoview: %v", err))
return
}
if res.CanCreateProfile, err = fes.canUserCreateProfile(userMetadata, utxoView); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetUserMetadata: error getting CanCreateProfile: %v", err))
return
}
// Get map of public keys user has blocked
if res.BlockedPubKeys, err = fes.GetBlockedPubKeysForUser(publicKeyBytes); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetUserMetadata: error getting blocked public keys: %v", err))
return
}
if err = json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetUserMetadata: Problem encoding response as JSON: %v", err))
return
}
}
type DeleteIdentityRequest struct{}
type DeleteIdentityResponse struct{}
func (fes *APIServer) DeleteIdentities(ww http.ResponseWriter, req *http.Request) {
// Decode the request data.
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := DeleteIdentityRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("DeleteIdentities: Problem parsing request body: %v", err))
return
}
for _, cookie := range req.Cookies() {
if strings.HasPrefix(cookie.Name, SeedInfoCookieKey) {
cookie := &http.Cookie{
Name: cookie.Name,
Value: "",
MaxAge: 1, // expire immediately
Secure: true,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
http.SetCookie(ww, cookie)
}
}
res := DeleteIdentityResponse{}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("DeleteIdentities: Problem encoding response as JSON: %v", err))
return
}
}
// GetProfilesStatelessRequest ...
type GetProfilesRequest struct {
// When set, we return profiles starting at the given pubkey up to numEntriesToReturn.
PublicKeyBase58Check string `safeForLogging:"true"`
// When set, we return profiles starting at the given username up to numEntriesToReturn.
Username string `safeForLogging:"true"`
// When specified, we filter out all profiles that don't have this
// string as a prefix on their username.
UsernamePrefix string `safeForLogging:"true"`
// When set, we filter out profiles that don't contain this string
// in their Description field.
Description string `safeForLogging:"true"`
OrderBy string `safeForLogging:"true"`
NumToFetch uint32 `safeForLogging:"true"`
// Public key of the user viewing the profile (affects post entry reader state).
ReaderPublicKeyBase58Check string `safeForLogging:"true"`
// Moderation type (currently empty string or 'leaderboard'). Empty string is for default
// moderation. 'Leaderboard' is a special subset of profiles only removed from the leaderboards.
ModerationType string `safeForLogging:"true"`
// If a single profile is requested, return a list of HODLers and amount they HODL.
FetchUsersThatHODL bool `safeForLogging:"true"`
// If set to true, then the posts in the response will contain a boolean about whether they're in the global feed
AddGlobalFeedBool bool `safeForLogging:"true"`
}
// GetProfilesResponse ...
type GetProfilesResponse struct {
ProfilesFound []*ProfileEntryResponse
NextPublicKey *string
}
type ProfileEntryResponse struct {
// PublicKey is the key used by the user to sign for things and generally
// verify her identity.
PublicKeyBase58Check string
Username string
Description string
IsHidden bool
IsReserved bool
IsVerified bool
Comments []*PostEntryResponse
Posts []*PostEntryResponse
// Creator coin fields
CoinEntry *CoinEntryResponse
// DAO Coin fields
DAOCoinEntry *DAOCoinEntryResponse
// Include current price for the frontend to display.
CoinPriceDeSoNanos uint64
CoinPriceBitCloutNanos uint64 // Deprecated
// Profiles of users that hold the coin + their balances.
UsersThatHODL []*BalanceEntryResponse
// If user is featured as a well known creator in the tutorial.
IsFeaturedTutorialWellKnownCreator bool
// If user is featured as an up and coming creator in the tutorial.
// Note: a user should not be both featured as well known and up and coming
IsFeaturedTutorialUpAndComingCreator bool
// ExtraData stores an arbitrary map of attributes of a ProfileEntry
ExtraData map[string]string
}
type CoinEntryResponse struct {
CreatorBasisPoints uint64
DeSoLockedNanos uint64
NumberOfHolders uint64
CoinsInCirculationNanos uint64
CoinWatermarkNanos uint64
// Deprecated: Temporary to add support for BitCloutLockedNanos
BitCloutLockedNanos uint64 // Deprecated
}
type DAOCoinEntryResponse struct {
NumberOfHolders uint64
CoinsInCirculationNanos uint256.Int
MintingDisabled bool
TransferRestrictionStatus TransferRestrictionStatusString
}
// GetProfiles ...
func (fes *APIServer) GetProfiles(ww http.ResponseWriter, req *http.Request) {
profileEntryResponses := []*ProfileEntryResponse{}
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := GetProfilesRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetProfiles: Problem parsing request body: %v", err))
return
}
// The default number of profiles returned is 20.
numToFetch := 20
if requestData.NumToFetch != 0 {
numToFetch = int(requestData.NumToFetch)
}
// Cap numToFetch at 100
if requestData.NumToFetch > 100 {
_AddBadRequestError(ww, fmt.Sprintf("GetProfiles: Max value for NumToFetch exceeded"))
return
}
// Decode the reader public key into bytes. Default to nil if no pub key is passed in.
var readerPubKey []byte
if requestData.ReaderPublicKeyBase58Check != "" {
var err error
readerPubKey, _, err = lib.Base58CheckDecode(requestData.ReaderPublicKeyBase58Check)
if requestData.ReaderPublicKeyBase58Check != "" && err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"GetProfiles: Problem decoding user public key: %v : %s", err, requestData.ReaderPublicKeyBase58Check))
return
}
}
// Get a utxo view for lookups.
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"GetProfiles: Error fetching profiles from mempool: %v", err))
return
}
// If this is a usernamePrefix request, we hit the DB.
if requestData.UsernamePrefix != "" {
// TODO(performance): This currently fetches all usernames that match this prefix, which
// could get slow. Bandaid fix would be to not search until we have a few characters.
profileEntries, err := fes.GetProfilesByUsernamePrefixAndDeSoLocked(
fes.blockchain.DB(), requestData.UsernamePrefix, readerPubKey, utxoView)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"GetProfiles: Error fetching profiles from view: %v", err))
return
}
for _, profileEntry := range profileEntries {
profileEntryResponses = append(
profileEntryResponses, fes._profileEntryToResponse(profileEntry, utxoView))
if len(profileEntryResponses) == numToFetch {
break
}
}
usernameSearchRes := &GetProfilesResponse{ProfilesFound: profileEntryResponses}
// If we get here, we already handled a username prefix search request and can bail.
if err = json.NewEncoder(ww).Encode(usernameSearchRes); err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"GetProfiles: Problem encoding response as JSON: %v", err))
return
}
return
}
// Decode the start public key into bytes. Default to nil if no pub key is passed in.
var startPubKey []byte
if requestData.PublicKeyBase58Check != "" {
var err error
startPubKey, _, err = lib.Base58CheckDecode(requestData.PublicKeyBase58Check)
if requestData.PublicKeyBase58Check != "" && err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"GetProfiles: Problem decoding user public key: %v : %s", err, requestData.PublicKeyBase58Check))
return
}
}
// If we don't have a public key, check for a username and get the public key if it exists.
if startPubKey == nil && requestData.Username != "" {
profile := utxoView.GetProfileEntryForUsername([]byte(requestData.Username))
if profile == nil {
_AddBadRequestError(ww, fmt.Sprintf(
"GetProfiles: Problem getting profile for username: %v : %s", err, requestData.Username))
return
}
startPubKey = profile.PublicKey
}
getPosts := false
if numToFetch == 1 {
// The only time we need comments and posts attached to profile entries right now
// is on the profile detail page where we are fetching a single profile.
getPosts = true
}
// Fetch the profiles.
// TODO: extraNumToFetchMultiplier is a dirty hack. We fetch more than numToFetch profiles
// to adjust for the fact that some profiles will be filtered out from the fetch due to their
// being blacklisted. The real fix would be to have GetProfilesByCoinValue to keep fetching
// until it has numToFetch profiles, while not considering blacklisted profiles. When numToFetch is 1, only fetch that
// single profile.
extraNumToFetchMultiplier := 5
totalToFetch := extraNumToFetchMultiplier * numToFetch
if numToFetch == 1 {
totalToFetch = 1
}
profileEntriesByPublicKey,
postsByProfilePublicKey,
postEntryReaderStates,
err := fes.GetProfilesByCoinValue(
utxoView, readerPubKey, startPubKey, totalToFetch,
getPosts, requestData.ModerationType)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetProfiles: Error fetching profiles from view: %v", err))
return
}
if numToFetch == 1 {
// If only one entry was requested, find that one.
profileEntry := profileEntriesByPublicKey[lib.MakePkMapKey(startPubKey)]
if profileEntry == nil {
_AddBadRequestError(ww, fmt.Sprintf("GetProfiles: Could not find profile for pub key: %v", startPubKey))
return
}
profileEntryResponse := fes.augmentProfileEntry(
profileEntry,
profileEntriesByPublicKey,
postsByProfilePublicKey,
postEntryReaderStates,
requestData.AddGlobalFeedBool,
utxoView,
readerPubKey,
)
// Get the users that HODL this profile, if requested.
hodlYouList := []*BalanceEntryResponse{}
if requestData.FetchUsersThatHODL {
// Get the users that the user hodls and vice versa
pkid := utxoView.GetPKIDForPublicKey(startPubKey)
_, hodlYouMap, err := fes.GetHodlingsForPublicKey(
pkid, true /*fetchProfiles*/, false, utxoView)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"GetProfiles: Could not find HODLers for pub key: %v", startPubKey))
return
}
for _, entryRes := range hodlYouMap {
hodlYouList = append(hodlYouList, entryRes)
}
// Note we sort the hodlYou list by amount held, descending. If creator is hodler, creator should be first
sort.Slice(hodlYouList, func(ii, jj int) bool {
if hodlYouList[ii].CreatorPublicKeyBase58Check == hodlYouList[ii].HODLerPublicKeyBase58Check {
return true
}
if hodlYouList[jj].CreatorPublicKeyBase58Check == hodlYouList[jj].HODLerPublicKeyBase58Check {
return false
}
return hodlYouList[ii].BalanceNanos > hodlYouList[jj].BalanceNanos
})
}
profileEntryResponse.UsersThatHODL = hodlYouList
// Add the completed profileEntryResponse to the list we return.
profileEntryResponses = append(profileEntryResponses, profileEntryResponse)
} else {
for _, profileEntry := range profileEntriesByPublicKey {
// Append the profile to the list
profileEntryResponses = append(profileEntryResponses, fes.augmentProfileEntry(
profileEntry,
profileEntriesByPublicKey,
postsByProfilePublicKey,
postEntryReaderStates,
requestData.AddGlobalFeedBool,
utxoView,
readerPubKey,
))
}
}
if requestData.OrderBy == "newest_last_post" {
// Sort each profile's posts so that the newest post is first.
for _, profileRes := range profileEntryResponses {
if len(profileRes.Posts) == 0 {
continue
}
sort.Slice(profileRes.Posts, func(ii, jj int) bool {
return profileRes.Posts[ii].TimestampNanos > profileRes.Posts[jj].TimestampNanos
})
}
// The posts should be sorted so that the latest post is first.
sort.Slice(profileEntryResponses, func(ii, jj int) bool {
lastPostTimeii := uint64(0)
if len(profileEntryResponses[ii].Posts) > 0 {
lastPostTimeii = profileEntryResponses[ii].Posts[0].TimestampNanos
}
lastPostTimejj := uint64(0)
if len(profileEntryResponses[jj].Posts) > 0 {
lastPostTimejj = profileEntryResponses[jj].Posts[0].TimestampNanos
}
return lastPostTimeii > lastPostTimejj
})
} else if requestData.OrderBy == "newest_last_comment" {
sort.Slice(profileEntryResponses, func(ii, jj int) bool {
lastCommentTimeii := uint64(0)
if len(profileEntryResponses[ii].Comments) > 0 {
lastCommentTimeii = profileEntryResponses[ii].Comments[len(profileEntryResponses[ii].Comments)-1].TimestampNanos
}
lastCommentTimejj := uint64(0)
if len(profileEntryResponses[jj].Comments) > 0 {
lastCommentTimejj = profileEntryResponses[jj].Comments[len(profileEntryResponses[jj].Comments)-1].TimestampNanos
}
return lastCommentTimeii > lastCommentTimejj
})
} else if requestData.OrderBy == "influencer_coin_price" {
sort.Slice(profileEntryResponses, func(ii, jj int) bool {
return profileEntryResponses[ii].CoinEntry.DeSoLockedNanos > profileEntryResponses[jj].CoinEntry.DeSoLockedNanos
})
}
// Sliced returned profiles found down to the number of entries specified, if necessary.
var res *GetProfilesResponse
if len(profileEntryResponses) > numToFetch || startPubKey != nil {
// Find the startPubKey and start response from that index
startIdx := 0
if startPubKey != nil {
for ii, profileEntryResponse := range profileEntryResponses {
if profileEntryResponse.PublicKeyBase58Check == requestData.PublicKeyBase58Check {
startIdx = ii
break
}
}
}
var maxIdx int
var nextPubKey *string
if len(profileEntryResponses) > startIdx+numToFetch {
maxIdx = startIdx + numToFetch
nextPubKey = &profileEntryResponses[maxIdx].PublicKeyBase58Check
} else {
maxIdx = len(profileEntryResponses)
nextPubKey = nil
}
res = &GetProfilesResponse{
ProfilesFound: profileEntryResponses[startIdx:maxIdx],
NextPublicKey: nextPubKey,
}
} else {
res = &GetProfilesResponse{ProfilesFound: profileEntryResponses}
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"GetProfiles: Problem encoding response as JSON: %v", err))
return
}
}
func (fes *APIServer) GetProfilesByUsernamePrefixAndDeSoLocked(
db *badger.DB, usernamePrefix string, readerPK []byte, utxoView *lib.UtxoView) (
_profileEntries []*lib.ProfileEntry, _err error) {
profileEntries, err := lib.DBGetProfilesByUsernamePrefixAndDeSoLocked(db, fes.blockchain.Snapshot(), usernamePrefix, utxoView)
pubKeyMap := make(map[lib.PkMapKey][]byte)
for _, profileEntry := range profileEntries {
pubKeyMap[lib.MakePkMapKey(profileEntry.PublicKey)] = profileEntry.PublicKey
}
filteredPubKeyMap, err := fes.FilterOutRestrictedPubKeysFromMap(pubKeyMap, readerPK, "leaderboard", utxoView)
if err != nil {
return nil, fmt.Errorf("DBGetProfilesByUsernamePrefixAndDeSoLocked: %v", err)
}
var filteredProfileEntries []*lib.ProfileEntry
for _, profileEntry := range profileEntries {
_, found := filteredPubKeyMap[lib.MakePkMapKey(profileEntry.PublicKey)]
if found {
filteredProfileEntries = append(filteredProfileEntries, profileEntry)
}
}
return filteredProfileEntries, nil
}
func (fes *APIServer) _profileEntryToResponse(profileEntry *lib.ProfileEntry, utxoView *lib.UtxoView) *ProfileEntryResponse {
if profileEntry == nil {
return nil
}
coinPriceDeSoNanos := uint64(0)
// CreatorCoins can't exceed uint64
if profileEntry.CreatorCoinEntry.CoinsInCirculationNanos.Uint64() != 0 {
// The price formula is:
// coinPriceDeSoNanos = DeSoLockedNanos / (CoinsInCirculationNanos * ReserveRatio) * NanosPerUnit
bigNanosPerUnit := lib.NewFloat().SetUint64(lib.NanosPerUnit)
// CreatorCoins can't exceed uint64
coinPriceDeSoNanos, _ = lib.Mul(lib.Div(
lib.Div(lib.NewFloat().SetUint64(profileEntry.CreatorCoinEntry.DeSoLockedNanos), bigNanosPerUnit),
lib.Mul(lib.Div(lib.NewFloat().SetUint64(profileEntry.CreatorCoinEntry.CoinsInCirculationNanos.Uint64()), bigNanosPerUnit),
fes.Params.CreatorCoinReserveRatio)), lib.NewFloat().SetUint64(lib.NanosPerUnit)).Uint64()
}
// TODO: Delete this and use global state for verifications once we move all usernames
// out of reserved_usernames.go.
isReserved := false
isVerified := false
lowercaseUsernameString := strings.ToLower(string(profileEntry.Username))
if val, ok := lib.IsReserved[lowercaseUsernameString]; ok {
isReserved = val
// As a quick hack, we set the value in our IsReserved map to false when a profile is claimed.
isVerified = !val
}
// Check global state for isVerified bool.
if fes.VerifiedUsernameToPKIDMap != nil && utxoView != nil {
pkidEntry := utxoView.GetPKIDForPublicKey(profileEntry.PublicKey)
verifiedUsernamePKID := fes.VerifiedUsernameToPKIDMap[strings.ToLower(string(profileEntry.Username))]
if verifiedUsernamePKID != nil {
// TODO: Delete the "isVerified" or statement once we kell reserved_usernames.go.
isVerified = (*verifiedUsernamePKID == *pkidEntry.PKID) || isVerified
}
}
// Generate profile entry response
profResponse := &ProfileEntryResponse{
PublicKeyBase58Check: lib.PkToString(profileEntry.PublicKey, fes.Params),
Username: string(profileEntry.Username),
Description: string(profileEntry.Description),
CoinEntry: &CoinEntryResponse{
CreatorBasisPoints: profileEntry.CreatorCoinEntry.CreatorBasisPoints,
DeSoLockedNanos: profileEntry.CreatorCoinEntry.DeSoLockedNanos,
NumberOfHolders: profileEntry.CreatorCoinEntry.NumberOfHolders,
CoinsInCirculationNanos: profileEntry.CreatorCoinEntry.CoinsInCirculationNanos.Uint64(),
CoinWatermarkNanos: profileEntry.CreatorCoinEntry.CoinWatermarkNanos,
BitCloutLockedNanos: profileEntry.CreatorCoinEntry.DeSoLockedNanos,
},
DAOCoinEntry: &DAOCoinEntryResponse{
NumberOfHolders: profileEntry.DAOCoinEntry.NumberOfHolders,
CoinsInCirculationNanos: profileEntry.DAOCoinEntry.CoinsInCirculationNanos,
MintingDisabled: profileEntry.DAOCoinEntry.MintingDisabled,
TransferRestrictionStatus: getTransferRestrictionStatusStringFromTransferRestrictionStatus(
profileEntry.DAOCoinEntry.TransferRestrictionStatus),
},
CoinPriceDeSoNanos: coinPriceDeSoNanos,
CoinPriceBitCloutNanos: coinPriceDeSoNanos,
IsHidden: profileEntry.IsHidden,
IsReserved: isReserved,
IsVerified: isVerified,
ExtraData: DecodeExtraDataMap(fes.Params, utxoView, profileEntry.ExtraData),
}
return profResponse
}
func getTransferRestrictionStatusStringFromTransferRestrictionStatus(
transferRestrictionStatus lib.TransferRestrictionStatus) TransferRestrictionStatusString {
switch transferRestrictionStatus {
case lib.TransferRestrictionStatusUnrestricted: