-
Notifications
You must be signed in to change notification settings - Fork 86
/
server.go
2696 lines (2535 loc) · 79.6 KB
/
server.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/json"
fmt "fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"sync"
"time"
"github.com/pkg/errors"
"github.com/btcsuite/btcd/btcec"
"github.com/deso-protocol/backend/config"
"github.com/golang-jwt/jwt/v4"
"github.com/tyler-smith/go-bip39"
"github.com/deso-protocol/core/lib"
"github.com/dgraph-io/badger/v3"
"github.com/golang/glog"
"github.com/kevinburke/twilio-go"
muxtrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/gorilla/mux"
)
const (
// MaxRequestBodySizeBytes is the maximum size of a request body we will
// generally be willing to process.
MaxRequestBodySizeBytes = 10 * 1e6 // 10M
SeedInfoCookieKey = "seed_info_cookie_key"
TwilioVoipCarrierType = "voip"
TwilioCheckPhoneNumberApproved = "approved"
SafeForLoggingKey = `safeForLogging`
SafeForLoggingValue = "true"
)
const (
RoutePathSendBitClout = "/api/v0/send-bitclout" // Deprecated
RoutePathGetRecloutsForPost = "/api/v0/get-reclouts-for-post" // Deprecated
RoutePathGetQuoteRecloutsForPost = "/api/v0/get-quote-reclouts-for-post" // Deprecated
// base.go
RoutePathHealthCheck = "/api/v0/health-check"
RoutePathGetExchangeRate = "/api/v0/get-exchange-rate"
RoutePathGetAppState = "/api/v0/get-app-state"
RoutePathGetIngressCookie = "/api/v0/get-ingress-cookie"
// transaction.go
RoutePathGetTxn = "/api/v0/get-txn"
RoutePathSubmitTransaction = "/api/v0/submit-transaction"
RoutePathUpdateProfile = "/api/v0/update-profile"
RoutePathExchangeBitcoin = "/api/v0/exchange-bitcoin"
RoutePathSendDeSo = "/api/v0/send-deso"
RoutePathSubmitPost = "/api/v0/submit-post"
RoutePathCreateFollowTxnStateless = "/api/v0/create-follow-txn-stateless"
RoutePathCreateLikeStateless = "/api/v0/create-like-stateless"
RoutePathBuyOrSellCreatorCoin = "/api/v0/buy-or-sell-creator-coin"
RoutePathTransferCreatorCoin = "/api/v0/transfer-creator-coin"
RoutePathSendDiamonds = "/api/v0/send-diamonds"
RoutePathAuthorizeDerivedKey = "/api/v0/authorize-derived-key"
RoutePathDAOCoin = "/api/v0/dao-coin"
RoutePathTransferDAOCoin = "/api/v0/transfer-dao-coin"
RoutePathCreateDAOCoinLimitOrder = "/api/v0/create-dao-coin-limit-order"
RoutePathCreateDAOCoinMarketOrder = "/api/v0/create-dao-coin-market-order"
RoutePathCancelDAOCoinLimitOrder = "/api/v0/cancel-dao-coin-limit-order"
RoutePathAppendExtraData = "/api/v0/append-extra-data"
RoutePathGetTransactionSpending = "/api/v0/get-transaction-spending"
RoutePathGetUsersStateless = "/api/v0/get-users-stateless"
RoutePathDeleteIdentities = "/api/v0/delete-identities"
RoutePathGetProfiles = "/api/v0/get-profiles"
RoutePathGetSingleProfile = "/api/v0/get-single-profile"
RoutePathGetSingleProfilePicture = "/api/v0/get-single-profile-picture"
RoutePathGetHodlersForPublicKey = "/api/v0/get-hodlers-for-public-key"
RoutePathGetHodlersCountForPublicKeys = "/api/v0/get-hodlers-count-for-public-keys"
RoutePathGetDiamondsForPublicKey = "/api/v0/get-diamonds-for-public-key"
RoutePathGetFollowsStateless = "/api/v0/get-follows-stateless"
RoutePathGetUserGlobalMetadata = "/api/v0/get-user-global-metadata"
RoutePathUpdateUserGlobalMetadata = "/api/v0/update-user-global-metadata"
RoutePathGetNotifications = "/api/v0/get-notifications"
RoutePathGetUnreadNotificationsCount = "/api/v0/get-unread-notifications-count"
RoutePathSetNotificationMetadata = "/api/v0/set-notification-metadata"
RoutePathBlockPublicKey = "/api/v0/block-public-key"
RoutePathIsFollowingPublicKey = "/api/v0/is-following-public-key"
RoutePathIsHodlingPublicKey = "/api/v0/is-hodling-public-key"
RoutePathGetUserDerivedKeys = "/api/v0/get-user-derived-keys"
RoutePathGetSingleDerivedKey = "/api/v0/get-single-derived-key"
RoutePathGetTransactionSpendingLimitHexString = "/api/v0/get-transaction-spending-limit-hex-string"
RoutePathGetAccessBytes = "/api/v0/get-access-bytes"
RoutePathGetTransactionSpendingLimitResponseFromHex = "/api/v0/get-transaction-spending-limit-response-from-hex"
RoutePathDeletePII = "/api/v0/delete-pii"
RoutePathGetUserMetadata = "/api/v0/get-user-metadata"
RoutePathGetUsernameForPublicKey = "/api/v0/get-user-name-for-public-key"
RoutePathGetPublicKeyForUsername = "/api/v0/get-public-key-for-user-name"
// dao_coin_exchange.go
RoutePathGetDaoCoinLimitOrders = "/api/v0/get-dao-coin-limit-orders"
RoutePathGetTransactorDaoCoinLimitOrders = "/api/v0/get-transactor-dao-coin-limit-orders"
// post.go
RoutePathGetPostsHashHexList = "/api/v0/get-posts-hashhexlist"
RoutePathGetPostsStateless = "/api/v0/get-posts-stateless"
RoutePathGetSinglePost = "/api/v0/get-single-post"
RoutePathGetLikesForPost = "/api/v0/get-likes-for-post"
RoutePathGetDiamondsForPost = "/api/v0/get-diamonds-for-post"
RoutePathGetRepostsForPost = "/api/v0/get-reposts-for-post"
RoutePathGetQuoteRepostsForPost = "/api/v0/get-quote-reposts-for-post"
RoutePathGetPostsForPublicKey = "/api/v0/get-posts-for-public-key"
RoutePathGetDiamondedPosts = "/api/v0/get-diamonded-posts"
// hot_feed.go
RoutePathGetHotFeed = "/api/v0/get-hot-feed"
// nft.go
RoutePathCreateNFT = "/api/v0/create-nft"
RoutePathUpdateNFT = "/api/v0/update-nft"
RoutePathGetNFTsForUser = "/api/v0/get-nfts-for-user"
RoutePathGetNFTBidsForUser = "/api/v0/get-nft-bids-for-user"
RoutePathCreateNFTBid = "/api/v0/create-nft-bid"
RoutePathAcceptNFTBid = "/api/v0/accept-nft-bid"
RoutePathGetNFTBidsForNFTPost = "/api/v0/get-nft-bids-for-nft-post"
RoutePathGetNFTShowcase = "/api/v0/get-nft-showcase"
RoutePathGetNextNFTShowcase = "/api/v0/get-next-nft-showcase"
RoutePathGetNFTCollectionSummary = "/api/v0/get-nft-collection-summary"
RoutePathGetNFTEntriesForPostHash = "/api/v0/get-nft-entries-for-nft-post"
RoutePathGetNFTsCreatedByPublicKey = "/api/v0/get-nfts-created-by-public-key"
RoutePathTransferNFT = "/api/v0/transfer-nft"
RoutePathAcceptNFTTransfer = "/api/v0/accept-nft-transfer"
RoutePathBurnNFT = "/api/v0/burn-nft"
RoutePathGetAcceptedBidHistory = "/api/v0/accepted-bid-history"
// media.go
RoutePathUploadImage = "/api/v0/upload-image"
RoutePathGetFullTikTokURL = "/api/v0/get-full-tiktok-url"
RoutePathUploadVideo = "/api/v0/upload-video"
RoutePathGetVideoStatus = "/api/v0/get-video-status"
RoutePathGetVideoDimensions = "/api/v0/get-video-dimensions"
RoutePathEnableVideoDownload = "/api/v0/enable-video-download"
// message.go
RoutePathSendMessageStateless = "/api/v0/send-message-stateless"
RoutePathGetMessagesStateless = "/api/v0/get-messages-stateless"
RoutePathMarkContactMessagesRead = "/api/v0/mark-contact-messages-read"
RoutePathMarkAllMessagesRead = "/api/v0/mark-all-messages-read"
RoutePathRegisterMessagingGroupKey = "/api/v0/register-messaging-group-key"
RoutePathGetAllMessagingGroupKeys = "/api/v0/get-all-messaging-group-keys"
RoutePathCheckPartyMessagingKeys = "/api/v0/check-party-messaging-keys"
RoutePathGetBulkMessagingPublicKeys = "/api/v0/get-bulk-messaging-public-keys"
// verify.go
RoutePathSendPhoneNumberVerificationText = "/api/v0/send-phone-number-verification-text"
RoutePathSubmitPhoneNumberVerificationCode = "/api/v0/submit-phone-number-verification-code"
RoutePathResendVerifyEmail = "/api/v0/resend-verify-email"
RoutePathVerifyEmail = "/api/v0/verify-email"
RoutePathJumioBegin = "/api/v0/jumio-begin"
RoutePathJumioCallback = "/api/v0/jumio-callback"
RoutePathJumioFlowFinished = "/api/v0/jumio-flow-finished"
RoutePathGetJumioStatusForPublicKey = "/api/v0/get-jumio-status-for-public-key"
// tutorial.go
RoutePathGetTutorialCreators = "/api/v0/get-tutorial-creators"
RoutePathStartOrSkipTutorial = "/api/v0/start-or-skip-tutorial"
RoutePathUpdateTutorialStatus = "/api/v0/update-tutorial-status"
// eth.go
RoutePathSubmitETHTx = "/api/v0/submit-eth-tx"
RoutePathMetamaskSignIn = "/api/v0/send-starter-deso-for-metamask-account"
RoutePathQueryETHRPC = "/api/v0/query-eth-rpc"
RoutePathAdminProcessETHTx = "/api/v0/admin/process-eth-tx"
// wyre.go
RoutePathGetWyreWalletOrderQuotation = "/api/v0/get-wyre-wallet-order-quotation"
RoutePathGetWyreWalletOrderReservation = "/api/v0/get-wyre-wallet-order-reservation"
RoutePathWyreWalletOrderSubscription = "/api/v0/wyre-wallet-order-subscription"
RoutePathGetWyreWalletOrdersForPublicKey = "/api/v0/admin/get-wyre-wallet-orders-for-public-key"
// miner.go
RoutePathGetBlockTemplate = "/api/v0/get-block-template"
RoutePathSubmitBlock = "/api/v0/submit-block"
// Admin route paths can only be accessed if a user's public key is whitelisted as an admin.
// admin_node.go
RoutePathNodeControl = "/api/v0/admin/node-control"
RoutePathAdminGetMempoolStats = "/api/v0/admin/get-mempool-stats"
// admin_buy_deso.go
RoutePathSetUSDCentsToDeSoReserveExchangeRate = "/api/v0/admin/set-usd-cents-to-deso-reserve-exchange-rate"
RoutePathGetUSDCentsToDeSoReserveExchangeRate = "/api/v0/admin/get-usd-cents-to-deso-reserve-exchange-rate"
RoutePathSetBuyDeSoFeeBasisPoints = "/api/v0/admin/set-buy-deso-fee-basis-points"
RoutePathGetBuyDeSoFeeBasisPoints = "/api/v0/admin/get-buy-deso-fee-basis-points"
// admin_transaction.go
RoutePathGetGlobalParams = "/api/v0/get-global-params"
RoutePathTestSignTransactionWithDerivedKey = "/api/v0/admin/test-sign-transaction-with-derived-key"
// Eventually we will deprecate the admin endpoint since it does not need to be protected.
RoutePathAdminGetGlobalParams = "/api/v0/admin/get-global-params"
RoutePathUpdateGlobalParams = "/api/v0/admin/update-global-params"
RoutePathSwapIdentity = "/api/v0/admin/swap-identity"
// admin_user.go
RoutePathAdminUpdateUserGlobalMetadata = "/api/v0/admin/update-user-global-metadata"
RoutePathAdminGetAllUserGlobalMetadata = "/api/v0/admin/get-all-user-global-metadata"
RoutePathAdminGetUserGlobalMetadata = "/api/v0/admin/get-user-global-metadata"
RoutePathAdminGrantVerificationBadge = "/api/v0/admin/grant-verification-badge"
RoutePathAdminRemoveVerificationBadge = "/api/v0/admin/remove-verification-badge"
RoutePathAdminGetVerifiedUsers = "/api/v0/admin/get-verified-users"
RoutePathAdminGetUsernameVerificationAuditLogs = "/api/v0/admin/get-username-verification-audit-logs"
RoutePathAdminGetUserAdminData = "/api/v0/admin/get-user-admin-data"
RoutePathAdminResetPhoneNumber = "/api/v0/admin/reset-phone-number"
// admin_feed.go
RoutePathAdminUpdateGlobalFeed = "/api/v0/admin/update-global-feed"
RoutePathAdminPinPost = "/api/v0/admin/pin-post"
RoutePathAdminRemoveNilPosts = "/api/v0/admin/remove-nil-posts"
// hot_feed.go
RoutePathAdminGetUnfilteredHotFeed = "/api/v0/admin/get-unfiltered-hot-feed"
RoutePathAdminGetHotFeedAlgorithm = "/api/v0/admin/get-hot-feed-algorithm"
RoutePathAdminUpdateHotFeedAlgorithm = "/api/v0/admin/update-hot-feed-algorithm"
RoutePathAdminUpdateHotFeedPostMultiplier = "/api/v0/admin/update-hot-feed-post-multiplier"
RoutePathAdminUpdateHotFeedUserMultiplier = "/api/v0/admin/update-hot-feed-user-multiplier"
RoutePathAdminGetHotFeedUserMultiplier = "/api/v0/admin/get-hot-feed-user-multiplier"
// admin_fees.go
RoutePathAdminSetTransactionFeeForTransactionType = "/api/v0/admin/set-txn-fee-for-txn-type"
RoutePathAdminSetAllTransactionFees = "/api/v0/admin/set-all-txn-fees"
RoutePathAdminGetTransactionFeeMap = "/api/v0/admin/get-transaction-fee-map"
RoutePathAdminAddExemptPublicKey = "/api/v0/admin/add-exempt-public-key"
RoutePathAdminGetExemptPublicKeys = "/api/v0/admin/get-exempt-public-keys"
// admin_nft.go
RoutePathAdminGetNFTDrop = "/api/v0/admin/get-nft-drop"
RoutePathAdminUpdateNFTDrop = "/api/v0/admin/update-nft-drop"
// admin_jumio.go
RoutePathAdminResetJumioForPublicKey = "/api/v0/admin/reset-jumio-for-public-key"
RoutePathAdminUpdateJumioDeSo = "/api/v0/admin/update-jumio-deso"
RoutePathAdminUpdateJumioUSDCents = "/api/v0/admin/update-jumio-usd-cents"
RoutePathAdminUpdateJumioKickbackUSDCents = "/api/v0/admin/update-jumio-kickback-usd-cents"
RoutePathAdminJumioCallback = "/api/v0/admin/jumio-callback"
RoutePathAdminUpdateJumioCountrySignUpBonus = "/api/v0/admin/update-jumio-country-sign-up-bonus"
RoutePathAdminGetAllCountryLevelSignUpBonuses = "/api/v0/admin/get-all-country-level-sign-up-bonuses"
// admin_referrals.go
RoutePathAdminCreateReferralHash = "/api/v0/admin/create-referral-hash"
RoutePathAdminGetAllReferralInfoForUser = "/api/v0/admin/get-all-referral-info-for-user"
RoutePathAdminUpdateReferralHash = "/api/v0/admin/update-referral-hash"
RoutePathAdminUploadReferralCSV = "/api/v0/admin/upload-referral-csv"
RoutePathAdminDownloadReferralCSV = "/api/v0/admin/download-referral-csv"
RoutePathAdminDownloadRefereeCSV = "/api/v0/admin/download-referee-csv"
// referrals.go
RoutePathGetReferralInfoForUser = "/api/v0/get-referral-info-for-user"
RoutePathGetReferralInfoForReferralHash = "/api/v0/get-referral-info-for-referral-hash"
// admin_tutorial.go
RoutePathAdminUpdateTutorialCreators = "/api/v0/admin/update-tutorial-creators"
RoutePathAdminResetTutorialStatus = "/api/v0/admin/reset-tutorial-status"
RoutePathAdminGetTutorialCreators = "/api/v0/admin/get-tutorial-creators"
// expose_global_state.go
RoutePathGetVerifiedUsernames = "/api/v0/get-verified-usernames"
RoutePathGetBlacklistedPublicKeys = "/api/v0/get-blacklisted-public-keys"
RoutePathGetGraylistedPublicKeys = "/api/v0/get-graylisted-public-keys"
RoutePathGetGlobalFeed = "/api/v0/get-global-feed"
// supply.go
RoutePathGetTotalSupply = "/api/v0/total-supply"
RoutePathGetRichList = "/api/v0/rich-list"
RoutePathGetCountKeysWithDESO = "/api/v0/count-keys-with-deso"
// access_group.go
RoutePathCreateAccessGroup = "/api/v0/create-access-group"
RoutePathUpdateAccessGroup = "/api/v0/update-access-group"
RoutePathAddAccessGroupMembers = "/api/v0/add-access-group-members"
RoutePathRemoveAccessGroupMembers = "/api/v0/remove-access-group-members"
RoutePathUpdateAccessGroupMembers = "/api/v0/update-access-group-members"
RoutePathGetAllUserAccessGroups = "/api/v0/get-all-user-access-groups"
RoutePathGetAllUserAccessGroupsOwned = "/api/v0/get-all-user-access-groups-owned"
RoutePathGetAllUserAccessGroupsMemberOnly = "/api/v0/get-all-user-access-groups-member-only"
RoutePathCheckPartyAccessGroups = "/api/v0/check-party-access-groups"
RoutePathGetAccessGroupInfo = "/api/v0/get-access-group-info"
RoutePathGetAccessGroupMemberInfo = "/api/v0/get-access-group-member-info"
RoutePathGetPaginatedAccessGroupMembers = "/api/v0/get-paginated-access-group-members"
RoutePathGetBulkAccessGroupEntries = "/api/v0/get-bulk-access-group-entries"
// new_message.go
RoutePathSendDmMessage = "/api/v0/send-dm-message"
RoutePathUpdateDmMessage = "/api/v0/update-dm-message"
RoutePathSendGroupChatMessage = "/api/v0/send-group-chat-message"
RoutePathUpdateGroupChatMessage = "/api/v0/update-group-chat-message"
RoutePathGetUserDmThreadsOrderedByTimestamp = "/api/v0/get-user-dm-threads-ordered-by-timestamp"
RoutePathGetPaginatedMessagesForDmThread = "/api/v0/get-paginated-messages-for-dm-thread"
RoutePathGetUserGroupChatThreadsOrderedByTimestamp = "/api/v0/get-user-group-chat-threads-ordered-by-timestamp"
RoutePathGetPaginatedMessagesForGroupChatThread = "/api/v0/get-paginated-messages-for-group-chat-thread"
RoutePathGetAllUserMessageThreads = "/api/v0/get-all-user-message-threads"
// associations.go
RoutePathUserAssociations = "/api/v0/user-associations"
RoutePathPostAssociations = "/api/v0/post-associations"
// snapshot.go
RoutePathSnapshotEpochMetadata = "/api/v0/snapshot-epoch-metadata"
RoutePathStateChecksum = "/api/v0/state-checksum"
)
// APIServer provides the interface between the blockchain and things like the
// web UI. In particular, it exposes a JSON API that can be used to do everything the
// frontend cares about, from posts to profiles to purchasing DeSo with Bitcoin.
type APIServer struct {
backendServer *lib.Server
mempool *lib.DeSoMempool
blockchain *lib.Blockchain
blockProducer *lib.DeSoBlockProducer
Params *lib.DeSoParams
Config *config.Config
MinFeeRateNanosPerKB uint64
// A pointer to the router that handles all requests.
router *muxtrace.Router
TXIndex *lib.TXIndex
// Used for getting/setting the global state. Usually either a db is set OR
// a remote node is set-- not both. When a remote node is set, global state
// is set and fetched from that node. Otherwise, it is set/fetched from the
// db. This makes it easy to run a local node in development.
GlobalState *GlobalState
// Optional, may be empty. Used for Twilio integration
Twilio *twilio.Client
// When set, BlockCypher is used to add extra security to BitcoinExchange
// transactions.
BlockCypherAPIKey string
// This lock is used when sending seed DeSo to avoid a race condition
// in which two calls to sending the seed DeSo use the same UTXO,
// causing one to error.
mtxSeedDeSo sync.RWMutex
UsdCentsPerDeSoExchangeRate uint64
UsdCentsPerBitCoinExchangeRate float64
UsdCentsPerETHExchangeRate uint64
// List of prices retrieved. This is culled everytime we update the current price.
LastTradeDeSoPriceHistory []LastTradePriceHistoryItem
// How far back do we consider trade prices when we set the current price of $DESO in nanoseconds
LastTradePriceLookback uint64
// most recent exchange prices fetched
MostRecentCoinbasePriceUSDCents uint64
MostRecentBlockchainDotComPriceUSDCents uint64
// Base-58 prefix to check for to determine if a string could be a public key.
PublicKeyBase58Prefix string
// A list of posts from the specified look-back period ordered by hotness score.
HotFeedOrderedList []*HotFeedEntry
// A map version of HotFeedOrderedList mapping each post to its hotness score for the tag feed and post age.
HotFeedPostHashToTagScoreMap map[lib.BlockHash]*HotnessPostInfo
// An in-memory map from post hash to post tags. This is used to cache tags to prevent hot feed algorithm from
// continuously parsing the text body from already processed posts.
PostHashToPostTagsMap map[lib.BlockHash][]string
// An in-memory map from post tag to post hash. This allows us to
// quickly get all the posts for a particular group.
// This is represented as a map of strings to a set of post hashes. A set is used instead of an array to allow for
// quicker de-duplication checks.
PostTagToPostHashesMap map[string]map[lib.BlockHash]bool
// For each tag, store ordered slice of post hashes based on hot feed ranking.
PostTagToOrderedHotFeedEntries map[string][]*HotFeedEntry
// For each tag, store ordered slice of post hashes based on newness.
PostTagToOrderedNewestEntries map[string][]*HotFeedEntry
// The height of the last block evaluated by the hotness routine.
HotFeedBlockHeight uint32
// A cache to store blocks for the block feed - in order to reduce processing time.
HotFeedBlockCache map[lib.BlockHash]*lib.MsgDeSoBlock
// Map of whitelisted post hashes used for serving the hot feed.
// The float64 value is a multiplier than can be modified and used in scoring.
HotFeedApprovedPostsToMultipliers map[lib.BlockHash]float64
LastHotFeedApprovedPostOpProcessedTstampNanos uint64
// Multipliers applied to individual PKIDs to help node operators better fit their
// hot feed to the type of content they would like to display.
HotFeedPKIDMultipliers map[lib.PKID]*HotFeedPKIDMultiplier
LastHotFeedPKIDMultiplierOpProcessedTstampNanos uint64
// Constants for the hotness score algorithm.
HotFeedInteractionCap uint64
HotFeedTagInteractionCap uint64
HotFeedTimeDecayBlocks uint64
HotFeedTagTimeDecayBlocks uint64
HotFeedTxnTypeMultiplierMap map[lib.TxnType]uint64
HotFeedPostMultiplierUpdated bool
HotFeedPKIDMultiplierUpdated bool
//Map of transaction type to []*lib.DeSoOutput that represent fees assessed on each transaction of that type.
TransactionFeeMap map[lib.TxnType][]*lib.DeSoOutput
// Map of public keys that are exempt from node fees
ExemptPublicKeyMap map[string]interface{}
// Global State cache
// VerifiedUsernameToPKIDMap is a map of lowercase usernames to PKIDs representing the current state of
// verifications this node is recognizing.
VerifiedUsernameToPKIDMap map[string]*lib.PKID
// BlacklistedPKIDMap is a map of PKID to a byte slice representing the PKID of a user as the key and the current
// blacklist state of that user as the key. If a PKID is not present in this map, then the user is NOT blacklisted.
BlacklistedPKIDMap map[lib.PKID][]byte
// BlacklistedResponseMap is a map of PKIDs converted to base58-encoded string to a byte slice. This is computed
// from the BlacklistedPKIDMap above and is a JSON-encodable version of that map. This map is only used when
// responding to requests for this node's blacklist. A JSON-encoded response is easier for any language to digest
// than a gob-encoded one.
BlacklistedResponseMap map[string][]byte
// GraylistedPKIDMap is a map of PKID to a byte slice representing the PKID of a user as the key and the current
// graylist state of that user as the key. If a PKID is not present in this map, then the user is NOT graylisted.
GraylistedPKIDMap map[lib.PKID][]byte
// GraylistedResponseMap is a map of PKIDs converted to base58-encoded string to a byte slice. This is computed
// from the GraylistedPKIDMap above and is a JSON-encodable version of that map. This map is only used when
// responding to requests for this node's graylist. A JSON-encoded response is easier for any language to digest
// than a gob-encoded one.
GraylistedResponseMap map[string][]byte
// GlobalFeedPostHashes is a slice of BlockHashes representing an ordered state of post hashes on the global feed on
// this node.
GlobalFeedPostHashes []*lib.BlockHash
// GlobalFeedPostEntries is a slice of PostEntries representing an ordered state of PostEntries on the global feed
// on this node. It is computed from the GlobalFeedPostHashes above.
GlobalFeedPostEntries []*lib.PostEntry
// Cache of Total Supply and Rich List
TotalSupplyNanos uint64
TotalSupplyDESO float64
RichList []RichListEntryResponse
CountKeysWithDESO uint64
// map of country name to sign up bonus data
AllCountryLevelSignUpBonuses map[string]CountrySignUpBonusResponse
// Frequently accessed data from global state
USDCentsToDESOReserveExchangeRate uint64
BuyDESOFeeBasisPoints uint64
JumioUSDCents uint64
JumioKickbackUSDCents uint64
// Public keys that need their balances monitored. Map of Label to Public key
PublicKeyBalancesToMonitor map[string]string
// Signals that the frontend server is in a stopped state
quit chan struct{}
}
type LastTradePriceHistoryItem struct {
LastTradePrice uint64
Timestamp uint64
}
// NewAPIServer ...
func NewAPIServer(
_backendServer *lib.Server,
_mempool *lib.DeSoMempool,
_blockchain *lib.Blockchain,
_blockProducer *lib.DeSoBlockProducer,
txIndex *lib.TXIndex,
params *lib.DeSoParams,
config *config.Config,
minFeeRateNanosPerKB uint64,
globalStateDB *badger.DB,
twilio *twilio.Client,
blockCypherAPIKey string,
) (*APIServer, error) {
globalState := &GlobalState{
GlobalStateRemoteSecret: config.GlobalStateRemoteSecret,
GlobalStateRemoteNode: config.GlobalStateRemoteNode,
GlobalStateDB: globalStateDB,
}
if globalStateDB == nil && globalState.GlobalStateRemoteNode == "" {
return nil, fmt.Errorf(
"NewAPIServer: Error: A globalStateDB or a globalStateRemoteNode is required")
}
publicKeyBase58Prefix := lib.Base58CheckEncode(make([]byte, btcec.PubKeyBytesLenCompressed), false, params)[0:3]
fes := &APIServer{
// TODO: It would be great if we could eliminate the dependency on
// the backendServer. Right now it's here because it was the easiest
// way to give the APIServer the ability to add transactions
// to the mempool and relay them to peers.
backendServer: _backendServer,
mempool: _mempool,
blockchain: _blockchain,
blockProducer: _blockProducer,
TXIndex: txIndex,
Params: params,
Config: config,
Twilio: twilio,
BlockCypherAPIKey: blockCypherAPIKey,
GlobalState: globalState,
LastTradeDeSoPriceHistory: []LastTradePriceHistoryItem{},
PublicKeyBase58Prefix: publicKeyBase58Prefix,
// We consider last trade prices from the last hour when determining the current price of DeSo.
// This helps prevents attacks that attempt to purchase $DESO at below market value.
LastTradePriceLookback: uint64(time.Hour.Nanoseconds()),
AllCountryLevelSignUpBonuses: make(map[string]CountrySignUpBonusResponse),
quit: make(chan struct{}),
}
fes.StartSeedBalancesMonitoring()
// Call this once upon starting server to ensure we have a good initial value
fes.UpdateUSDCentsToDeSoExchangeRate()
fes.UpdateUSDToBTCPrice()
fes.UpdateUSDToETHPrice()
// Get the transaction fee map from global state if it exists
fes.TransactionFeeMap = fes.GetTransactionFeeMapFromGlobalState()
fes.ExemptPublicKeyMap = fes.GetExemptPublicKeyMapFromGlobalState()
// Then monitor them
fes.StartExchangePriceMonitoring()
if fes.Config.RunHotFeedRoutine {
fes.StartHotFeedRoutine()
}
if fes.Config.RunSupplyMonitoringRoutine {
fes.StartSupplyMonitoring()
fes.UpdateSupplyStats()
}
fes.SetGlobalStateCache()
// Kick off Global State Monitoring to set up cache of Verified Username, Blacklist, and Graylist.
fes.StartGlobalStateMonitoring()
return fes, nil
}
type AccessLevel int
const (
PublicAccess AccessLevel = iota
AdminAccess
SuperAdminAccess
)
// Route ...
type Route struct {
Name string
Method []string
Pattern string
HandlerFunc http.HandlerFunc
AccessLevel AccessLevel
}
// InitRoutes ...
// Note: Be very careful when editing existing routes in this list.
// This *must* be kept in-sync with the backend-api.service.ts file in the
// frontend code. If not, then requests will fail.
func (fes *APIServer) NewRouter() *muxtrace.Router {
var FrontendRoutes = []Route{
// Deprecated
{
"SendBitClout",
[]string{"POST", "OPTIONS"},
RoutePathSendBitClout,
fes.SendDeSo,
PublicAccess,
},
{
"GetRecloutsForPost",
[]string{"POST", "OPTIONS"},
RoutePathGetRecloutsForPost,
fes.GetRepostsForPost,
PublicAccess,
},
{
"GetQuoteRecloutsForPost",
[]string{"POST", "OPTIONS"},
RoutePathGetQuoteRecloutsForPost,
fes.GetQuoteRepostsForPost,
PublicAccess,
},
{
"Index",
[]string{"GET"},
"/",
fes.Index,
PublicAccess,
},
{
"HealthCheck",
[]string{"GET"},
RoutePathHealthCheck,
fes.HealthCheck,
PublicAccess,
},
// Routes for populating various UI elements.
{
"GetExchangeRate",
[]string{"GET"},
RoutePathGetExchangeRate,
fes.GetExchangeRate,
PublicAccess,
},
{
"GetGlobalParams",
[]string{"POST", "OPTIONS"},
RoutePathGetGlobalParams,
fes.GetGlobalParams,
PublicAccess,
},
// Route for sending DeSo
{
"SendDeSo",
[]string{"POST", "OPTIONS"},
RoutePathSendDeSo,
fes.SendDeSo,
PublicAccess,
},
// Route for exchanging Bitcoin for DeSo
{
"ExchangeBitcoin",
[]string{"POST", "OPTIONS"},
RoutePathExchangeBitcoin,
fes.ExchangeBitcoinStateless,
PublicAccess,
},
// Route for submitting signed transactions for network broadcast
{
"SubmitTransaction",
[]string{"POST", "OPTIONS"},
RoutePathSubmitTransaction,
fes.SubmitTransaction,
PublicAccess,
},
// Temporary route to wipe seedinfo cookies
{
"DeleteIdentities",
[]string{"POST", "OPTIONS"},
RoutePathDeleteIdentities,
fes.DeleteIdentities,
PublicAccess,
},
// Endpoint to trigger granting a user a verified badge
// The new DeSo endpoints start here.
{
"GetUsersStateless",
[]string{"POST", "OPTIONS"},
RoutePathGetUsersStateless,
fes.GetUsersStateless,
PublicAccess,
},
{
"SendPhoneNumberVerificationText",
[]string{"POST", "OPTIONS"},
RoutePathSendPhoneNumberVerificationText,
fes.SendPhoneNumberVerificationText,
PublicAccess,
},
{
"SubmitPhoneNumberVerificationCode",
[]string{"POST", "OPTIONS"},
RoutePathSubmitPhoneNumberVerificationCode,
fes.SubmitPhoneNumberVerificationCode,
PublicAccess,
},
{
"UploadImage",
[]string{"POST", "OPTIONS"},
RoutePathUploadImage,
fes.UploadImage,
PublicAccess,
},
{
"SubmitPost",
[]string{"POST", "OPTIONS"},
RoutePathSubmitPost,
fes.SubmitPost,
PublicAccess,
},
{
"PostsHashHexList",
[]string{"POST", "OPTIONS"},
RoutePathGetPostsHashHexList,
fes.GetPostsHashHexList,
PublicAccess,
},
{
"GetPostsStateless",
[]string{"POST", "OPTIONS"},
RoutePathGetPostsStateless,
fes.GetPostsStateless,
// CheckSecret: No need to check the secret since this is a read-only endpoint.
PublicAccess,
},
{
"UpdateProfile",
[]string{"POST", "OPTIONS"},
RoutePathUpdateProfile,
fes.UpdateProfile,
PublicAccess,
},
{
"GetProfiles",
[]string{"POST", "OPTIONS"},
RoutePathGetProfiles,
fes.GetProfiles,
// CheckSecret: No need to check the secret since this is a read-only endpoint.
PublicAccess,
},
{
"GetSingleProfile",
[]string{"POST", "OPTIONS"},
RoutePathGetSingleProfile,
fes.GetSingleProfile,
PublicAccess,
},
{
"GetSingleProfilePicture",
[]string{"GET"},
RoutePathGetSingleProfilePicture + "/{publicKeyBase58Check:[0-9a-zA-Z]{54,55}}",
fes.GetSingleProfilePicture,
PublicAccess,
},
{
"GetPostsForPublicKey",
[]string{"POST", "OPTIONS"},
RoutePathGetPostsForPublicKey,
fes.GetPostsForPublicKey,
PublicAccess,
},
{
"GetDiamondsForPublicKey",
[]string{"POST", "OPTIONS"},
RoutePathGetDiamondsForPublicKey,
fes.GetDiamondsForPublicKey,
PublicAccess,
},
{
"GetDiamondedPosts",
[]string{"POST", "OPTIONS"},
RoutePathGetDiamondedPosts,
fes.GetDiamondedPosts,
PublicAccess,
},
{
"GetHotFeed",
[]string{"POST", "OPTIONS"},
RoutePathGetHotFeed,
fes.GetHotFeed,
PublicAccess,
},
{
"CreateNFT",
[]string{"POST", "OPTIONS"},
RoutePathCreateNFT,
fes.CreateNFT,
PublicAccess,
},
{
"TransferNFT",
[]string{"POST", "OPTIONS"},
RoutePathTransferNFT,
fes.TransferNFT,
PublicAccess,
},
{
"AcceptNFTTransfer",
[]string{"POST", "OPTIONS"},
RoutePathAcceptNFTTransfer,
fes.AcceptNFTTransfer,
PublicAccess,
},
{
"BurnNFT",
[]string{"POST", "OPTIONS"},
RoutePathBurnNFT,
fes.BurnNFT,
PublicAccess,
},
{
"GetAcceptedBidHistory",
[]string{"GET"},
RoutePathGetAcceptedBidHistory + "/{postHashHex:[0-9a-zA-Z]{64}}",
fes.GetAcceptedBidHistory,
PublicAccess,
},
{
"UpdateNFT",
[]string{"POST", "OPTIONS"},
RoutePathUpdateNFT,
fes.UpdateNFT,
PublicAccess,
},
{
"CreateNFTBid",
[]string{"POST", "OPTIONS"},
RoutePathCreateNFTBid,
fes.CreateNFTBid,
PublicAccess,
},
{
"AcceptNFTBid",
[]string{"POST", "OPTIONS"},
RoutePathAcceptNFTBid,
fes.AcceptNFTBid,
PublicAccess,
},
{
"GetNFTBidsForNFTPost",
[]string{"POST", "OPTIONS"},
RoutePathGetNFTBidsForNFTPost,
fes.GetNFTBidsForNFTPost,
PublicAccess,
},
{
"GetNFTShowcase",
[]string{"POST", "OPTIONS"},
RoutePathGetNFTShowcase,
fes.GetNFTShowcase,
PublicAccess,
},
{
"GetNextNFTShowcase",
[]string{"POST", "OPTIONS"},
RoutePathGetNextNFTShowcase,
fes.GetNextNFTShowcase,
PublicAccess,
},
{
"GetNFTsForUser",
[]string{"POST", "OPTIONS"},
RoutePathGetNFTsForUser,
fes.GetNFTsForUser,
PublicAccess,
},
{
"GetNFTBidsForUser",
[]string{"POST", "OPTIONS"},
RoutePathGetNFTBidsForUser,
fes.GetNFTBidsForUser,
PublicAccess,
},
{
"GetNFTCollectionSummary",
[]string{"POST", "OPTIONS"},
RoutePathGetNFTCollectionSummary,
fes.GetNFTCollectionSummary,
PublicAccess,
},
{
"GetNFTEntriesForPostHash",
[]string{"POST", "OPTIONS"},
RoutePathGetNFTEntriesForPostHash,
fes.GetNFTEntriesForPostHash,
PublicAccess,
},
{
"GetNFTsCreatedByPublicKey",
[]string{"POST", "OPTIONS"},
RoutePathGetNFTsCreatedByPublicKey,
fes.GetNFTsCreatedByPublicKey,
PublicAccess,
},
{
"GetHodlersForPublicKey",
[]string{"POST", "OPTIONS"},
RoutePathGetHodlersForPublicKey,
fes.GetHodlersForPublicKey,
PublicAccess,
},
{
"GetHodlersCountForPublicKeys",
[]string{"POST", "OPTIONS"},
RoutePathGetHodlersCountForPublicKeys,
fes.GetHodlersCountForPublicKeys,
PublicAccess,
},
{
"GetFollowsStateless",
[]string{"POST", "OPTIONS"},
RoutePathGetFollowsStateless,
fes.GetFollowsStateless,
PublicAccess,
},
{
"CreateFollowTxnStateless",
[]string{"POST", "OPTIONS"},
RoutePathCreateFollowTxnStateless,
fes.CreateFollowTxnStateless,
PublicAccess,
},
{
"CreateLikeStateless",
[]string{"POST", "OPTIONS"},
RoutePathCreateLikeStateless,
fes.CreateLikeStateless,
PublicAccess,
},
{
"BuyOrSellCreatorCoin",
[]string{"POST", "OPTIONS"},
RoutePathBuyOrSellCreatorCoin,
fes.BuyOrSellCreatorCoin,
PublicAccess,
},
{
"TransferCreatorCoin",
[]string{"POST", "OPTIONS"},
RoutePathTransferCreatorCoin,
fes.TransferCreatorCoin,
PublicAccess,
},
{
"SendDiamonds",
[]string{"POST", "OPTIONS"},
RoutePathSendDiamonds,
fes.SendDiamonds,
PublicAccess,
},
{
"AuthorizeDerivedKey",
[]string{"POST", "OPTIONS"},
RoutePathAuthorizeDerivedKey,
fes.AuthorizeDerivedKey,
PublicAccess,
},
{
"DAOCoin",
[]string{"POST", "OPTIONS"},
RoutePathDAOCoin,
fes.DAOCoin,
PublicAccess,
},
{
"TransferDAOCoin",
[]string{"POST", "OPTIONS"},
RoutePathTransferDAOCoin,
fes.TransferDAOCoin,
PublicAccess,
},
{
"CreateDAOCoinLimitOrder",
[]string{"POST", "OPTIONS"},
RoutePathCreateDAOCoinLimitOrder,
fes.CreateDAOCoinLimitOrder,
PublicAccess,
},
{
"CreateDAOCoinMarketOrder",
[]string{"POST", "OPTIONS"},
RoutePathCreateDAOCoinMarketOrder,
fes.CreateDAOCoinMarketOrder,
PublicAccess,
},
{
"CancelDAOCoinLimitOrder",
[]string{"POST", "OPTIONS"},
RoutePathCancelDAOCoinLimitOrder,
fes.CancelDAOCoinLimitOrder,
PublicAccess,
},
{
"AppendExtraData",
[]string{"POST", "OPTIONS"},
RoutePathAppendExtraData,
fes.AppendExtraData,
PublicAccess,
},
{
"GetTransactionSpending",
[]string{"POST", "OPTIONS"},
RoutePathGetTransactionSpending,
fes.GetTransactionSpending,
PublicAccess,
},
{
"GetNotifications",
[]string{"POST", "OPTIONS"},
RoutePathGetNotifications,
fes.GetNotifications,
PublicAccess,
},
{
"GetUnreadNotificationsCount",
[]string{"POST", "OPTIONS"},
RoutePathGetUnreadNotificationsCount,
fes.GetNotificationsCount,