-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathtransaction.go
More file actions
1841 lines (1630 loc) · 68.8 KB
/
Copy pathtransaction.go
File metadata and controls
1841 lines (1630 loc) · 68.8 KB
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"
"io"
"net/http"
"reflect"
"strings"
"time"
"github.com/bitclout/core/lib"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/golang/glog"
merkletree "github.com/laser/go-merkle-tree"
"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)
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.MsgBitCloutTxn
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.MsgBitCloutTxn{}
err = txn.FromBytes(txnBytes)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SubmitTransactionRequest: Problem deserializing transaction from bytes: %v", err))
return
}
err = fes.backendServer.VerifyAndBroadcastTransaction(txn)
if 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.MsgBitCloutTxn, 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)
}
// attach a ProfileEntry to the PostEntryResponse
verifiedMap, err := fes.GetVerifiedUsernameToPKIDMap()
if err != nil {
return err
}
profileEntry := utxoView.GetProfileEntryForPublicKey(postEntry.PosterPublicKey)
postEntryResponse.ProfileEntryResponse = _profileEntryToResponse(profileEntry, fes.Params, verifiedMap, utxoView)
// attach everything to the response
response.PostEntryResponse = postEntryResponse
if len(postHashToModify) == 0 {
// 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, "GlobalStateGet 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 reclout.
if userMetadata.WhitelistPosts && len(postEntry.ParentStakeID) == 0 && (postEntry.IsQuotedReclout || postEntry.RecloutedPostHash == 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 {
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.GlobalStatePut(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"`
MinFeeRateNanosPerKB uint64 `safeForLogging:"true"`
}
// UpdateProfileResponse ...
type UpdateProfileResponse struct {
TotalInputNanos uint64
ChangeAmountNanos uint64
FeeNanos uint64
Transaction *lib.MsgBitCloutTxn
TransactionHex string
TxnHashHex 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
}
// 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 BitClout."))
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, "BC") == 0 ||
strings.Index(requestData.NewUsername, "tBC") == 0) {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateProfile: Username cannot start with BC or tBC"))
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))
if existingProfile, usernameExists := utxoView.ProfileUsernameToProfileEntry[lib.MakeUsernameMapKey([]byte(requestData.NewUsername))]; usernameExists && !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
}
}
additionalFees, err := fes.CompProfileCreation(profilePublicKey, userMetadata, utxoView)
if err != nil {
_AddBadRequestError(ww, err.Error())
return
}
// 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,
requestData.MinFeeRateNanosPerKB, fes.backendServer.GetMempool())
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateProfile: Problem creating transaction: %v", err))
return
}
txnBytes, err := txn.ToBytes(true)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateProfile: Problem serializing transaction: %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(),
}
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, _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
}
// 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 bitclout seed configured and the user
// has verified their profile.
if !fes.IsCompProfileCreation || fes.StarterBitCloutSeed == "" || fes.Twilio == nil || userMetadata.PhoneNumber == "" {
return additionalFees, nil
}
var phoneNumberMetadata *PhoneNumberMetadata
phoneNumberMetadata, err := fes.getPhoneNumberMetadataFromGlobalState(userMetadata.PhoneNumber)
if err != nil {
return 0, errors.Wrap(fmt.Errorf("UpdateProfile: error getting phone number metadata for public key %v: %v", profilePublicKey, err), "")
}
if phoneNumberMetadata == nil {
return 0, errors.Wrap(fmt.Errorf("UpdateProfile: no phone number metadata for phone number %v", userMetadata.PhoneNumber), "")
}
var currentBalanceNanos uint64
currentBalanceNanos, err = GetBalanceForPublicKeyUsingUtxoView(profilePublicKey, utxoView)
if err != nil {
return 0, errors.Wrap(fmt.Errorf("UpdateProfile: error getting current balance: %v", err), "")
}
createProfileFeeNanos := utxoView.GlobalParamsEntry.CreateProfileFeeNanos
if !phoneNumberMetadata.ShouldCompProfileCreation || currentBalanceNanos > createProfileFeeNanos {
return additionalFees, nil
}
// Find the minimum starter bit clout amount
minStarterBitCloutNanos := fes.StarterBitCloutAmountNanos
if len(fes.StarterBitCloutPrefixExceptionMap) > 0 {
for _, starterBitClout := range fes.StarterBitCloutPrefixExceptionMap {
if starterBitClout < minStarterBitCloutNanos {
minStarterBitCloutNanos = starterBitClout
}
}
}
// We comp the create profile fee minus the minimum starter bitclout amount divided by 2.
// // This discourages botting while covering users who verify a phone number.
compAmount := createProfileFeeNanos - (minStarterBitCloutNanos / 2)
// If the user won't have enough bitclout to cover the fee, this is an error.
if currentBalanceNanos+compAmount < createProfileFeeNanos {
return 0, errors.Wrap(fmt.Errorf("Creating a profile requires BitClout. Please purchase some to create a profile."), "")
}
// Set should comp to false so we don't continually comp a public key
phoneNumberMetadata.ShouldCompProfileCreation = false
err = fes.putPhoneNumberMetadataInGlobalState(phoneNumberMetadata)
if err != nil {
return 0, errors.Wrap(fmt.Errorf("UpdateProfile: Error setting ShouldComp to false for phone number metadata: %v", err), "")
}
// Send the comp amount to the public key
_, err = fes.SendSeedBitClout(profilePublicKey, compAmount, false)
if err != nil {
return 0, errors.Wrap(fmt.Errorf("UpdateProfile: error comping create profile fee: %v", err), "")
}
return additionalFees, 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
}
// BurnBitcoinRequest ...
type BurnBitcoinRequest 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
}
// BurnBitcoinResponse ...
type BurnBitcoinResponse struct {
TotalInputSatoshis uint64
BurnAmountSatoshis uint64
ChangeAmountSatoshis uint64
FeeSatoshis uint64
BitcoinTransaction *wire.MsgTx
SerializedTxnHex string
TxnHashHex string
BitCloutTxnHashHex string
UnsignedHashes []string
}
// BurnBitcoinStateless ...
func (fes *APIServer) BurnBitcoinStateless(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := BurnBitcoinRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("BurnBitcoin: Problem parsing request body: %v", err))
return
}
// Make sure the fee rate isn't negative.
if requestData.FeeRateSatoshisPerKB < 0 {
_AddBadRequestError(ww, fmt.Sprintf("BurnBitcoin: 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("BurnBitcoin: 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("BurnBitcoin: Transaction fee %d is "+
"so high that we can't spend the inputs total=%d", txFee, totalInput))
return
}
burnAmountSatoshis = totalInput - int64(txFee)
glog.Tracef("BurnBitcoin: 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("BurnBitcoin: 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.BitCloutParams) ([]*lib.BitcoinUtxo, error) {
if spendAddr != requestData.BTCDepositAddress {
return nil, fmt.Errorf("ButnBitcoin.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, "BurnBitcoin: Invalid public key")
return
}
addressPubKey, err := btcutil.NewAddressPubKey(pkBytes, fes.Params.BitcoinBtcdParams)
if err != nil {
_AddBadRequestError(ww, "BurnBitcoin: Invalid public key")
return
}
pubKey := addressPubKey.PubKey()
bitcoinTxn, totalInputSatoshis, fee, unsignedHashes, bitcoinSpendErr := lib.CreateBitcoinSpendTransaction(
uint64(burnAmountSatoshis),
uint64(requestData.FeeRateSatoshisPerKB),
pubKey,
fes.Params.BitcoinBurnAddress,
fes.Params,
utxoSource)
if bitcoinSpendErr != nil {
_AddBadRequestError(ww, fmt.Sprintf("BurnBitcoin: 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("BurnBitcoin: Failed to decode hash: %v", err))
return
}
parsedSig, err := btcec.ParseDERSignature(sig, btcec.S256())
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("BurnBitcoin: Parsing "+
"signature failed: %v: %v", signedHash, err))
return
}
sigWithLowS := parsedSig.Serialize()
glog.Errorf("BitcoinBurn: 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("BurnBitcoin: 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("BurnBitcoin: Problem serializing Bitcoin transaction: %v", err))
return
}
bitcoinTxnBytes := bitcoinTxnBuffer.Bytes()
bitcoinTxnHash := bitcoinTxn.TxHash()
var bitcloutTxn *lib.MsgBitCloutTxn
if requestData.Broadcast {
glog.Infof("BurnBitcoin: Broadcasting Bitcoin txn: %v", bitcoinTxn)
// 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("BurnBitcoin: 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("BurnBitcoin: 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.
err := lib.BlockCypherPushAndWaitForTxn(
hex.EncodeToString(bitcoinTxnBytes), &bitcoinTxnHash,
fes.BlockCypherAPIKey, fes.Params.BitcoinDoubleSpendWaitSeconds,
fes.Params)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("BurnBitcoin: Error broadcasting transaction: %v", err))
return
}
}
// We have the Bitcoin transaction now so broadcast it to the Bitcoin
// chain. This waits for confirmation from the Bitcoin node before
// returning.
glog.Infof("BurnBitcoin: Broadcasting txn to Bitcoin nodes: %v", &bitcoinTxnHash)
if err := fes.backendServer.GetBitcoinManager().BroadcastTxnAndCheckAddedRedundant(
bitcoinTxn, 30 /*timeoutSecs*/, 10 /*numNodesToPing*/); err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"BurnBitcoin: Error broadcasting transaction: %v", err))
return
}
// Now that we know the txn is valid on the Bitcoin chain, wrap it into
// a BitClout BitcoinExchange txn and broadcast it to the other BitClout
// nodes.
//
// The only thing a BitcoinExchange transaction has set is its TxnMeta.
// Everything else is left blank because it is not needed. Note that the
// recipient of the BitClout that will be created is the first valid input in
// the BitcoinTransaction specified. Note also that the
// fee is deducted as a percentage of the eventual BitClout that will get
// created as a result of this transaction.
bitcoinExchangeMetadata := &lib.BitcoinExchangeMetadata{
BitcoinTransaction: bitcoinTxn,
BitcoinBlockHash: &lib.BlockHash{},
// Not including a merkle proof causes the mempool/broadcast code to
// do a simpler check of the txn's validity. In order for it to actually
// be mined into a BitClout block, however, the transaction needs to
// ultimately have its merkle proof filled in once the Bitcoin txn has
// been mined into a Bitcoin block.
BitcoinMerkleRoot: &lib.BlockHash{},
BitcoinMerkleProof: []*merkletree.ProofPart{},
}
bitcloutTxn = &lib.MsgBitCloutTxn{
TxnMeta: bitcoinExchangeMetadata,
}
// Broadcast the newly-created BitClout txn. This call is asynchronous.
if _, err := fes.backendServer.BroadcastTransaction(bitcloutTxn); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("BurnBitcoin: Problem broadcasting "+
"bitclout txn: %v", err))
return
}
/*********************************************************************
// Update our global state record of how much the user has bought
*********************************************************************/
userMetadata, err := fes.getUserMetadataFromGlobalState(requestData.PublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"BurnBitcoin: Problem with getUserMetadataFromGlobalState: %v", err))
return
}
userMetadata.SatoshisBurnedSoFar += totalInputSatoshis
// If the user has burned enough to create a profile, update that boolean
if userMetadata.SatoshisBurnedSoFar >= fes.MinSatoshisBurnedForProfileCreation {
userMetadata.HasBurnedEnoughSatoshisToCreateProfile = true
}
// Update the amount of BitClout purchased so far based on the purchase
// the user just made
err = fes.putUserMetadataInGlobalState(userMetadata)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"BurnBitcoin: Problem with putUserMetadataInGlobalState: %v", err))
return
}
}
bitCloutTxnHashHex := ""
if bitcloutTxn != nil {
bitCloutTxnHashHex = bitcloutTxn.Hash().String()
}
res := &BurnBitcoinResponse{
TotalInputSatoshis: totalInputSatoshis,
BurnAmountSatoshis: uint64(burnAmountSatoshis),
FeeSatoshis: fee,
ChangeAmountSatoshis: totalInputSatoshis - uint64(burnAmountSatoshis) - fee,
BitcoinTransaction: bitcoinTxn,
SerializedTxnHex: hex.EncodeToString(bitcoinTxnBytes),
TxnHashHex: bitcoinTxn.TxHash().String(),
BitCloutTxnHashHex: bitCloutTxnHashHex,
UnsignedHashes: unsignedHashes,
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("BurnBitcoin: Problem encoding response as JSON: %v", err))
return
}
}
// SendBitCloutRequest ...
type SendBitCloutRequest struct {
SenderPublicKeyBase58Check string `safeForLogging:"true"`
RecipientPublicKeyOrUsername string `safeForLogging:"true"`
AmountNanos int64 `safeForLogging:"true"`
MinFeeRateNanosPerKB uint64 `safeForLogging:"true"`
}
// SendBitCloutResponse ...
type SendBitCloutResponse struct {
TotalInputNanos uint64
SpendAmountNanos uint64
ChangeAmountNanos uint64
FeeNanos uint64
TransactionIDBase58Check string
Transaction *lib.MsgBitCloutTxn
TransactionHex string
TxnHashHex string
}
// SendBitClout ...
func (fes *APIServer) SendBitClout(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := SendBitCloutRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendBitClout: Problem parsing request body: %v", err))
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, "BC") == 0 ||
strings.Index(requestData.RecipientPublicKeyOrUsername, "tBC") == 0 {
// Decode the recipient's public key.
var err error
recipientPkBytes, _, err = lib.Base58CheckDecode(requestData.RecipientPublicKeyOrUsername)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendBitClout: 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("SendBitClout: Error generating "+
"view to verify username: %v", err))
return
}
profileEntry := utxoView.GetProfileEntryForUsername(
[]byte(requestData.RecipientPublicKeyOrUsername))
if profileEntry == nil {
_AddBadRequestError(ww, fmt.Sprintf("SendBitClout: Profile with username "+
"%v does not exist", requestData.RecipientPublicKeyOrUsername))
return
}
recipientPkBytes = profileEntry.PublicKey
}
if len(recipientPkBytes) == 0 {
_AddBadRequestError(ww, fmt.Sprintf("SendBitClout: Unknown error parsing public key."))
return
}
// Decode the sender public key.
senderPkBytes, _, err := lib.Base58CheckDecode(requestData.SenderPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendBitClout: Problem decoding sender base58 public key %s: %v", requestData.SenderPublicKeyBase58Check, err))
return
}
// If the AmountNanos is less than zero then we have a special case where we create
// a transaction with the maximum spend.
var txnn *lib.MsgBitCloutTxn
var totalInputt uint64
var spendAmountt uint64
var changeAmountt uint64
var feeNanoss uint64
if requestData.AmountNanos < 0 {
// Create a MAX transaction
txnn, totalInputt, spendAmountt, feeNanoss, err = fes.blockchain.CreateMaxSpend(
senderPkBytes, recipientPkBytes, requestData.MinFeeRateNanosPerKB,
fes.backendServer.GetMempool())
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendBitClout: Error processing MAX transaction: %v", err))
return
}
} else {
// In this case, we are spending what the user asked us to spend as opposed to
// spending the maximum amount posssible.
// Create the transaction outputs and add the recipient's public key and the
// amount we want to pay them
txnOutputs := []*lib.BitCloutOutput{}
txnOutputs = append(txnOutputs, &lib.BitCloutOutput{
PublicKey: recipientPkBytes,
// If we get here we know the amount is non-negative.
AmountNanos: uint64(requestData.AmountNanos),
})
// Assemble the transaction so that inputs can be found and fees can
// be computed.
txnn = &lib.MsgBitCloutTxn{
// The inputs will be set below.
TxInputs: []*lib.BitCloutInput{},
TxOutputs: txnOutputs,
PublicKey: senderPkBytes,
TxnMeta: &lib.BasicTransferMetadata{},
// We wait to compute the signature until we've added all the
// inputs and change.
}
// Add inputs to the transaction and do signing, validation, and broadcast
// depending on what the user requested.
totalInputt, spendAmountt, changeAmountt, feeNanoss, err =
fes.blockchain.AddInputsAndChangeToTransaction(
txnn, requestData.MinFeeRateNanosPerKB, fes.mempool)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendBitClout: Error processing transaction: %v", err))
return
}
}
// Sanity check that the input is equal to:
// (spend amount + change amount + fees)
if totalInputt != (spendAmountt + changeAmountt + feeNanoss) {
_AddBadRequestError(ww, fmt.Sprintf("SendBitClout: totalInput=%d is not equal "+
"to the sum of the (spend amount=%d, change=%d, and fees=%d) which sums "+
"to %d. This means there was likely a problem with CreateMaxSpend",
totalInputt, spendAmountt, changeAmountt, feeNanoss, (spendAmountt+changeAmountt+feeNanoss)))
return
}
// If we got here and if broadcast was requested then it means the
// transaction passed validation and it's therefore reasonable to
// update the user objects to reflect that.
txID := lib.PkToString(txnn.Hash()[:], fes.Params)
txnBytes, err := txnn.ToBytes(true)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendBitClout: Problem serializing transaction: %v", err))
return
}
// Return the transaction in the response along with some metadata. If we
// get to this point and if the user requested that the transaction be
// validated or broadcast, the user can assume that those operations
// occurred successfully.
res := SendBitCloutResponse{
TotalInputNanos: totalInputt,
SpendAmountNanos: spendAmountt,
ChangeAmountNanos: changeAmountt,
FeeNanos: feeNanoss,
TransactionIDBase58Check: txID,
Transaction: txnn,
TransactionHex: hex.EncodeToString(txnBytes),
TxnHashHex: txnn.Hash().String(),
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SendBitClout: Problem encoding response as JSON: %v", err))
return
}
}
// CreateLikeStatelessRequest ...
type CreateLikeStatelessRequest struct {
ReaderPublicKeyBase58Check string `safeForLogging:"true"`
LikedPostHashHex string `safeForLogging:"true"`
IsUnlike bool `safeForLogging:"true"`
MinFeeRateNanosPerKB uint64 `safeForLogging:"true"`
}
// CreateLikeStatelessResponse ...
type CreateLikeStatelessResponse struct {
TotalInputNanos uint64
ChangeAmountNanos uint64
FeeNanos uint64
Transaction *lib.MsgBitCloutTxn
TransactionHex string
}