-
Notifications
You must be signed in to change notification settings - Fork 2
/
transaction.go
3565 lines (3137 loc) · 138 KB
/
transaction.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"
"math/big"
"net/http"
"reflect"
"strings"
"time"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/deso-smart/deso-core/v2/lib"
"github.com/golang/glog"
"github.com/pkg/errors"
)
type GetTxnRequest struct {
// TxnHash to fetch.
TxnHashHex string `safeForLogging:"true"`
}
type GetTxnResponse struct {
TxnFound bool
}
func (fes *APIServer) GetTxn(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := GetTxnRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetTxn: Problem parsing request body: %v", err))
return
}
// Decode the postHash.
var txnHash *lib.BlockHash
if requestData.TxnHashHex == "" {
_AddBadRequestError(ww, fmt.Sprintf("GetTxn: Must provide a TxnHashHex."))
return
} else {
txnHashBytes, err := hex.DecodeString(requestData.TxnHashHex)
if err != nil || len(txnHashBytes) != lib.HashSizeBytes {
_AddBadRequestError(ww, fmt.Sprintf("GetTxn: Error parsing post hash %v: %v",
requestData.TxnHashHex, err))
return
}
txnHash = &lib.BlockHash{}
copy(txnHash[:], txnHashBytes)
}
txnFound := fes.mempool.IsTransactionInPool(txnHash)
if !txnFound {
txnFound = lib.DbCheckTxnExistence(fes.TXIndex.TXIndexChain.DB(), txnHash)
}
res := &GetTxnResponse{
TxnFound: txnFound,
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetSinglePost: Problem encoding response as JSON: %v", err))
return
}
}
type SubmitTransactionRequest struct {
TransactionHex string `safeForLogging:"true"`
}
type SubmitTransactionResponse struct {
Transaction *lib.MsgDeSoTxn
TxnHashHex string
// include the PostEntryResponse if a post was submitted
PostEntryResponse *PostEntryResponse
}
func (fes *APIServer) SubmitTransaction(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := SubmitTransactionRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SubmitTransactionRequest: Problem parsing request body: %v", err))
return
}
txnBytes, err := hex.DecodeString(requestData.TransactionHex)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SubmitTransactionRequest: Problem deserializing transaction hex: %v", err))
return
}
txn := &lib.MsgDeSoTxn{}
err = txn.FromBytes(txnBytes)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SubmitTransactionRequest: Problem deserializing transaction from bytes: %v", err))
return
}
_, diamondPostHashKeyExists := txn.ExtraData[lib.DiamondPostHashKey]
// If this is a basic transfer (but not a diamond action), we check if user has completed the tutorial (if this node is configured for Jumio)
if !diamondPostHashKeyExists && txn.TxnMeta.GetTxnType() == lib.TxnTypeBasicTransfer && fes.IsConfiguredForJumio() {
var userMetadata *UserMetadata
userMetadata, err = fes.getUserMetadataFromGlobalStateByPublicKeyBytes(txn.PublicKey)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SubmitTransactionRequest: Problem getting usermetadata from global state for basic transfer: %v", err))
return
}
if userMetadata.MustCompleteTutorial && userMetadata.TutorialStatus != COMPLETE && userMetadata.TutorialStatus != SKIPPED {
_AddBadRequestError(ww, fmt.Sprintf("SubmitTransactionRequest: If you receive money from Jumio, you must complete the tutorial: %v", err))
return
}
}
if err = fes.backendServer.VerifyAndBroadcastTransaction(txn); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SubmitTransaction: Problem processing transaction: %v", err))
return
}
res := &SubmitTransactionResponse{
Transaction: txn,
TxnHashHex: txn.Hash().String(),
}
if txn.TxnMeta.GetTxnType() == lib.TxnTypeSubmitPost {
err = fes._afterProcessSubmitPostTransaction(txn, res)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("_afterSubmitPostTransaction: %v", err))
}
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SubmitTransactionResponse: Problem encoding response as JSON: %v", err))
return
}
}
// After we submit a new post transaction we need to do run a few callbacks
// 1. Attach the PostEntry to the response so the client can render it
// 2. Attempt to auto-whitelist the post for the global feed
func (fes *APIServer) _afterProcessSubmitPostTransaction(txn *lib.MsgDeSoTxn, response *SubmitTransactionResponse) error {
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
return errors.Errorf("Problem with GetAugmentedUniversalView: %v", err)
}
// The post hash is either the hash of the transaction that was added or
// the hash of the post that this request was modifying.
postHashToModify := txn.TxnMeta.(*lib.SubmitPostMetadata).PostHashToModify
postHash := txn.Hash()
if len(postHashToModify) == lib.HashSizeBytes {
postHash = &lib.BlockHash{}
copy(postHash[:], postHashToModify[:])
}
postEntry := utxoView.GetPostEntryForPostHash(postHash)
if postEntry == nil {
return errors.Errorf("Problem finding post after adding to view")
}
updaterPublicKeyBytes := txn.PublicKey
postEntryResponse, err := fes._postEntryToResponse(postEntry, false, fes.Params, utxoView, updaterPublicKeyBytes, 2)
if err != nil {
return errors.Errorf("Problem obtaining post entry response: %v", err)
}
profileEntry := utxoView.GetProfileEntryForPublicKey(postEntry.PosterPublicKey)
postEntryResponse.ProfileEntryResponse = fes._profileEntryToResponse(profileEntry, utxoView)
// attach everything to the response
response.PostEntryResponse = postEntryResponse
// Try to whitelist a post if it is not a comment and is not a vanilla repost.
if len(postHashToModify) == 0 && !lib.IsVanillaRepost(postEntry) {
// If this is a new post, let's try and auto-whitelist it now that it has been broadcast.
// First we need to figure out if the user is whitelisted.
userMetadata, err := fes.getUserMetadataFromGlobalState(lib.PkToString(updaterPublicKeyBytes, fes.Params))
if err != nil {
return errors.Wrapf(err, "Get error: Problem getting "+
"metadata from global state.")
}
// Only whitelist posts for users that are auto-whitelisted and the post is not a comment or a vanilla repost.
if userMetadata.WhitelistPosts && len(postEntry.ParentStakeID) == 0 && (postEntry.IsQuotedRepost || postEntry.RepostedPostHash == nil) {
minTimestampNanos := time.Now().UTC().AddDate(0, 0, -1).UnixNano() // last 24 hours
_, dbPostAndCommentHashes, _, err := lib.DBGetAllPostsAndCommentsForPublicKeyOrderedByTimestamp(
fes.blockchain.DB(), updaterPublicKeyBytes, false /*fetchEntries*/, uint64(minTimestampNanos), 0, /*maxTimestampNanos*/
)
if err != nil {
return errors.Errorf("Problem fetching last 24 hours of user posts: %v", err)
}
// Collect all the posts the user made in the last 24 hours.
maxAutoWhitelistPostsPerDay := 5
postEntriesInLastDay := 0
for _, dbPostOrCommentHash := range dbPostAndCommentHashes {
if existingPostEntry := utxoView.GetPostEntryForPostHash(dbPostOrCommentHash); len(existingPostEntry.ParentStakeID) == 0 && !lib.IsVanillaRepost(existingPostEntry) {
postEntriesInLastDay += 1
}
if maxAutoWhitelistPostsPerDay >= postEntriesInLastDay {
break
}
}
// If the whitelited user has made <5 posts in the last 24hrs add this post to the feed.
if postEntriesInLastDay < maxAutoWhitelistPostsPerDay {
dbKey := GlobalStateKeyForTstampPostHash(postEntry.TimestampNanos, postHash)
// Encode the post entry and stick it in the database.
if err = fes.GlobalState.Put(dbKey, []byte{1}); err != nil {
return errors.Errorf("Problem adding post to global state: %v", err)
}
}
}
}
return nil
}
// UpdateProfileRequest ...
type UpdateProfileRequest struct {
// The public key of the user who is trying to update their profile.
UpdaterPublicKeyBase58Check string `safeForLogging:"true"`
// This is only set when the user wants to modify a profile
// that isn't theirs. Otherwise, the UpdaterPublicKeyBase58Check is
// assumed to own the profile being updated.
ProfilePublicKeyBase58Check string `safeForLogging:"true"`
NewUsername string `safeForLogging:"true"`
NewDescription string `safeForLogging:"true"`
// The profile pic string encoded as a link e.g.
// data:image/png;base64,<data in base64>
NewProfilePic string
NewCreatorBasisPoints uint64 `safeForLogging:"true"`
NewStakeMultipleBasisPoints uint64 `safeForLogging:"true"`
IsHidden bool `safeForLogging:"true"`
// ExtraData
ExtraData map[string]string `safeForLogging:"true"`
MinFeeRateNanosPerKB uint64 `safeForLogging:"true"`
// No need to specify ProfileEntryResponse in each TransactionFee
TransactionFees []TransactionFee `safeForLogging:"true"`
}
// UpdateProfileResponse ...
type UpdateProfileResponse struct {
TotalInputNanos uint64
ChangeAmountNanos uint64
FeeNanos uint64
Transaction *lib.MsgDeSoTxn
TransactionHex string
TxnHashHex string
CompProfileCreationTxnHashHex string
}
// UpdateProfile ...
func (fes *APIServer) UpdateProfile(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := UpdateProfileRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateProfile: Problem parsing request body: %v", err))
return
}
// Decode the public key
updaterPublicKeyBytes, _, err := lib.Base58CheckDecode(requestData.UpdaterPublicKeyBase58Check)
if err != nil || len(updaterPublicKeyBytes) != btcec.PubKeyBytesLenCompressed {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateProfile: Problem decoding public key %s: %v",
requestData.UpdaterPublicKeyBase58Check, err))
return
}
// Compute the additional transaction fees as specified by the request body and the node-level fees.
additionalOutputs, err := fes.getTransactionFee(lib.TxnTypeUpdateProfile, updaterPublicKeyBytes, requestData.TransactionFees)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateProfile: TransactionFees specified in Request body are invalid: %v", err))
return
}
// Validate that the user can create a profile
userMetadata, err := fes.getUserMetadataFromGlobalState(requestData.UpdaterPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateProfile: Problem with getUserMetadataFromGlobalState: %v", err))
return
}
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateProfile: Error fetching mempool view: %v", err))
return
}
canCreateProfile, err := fes.canUserCreateProfile(userMetadata, utxoView)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateProfile: Problem with canUserCreateProfile: %v", err))
return
}
if !canCreateProfile {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateProfile: Not allowed to update profile. Please verify your phone number or buy DeSo."))
return
}
// When this is nil then the UpdaterPublicKey is assumed to be the owner of
// the profile.
var profilePublicKeyBytess []byte
if requestData.ProfilePublicKeyBase58Check != "" {
profilePublicKeyBytess, _, err = lib.Base58CheckDecode(requestData.ProfilePublicKeyBase58Check)
if err != nil || len(profilePublicKeyBytess) != btcec.PubKeyBytesLenCompressed {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateProfile: Problem decoding public key %s: %v",
requestData.ProfilePublicKeyBase58Check, err))
return
}
}
// Get the public key.
profilePublicKey := updaterPublicKeyBytes
if requestData.ProfilePublicKeyBase58Check != "" {
profilePublicKey = profilePublicKeyBytess
}
if len(requestData.NewUsername) > 0 && strings.Index(requestData.NewUsername, fes.PublicKeyBase58Prefix) == 0 {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateProfile: Username cannot start with %s", fes.PublicKeyBase58Prefix))
return
}
if uint64(len([]byte(requestData.NewUsername))) > utxoView.Params.MaxUsernameLengthBytes {
_AddBadRequestError(ww, lib.RuleErrorProfileUsernameTooLong.Error())
return
}
if uint64(len([]byte(requestData.NewDescription))) > utxoView.Params.MaxUserDescriptionLengthBytes {
_AddBadRequestError(ww, lib.RuleErrorProfileDescriptionTooLong.Error())
return
}
// If an image is set on the request then resize it.
// Convert image to base64 by stripping the data: prefix.
if requestData.NewProfilePic != "" {
var resizedImageBytes []byte
resizedImageBytes, err = resizeAndConvertToWebp(requestData.NewProfilePic, uint(fes.Params.MaxProfilePicDimensions))
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("Problem resizing profile picture: %v", err))
return
}
// Convert the image back into base64
webpBase64 := base64.StdEncoding.EncodeToString(resizedImageBytes)
requestData.NewProfilePic = "data:image/webp;base64," + webpBase64
if uint64(len([]byte(requestData.NewProfilePic))) > utxoView.Params.MaxProfilePicLengthBytes {
_AddBadRequestError(ww, lib.RuleErrorMaxProfilePicSize.Error())
return
}
}
// CreatorBasisPoints > 0 < max, uint64 can't be less than zero
if requestData.NewCreatorBasisPoints > fes.Params.MaxCreatorBasisPoints {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateProfile: Creator percentage must be less than %v percent",
fes.Params.MaxCreatorBasisPoints/100))
return
}
// Verify that this username doesn't exist in the mempool.
if len(requestData.NewUsername) > 0 {
utxoView.GetProfileEntryForUsername([]byte(requestData.NewUsername))
existingProfile, usernameExists := utxoView.ProfileUsernameToProfileEntry[lib.MakeUsernameMapKey([]byte(requestData.NewUsername))]
if usernameExists && existingProfile != nil && !existingProfile.IsDeleted() {
// Check that the existing profile does not belong to the profile public key
if utxoView.GetPKIDForPublicKey(profilePublicKey) != utxoView.GetPKIDForPublicKey(existingProfile.PublicKey) {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateProfile: Username %v already exists", string(existingProfile.Username)))
return
}
}
if !lib.UsernameRegex.Match([]byte(requestData.NewUsername)) {
_AddBadRequestError(ww, lib.RuleErrorInvalidUsername.Error())
return
}
}
extraData := preprocessExtraData(requestData.ExtraData)
additionalFees, compProfileCreationTxnHash, err := fes.CompProfileCreation(profilePublicKey, userMetadata, utxoView)
if err != nil {
_AddBadRequestError(ww, err.Error())
return
}
var compProfileCreationTxnHashHex string
if compProfileCreationTxnHash != nil {
compProfileCreationTxnHashHex = compProfileCreationTxnHash.String()
}
// Try and create the UpdateProfile txn for the user.
txn, totalInput, changeAmount, fees, err := fes.blockchain.CreateUpdateProfileTxn(
updaterPublicKeyBytes,
profilePublicKeyBytess,
requestData.NewUsername,
requestData.NewDescription,
requestData.NewProfilePic,
requestData.NewCreatorBasisPoints,
requestData.NewStakeMultipleBasisPoints,
requestData.IsHidden,
additionalFees,
extraData,
requestData.MinFeeRateNanosPerKB, fes.backendServer.GetMempool(), additionalOutputs)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateProfile: 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("UpdateProfile: Problem serializing transaction: %v", err))
return
}
// TODO: for consistency, should we add InTutorial to the request data. It doesn't save us much since we need fetch the user metadata regardless.
if userMetadata.TutorialStatus == STARTED || userMetadata.TutorialStatus == INVEST_OTHERS_SELL {
userMetadata.TutorialStatus = CREATE_PROFILE
if err = fes.putUserMetadataInGlobalState(userMetadata); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateProfile: Problem updating tutorial status to update profile completed: %v", err))
return
}
}
// Return all the data associated with the transaction in the response
res := UpdateProfileResponse{
TotalInputNanos: totalInput,
ChangeAmountNanos: changeAmount,
FeeNanos: fees,
Transaction: txn,
TransactionHex: hex.EncodeToString(txnBytes),
TxnHashHex: txn.Hash().String(),
CompProfileCreationTxnHashHex: compProfileCreationTxnHashHex,
}
if err = json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendMessage: Problem encoding response as JSON: %v", err))
return
}
}
func (fes *APIServer) CompProfileCreation(profilePublicKey []byte, userMetadata *UserMetadata, utxoView *lib.UtxoView) (_additionalFee uint64, _txnHash *lib.BlockHash, _err error) {
// Determine if this is a profile creation request and if we need to comp the user for creating the profile.
existingProfileEntry := utxoView.GetProfileEntryForPublicKey(profilePublicKey)
// If we are updating an existing profile, there is no fee and we do not comp anything.
if existingProfileEntry != nil {
return 0, nil, nil
}
// Additional fee is set to the create profile fee when we are creating a profile
additionalFees := utxoView.GlobalParamsEntry.CreateProfileFeeNanos
// Only comp create profile fee if frontend server has both twilio and starter deso seed configured and the user
// has verified their profile.
if !fes.Config.CompProfileCreation || fes.Config.StarterDESOSeed == "" || fes.Twilio == nil || (userMetadata.PhoneNumber == "" && !userMetadata.JumioVerified) {
return additionalFees, nil, nil
}
var currentBalanceNanos uint64
currentBalanceNanos, err := GetBalanceForPublicKeyUsingUtxoView(profilePublicKey, utxoView)
if err != nil {
return 0, nil, errors.Wrap(fmt.Errorf("UpdateProfile: error getting current balance: %v", err), "")
}
createProfileFeeNanos := utxoView.GlobalParamsEntry.CreateProfileFeeNanos
// If a user is jumio verified, we just comp the profile even if their balance is greater than the create profile fee.
// If a user has a phone number verified but is not jumio verified, we need to check that they haven't spent all their
// starter deso already and that ShouldCompProfileCreation is true
var phoneNumberMetadata *PhoneNumberMetadata
if userMetadata.PhoneNumber != "" && !userMetadata.JumioVerified {
phoneNumberMetadata, err = fes.getPhoneNumberMetadataFromGlobalState(userMetadata.PhoneNumber)
if err != nil {
return 0, nil, errors.Wrap(fmt.Errorf("UpdateProfile: error getting phone number metadata for public key %v: %v", profilePublicKey, err), "")
}
if phoneNumberMetadata == nil {
return 0, nil, errors.Wrap(fmt.Errorf("UpdateProfile: no phone number metadata for phone number %v", userMetadata.PhoneNumber), "")
}
if !phoneNumberMetadata.ShouldCompProfileCreation || currentBalanceNanos > createProfileFeeNanos {
return additionalFees, nil, nil
}
} else {
// User has been Jumio verified but should comp profile creation is false, just return
if !userMetadata.JumioShouldCompProfileCreation {
return additionalFees, nil, nil
}
}
// Find the minimum starter bit deso amount
minStarterDESONanos := fes.Config.StarterDESONanos
if len(fes.Config.StarterPrefixNanosMap) > 0 {
for _, starterDeSo := range fes.Config.StarterPrefixNanosMap {
if starterDeSo < minStarterDESONanos {
minStarterDESONanos = starterDeSo
}
}
}
// We comp the create profile fee minus the minimum starter deso amount divided by 2.
// This discourages botting while covering users who verify a phone number.
compAmount := createProfileFeeNanos - (minStarterDESONanos / 2)
// If the user won't have enough deso to cover the fee, this is an error.
if currentBalanceNanos+compAmount < createProfileFeeNanos {
return 0, nil, errors.Wrap(fmt.Errorf("Creating a profile requires DeSo. Please purchase some to create a profile."), "")
}
// Set should comp to false so we don't continually comp a public key. PhoneNumberMetadata is only non-nil if
// a user verified their phone number but is not jumio verified.
if phoneNumberMetadata != nil {
phoneNumberMetadata.ShouldCompProfileCreation = false
if err = fes.putPhoneNumberMetadataInGlobalState(phoneNumberMetadata); err != nil {
return 0, nil, errors.Wrap(fmt.Errorf("UpdateProfile: Error setting ShouldComp to false for phone number metadata: %v", err), "")
}
} else {
// Set JumioShouldCompProfileCreation to false so we don't continue to comp profile creation.
userMetadata.JumioShouldCompProfileCreation = false
if err = fes.putUserMetadataInGlobalState(userMetadata); err != nil {
return 0, nil, errors.Wrap(fmt.Errorf("UpdateProfile: Error setting ShouldComp to false for jumio user metadata: %v", err), "")
}
}
// Send the comp amount to the public key
txnHash, err := fes.SendSeedDeSo(profilePublicKey, compAmount, false)
if err != nil {
return 0, nil, errors.Wrap(fmt.Errorf("UpdateProfile: error comping create profile fee: %v", err), "")
}
return additionalFees, txnHash, nil
}
func GetBalanceForPublicKeyUsingUtxoView(
publicKeyBytes []byte, utxoView *lib.UtxoView) (_balance uint64, _err error) {
// Get unspent utxos from the view.
utxoEntriesFound, err := utxoView.GetUnspentUtxoEntrysForPublicKey(publicKeyBytes)
if err != nil {
return 0, fmt.Errorf("UpdateProfile: Problem getting spendable utxos from UtxoView: %v", err)
}
totalBalanceNanos := uint64(0)
for _, utxoEntry := range utxoEntriesFound {
totalBalanceNanos += utxoEntry.AmountNanos
}
return totalBalanceNanos, nil
}
// ExchangeBitcoinRequest ...
type ExchangeBitcoinRequest struct {
// The public key of the user who we're creating the burn for.
PublicKeyBase58Check string `safeForLogging:"true"`
// Note: When BurnAmountSatoshis is negative, we assume that the user wants
// to burn the maximum amount of satoshi she has available.
BurnAmountSatoshis int64 `safeForLogging:"true"`
FeeRateSatoshisPerKB int64 `safeForLogging:"true"`
// We rely on the frontend to query the API and give us the response.
// Doing it this way makes it so that we don't exhaust our quota on the
// free tier.
LatestBitcionAPIResponse *lib.BlockCypherAPIFullAddressResponse
// The Bitcoin address we will be processing this transaction for.
BTCDepositAddress string `safeForLogging:"true"`
// Whether or not we should broadcast the transaction after constructing
// it. This will also validate the transaction if it's set.
// The client must provide SignedHashes which it calculates by signing
// all the UnsignedHashes in the identity service
Broadcast bool `safeForLogging:"true"`
// Signed hashes from the identity service
// One for each transaction input
SignedHashes []string
}
// ExchangeBitcoinResponse ...
type ExchangeBitcoinResponse struct {
TotalInputSatoshis uint64
BurnAmountSatoshis uint64
ChangeAmountSatoshis uint64
FeeSatoshis uint64
BitcoinTransaction *wire.MsgTx
SerializedTxnHex string
TxnHashHex string
DeSoTxnHashHex string
UnsignedHashes []string
}
// ExchangeBitcoinStateless ...
func (fes *APIServer) ExchangeBitcoinStateless(ww http.ResponseWriter, req *http.Request) {
if fes.Config.BuyDESOSeed == "" {
_AddBadRequestError(ww, "ExchangeBitcoinStateless: This node is not configured to sell DeSo for Bitcoin")
return
}
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := ExchangeBitcoinRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Problem parsing request body: %v", err))
return
}
// Make sure the fee rate isn't negative.
if requestData.FeeRateSatoshisPerKB < 0 {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: BurnAmount %d or "+
"FeeRateSatoshisPerKB %d cannot be negative",
requestData.BurnAmountSatoshis, requestData.FeeRateSatoshisPerKB))
return
}
// If BurnAmountSatoshis is negative, set it to the maximum amount of satoshi
// that can be burned while accounting for the fee.
burnAmountSatoshis := requestData.BurnAmountSatoshis
if burnAmountSatoshis < 0 {
bitcoinUtxos, err := lib.BlockCypherExtractBitcoinUtxosFromResponse(
requestData.LatestBitcionAPIResponse, requestData.BTCDepositAddress,
fes.Params)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Problem getting "+
"Bitcoin UTXOs: %v", err))
return
}
totalInput := int64(0)
for _, utxo := range bitcoinUtxos {
totalInput += utxo.AmountSatoshis
}
// We have one output in this case because we're sending all of the Bitcoin to
// the burn address with no change left over.
txFee := lib.EstimateBitcoinTxFee(
len(bitcoinUtxos), 1, uint64(requestData.FeeRateSatoshisPerKB))
if int64(txFee) > totalInput {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Transaction fee %d is "+
"so high that we can't spend the inputs total=%d", txFee, totalInput))
return
}
burnAmountSatoshis = totalInput - int64(txFee)
glog.V(2).Infof("ExchangeBitcoinStateless: Getting ready to burn %d Satoshis", burnAmountSatoshis)
}
// Prevent the user from creating a burn transaction with a dust output since
// this will result in the transaction being rejected by Bitcoin nodes.
if burnAmountSatoshis < 10000 {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: You must burn at least .0001 Bitcoins "+
"or else Bitcoin nodes will reject your transaction as \"dust.\""))
return
}
// Get a UtxoSource from the user's BitcoinAPI data. Note we could change the API
// around a bit to not have to do this but oh well.
utxoSource := func(spendAddr string, params *lib.DeSoParams) ([]*lib.BitcoinUtxo, error) {
if spendAddr != requestData.BTCDepositAddress {
return nil, fmt.Errorf("ExchangeBitcoinStateless.UtxoSource: Expecting deposit address %s "+
"but got unrecognized address %s", requestData.BTCDepositAddress, spendAddr)
}
return lib.BlockCypherExtractBitcoinUtxosFromResponse(
requestData.LatestBitcionAPIResponse, requestData.BTCDepositAddress, fes.Params)
}
// Get the pubKey from the request
pkBytes, _, err := lib.Base58CheckDecode(requestData.PublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, "ExchangeBitcoinStateless: Invalid public key")
return
}
addressPubKey, err := btcutil.NewAddressPubKey(pkBytes, fes.Params.BitcoinBtcdParams)
if err != nil {
_AddBadRequestError(ww, "ExchangeBitcoinStateless: Invalid public key")
return
}
pubKey := addressPubKey.PubKey()
bitcoinTxn, totalInputSatoshis, fee, unsignedHashes, bitcoinSpendErr := lib.CreateBitcoinSpendTransaction(
uint64(burnAmountSatoshis),
uint64(requestData.FeeRateSatoshisPerKB),
pubKey,
fes.Config.BuyDESOBTCAddress,
fes.Params,
utxoSource)
if bitcoinSpendErr != nil {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Problem creating Bitcoin spend "+
"transaction given input: %v", bitcoinSpendErr))
return
}
// Add all the signatures to the inputs
pkData := pubKey.SerializeCompressed()
for ii, signedHash := range requestData.SignedHashes {
sig, err := hex.DecodeString(signedHash)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Failed to decode hash: %v", err))
return
}
parsedSig, err := btcec.ParseDERSignature(sig, btcec.S256())
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Parsing "+
"signature failed: %v: %v", signedHash, err))
return
}
sigWithLowS := parsedSig.Serialize()
glog.Errorf("ExchangeBitcoinStateless: Bitcoin sig from frontend: %v; Bitcoin "+
"sig with low S breaker: %v; Equal? %v",
hex.EncodeToString(sig), hex.EncodeToString(sigWithLowS), reflect.DeepEqual(sig, sigWithLowS))
sig = sigWithLowS
sig = append(sig, byte(txscript.SigHashAll))
sigScript, err := txscript.NewScriptBuilder().AddData(sig).AddData(pkData).Script()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Failed to generate signature: %v", err))
return
}
bitcoinTxn.TxIn[ii].SignatureScript = sigScript
}
// Serialize the Bitcoin transaction the hex so that the FE can trigger
// a rebroadcast later.
bitcoinTxnBuffer := bytes.Buffer{}
err = bitcoinTxn.SerializeNoWitness(&bitcoinTxnBuffer)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Problem serializing Bitcoin transaction: %v", err))
return
}
bitcoinTxnBytes := bitcoinTxnBuffer.Bytes()
bitcoinTxnHash := bitcoinTxn.TxHash()
// Update the current exchange price.
fes.UpdateUSDCentsToDeSoExchangeRate()
// Check that DeSo purchased they would get does not exceed current balance.
nanosPurchased := fes.GetNanosFromSats(uint64(burnAmountSatoshis), fes.BuyDESOFeeBasisPoints)
balanceInsufficient, err := fes.ExceedsDeSoBalance(nanosPurchased, fes.Config.BuyDESOSeed)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Error checking if send deso balance is sufficient: %v", err))
return
}
if balanceInsufficient {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: SendDeSo wallet balance is below nanos purchased"))
return
}
var desoTxnHash *lib.BlockHash
if requestData.Broadcast {
glog.Infof("ExchangeBitcoinStateless: Broadcasting Bitcoin txn: %v", bitcoinTxn.TxHash())
// Check whether the deposits being used to construct this transaction have RBF enabled.
// If they do then we force the user to wait until those deposits have been mined into a
// block before allowing this transaction to go through. This prevents double-spend
// attacks where someone replaces a dependent transaction with a higher fee.
//
// TODO: We use a pretty janky API to check for this, and if it goes down then
// BitcoinExchange txns break. But without it we're vulnerable to double-spends
// so we keep it for now.
if fes.Params.NetworkType == lib.NetworkType_MAINNET {
// Go through the transaction's inputs. If any of them have RBF set then we
// must assume that this transaction has RBF as well.
for _, txIn := range bitcoinTxn.TxIn {
isRBF, err := lib.BlockonomicsCheckRBF(txIn.PreviousOutPoint.Hash.String())
if err != nil {
glog.Errorf("ExchangeBitcoinStateless: ERROR: Blockonomics request to check RBF for txn "+
"hash %v failed. This is bad because it means users are not able to "+
"complete Bitcoin burns: %v", txIn.PreviousOutPoint.Hash.String(), err)
_AddBadRequestError(ww, fmt.Sprintf(
"The nodes are still processing your deposit. Please wait a few seconds "+
"and try again."))
return
}
// If we got a success response from Blockonomics then bail if the transaction has
// RBF set.
if isRBF {
glog.Errorf("ExchangeBitcoinStateless: ERROR: Blockonomics found RBF txn: %v", bitcoinTxnHash.String())
_AddBadRequestError(ww, fmt.Sprintf(
"Your deposit has \"replace by fee\" set, "+
"which means we must wait for one confirmation on the Bitcoin blockchain before "+
"allowing you to buy. This usually takes about ten minutes.<br><br>"+
"You can see how many confirmations your deposit has by "+
"<a target=\"_blank\" href=\"https://www.blockchain.com/btc/tx/%v\">clicking here</a>.", txIn.PreviousOutPoint.Hash.String()))
return
}
}
}
// If a BlockCypher API key is set then use BlockCypher to do the checks. Otherwise
// use Bitcoin nodes to do it. Note that BLockCypher tends to be the more reliable path.
if fes.BlockCypherAPIKey != "" {
// Push the transaction to BlockCypher and ensure no error occurs.
if isDoubleSpend, err := lib.BlockCypherPushAndWaitForTxn(
hex.EncodeToString(bitcoinTxnBytes), &bitcoinTxnHash,
fes.BlockCypherAPIKey, fes.Params.BitcoinDoubleSpendWaitSeconds,
fes.Params); err != nil {
if !isDoubleSpend {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Error broadcasting "+
"transaction - not double spend: %v", err))
return
}
// If we hit an error, kick off a goroutine to retry this txn every
// minute for a few hours.
//
// TODO: This code is very ugly and highly error-prone. If you write it
// incorrectly, it will send infinite money to someone. Don't change it
// unless you absolutely have to...
go func() {
endTime := time.Now().Add(3 * time.Hour)
for time.Now().Before(endTime) {
err = lib.CheckBitcoinDoubleSpend(
&bitcoinTxnHash, fes.BlockCypherAPIKey, fes.Params)
if err == nil {
// If we get here then it means the txn *finally* worked. Blast
// out the DESO in this case and return.
glog.Infof("Eventually mined Bitcoin txn %v. Sending DESO...", bitcoinTxnHash)
desoTxnHash, err = fes.SendSeedDeSo(pkBytes, nanosPurchased, true)
if err != nil {
glog.Errorf("Error sending DESO for Bitcoin txn %v", bitcoinTxnHash)
}
// Note that if we don't return we'll send money to this person infinitely...
return
} else {
glog.Infof("Error when re-checking double-spend for Bitcoin txn %v: %v", bitcoinTxnHash, err)
}
// Sleep for a bit each time.
glog.Infof("Sleeping for 1 minute while waiting for Bitcoin "+
"txn %v to mine...", bitcoinTxnHash)
sleepTime := time.Minute
time.Sleep(sleepTime)
}
glog.Infof("Bitcoin txn %v did not end up mining after several hours", bitcoinTxnHash)
}()
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Error broadcasting transaction: %v", err))
return
}
} else {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: BlockCypher API is required for bitcoin transactions"))
return
}
desoTxnHash, err = fes.SendSeedDeSo(pkBytes, nanosPurchased, true)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("ExchangeBitcoinStateless: Error sending DeSo: %v", err))
return
}
}
desoTxnHashString := ""
if desoTxnHash != nil {
desoTxnHashString = desoTxnHash.String()
}
res := &ExchangeBitcoinResponse{
TotalInputSatoshis: totalInputSatoshis,
BurnAmountSatoshis: uint64(burnAmountSatoshis),
FeeSatoshis: fee,
ChangeAmountSatoshis: totalInputSatoshis - uint64(burnAmountSatoshis) - fee,
BitcoinTransaction: bitcoinTxn,
SerializedTxnHex: hex.EncodeToString(bitcoinTxnBytes),
TxnHashHex: bitcoinTxn.TxHash().String(),
DeSoTxnHashHex: desoTxnHashString,
UnsignedHashes: unsignedHashes,
}
if err = json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("BurnBitcoin: Problem encoding response as JSON: %v", err))
return
}
}
// GetNanosFromSats - convert Satoshis to DeSo nanos
func (fes *APIServer) GetNanosFromSats(satoshis uint64, feeBasisPoints uint64) uint64 {
usdCentsPerBitcoin := fes.UsdCentsPerBitCoinExchangeRate
// If we don't have a valid value from monitoring at this time, use the price from the protocol
if usdCentsPerBitcoin == 0 {
readUtxoView, _ := fes.backendServer.GetMempool().GetAugmentedUniversalView()
usdCentsPerBitcoin = float64(readUtxoView.GetCurrentUSDCentsPerBitcoin())
}
usdCents := (float64(satoshis) * usdCentsPerBitcoin) / lib.SatoshisPerBitcoin
return fes.GetNanosFromUSDCents(usdCents, feeBasisPoints)
}
// GetNanosFromETH - convert ETH to DESO nanos
func (fes *APIServer) GetNanosFromETH(eth *big.Float, feeBasisPoints uint64) uint64 {
usdCentsPerETH := big.NewFloat(float64(fes.UsdCentsPerETHExchangeRate))
usdCentsETH := big.NewFloat(0).Mul(eth, usdCentsPerETH)
// This number should always fit into a float64 so we shouldn't have a problem
// with overflow.
usdCentsFloat, _ := usdCentsETH.Float64()
return fes.GetNanosFromUSDCents(usdCentsFloat, feeBasisPoints)
}
// GetNanosFromUSDCents - convert USD cents to DeSo nanos
func (fes *APIServer) GetNanosFromUSDCents(usdCents float64, feeBasisPoints uint64) uint64 {
// Get Exchange Price gets the max of price from blockchain.com and the reserve price.
usdCentsPerDeSo := fes.GetExchangeDeSoPrice()
conversionRateAfterFee := float64(usdCentsPerDeSo) * (1 + (float64(feeBasisPoints) / (100.0 * 100.0)))
nanosPurchased := uint64(usdCents * float64(lib.NanosPerUnit) / conversionRateAfterFee)
return nanosPurchased
}
func (fes *APIServer) GetUSDFromNanos(nanos uint64) float64 {
usdCentsPerDeSo := float64(fes.UsdCentsPerDeSoExchangeRate)
return usdCentsPerDeSo * float64(nanos/lib.NanosPerUnit) / 100
}
// ExceedsSendDeSoBalance - Check if nanosPurchased is greater than the balance of the BuyDESO wallet.
func (fes *APIServer) ExceedsDeSoBalance(nanosPurchased uint64, seed string) (bool, error) {
buyDeSoSeedBalance, err := fes.getBalanceForSeed(seed)
if err != nil {
return false, fmt.Errorf("Error getting buy deso balance: %v", err)
}
return nanosPurchased > buyDeSoSeedBalance, nil
}
// SendDeSoRequest ...
type SendDeSoRequest struct {
SenderPublicKeyBase58Check string `safeForLogging:"true"`
RecipientPublicKeyOrUsername string `safeForLogging:"true"`
AmountNanos int64 `safeForLogging:"true"`
MinFeeRateNanosPerKB uint64 `safeForLogging:"true"`
// No need to specify ProfileEntryResponse in each TransactionFee
TransactionFees []TransactionFee `safeForLogging:"true"`
}
// SendDeSoResponse ...
type SendDeSoResponse struct {
TotalInputNanos uint64
SpendAmountNanos uint64
ChangeAmountNanos uint64
FeeNanos uint64
TransactionIDBase58Check string
Transaction *lib.MsgDeSoTxn
TransactionHex string
TxnHashHex string
}
// SendDeSo ...
func (fes *APIServer) SendDeSo(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := SendDeSoRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendDeSo: Problem parsing request body: %v", err))
return
}
if fes.IsConfiguredForJumio() {
userMetadata, err := fes.getUserMetadataFromGlobalState(requestData.SenderPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendDeSo: problem getting user metadata from global state: %v", err))
return
}
if userMetadata.JumioVerified && userMetadata.MustCompleteTutorial && userMetadata.TutorialStatus != COMPLETE {
_AddBadRequestError(ww, fmt.Sprintf("You must complete the tutorial before you can perform a basic transfer"))
return
}
}
// If the string starts with the public key characters than interpret it as
// a public key. Otherwise we interpret it as a username and try to look up
// the corresponding profile.
var recipientPkBytes []byte
if strings.Index(requestData.RecipientPublicKeyOrUsername, fes.PublicKeyBase58Prefix) == 0 {
// Decode the recipient's public key.
var err error
recipientPkBytes, _, err = lib.Base58CheckDecode(requestData.RecipientPublicKeyOrUsername)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendDeSo: Problem decoding recipient "+
"base58 public key %s: %v", requestData.RecipientPublicKeyOrUsername, err))
return
}
} else {
// TODO(performance): This is inefficient because it loads all mempool
// transactions.
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendDeSo: Error generating "+
"view to verify username: %v", err))
return
}
profileEntry := utxoView.GetProfileEntryForUsername(
[]byte(requestData.RecipientPublicKeyOrUsername))
if profileEntry == nil {
_AddBadRequestError(ww, fmt.Sprintf("SendDeSo: Profile with username "+
"%v does not exist", requestData.RecipientPublicKeyOrUsername))
return