-
Notifications
You must be signed in to change notification settings - Fork 2
/
nft.go
2174 lines (1886 loc) · 82 KB
/
nft.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 (
"encoding/hex"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"io"
"net/http"
"reflect"
"sort"
"time"
"github.com/deso-smart/deso-core/v2/lib"
)
type NFTEntryResponse struct {
OwnerPublicKeyBase58Check string `safeForLogging:"true"`
ProfileEntryResponse *ProfileEntryResponse `json:",omitempty"`
PostEntryResponse *PostEntryResponse `json:",omitempty"`
SerialNumber uint64 `safeForLogging:"true"`
IsForSale bool `safeForLogging:"true"`
IsPending bool `safeForLogging:"true"`
IsBuyNow bool `safeForLogging:"true"`
BuyNowPriceNanos uint64 `safeForLogging:"true"`
MinBidAmountNanos uint64 `safeForLogging:"true"`
LastAcceptedBidAmountNanos uint64 `safeForLogging:"true"`
HighestBidAmountNanos uint64 `safeForLogging:"true"`
LowestBidAmountNanos uint64 `safeForLogging:"true"`
// These fields are only populated when the reader is the owner.
LastOwnerPublicKeyBase58Check *string `json:",omitempty"`
EncryptedUnlockableText *string `json:",omitempty"`
// ExtraData is an arbitrary key value map
ExtraData map[string]string `safeForLogging:"true"`
}
type NFTCollectionResponse struct {
ProfileEntryResponse *ProfileEntryResponse `json:",omitempty"`
PostEntryResponse *PostEntryResponse `json:",omitempty"`
HighestBidAmountNanos uint64 `safeForLogging:"true"`
LowestBidAmountNanos uint64 `safeForLogging:"true"`
HighestBuyNowPriceNanos *uint64 `safeForLogging:"true"`
LowestBuyNowPriceNanos *uint64 `safeForLogging:"true"`
NumCopiesForSale uint64 `safeForLogging:"true"`
NumCopiesBuyNow uint64 `safeForLogging:"true"`
AvailableSerialNumbers []uint64 `safeForLogging:"true"`
}
type NFTBidEntryResponse struct {
PublicKeyBase58Check string
ProfileEntryResponse *ProfileEntryResponse `json:",omitempty"`
PostHashHex *string `json:",omitempty"`
// likely nil if included in a list of NFTBidEntryResponses for a single NFT
PostEntryResponse *PostEntryResponse `json:",omitempty"`
SerialNumber uint64 `safeForLogging:"true"`
BidAmountNanos uint64 `safeForLogging:"true"`
// What is the highest bid and the lowest bid on this serial number
HighestBidAmountNanos *uint64 `json:",omitempty"`
LowestBidAmountNanos *uint64 `json:",omitempty"`
// If we fetched the accepted bid history, include the accepted block height.
AcceptedBlockHeight *uint32 `json:",omitempty"`
// Current balance of this bidder.
BidderBalanceNanos uint64
}
type CreateNFTRequest struct {
UpdaterPublicKeyBase58Check string `safeForLogging:"true"`
NFTPostHashHex string `safeForLogging:"true"`
NumCopies int `safeForLogging:"true"`
NFTRoyaltyToCreatorBasisPoints int `safeForLogging:"true"`
NFTRoyaltyToCoinBasisPoints int `safeForLogging:"true"`
HasUnlockable bool `safeForLogging:"true"`
IsForSale bool `safeForLogging:"true"`
MinBidAmountNanos int `safeForLogging:"true"`
IsBuyNow bool `safeForLogging:"true"`
BuyNowPriceNanos uint64 `safeForLogging:"true"`
AdditionalDESORoyaltiesMap map[string]uint64 `safeForLogging:"true"`
AdditionalCoinRoyaltiesMap map[string]uint64 `safeForLogging:"true"`
ExtraData map[string]string `safeForLogging:"true"`
MinFeeRateNanosPerKB uint64 `safeForLogging:"true"`
// No need to specify ProfileEntryResponse in each TransactionFee
TransactionFees []TransactionFee `safeForLogging:"true"`
}
type CreateNFTResponse struct {
NFTPostHashHex string `safeForLogging:"true"`
TotalInputNanos uint64
ChangeAmountNanos uint64
FeeNanos uint64
Transaction *lib.MsgDeSoTxn
TransactionHex string
}
func (fes *APIServer) CreateNFT(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := CreateNFTRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFT: Error parsing request body: %v", err))
return
}
// Grab a view (needed for getting global params, etc).
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFT: Error getting utxoView: %v", err))
return
}
// Validate the requestData.
if requestData.NFTPostHashHex == "" {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFT: Must include NFTPostHashHex"))
return
} else if requestData.UpdaterPublicKeyBase58Check == "" {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFT: Must include UpdaterPublicKeyBase58Check"))
return
} else if utxoView.GlobalParamsEntry.MaxCopiesPerNFT == 0 {
_AddBadRequestError(ww,
"NFT minting has not been enabled yet. Check back soon :)")
return
} else if requestData.NumCopies <= 0 || requestData.NumCopies > int(utxoView.GlobalParamsEntry.MaxCopiesPerNFT) {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFT: NumCopies must be between %d and %d, received: %d",
1, utxoView.GlobalParamsEntry.MaxCopiesPerNFT, requestData.NumCopies))
return
} else if requestData.NFTRoyaltyToCreatorBasisPoints < 0 || requestData.NFTRoyaltyToCreatorBasisPoints > int(fes.Params.MaxNFTRoyaltyBasisPoints) {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFT: NFTRoyaltyToCreatorBasisPoints must be between %d and %d, received: %d",
0, fes.Params.MaxNFTRoyaltyBasisPoints, requestData.NFTRoyaltyToCreatorBasisPoints))
return
} else if requestData.MinBidAmountNanos < 0 {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFT: MinBidAmountNanos must be >= 0, got: %d", requestData.MinBidAmountNanos))
return
} else if requestData.NFTRoyaltyToCoinBasisPoints < 0 || requestData.NFTRoyaltyToCoinBasisPoints > int(fes.Params.MaxNFTRoyaltyBasisPoints) {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFT: NFTRoyaltyToCoinBasisPoints must be between %d and %d, received: %d",
0, fes.Params.MaxNFTRoyaltyBasisPoints, requestData.NFTRoyaltyToCoinBasisPoints))
return
} else if !requestData.IsBuyNow && requestData.BuyNowPriceNanos > 0 {
_AddBadRequestError(ww, fmt.Sprint("CreateNFT: cannot set BuyNowPriceNanos if NFT is not going to be "+
"sold in a 'Buy Now' fashion"))
return
} else if requestData.IsBuyNow && requestData.BuyNowPriceNanos < uint64(requestData.MinBidAmountNanos) {
_AddBadRequestError(ww, fmt.Sprint("CreateNFT: cannot set BuyNowPriceNanos less than MinBidAmountNanos"))
return
}
// Sum basis points for DESO royalties
additionalDESORoyaltiesBasisPoints := uint64(0)
additionalDESORoyaltiesPubKeyMap := make(map[lib.PublicKey]uint64)
for desoRoyaltyPublicKey, basisPoints := range requestData.AdditionalDESORoyaltiesMap {
// Check that the public key is valid
additionalDESORoyaltyPublicKeyBytes, _, err := lib.Base58CheckDecode(desoRoyaltyPublicKey)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFT: Problem decoding Additional DESO Royalty public key %s: %v", desoRoyaltyPublicKey, err))
return
}
// only add this to the map if basis points > 0
if basisPoints > 0 {
additionalDESORoyaltiesBasisPoints += basisPoints
additionalDESORoyaltiesPubKeyMap[*lib.NewPublicKey(additionalDESORoyaltyPublicKeyBytes)] = basisPoints
}
}
// Sum basis points for Coin royalties
additionalCoinRoyaltiesBasisPoints := uint64(0)
additionalCoinRoyaltiesPubKeyMap := make(map[lib.PublicKey]uint64)
for coinRoyaltyPublicKey, basisPoints := range requestData.AdditionalCoinRoyaltiesMap {
// Check that the public key is valid
additionalCoinRoyaltyPublicKeyBytes, _, err := lib.Base58CheckDecode(coinRoyaltyPublicKey)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFT: Problem decoding Additional Coin Royalty public key %s: %v", coinRoyaltyPublicKey, err))
return
}
// PKID must map to an existing profile in order for us to give royalties to that coin
profileEntry := utxoView.GetProfileEntryForPublicKey(additionalCoinRoyaltyPublicKeyBytes)
if profileEntry == nil || profileEntry.IsDeleted() {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFT: No profile found for public key %s", coinRoyaltyPublicKey))
return
}
// only add this to the map if basis points > 0
if basisPoints > 0 {
additionalCoinRoyaltiesBasisPoints += basisPoints
additionalCoinRoyaltiesPubKeyMap[*lib.NewPublicKey(additionalCoinRoyaltyPublicKeyBytes)] = basisPoints
}
}
if additionalCoinRoyaltiesBasisPoints+additionalDESORoyaltiesBasisPoints+
uint64(requestData.NFTRoyaltyToCoinBasisPoints)+uint64(requestData.NFTRoyaltyToCreatorBasisPoints) >
fes.Params.MaxNFTRoyaltyBasisPoints {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFT: Total royalty basis points too high: creator royalty %d, coin royalty %d, "+
"additional DESO royalties %d, additional coin royalties %d",
requestData.NFTRoyaltyToCreatorBasisPoints, requestData.NFTRoyaltyToCoinBasisPoints,
additionalDESORoyaltiesBasisPoints, additionalCoinRoyaltiesBasisPoints))
return
}
// Get the PostHash for the NFT we are creating.
nftPostHashBytes, err := hex.DecodeString(requestData.NFTPostHashHex)
if err != nil || len(nftPostHashBytes) != lib.HashSizeBytes {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFT: Error parsing post hash %v: %v",
requestData.NFTPostHashHex, err))
return
}
nftPostHash := &lib.BlockHash{}
copy(nftPostHash[:], nftPostHashBytes)
// Get the updater's public key.
updaterPublicKeyBytes, _, err := lib.Base58CheckDecode(requestData.UpdaterPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFT: Problem decoding user public key: %v", err))
return
}
// Compute the additional transaction fees as specified by the request body and the node-level fees.
additionalOutputs, err := fes.getTransactionFee(lib.TxnTypeCreateNFT, updaterPublicKeyBytes, requestData.TransactionFees)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFT: TransactionFees specified in Request body are invalid: %v", err))
return
}
nftFee := utxoView.GlobalParamsEntry.CreateNFTFeeNanos * uint64(requestData.NumCopies)
// Try and create the create NFT txn for the user.
txn, totalInput, changeAmount, fees, err := fes.blockchain.CreateCreateNFTTxn(
updaterPublicKeyBytes,
nftPostHash,
uint64(requestData.NumCopies),
requestData.HasUnlockable,
requestData.IsForSale,
uint64(requestData.MinBidAmountNanos),
nftFee,
uint64(requestData.NFTRoyaltyToCreatorBasisPoints),
uint64(requestData.NFTRoyaltyToCoinBasisPoints),
requestData.IsBuyNow,
requestData.BuyNowPriceNanos,
additionalDESORoyaltiesPubKeyMap,
additionalCoinRoyaltiesPubKeyMap,
preprocessExtraData(requestData.ExtraData),
requestData.MinFeeRateNanosPerKB, fes.backendServer.GetMempool(), additionalOutputs)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFT: 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("CreateNFT: Problem serializing transaction: %v", err))
return
}
// Return all the data associated with the transaction in the response
res := CreateNFTResponse{
NFTPostHashHex: requestData.NFTPostHashHex,
TotalInputNanos: totalInput,
ChangeAmountNanos: changeAmount,
FeeNanos: fees,
Transaction: txn,
TransactionHex: hex.EncodeToString(txnBytes),
}
if err = json.NewEncoder(ww).Encode(res); err != nil {
_AddInternalServerError(ww, fmt.Sprintf("CreateNFT: Problem serializing object to JSON: %v", err))
return
}
}
type UpdateNFTRequest struct {
UpdaterPublicKeyBase58Check string `safeForLogging:"true"`
NFTPostHashHex string `safeForLogging:"true"`
SerialNumber int `safeForLogging:"true"`
IsForSale bool `safeForLogging:"true"`
MinBidAmountNanos int `safeForLogging:"true"`
IsBuyNow bool `safeForLogging:"true"`
BuyNowPriceNanos uint64 `safeForLogging:"true"`
MinFeeRateNanosPerKB uint64 `safeForLogging:"true"`
// No need to specify ProfileEntryResponse in each TransactionFee
TransactionFees []TransactionFee `safeForLogging:"true"`
}
type UpdateNFTResponse struct {
NFTPostHashHex string `safeForLogging:"true"`
SerialNumber int `safeForLogging:"true"`
TotalInputNanos uint64
ChangeAmountNanos uint64
FeeNanos uint64
Transaction *lib.MsgDeSoTxn
TransactionHex string
}
func (fes *APIServer) UpdateNFT(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := UpdateNFTRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateNFT: Error parsing request body: %v", err))
return
}
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateNFT: Error getting utxoView: %v", err))
return
}
// Do a simple validation of the requestData.
if requestData.NFTPostHashHex == "" {
_AddBadRequestError(ww, fmt.Sprintf("UpdateNFT: Must include NFTPostHashHex"))
return
} else if requestData.UpdaterPublicKeyBase58Check == "" {
_AddBadRequestError(ww, fmt.Sprintf("UpdateNFT: Must include UpdaterPublicKeyBase58Check"))
return
} else if requestData.SerialNumber <= 0 || requestData.SerialNumber > int(utxoView.GlobalParamsEntry.MaxCopiesPerNFT) {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateNFT: SerialNumbers must be between %d and %d, received: %d",
1, utxoView.GlobalParamsEntry.MaxCopiesPerNFT, requestData.SerialNumber))
return
} else if requestData.MinBidAmountNanos < 0 {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateNFT: MinBidAmountNanos must be >= 0, got: %d", requestData.MinBidAmountNanos))
return
} else if !requestData.IsBuyNow && requestData.BuyNowPriceNanos > 0 {
_AddBadRequestError(ww, fmt.Sprint("UpdateNFT: cannot set BuyNowPriceNanos if NFT is not going to be "+
"sold in a 'Buy Now' fashion"))
return
} else if requestData.IsBuyNow && requestData.BuyNowPriceNanos < uint64(requestData.MinBidAmountNanos) {
_AddBadRequestError(ww, fmt.Sprint("UpdateNFT: cannot set BuyNowPriceNanos less than MinBidAmountNanos"))
return
}
// Get the PostHash for the NFT.
nftPostHashBytes, err := hex.DecodeString(requestData.NFTPostHashHex)
if err != nil || len(nftPostHashBytes) != lib.HashSizeBytes {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateNFT: Error parsing post hash %v: %v",
requestData.NFTPostHashHex, err))
return
}
nftPostHash := &lib.BlockHash{}
copy(nftPostHash[:], nftPostHashBytes)
// Get the updater's public key.
updaterPublicKeyBytes, _, err := lib.Base58CheckDecode(requestData.UpdaterPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateNFT: Problem decoding user public key: %v", err))
return
}
// Compute the additional transaction fees as specified by the request body and the node-level fees.
additionalOutputs, err := fes.getTransactionFee(lib.TxnTypeUpdateNFT, updaterPublicKeyBytes, requestData.TransactionFees)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateNFT: TransactionFees specified in Request body are invalid: %v", err))
return
}
// Get the NFT in question so we can do a more hardcore validation of the request data.
nftKey := lib.MakeNFTKey(nftPostHash, uint64(requestData.SerialNumber))
nftEntry := utxoView.GetNFTEntryForNFTKey(&nftKey)
if nftEntry == nil {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateNFT: Error could not find the NFT an NFT with postHash %v and serialNumber %d",
requestData.NFTPostHashHex, requestData.SerialNumber))
return
} else if nftEntry.IsForSale == requestData.IsForSale {
_AddBadRequestError(ww, fmt.Sprintf(
"UpdateNFT: NFT already has IsForSale=%v", requestData.IsForSale))
return
}
// Try and create the update NFT txn for the user.
txn, totalInput, changeAmount, fees, err := fes.blockchain.CreateUpdateNFTTxn(
updaterPublicKeyBytes,
nftPostHash,
uint64(requestData.SerialNumber),
requestData.IsForSale,
uint64(requestData.MinBidAmountNanos),
requestData.IsBuyNow,
requestData.BuyNowPriceNanos,
requestData.MinFeeRateNanosPerKB, fes.backendServer.GetMempool(), additionalOutputs)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("UpdateNFT: 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("UpdateNFT: Problem serializing transaction: %v", err))
return
}
// Return all the data associated with the transaction in the response
res := UpdateNFTResponse{
NFTPostHashHex: requestData.NFTPostHashHex,
SerialNumber: requestData.SerialNumber,
TotalInputNanos: totalInput,
ChangeAmountNanos: changeAmount,
FeeNanos: fees,
Transaction: txn,
TransactionHex: hex.EncodeToString(txnBytes),
}
if err = json.NewEncoder(ww).Encode(res); err != nil {
_AddInternalServerError(ww, fmt.Sprintf("UpdateNFT: Problem serializing object to JSON: %v", err))
return
}
}
type CreateNFTBidRequest struct {
UpdaterPublicKeyBase58Check string `safeForLogging:"true"`
NFTPostHashHex string `safeForLogging:"true"`
SerialNumber int `safeForLogging:"true"`
BidAmountNanos int `safeForLogging:"true"`
MinFeeRateNanosPerKB uint64 `safeForLogging:"true"`
// No need to specify ProfileEntryResponse in each TransactionFee
TransactionFees []TransactionFee `safeForLogging:"true"`
}
type CreateNFTBidResponse struct {
UpdaterPublicKeyBase58Check string `safeForLogging:"true"`
NFTPostHashHex string `safeForLogging:"true"`
SerialNumber int `safeForLogging:"true"`
BidAmountNanos int `safeForLogging:"true"`
TotalInputNanos uint64
ChangeAmountNanos uint64
FeeNanos uint64
Transaction *lib.MsgDeSoTxn
TransactionHex string
}
func (fes *APIServer) CreateNFTBid(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := CreateNFTBidRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFTBid: Error parsing request body: %v", err))
return
}
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFTBid: Error getting utxoView: %v", err))
return
}
// Do a simple validation of the requestData.
if requestData.NFTPostHashHex == "" {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFTBid: Must include NFTPostHashHex"))
return
} else if requestData.UpdaterPublicKeyBase58Check == "" {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFTBid: Must include UpdaterPublicKeyBase58Check"))
return
} else if requestData.SerialNumber <= 0 || requestData.SerialNumber > int(utxoView.GlobalParamsEntry.MaxCopiesPerNFT) {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFTBid: SerialNumbers must be between %d and %d, received: %d",
1, utxoView.GlobalParamsEntry.MaxCopiesPerNFT, requestData.SerialNumber))
return
} else if requestData.BidAmountNanos < 0 {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFTBid: BidAmountNanos must be non-negative, received: %d", requestData.BidAmountNanos))
return
}
// Get the PostHash for the NFT.
nftPostHashBytes, err := hex.DecodeString(requestData.NFTPostHashHex)
if err != nil || len(nftPostHashBytes) != lib.HashSizeBytes {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFTBid: Error parsing post hash %v: %v",
requestData.NFTPostHashHex, err))
return
}
nftPostHash := &lib.BlockHash{}
copy(nftPostHash[:], nftPostHashBytes)
// Get the updater's public key.
updaterPublicKeyBytes, _, err := lib.Base58CheckDecode(requestData.UpdaterPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFTBid: Problem decoding user public key: %v", err))
return
}
// Compute the additional transaction fees as specified by the request body and the node-level fees.
additionalOutputs, err := fes.getTransactionFee(lib.TxnTypeNFTBid, updaterPublicKeyBytes, requestData.TransactionFees)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFTBid: TransactionFees specified in Request body are invalid: %v", err))
return
}
// Get the NFT in question so we can do a more hardcore validation of the request data.
if requestData.SerialNumber != 0 {
nftKey := lib.MakeNFTKey(nftPostHash, uint64(requestData.SerialNumber))
nftEntry := utxoView.GetNFTEntryForNFTKey(&nftKey)
if nftEntry == nil {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFTBid: Error could not find the NFT an NFT with postHash %v and serialNumber %d",
requestData.NFTPostHashHex, requestData.SerialNumber))
return
} else if !nftEntry.IsForSale {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFTBid: NFT with postHash %v and serialNumber %d is not for sale.",
requestData.NFTPostHashHex, requestData.SerialNumber))
return
}
} else {
// The user can bid on serial number zero as long as it is the post hash provided is an NFT.
postEntry := utxoView.GetPostEntryForPostHash(nftPostHash)
if postEntry == nil {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFTBid: Error could not find a post with postHash %v", requestData.NFTPostHashHex))
return
} else if !postEntry.IsNFT {
_AddBadRequestError(ww, fmt.Sprintf(
"CreateNFTBid: Post with postHash %v is not an NFT.", requestData.NFTPostHashHex))
return
}
}
// RPH-FIXME: Make sure the user has sufficient funds to make this bid.
// Try and create the NFT bid txn for the user.
txn, totalInput, changeAmount, fees, err := fes.blockchain.CreateNFTBidTxn(
updaterPublicKeyBytes,
nftPostHash,
uint64(requestData.SerialNumber),
uint64(requestData.BidAmountNanos),
requestData.MinFeeRateNanosPerKB, fes.backendServer.GetMempool(), additionalOutputs)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("CreateNFTBid: 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("CreateNFTBid: Problem serializing transaction: %v", err))
return
}
// Return all the data associated with the transaction in the response
res := CreateNFTBidResponse{
UpdaterPublicKeyBase58Check: requestData.UpdaterPublicKeyBase58Check,
NFTPostHashHex: requestData.NFTPostHashHex,
SerialNumber: requestData.SerialNumber,
BidAmountNanos: requestData.BidAmountNanos,
TotalInputNanos: totalInput,
ChangeAmountNanos: changeAmount,
FeeNanos: fees,
Transaction: txn,
TransactionHex: hex.EncodeToString(txnBytes),
}
if err = json.NewEncoder(ww).Encode(res); err != nil {
_AddInternalServerError(ww, fmt.Sprintf("CreateNFTBid: Problem serializing object to JSON: %v", err))
return
}
}
type AcceptNFTBidRequest struct {
UpdaterPublicKeyBase58Check string `safeForLogging:"true"`
NFTPostHashHex string `safeForLogging:"true"`
SerialNumber int `safeForLogging:"true"`
BidderPublicKeyBase58Check string `safeForLogging:"true"`
BidAmountNanos int `safeForLogging:"true"`
EncryptedUnlockableText string `safeForLogging:"true"`
MinFeeRateNanosPerKB uint64 `safeForLogging:"true"`
// No need to specify ProfileEntryResponse in each TransactionFee
TransactionFees []TransactionFee `safeForLogging:"true"`
}
type AcceptNFTBidResponse struct {
BidderPublicKeyBase58Check string `safeForLogging:"true"`
NFTPostHashHex string `safeForLogging:"true"`
SerialNumber int `safeForLogging:"true"`
BidAmountNanos int `safeForLogging:"true"`
TotalInputNanos uint64
ChangeAmountNanos uint64
FeeNanos uint64
Transaction *lib.MsgDeSoTxn
TransactionHex string
}
func (fes *APIServer) AcceptNFTBid(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := AcceptNFTBidRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AcceptNFTBid: Error parsing request body: %v", err))
return
}
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AcceptNFTBid: Error getting utxoView: %v", err))
return
}
// Do a simple validation of the requestData.
if requestData.NFTPostHashHex == "" {
_AddBadRequestError(ww, fmt.Sprintf("AcceptNFTBid: Must include NFTPostHashHex"))
return
} else if requestData.UpdaterPublicKeyBase58Check == "" || requestData.BidderPublicKeyBase58Check == "" {
_AddBadRequestError(ww, fmt.Sprintf(
"AcceptNFTBid: Must include UpdaterPublicKeyBase58Check and BidderPublicKeyBase58Check"))
return
} else if requestData.SerialNumber <= 0 || requestData.SerialNumber > int(utxoView.GlobalParamsEntry.MaxCopiesPerNFT) {
_AddBadRequestError(ww, fmt.Sprintf(
"AcceptNFTBid: SerialNumbers must be between %d and %d, received: %d",
1, utxoView.GlobalParamsEntry.MaxCopiesPerNFT, requestData.SerialNumber))
return
} else if requestData.BidAmountNanos < 0 {
_AddBadRequestError(ww, fmt.Sprintf(
"AcceptNFTBid: BidAmountNanos must be non-negative, received: %d", requestData.BidAmountNanos))
return
}
// Get the PostHash for the NFT.
nftPostHashBytes, err := hex.DecodeString(requestData.NFTPostHashHex)
if err != nil || len(nftPostHashBytes) != lib.HashSizeBytes {
_AddBadRequestError(ww, fmt.Sprintf(
"AcceptNFTBid: Error parsing post hash %v: %v",
requestData.NFTPostHashHex, err))
return
}
nftPostHash := &lib.BlockHash{}
copy(nftPostHash[:], nftPostHashBytes)
// Get the updater's public key.
updaterPublicKeyBytes, _, err := lib.Base58CheckDecode(requestData.UpdaterPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AcceptNFTBid: Problem decoding user public key: %v", err))
return
}
// Compute the additional transaction fees as specified by the request body and the node-level fees.
additionalOutputs, err := fes.getTransactionFee(lib.TxnTypeAcceptNFTBid, updaterPublicKeyBytes, requestData.TransactionFees)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AcceptNFTBid: TransactionFees specified in Request body are invalid: %v", err))
return
}
// Get the bidder's public key.
bidderPublicKeyBytes, _, err := lib.Base58CheckDecode(requestData.BidderPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AcceptNFTBid: Problem decoding bidder public key: %v", err))
return
}
// Get the NFT bid so we can do a more hardcore validation of the request data.
bidderPKID := utxoView.GetPKIDForPublicKey(bidderPublicKeyBytes)
if bidderPKID == nil {
_AddBadRequestError(ww, fmt.Sprintf(
"AcceptNFTBid: Error could not find PKID for bidder pub key %v",
requestData.BidderPublicKeyBase58Check))
return
}
nftBidKey := lib.MakeNFTBidKey(bidderPKID.PKID, nftPostHash, uint64(requestData.SerialNumber))
nftBidEntry := utxoView.GetNFTBidEntryForNFTBidKey(&nftBidKey)
if nftBidEntry == nil {
_AddBadRequestError(ww, fmt.Sprintf(
"AcceptNFTBid: Error could not find an NFT bid entry for bidder pub key %v, "+
"postHash %v and serialNumber %d", requestData.BidderPublicKeyBase58Check,
requestData.NFTPostHashHex, requestData.SerialNumber))
return
}
// RPH-FIXME: Make sure the bidder has sufficient funds to fill this bid.
var encryptedUnlockableTextBytes []byte
if requestData.EncryptedUnlockableText != "" {
encryptedUnlockableTextBytes = []byte(requestData.EncryptedUnlockableText)
}
// Try and create the accept NFT bid txn for the user.
txn, totalInput, changeAmount, fees, err := fes.blockchain.CreateAcceptNFTBidTxn(
updaterPublicKeyBytes,
nftPostHash,
uint64(requestData.SerialNumber),
bidderPKID.PKID,
uint64(requestData.BidAmountNanos),
encryptedUnlockableTextBytes,
requestData.MinFeeRateNanosPerKB, fes.backendServer.GetMempool(), additionalOutputs)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("AcceptNFTBid: 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("AcceptNFTBid: Problem serializing transaction: %v", err))
return
}
// Return all the data associated with the transaction in the response
res := AcceptNFTBidResponse{
BidderPublicKeyBase58Check: requestData.BidderPublicKeyBase58Check,
NFTPostHashHex: requestData.NFTPostHashHex,
SerialNumber: requestData.SerialNumber,
BidAmountNanos: requestData.BidAmountNanos,
TotalInputNanos: totalInput,
ChangeAmountNanos: changeAmount,
FeeNanos: fees,
Transaction: txn,
TransactionHex: hex.EncodeToString(txnBytes),
}
if err = json.NewEncoder(ww).Encode(res); err != nil {
_AddInternalServerError(ww, fmt.Sprintf("AcceptNFTBid: Problem serializing object to JSON: %v", err))
return
}
}
type GetNFTShowcaseRequest struct {
ReaderPublicKeyBase58Check string `safeForLogging:"true"`
}
type GetNFTShowcaseResponse struct {
NFTCollections []*NFTCollectionResponse
}
func (fes *APIServer) GetNFTShowcase(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := GetNFTShowcaseRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetNFTShowcase: Error parsing request body: %v", err))
return
}
var readerPublicKeyBytes []byte
var err error
if requestData.ReaderPublicKeyBase58Check != "" {
readerPublicKeyBytes, _, err = lib.Base58CheckDecode(requestData.ReaderPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetNFTShowcase: Problem decoding reader public key: %v", err))
return
}
}
dropEntry, err := fes.GetLatestNFTDropEntry()
if err != nil {
_AddInternalServerError(ww, fmt.Sprintf("GetNFTShowcase: Problem getting latest drop: %v", err))
return
}
currentTime := uint64(time.Now().UnixNano())
if dropEntry.DropTstampNanos > currentTime {
// In this case, we have found a pending drop. We must go back one drop in order to
// get the current active drop.
if dropEntry.DropNumber == 1 {
// If the pending drop is drop #1, we need to return a blank dropEntry.
dropEntry = &NFTDropEntry{}
}
if dropEntry.DropNumber > 1 {
dropNumToFetch := dropEntry.DropNumber - 1
dropEntry, err = fes.GetNFTDropEntry(dropNumToFetch)
if err != nil {
_AddInternalServerError(ww, fmt.Sprintf(
"GetNFTShowcase: Problem getting drop #%d: %v", dropNumToFetch, err))
return
}
}
}
// Now that we have the drop entry, fetch the NFTs.
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetNFTShowcase: Error getting utxoView: %v", err))
return
}
var readerPKID *lib.PKID
if requestData.ReaderPublicKeyBase58Check != "" {
readerPKID = utxoView.GetPKIDForPublicKey(readerPublicKeyBytes).PKID
}
var nftCollectionResponses []*NFTCollectionResponse
for _, nftHash := range dropEntry.NFTHashes {
postEntry := utxoView.GetPostEntryForPostHash(nftHash)
if postEntry == nil {
_AddInternalServerError(ww, fmt.Sprint("GetNFTShowcase: Found nil post entry for NFT hash."))
return
}
if postEntry.NumNFTCopiesBurned == postEntry.NumNFTCopies {
continue
}
nftKey := lib.MakeNFTKey(nftHash, 1)
nftEntry := utxoView.GetNFTEntryForNFTKey(&nftKey)
postEntryResponse, err := fes._postEntryToResponse(
postEntry, false, fes.Params, utxoView, readerPublicKeyBytes, 2)
if err != nil {
_AddInternalServerError(ww, fmt.Sprint("GetNFTShowcase: Found invalid post entry for NFT hash."))
return
}
postEntryResponse.PostEntryReaderState = utxoView.GetPostEntryReaderState(readerPublicKeyBytes, postEntry)
nftCollectionResponse := fes._nftEntryToNFTCollectionResponse(nftEntry, postEntry.PosterPublicKey, postEntryResponse, utxoView, readerPKID)
nftCollectionResponses = append(nftCollectionResponses, nftCollectionResponse)
}
// Return all the data associated with the transaction in the response
res := GetNFTShowcaseResponse{
NFTCollections: nftCollectionResponses,
}
if err = json.NewEncoder(ww).Encode(res); err != nil {
_AddInternalServerError(ww, fmt.Sprintf("GetNFTShowcase: Problem serializing object to JSON: %v", err))
return
}
}
type GetNextNFTShowcaseRequest struct{}
type GetNextNFTShowcaseResponse struct {
NextNFTShowcaseTstamp uint64
}
func (fes *APIServer) GetNextNFTShowcase(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := GetNextNFTShowcaseRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetNextNFTShowcase: Error parsing request body: %v", err))
return
}
dropEntry, err := fes.GetLatestNFTDropEntry()
if err != nil {
_AddInternalServerError(ww, fmt.Sprintf("GetNextNFTShowcase: Problem getting latest drop: %v", err))
return
}
var nextNFTShowcaseTstamp uint64
currentTime := uint64(time.Now().UnixNano())
if dropEntry.DropTstampNanos > currentTime && dropEntry.IsActive {
// If there is a pending+active drop, return its timestamp.
nextNFTShowcaseTstamp = dropEntry.DropTstampNanos
}
// Return all the data associated with the transaction in the response
res := GetNextNFTShowcaseResponse{
NextNFTShowcaseTstamp: nextNFTShowcaseTstamp,
}
if err = json.NewEncoder(ww).Encode(res); err != nil {
_AddInternalServerError(ww, fmt.Sprintf("GetNextNFTShowcase: Problem serializing object to JSON: %v", err))
return
}
}
type GetNFTsForUserRequest struct {
UserPublicKeyBase58Check string `safeForLogging:"true"`
ReaderPublicKeyBase58Check string `safeForLogging:"true"`
IsForSale *bool `safeForLogging:"true"`
// Ignored if IsForSale is provided
IsPending *bool `safeForLogging:"true"`
}
type NFTEntryAndPostEntryResponse struct {
PostEntryResponse *PostEntryResponse
NFTEntryResponses []*NFTEntryResponse
}
type GetNFTsForUserResponse struct {
NFTsMap map[string]*NFTEntryAndPostEntryResponse
}
func (fes *APIServer) GetNFTsForUser(ww http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(io.LimitReader(req.Body, MaxRequestBodySizeBytes))
requestData := GetNFTsForUserRequest{}
if err := decoder.Decode(&requestData); err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetNFTsForUser: Error parsing request body: %v", err))
return
}
if requestData.UserPublicKeyBase58Check == "" {
_AddBadRequestError(ww, fmt.Sprintf("GetNFTsForUser: must provide UserPublicKeyBase58Check"))
return
}
userPublicKey, _, err := lib.Base58CheckDecode(requestData.UserPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetNFTsForUser: Problem decoding reader public key: %v", err))
return
}
var readerPublicKeyBytes []byte
if requestData.ReaderPublicKeyBase58Check != "" {
readerPublicKeyBytes, _, err = lib.Base58CheckDecode(requestData.ReaderPublicKeyBase58Check)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetNFTsForUser: Problem decoding reader public key: %v", err))
return
}
}
// Get the NFT bid so we can do a more hardcore validation of the request data.
utxoView, err := fes.backendServer.GetMempool().GetAugmentedUniversalView()
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetNFTsForUser: Error getting utxoView: %v", err))
return
}
// Return all the data associated with the transaction in the response
res := GetNFTsForUserResponse{
NFTsMap: make(map[string]*NFTEntryAndPostEntryResponse),
}
pkid := utxoView.GetPKIDForPublicKey(userPublicKey)
readerPKIDEntry := utxoView.GetPKIDForPublicKey(readerPublicKeyBytes)
var readerPKID *lib.PKID
if readerPKIDEntry != nil {
readerPKID = readerPKIDEntry.PKID
}
nftEntries := utxoView.GetNFTEntriesForPKID(pkid.PKID)
filteredNFTEntries := []*lib.NFTEntry{}
if requestData.IsForSale != nil {
checkForSale := *requestData.IsForSale
for _, nftEntry := range nftEntries {
if checkForSale == nftEntry.IsForSale {
filteredNFTEntries = append(filteredNFTEntries, nftEntry)
}
}
} else if requestData.IsPending != nil {
checkIsPending := *requestData.IsPending
for _, nftEntry := range nftEntries {
if checkIsPending == nftEntry.IsPending {
filteredNFTEntries = append(filteredNFTEntries, nftEntry)
}
}
} else {
filteredNFTEntries = nftEntries
}
postHashToEntryResponseMap := make(map[*lib.BlockHash]*PostEntryResponse)
publicKeyToProfileEntryResponse := make(map[string]*ProfileEntryResponse)
for _, nftEntry := range filteredNFTEntries {
postEntryResponse := postHashToEntryResponseMap[nftEntry.NFTPostHash]
if postEntryResponse == nil {
postEntry := utxoView.GetPostEntryForPostHash(nftEntry.NFTPostHash)
postEntryResponse, err = fes._postEntryToResponse(postEntry, true, fes.Params, utxoView, readerPublicKeyBytes, 2)
if err != nil {
_AddBadRequestError(ww, fmt.Sprintf("GetNFTsForUser: Problem converting post entry to response: %v", err))
return
}
if peResponse, exists := publicKeyToProfileEntryResponse[postEntryResponse.PosterPublicKeyBase58Check]; !exists {
profileEntry := utxoView.GetProfileEntryForPublicKey(postEntry.PosterPublicKey)
profileEntryResponse := fes._profileEntryToResponse(profileEntry, utxoView)
postEntryResponse.ProfileEntryResponse = profileEntryResponse
postEntryResponse.PostEntryReaderState = utxoView.GetPostEntryReaderState(readerPublicKeyBytes, postEntry)
publicKeyToProfileEntryResponse[postEntryResponse.PosterPublicKeyBase58Check] = profileEntryResponse
} else {