-
Notifications
You must be signed in to change notification settings - Fork 86
/
transaction.go
4572 lines (4050 loc) · 178 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"
ecdsa2 "github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa"
"io"
"math/big"
"net/http"
"reflect"
"strings"
"time"
"github.com/deso-protocol/uint256"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/deso-protocol/core/lib"
"github.com/golang/glog"
"github.com/pkg/errors"
)
type TxnStatus string
const (
TxnStatusInMempool TxnStatus = "InMempool"
TxnStatusCommitted TxnStatus = "Committed"
// TODO: It would be useful to have one that is "UnconfirmedBlocks" or something like that, which
// means we'll consider txns that are in unconfirmed blocks but will *not* consider txns
// that are in the mempool. It's a kindof middle-ground.
)
type GetTxnRequest struct {
// TxnHashHex to fetch.
TxnHashHex string `safeForLogging:"true"`
// If unset, defaults to TxnStatusInMempool
TxnStatus TxnStatus `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)
}
// The order of operations is tricky here. We need to do the following in this
// exact order:
// 1. Check the mempool for the txn
// 2. Wait for txindex to fully sync
// 3. Then check txindex
//
// If we instead check the mempool afterward, then there is a chance that the txn
// has been removed by a new block that is not yet in txindex. This would cause the
// endpoint to incorrectly report that the txn doesn't exist on the node, when in
// fact it is in "limbo" between the mempool and txindex.
txnStatus := requestData.TxnStatus
if txnStatus == "" {
txnStatus = TxnStatusInMempool
}
txnInMempool := fes.backendServer.GetMempool().IsTransactionInPool(txnHash)
startTime := time.Now()
// We have to wait until txindex has reached the uncommitted tip height, not the
// committed tip height. Otherwise we'll be missing ~2 blocks in limbo.
coreChainTipHeight := fes.TXIndex.CoreChain.BlockTip().Height
for fes.TXIndex.TXIndexChain.BlockTip().Height < coreChainTipHeight {
if time.Since(startTime) > 30*time.Second {
_AddBadRequestError(ww, fmt.Sprintf("GetTxn: Timed out waiting for txindex to sync."))
return
}
time.Sleep(10 * time.Millisecond)
}
txnInTxindex := lib.DbCheckTxnExistence(fes.TXIndex.TXIndexChain.DB(), nil, txnHash)
txnFound := false
switch txnStatus {
case TxnStatusInMempool:
// In this case, we're fine if the txn is either in the mempool or in txindex.
txnFound = txnInMempool || txnInTxindex
case TxnStatusCommitted:
// In this case we will not consider a txn until it shows up in txindex, which means that
// it is committed.
txnFound = txnInTxindex
default:
_AddBadRequestError(ww, fmt.Sprintf("GetTxn: Invalid TxnStatus: %v. Options are "+
"{InMempool, Committed}", txnStatus))
return
}
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
}
}
// SubmitAtomicTransactionRequest is meant to aid in the submission of atomic transactions
// with identity service signed transactions. Specifically, it takes an incomplete atomic transaction
// and "completes" the transaction by adding in identity service signed transactions.
type SubmitAtomicTransactionRequest struct {
// IncompleteAtomicTransactionHex is a hex encoded transaction of type TxnTypeAtomicTxnsWrapper who
// is "incomplete" only by missing the signature fields of various inner transactions.
IncompleteAtomicTransactionHex string `safeForLogging:"true"`
// SignedInnerTransactionsHex are the hex-encoded signed inner transactions that
// will be used to complete the atomic transaction.
SignedInnerTransactionsHex []string `safeForLogging:"true"`
}
type SubmitAtomicTransactionResponse struct {
Transaction *lib.MsgDeSoTxn
TxnHashHex string
TransactionIDBase58Check string
}
func (fes *APIServer) SubmitAtomicTransaction(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := SubmitAtomicTransactionRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("SubmitAtomicTransaction: Problem parsing request body: %v", err))
return
}
// Fetch the incomplete atomic transaction.
atomicTxnBytes, err := hex.DecodeString(requestData.IncompleteAtomicTransactionHex)
if err != nil {
_AddBadRequestError(ww,
fmt.Sprintf("SubmitAtomicTransaction: "+
"Problem deserializing atomic transaction hex: %v", err))
return
}
atomicTxn := &lib.MsgDeSoTxn{}
err = atomicTxn.FromBytes(atomicTxnBytes)
if err != nil {
_AddBadRequestError(ww,
fmt.Sprintf("SubmitAtomicTransaction: "+
"Problem deserializing atomic transaction from bytes: %v", err))
return
}
if atomicTxn.TxnMeta.GetTxnType() != lib.TxnTypeAtomicTxnsWrapper {
_AddBadRequestError(ww, fmt.Sprintf("SubmitAtomicTransaction: "+
"IncompleteAtomicTransaction must be an atomic transaction"))
return
}
// Create a map from the pre-signature inner transaction hash to DeSo signature.
innerTxnPreSignatureHashToSignature := make(map[lib.BlockHash]lib.DeSoSignature)
for ii, signedInnerTxnHex := range requestData.SignedInnerTransactionsHex {
// Decode the signed inner transaction.
signedTxnBytes, err := hex.DecodeString(signedInnerTxnHex)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"SubmitAtomicTransaction: Problem decoding signed transaction hex: %v", err))
return
}
// Deserialize the signed transaction.
signedInnerTxn := &lib.MsgDeSoTxn{}
if err := signedInnerTxn.FromBytes(signedTxnBytes); err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"SubmitAtomicTransaction: Problem deserializing signed transaction %d from bytes: %v",
ii, err))
return
}
// Verify the signature is present.
if signedInnerTxn.Signature.Sign == nil {
_AddBadRequestError(ww, fmt.Sprintf(
"SubmitAtomicTransaction: Signed transaction %d hex missing signature", ii))
return
}
// Find the pre-signature DeSo transaction hash.
// NOTE: We do not use the lib.MsgDeSoTxn.Hash() function here as
// the transactions included in the atomic transaction do not yet
// have their signature fields set.
preSignatureInnerTxnBytes, err := signedInnerTxn.ToBytes(true)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"SubmitAtomicTransaction: Problem serializing "+
"signed transaction %d without signature: %v", ii, err))
return
}
preSignatureInnerTxnHash := lib.Sha256DoubleHash(preSignatureInnerTxnBytes)
innerTxnPreSignatureHashToSignature[*preSignatureInnerTxnHash] = signedInnerTxn.Signature
}
// Based on the provided signatures, complete the atomic transaction.
for jj, innerTxn := range atomicTxn.TxnMeta.(*lib.AtomicTxnsWrapperMetadata).Txns {
// Skip signed inner transactions.
if innerTxn.Signature.Sign != nil {
continue
}
// Find the pre-signature DeSo transaction hash for this transaction.
preSignatureInnerTxnBytes, err := innerTxn.ToBytes(true)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"SubmitAtomicTransaction: Problem serializing "+
"transaction %d of atomic transaction wrapper without signature: %v", jj, err))
return
}
preSignatureInnerTxnHash := lib.Sha256DoubleHash(preSignatureInnerTxnBytes)
// Check that we have the signature.
if _, exists := innerTxnPreSignatureHashToSignature[*preSignatureInnerTxnHash]; !exists {
_AddBadRequestError(ww, fmt.Sprintf(
"SubmitAtomicTransaction: Transaction %d in atomic transaction still missing signature", jj))
return
}
// Set the signature in the atomic transaction.
atomicTxn.TxnMeta.(*lib.AtomicTxnsWrapperMetadata).Txns[jj].Signature =
innerTxnPreSignatureHashToSignature[*preSignatureInnerTxnHash]
}
atomicTxnLen, err := atomicTxn.ToBytes(false)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"SubmitAtomicTransaction: Problem serializing completed atomic transaction: %v", err))
return
}
if TransactionFeeRateTooHigh(atomicTxn, uint64(len(atomicTxnLen))) {
_AddBadRequestError(ww, fmt.Sprintf("SubmitAtomicTransaction: Transaction fee rate too high"))
return
}
// Verify and broadcast the completed atomic transaction.
if err := fes.backendServer.VerifyAndBroadcastTransaction(atomicTxn); err != nil {
_AddBadRequestError(ww,
fmt.Sprintf("SubmitAtomicTransaction: Problem broadcasting transaction: %v", err))
return
}
res := &SubmitAtomicTransactionResponse{
Transaction: atomicTxn,
TxnHashHex: atomicTxn.Hash().String(),
TransactionIDBase58Check: lib.PkToString(atomicTxn.Hash()[:], fes.Params),
}
if err := json.NewEncoder(ww).Encode(res); err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"SubmitAtomicTransaction: Problem encoding response as JSON: %v", err))
return
}
}
type SubmitTransactionRequest struct {
TransactionHex string `safeForLogging:"true"`
}
type SubmitTransactionResponse struct {
Transaction *lib.MsgDeSoTxn
TxnHashHex string
TransactionIDBase58Check string
// include the PostEntryResponse if a post was submitted
PostEntryResponse *PostEntryResponse
}
// FeeRateNanosPerKBThreshold is the threshold above which transactions will be rejected if the fee rate exceeds it.
const FeeRateNanosPerKBThreshold = 1e8
func TransactionFeeRateTooHigh(txn *lib.MsgDeSoTxn, txnLen uint64) bool {
// Handle base cases.
if txn.TxnFeeNanos == 0 || txnLen == 0 {
return false
}
// Compute the fee rate in nanos per KB.
feeRateNanosPerKB := (txn.TxnFeeNanos * 1000) / txnLen
return feeRateNanosPerKB > FeeRateNanosPerKBThreshold
}
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
}
if TransactionFeeRateTooHigh(txn, uint64(len(txnBytes))) {
_AddBadRequestError(ww, fmt.Sprintf("SubmitTransactionRequest: Transaction fee rate too high"))
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(),
TransactionIDBase58Check: lib.PkToString(txn.Hash()[:], fes.Params),
}
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 {
fes.backendServer.GetMempool().BlockUntilReadOnlyViewRegenerated()
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(), fes.blockchain.Snapshot(), 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"`
OptionalPrecedingTransactions []*lib.MsgDeSoTxn `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 := lib.GetAugmentedUniversalViewWithAdditionalTransactions(
fes.backendServer.GetMempool(),
requestData.OptionalPrecedingTransactions,
)
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
}
// Validate the request.
if err := fes.ValidateAndConvertUpdateProfileRequest(&requestData, profilePublicKey, utxoView); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateProfile: Problem validating request: %v", err))
return
}
extraData, err := EncodeExtraDataMap(requestData.ExtraData)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateProfile: Problem encoding ExtraData: %v", err))
return
}
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) ValidateAndConvertUpdateProfileRequest(
requestData *UpdateProfileRequest,
profilePublicKey []byte,
utxoView *lib.UtxoView,
) error {
if len(requestData.NewUsername) > 0 && strings.Index(requestData.NewUsername, fes.PublicKeyBase58Prefix) == 0 {
return fmt.Errorf(
"ValidateAndConvertUpdateProfileRequest: Username cannot start with %s", fes.PublicKeyBase58Prefix)
}
if uint64(len([]byte(requestData.NewUsername))) > utxoView.Params.MaxUsernameLengthBytes {
return errors.Wrap(lib.RuleErrorProfileUsernameTooLong, "ValidateAndConvertUpdateProfileRequest")
}
if uint64(len([]byte(requestData.NewDescription))) > utxoView.Params.MaxUserDescriptionLengthBytes {
return errors.Wrap(lib.RuleErrorProfileDescriptionTooLong, "ValidateAndConvertUpdateProfileRequest")
}
// If an image is set on the request then resize it.
// Convert image to base64 by stripping the data: prefix.
if requestData.NewProfilePic != "" {
// split on base64 to get the extension
extensionSplit := strings.Split(requestData.NewProfilePic, ";base64")
if len(extensionSplit) != 2 {
return fmt.Errorf("ValidateAndConvertUpdateProfileRequest: " +
"Problem parsing profile pic extension; invalid extension split")
}
extension := extensionSplit[0]
switch {
case strings.Contains(extension, "image/png"):
extension = ".png"
case strings.Contains(extension, "image/jpeg"):
extension = ".jpeg"
case strings.Contains(extension, "image/webp"):
extension = ".webp"
case strings.Contains(extension, "image/gif"):
extension = ".gif"
default:
return fmt.Errorf(
"ValidateAndConvertUpdateProfileRequest: Unsupported image type: %v", extension)
}
var resizedImageBytes []byte
resizedImageBytes, err := resizeAndConvertToWebp(
requestData.NewProfilePic, uint(fes.Params.MaxProfilePicDimensions), extension)
if err != nil {
return fmt.Errorf(
"ValidateAndConvertUpdateProfileRequest: Problem resizing profile picture: %v", err)
}
// 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 {
return errors.Wrap(lib.RuleErrorMaxProfilePicSize, "ValidateAndConvertUpdateProfileRequest")
}
}
// CreatorBasisPoints > 0 < max, uint64 can't be less than zero
if requestData.NewCreatorBasisPoints > fes.Params.MaxCreatorBasisPoints {
return fmt.Errorf(
"ValidateAndConvertUpdateProfileRequest: Creator percentage must be less than %v percent",
fes.Params.MaxCreatorBasisPoints/100)
}
// 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) {
return fmt.Errorf(
"ValidateAndConvertUpdateProfileRequest: Username %v already exists",
string(existingProfile.Username))
}
}
if !lib.UsernameRegex.Match([]byte(requestData.NewUsername)) {
return errors.Wrap(lib.RuleErrorInvalidUsername, "ValidateAndConvertUpdateProfileRequest")
}
}
return nil
}
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.GetCurrentGlobalParamsEntry().CreateProfileFeeNanos
if additionalFees == 0 {
return 0, nil, nil
}
existingMetamaskAirdropMetadata, err := fes.GetMetamaskAirdropMetadata(profilePublicKey)
if err != nil {
return 0, nil, fmt.Errorf("Error geting metamask airdrop metadata from global state: %v", err)
}
// 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.Config.HCaptchaSecret == "" && fes.Twilio == nil) || (userMetadata.PhoneNumber == "" && !userMetadata.JumioVerified && existingMetamaskAirdropMetadata == nil && userMetadata.LastHcaptchaBlockHeight == 0) {
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.GetCurrentGlobalParamsEntry().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 multiPhoneNumberMetadata []*PhoneNumberMetadata
var updateMetamaskAirdropMetadata bool
if userMetadata.PhoneNumber != "" && !userMetadata.JumioVerified {
multiPhoneNumberMetadata, err = fes.getMultiPhoneNumberMetadataFromGlobalState(userMetadata.PhoneNumber)
if err != nil {
return 0, nil, fmt.Errorf("UpdateProfile: error getting phone number metadata for public key %v: %v", profilePublicKey, err)
}
if len(multiPhoneNumberMetadata) == 0 {
return 0, nil, fmt.Errorf("UpdateProfile: no phone number metadata for phone number %v", userMetadata.PhoneNumber)
}
var phoneNumberMetadata *PhoneNumberMetadata
for _, phoneNumMetadata := range multiPhoneNumberMetadata {
if bytes.Equal(phoneNumMetadata.PublicKey, profilePublicKey) {
phoneNumberMetadata = phoneNumMetadata
break
}
}
if phoneNumberMetadata == nil {
return 0, nil, fmt.Errorf("UpdateProfile: phone number metadata not found in slice for public key")
}
if !phoneNumberMetadata.ShouldCompProfileCreation || currentBalanceNanos > createProfileFeeNanos {
return additionalFees, nil, nil
}
} else if existingMetamaskAirdropMetadata != nil {
if !existingMetamaskAirdropMetadata.ShouldCompProfileCreation {
return additionalFees, nil, nil
}
updateMetamaskAirdropMetadata = true
} else if userMetadata.JumioVerified {
// User has been Jumio verified but should comp profile creation is false, just return
if !userMetadata.JumioShouldCompProfileCreation {
return additionalFees, nil, nil
}
} else if userMetadata.LastHcaptchaBlockHeight != 0 {
// User has been captcha verified but should comp profile creation is false, just return
if !userMetadata.HcaptchaShouldCompProfileCreation {
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
}
}
}
// If metamask airdrop is less than min phone number amount, we set the min amount to the airdrop value
if fes.Config.MetamaskAirdropDESONanosAmount != 0 && minStarterDESONanos > fes.Config.MetamaskAirdropDESONanosAmount {
minStarterDESONanos = fes.Config.MetamaskAirdropDESONanosAmount
}
// 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 (minStarterDESONanos / 2) > createProfileFeeNanos {
compAmount = createProfileFeeNanos
}
// If the user won't have enough deso to cover the fee, this is an error.
if currentBalanceNanos+compAmount < createProfileFeeNanos {
return 0, nil, 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 len(multiPhoneNumberMetadata) > 0 {
newPhoneNumberMetadata := []*PhoneNumberMetadata{}
for _, phoneNumMetadata := range multiPhoneNumberMetadata {
if bytes.Equal(phoneNumMetadata.PublicKey, profilePublicKey) {
phoneNumMetadata.ShouldCompProfileCreation = false
}
newPhoneNumberMetadata = append(newPhoneNumberMetadata, phoneNumMetadata)
}
if err = fes.putPhoneNumberMetadataInGlobalState(newPhoneNumberMetadata, userMetadata.PhoneNumber); err != nil {
return 0, nil, fmt.Errorf("UpdateProfile: Error setting ShouldComp to false for phone number metadata: %v", err)
}
} else if userMetadata.LastHcaptchaBlockHeight != 0 {
userMetadata.HcaptchaShouldCompProfileCreation = false
if err = fes.putUserMetadataInGlobalState(userMetadata); err != nil {
return 0, nil, fmt.Errorf("UpdateProfile: Error setting ShouldComp to false for jumio user 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, fmt.Errorf("UpdateProfile: Error setting ShouldComp to false for jumio user metadata: %v", err)
}
if existingMetamaskAirdropMetadata != nil && updateMetamaskAirdropMetadata {
existingMetamaskAirdropMetadata.ShouldCompProfileCreation = false
if err = fes.PutMetamaskAirdropMetadata(existingMetamaskAirdropMetadata); err != nil {
return 0, nil, fmt.Errorf("UpdateProfile: Error updating metamask airdrop metadata in global state: %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) {
return utxoView.GetDeSoBalanceNanosForPublicKey(publicKeyBytes)
}
// ExchangeBitcoinRequest ...
type ExchangeBitcoinRequest struct {
// The public key of the user who we're creating the burn for.
PublicKeyBase58Check string `safeForLogging:"true"`
// If passed, we will check if the user intends to burn btc through a derived key.
DerivedPublicKeyBase58Check 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
}
// If a derived key was passed, we will look for deposits in the derived btc address.
if requestData.DerivedPublicKeyBase58Check != "" {
// First decode the derived key.
derivedPkBytes, _, err := lib.Base58CheckDecode(requestData.DerivedPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, errors.Wrapf(err, "ExchangeBitcoinStateless: Invalid derived public key").Error())
return
}
// Verify that the derived key has been authorized by the provided owner public key.
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, errors.Wrapf(err, "ExchangeBitcoinStateless: Problem getting universal view from mempool").Error())
return
}
// Get the current block height for the derived key validation.
blockHeight := fes.blockchain.BlockTip().Height
// Now verify that the derived key has been authorized and hasn't expired.
if err := utxoView.ValidateDerivedKey(pkBytes, derivedPkBytes, uint64(blockHeight)); err != nil {
_AddBadRequestError(ww, errors.Wrapf(err, "ExchangeBitcoinStateless: Problem verifying the derived key").Error())
return
}
// If we get here it means a valid derived key was passed in the request. We will now get it's btc address for the deposit.
// FIXME (delete): At this point derived key deposits are pretty much done. The rest of this function stays the same,
// note that SendSeedDeSo will use the owner public key for the transaction recipient.
addressPubKey, err = btcutil.NewAddressPubKey(derivedPkBytes, fes.Params.BitcoinBtcdParams)
if err != nil {