-
Notifications
You must be signed in to change notification settings - Fork 0
/
block_view_nft.go
2660 lines (2320 loc) · 105 KB
/
block_view_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 lib
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/btcsuite/btcd/btcec"
"github.com/golang/glog"
"github.com/pkg/errors"
"math"
"math/big"
"reflect"
"sort"
)
func (bav *UtxoView) _setNFTEntryMappings(nftEntry *NFTEntry) {
// This function shouldn't be called with nil.
if nftEntry == nil {
glog.Errorf("_setNFTEntryMappings: Called with nil NFTEntry; " +
"this should never happen.")
return
}
nftKey := MakeNFTKey(nftEntry.NFTPostHash, nftEntry.SerialNumber)
bav.NFTKeyToNFTEntry[nftKey] = nftEntry
}
func (bav *UtxoView) _deleteNFTEntryMappings(nftEntry *NFTEntry) {
// Create a tombstone entry.
tombstoneNFTEntry := *nftEntry
tombstoneNFTEntry.isDeleted = true
// Set the mappings to point to the tombstone entry.
bav._setNFTEntryMappings(&tombstoneNFTEntry)
}
func (bav *UtxoView) GetNFTEntryForNFTKey(nftKey *NFTKey) *NFTEntry {
// If an entry exists in the in-memory map, return the value of that mapping.
mapValue, existsMapValue := bav.NFTKeyToNFTEntry[*nftKey]
if existsMapValue {
return mapValue
}
// If we get here it means no value exists in our in-memory map. In this case,
// defer to the db. If a mapping exists in the db, return it. If not, return
// nil.
var nftEntry *NFTEntry
if bav.Postgres != nil {
nft := bav.Postgres.GetNFT(&nftKey.NFTPostHash, nftKey.SerialNumber)
if nft != nil {
nftEntry = nft.NewNFTEntry()
}
} else {
nftEntry = DBGetNFTEntryByPostHashSerialNumber(bav.Handle, bav.Snapshot,
&nftKey.NFTPostHash, nftKey.SerialNumber)
}
if nftEntry != nil {
bav._setNFTEntryMappings(nftEntry)
}
return nftEntry
}
func (bav *UtxoView) GetNFTEntriesForPostHash(nftPostHash *BlockHash) []*NFTEntry {
// Get all the entries in the DB.
var dbNFTEntries []*NFTEntry
if bav.Postgres != nil {
nfts := bav.Postgres.GetNFTsForPostHash(nftPostHash)
for _, nft := range nfts {
dbNFTEntries = append(dbNFTEntries, nft.NewNFTEntry())
}
} else {
dbNFTEntries = DBGetNFTEntriesForPostHash(bav.Handle, nftPostHash)
}
// Make sure all of the DB entries are loaded in the view.
for _, dbNFTEntry := range dbNFTEntries {
nftKey := MakeNFTKey(dbNFTEntry.NFTPostHash, dbNFTEntry.SerialNumber)
// If the NFT is not in the view, add it to the view.
if _, ok := bav.NFTKeyToNFTEntry[nftKey]; !ok {
bav._setNFTEntryMappings(dbNFTEntry)
}
}
// Loop over the view and build the final set of NFTEntries to return.
nftEntries := []*NFTEntry{}
for _, nftEntry := range bav.NFTKeyToNFTEntry {
if !nftEntry.isDeleted && reflect.DeepEqual(nftEntry.NFTPostHash, nftPostHash) {
nftEntries = append(nftEntries, nftEntry)
}
}
return nftEntries
}
func (bav *UtxoView) GetNFTEntriesForPKID(ownerPKID *PKID) []*NFTEntry {
var dbNFTEntries []*NFTEntry
if bav.Postgres != nil {
nfts := bav.Postgres.GetNFTsForPKID(ownerPKID)
for _, nft := range nfts {
dbNFTEntries = append(dbNFTEntries, nft.NewNFTEntry())
}
} else {
dbNFTEntries = DBGetNFTEntriesForPKID(bav.Handle, ownerPKID)
}
// Make sure all of the DB entries are loaded in the view.
for _, dbNFTEntry := range dbNFTEntries {
nftKey := MakeNFTKey(dbNFTEntry.NFTPostHash, dbNFTEntry.SerialNumber)
// If the NFT is not in the view, add it to the view.
if _, ok := bav.NFTKeyToNFTEntry[nftKey]; !ok {
bav._setNFTEntryMappings(dbNFTEntry)
}
}
// Loop over the view and build the final set of NFTEntries to return.
nftEntries := []*NFTEntry{}
for _, nftEntry := range bav.NFTKeyToNFTEntry {
if !nftEntry.isDeleted && reflect.DeepEqual(nftEntry.OwnerPKID, ownerPKID) {
nftEntries = append(nftEntries, nftEntry)
}
}
return nftEntries
}
func (bav *UtxoView) GetNFTBidEntriesForPKID(bidderPKID *PKID) (_nftBidEntries []*NFTBidEntry) {
var dbNFTBidEntries []*NFTBidEntry
if bav.Postgres != nil {
bids := bav.Postgres.GetNFTBidsForPKID(bidderPKID)
for _, bid := range bids {
dbNFTBidEntries = append(dbNFTBidEntries, bid.NewNFTBidEntry())
}
} else {
dbNFTBidEntries = DBGetNFTBidEntriesForPKID(bav.Handle, bidderPKID)
}
// Make sure all of the DB entries are loaded in the view.
for _, dbNFTBidEntry := range dbNFTBidEntries {
nftBidKey := MakeNFTBidKey(bidderPKID, dbNFTBidEntry.NFTPostHash, dbNFTBidEntry.SerialNumber)
// If the NFT is not in the view, add it to the view.
if _, ok := bav.NFTBidKeyToNFTBidEntry[nftBidKey]; !ok {
bav._setNFTBidEntryMappings(dbNFTBidEntry)
}
}
// Loop over the view and build the final set of NFTEntries to return.
nftBidEntries := []*NFTBidEntry{}
for _, nftBidEntry := range bav.NFTBidKeyToNFTBidEntry {
if !nftBidEntry.isDeleted && reflect.DeepEqual(nftBidEntry.BidderPKID, bidderPKID) {
nftBidEntries = append(nftBidEntries, nftBidEntry)
}
}
return nftBidEntries
}
// TODO: Postgres
func (bav *UtxoView) GetHighAndLowBidsForNFTCollection(
nftHash *BlockHash,
) (_highBid uint64, _lowBid uint64) {
highBid := uint64(0)
lowBid := uint64(0)
postEntry := bav.GetPostEntryForPostHash(nftHash)
// First we get the highest and lowest bids from the db.
for ii := uint64(1); ii <= postEntry.NumNFTCopies; ii++ {
highBidForSerialNum, lowBidForSerialNum := bav.GetDBHighAndLowBidsForNFT(nftHash, ii)
if highBidForSerialNum > highBid {
highBid = highBidForSerialNum
}
if lowBidForSerialNum < lowBid {
lowBid = lowBidForSerialNum
}
}
// Then we loop over the view to for anything we missed.
for _, nftBidEntry := range bav.NFTBidKeyToNFTBidEntry {
if !nftBidEntry.isDeleted && reflect.DeepEqual(nftBidEntry.NFTPostHash, nftHash) {
if nftBidEntry.BidAmountNanos > highBid {
highBid = nftBidEntry.BidAmountNanos
}
if nftBidEntry.BidAmountNanos < lowBid {
lowBid = nftBidEntry.BidAmountNanos
}
}
}
return highBid, lowBid
}
// TODO: Postgres
func (bav *UtxoView) GetHighAndLowBidsForNFTSerialNumber(nftHash *BlockHash, serialNumber uint64) (_highBid uint64, _lowBid uint64) {
highBid := uint64(0)
lowBid := uint64(0)
highBidEntry, lowBidEntry := bav.GetDBHighAndLowBidEntriesForNFT(nftHash, serialNumber)
if highBidEntry != nil {
highBidKey := MakeNFTBidKey(highBidEntry.BidderPKID, highBidEntry.NFTPostHash, highBidEntry.SerialNumber)
if _, exists := bav.NFTBidKeyToNFTBidEntry[highBidKey]; !exists {
bav._setNFTBidEntryMappings(highBidEntry)
}
highBid = highBidEntry.BidAmountNanos
}
if lowBidEntry != nil {
lowBidKey := MakeNFTBidKey(lowBidEntry.BidderPKID, lowBidEntry.NFTPostHash, lowBidEntry.SerialNumber)
if _, exists := bav.NFTBidKeyToNFTBidEntry[lowBidKey]; !exists {
bav._setNFTBidEntryMappings(lowBidEntry)
}
lowBid = lowBidEntry.BidAmountNanos
}
// Then we loop over the view to for anything we missed.
for _, nftBidEntry := range bav.NFTBidKeyToNFTBidEntry {
if !nftBidEntry.isDeleted && nftBidEntry.SerialNumber == serialNumber && reflect.DeepEqual(nftBidEntry.NFTPostHash, nftHash) {
if nftBidEntry.BidAmountNanos > highBid {
highBid = nftBidEntry.BidAmountNanos
}
if nftBidEntry.BidAmountNanos < lowBid {
lowBid = nftBidEntry.BidAmountNanos
}
}
}
return highBid, lowBid
}
// TODO: Postgres
func (bav *UtxoView) GetDBHighAndLowBidsForNFT(nftHash *BlockHash, serialNumber uint64) (_highBid uint64, _lowBid uint64) {
highBidAmount := uint64(0)
lowBidAmount := uint64(0)
highBidEntry, lowBidEntry := bav.GetDBHighAndLowBidEntriesForNFT(nftHash, serialNumber)
if highBidEntry != nil {
highBidAmount = highBidEntry.BidAmountNanos
}
if lowBidEntry != nil {
lowBidAmount = lowBidEntry.BidAmountNanos
}
return highBidAmount, lowBidAmount
}
// This function gets the highest and lowest bids for a specific NFT that
// have not been deleted in the view.
// TODO: Postgres
func (bav *UtxoView) GetDBHighAndLowBidEntriesForNFT(
nftHash *BlockHash, serialNumber uint64,
) (_highBidEntry *NFTBidEntry, _lowBidEntry *NFTBidEntry) {
numPerDBFetch := 5
var highestBidEntry *NFTBidEntry
var lowestBidEntry *NFTBidEntry
// Loop until we find the highest bid in the database that hasn't been deleted in the view.
exitLoop := false
highBidEntries := DBGetNFTBidEntriesPaginated(
bav.Handle, nftHash, serialNumber, nil, numPerDBFetch, true)
for _, bidEntry := range highBidEntries {
bidEntryKey := MakeNFTBidKey(bidEntry.BidderPKID, bidEntry.NFTPostHash, bidEntry.SerialNumber)
if _, exists := bav.NFTBidKeyToNFTBidEntry[bidEntryKey]; !exists {
bav._setNFTBidEntryMappings(bidEntry)
}
}
for {
for _, highBidEntry := range highBidEntries {
bidKey := &NFTBidKey{
NFTPostHash: *highBidEntry.NFTPostHash,
SerialNumber: highBidEntry.SerialNumber,
BidderPKID: *highBidEntry.BidderPKID,
}
bidEntry := bav.NFTBidKeyToNFTBidEntry[*bidKey]
if !bidEntry.isDeleted && !exitLoop {
exitLoop = true
highestBidEntry = bidEntry
}
}
if len(highBidEntries) < numPerDBFetch {
exitLoop = true
}
if exitLoop {
break
} else {
nextStartEntry := highBidEntries[len(highBidEntries)-1]
highBidEntries = DBGetNFTBidEntriesPaginated(
bav.Handle, nftHash, serialNumber, nextStartEntry, numPerDBFetch, true,
)
}
}
// Loop until we find the lowest bid in the database that hasn't been deleted in the view.
exitLoop = false
lowBidEntries := DBGetNFTBidEntriesPaginated(
bav.Handle, nftHash, serialNumber, nil, numPerDBFetch, false)
for _, bidEntry := range lowBidEntries {
bidEntryKey := MakeNFTBidKey(bidEntry.BidderPKID, bidEntry.NFTPostHash, bidEntry.SerialNumber)
if _, exists := bav.NFTBidKeyToNFTBidEntry[bidEntryKey]; !exists {
bav._setNFTBidEntryMappings(bidEntry)
}
}
for {
for _, lowBidEntry := range lowBidEntries {
bidKey := &NFTBidKey{
NFTPostHash: *lowBidEntry.NFTPostHash,
SerialNumber: lowBidEntry.SerialNumber,
BidderPKID: *lowBidEntry.BidderPKID,
}
bidEntry := bav.NFTBidKeyToNFTBidEntry[*bidKey]
if !bidEntry.isDeleted && !exitLoop {
exitLoop = true
lowestBidEntry = bidEntry
}
}
if len(lowBidEntries) < numPerDBFetch {
exitLoop = true
}
if exitLoop {
break
} else {
nextStartEntry := lowBidEntries[len(lowBidEntries)-1]
lowBidEntries = DBGetNFTBidEntriesPaginated(
bav.Handle, nftHash, serialNumber, nextStartEntry, numPerDBFetch, false,
)
}
}
return highestBidEntry, lowestBidEntry
}
func (bav *UtxoView) _setAcceptNFTBidHistoryMappings(nftKey NFTKey, nftBidEntries *[]*NFTBidEntry) {
if nftBidEntries == nil {
glog.Errorf("_setAcceptedNFTBidHistoryMappings: Called with nil nftBidEntries; " +
"this should never happen.")
return
}
bav.NFTKeyToAcceptedNFTBidHistory[nftKey] = nftBidEntries
}
func (bav *UtxoView) GetAcceptNFTBidHistoryForNFTKey(nftKey *NFTKey) *[]*NFTBidEntry {
// If an entry exists in the in-memory map, return the value of that mapping.
mapValue, existsMapValue := bav.NFTKeyToAcceptedNFTBidHistory[*nftKey]
if existsMapValue {
return mapValue
}
// If we get here it means no value exists in our in-memory map. In this case,
// defer to the db. If a mapping exists in the db, return it. If not, return
// nil.
dbNFTBidEntries := DBGetAcceptedNFTBidEntriesByPostHashSerialNumber(
bav.Handle, bav.Snapshot, &nftKey.NFTPostHash, nftKey.SerialNumber)
if dbNFTBidEntries != nil {
bav._setAcceptNFTBidHistoryMappings(*nftKey, dbNFTBidEntries)
return dbNFTBidEntries
}
// We return an empty slice instead of nil
return &[]*NFTBidEntry{}
}
func (bav *UtxoView) _setNFTBidEntryMappings(nftBidEntry *NFTBidEntry) {
// This function shouldn't be called with nil.
if nftBidEntry == nil {
glog.Errorf("_setNFTBidEntryMappings: Called with nil nftBidEntry; " +
"this should never happen.")
return
}
nftBidKey := MakeNFTBidKey(nftBidEntry.BidderPKID, nftBidEntry.NFTPostHash, nftBidEntry.SerialNumber)
bav.NFTBidKeyToNFTBidEntry[nftBidKey] = nftBidEntry
}
func (bav *UtxoView) _deleteNFTBidEntryMappings(nftBidEntry *NFTBidEntry) {
// Create a tombstone entry.
tombstoneNFTBidEntry := *nftBidEntry
tombstoneNFTBidEntry.isDeleted = true
// Set the mappings to point to the tombstone entry.
bav._setNFTBidEntryMappings(&tombstoneNFTBidEntry)
}
func (bav *UtxoView) GetNFTBidEntryForNFTBidKey(nftBidKey *NFTBidKey) *NFTBidEntry {
// If an entry exists in the in-memory map, return the value of that mapping.
mapValue, existsMapValue := bav.NFTBidKeyToNFTBidEntry[*nftBidKey]
if existsMapValue {
return mapValue
}
// If we get here it means no value exists in our in-memory map. In this case,
// defer to the db. If a mapping exists in the db, return it. If not, return
// nil.
var dbNFTBidEntry *NFTBidEntry
if bav.Postgres != nil {
bidEntry := bav.Postgres.GetNFTBid(&nftBidKey.NFTPostHash, &nftBidKey.BidderPKID, nftBidKey.SerialNumber)
if bidEntry != nil {
dbNFTBidEntry = bidEntry.NewNFTBidEntry()
}
} else {
dbNFTBidEntry = DBGetNFTBidEntryForNFTBidKey(bav.Handle, bav.Snapshot, nftBidKey)
}
if dbNFTBidEntry != nil {
bav._setNFTBidEntryMappings(dbNFTBidEntry)
}
return dbNFTBidEntry
}
func (bav *UtxoView) GetAllNFTBidEntries(nftPostHash *BlockHash, serialNumber uint64) []*NFTBidEntry {
// Get all the entries in the DB.
var dbEntries []*NFTBidEntry
if bav.Postgres != nil {
bids := bav.Postgres.GetNFTBidsForSerial(nftPostHash, serialNumber)
for _, bid := range bids {
dbEntries = append(dbEntries, bid.NewNFTBidEntry())
}
} else {
dbEntries = DBGetNFTBidEntries(bav.Handle, nftPostHash, serialNumber)
}
// Make sure all of the DB entries are loaded in the view.
for _, dbEntry := range dbEntries {
nftBidKey := MakeNFTBidKey(dbEntry.BidderPKID, dbEntry.NFTPostHash, dbEntry.SerialNumber)
// If the bidEntry is not in the view, add it to the view.
if _, ok := bav.NFTBidKeyToNFTBidEntry[nftBidKey]; !ok {
bav._setNFTBidEntryMappings(dbEntry)
}
}
// Loop over the view and build the final set of NFTBidEntries to return.
nftBidEntries := []*NFTBidEntry{}
for _, nftBidEntry := range bav.NFTBidKeyToNFTBidEntry {
if nftBidEntry.SerialNumber == serialNumber && !nftBidEntry.isDeleted &&
reflect.DeepEqual(nftBidEntry.NFTPostHash, nftPostHash) {
nftBidEntries = append(nftBidEntries, nftBidEntry)
}
}
// Make sure NFT Bid entries are returned in a deterministic order. Bids must differ by BidderPKID, given they have
// distinct NFTBidKeys in the NFTBidKeyToNFTBidEntry map, so we use BidderPKID to order the bid entries.
sort.Slice(nftBidEntries, func(i int, j int) bool {
switch bytes.Compare(nftBidEntries[i].BidderPKID.ToBytes(), nftBidEntries[j].BidderPKID.ToBytes()) {
case 0:
return true
case -1:
return true
case 1:
return false
}
return false
})
return nftBidEntries
}
func (bav *UtxoView) _getBuyNowExtraData(txn *MsgDeSoTxn, blockHeight uint32) (
_isBuyNow bool, _buyNowPrice uint64, _err error) {
isBuyNow := false
buyNowPrice := uint64(0)
// Only extract the BuyNowPriceKey value if we are past the BuyNowAndNFTSplitsBlockHeight
if val, exists := txn.ExtraData[BuyNowPriceKey]; exists &&
blockHeight >= bav.Params.ForkHeights.BuyNowAndNFTSplitsBlockHeight {
var bytesRead int
buyNowPrice, bytesRead = Uvarint(val)
if bytesRead <= 0 {
return false, 0, errors.New(
"_getBuyNowExtraData: Problem reading bytes for BuyNowPriceNanos")
}
isBuyNow = true
}
return isBuyNow, buyNowPrice, nil
}
// Pull out a function that converts extraData to the map that we need
// for royalties.
func (bav *UtxoView) extractAdditionalRoyaltyMap(
key string, extraData map[string][]byte, blockHeight uint32) (
_additionalRoyaltiesMap map[PKID]uint64, _additionalRoyaltyBasisPoints uint64, _err error) {
additionalRoyalties := make(map[PKID]uint64)
additionalRoyaltiesBasisPoints := uint64(0)
if mapBytes, exists := extraData[key]; exists &&
blockHeight >= bav.Params.ForkHeights.BuyNowAndNFTSplitsBlockHeight {
var err error
additionalRoyaltiesByPubKey, err := DeserializePubKeyToUint64Map(mapBytes)
if err != nil {
return nil, 0, errors.Wrap(err,
"Problem reading bytes for additional royalties: ")
}
// Check that public keys are valid and sum basis points
for pkBytesIter, bps := range additionalRoyaltiesByPubKey {
// Make a copy of the iterator
pkBytess := pkBytesIter
// Validate the public key
if _, err = btcec.ParsePubKey(pkBytess[:], btcec.S256()); err != nil {
return nil, 0, errors.Wrapf(
RuleErrorAdditionalRoyaltyPubKeyMustBeValid,
"Error parsing public key: %v, %v", PkToStringBoth(pkBytess[:]), err)
}
// Set the PKID on the map
pkid := bav.GetPKIDForPublicKey(pkBytess[:])
additionalRoyalties[*pkid.PKID] = bps
// Check for overflow when summing the bps
if additionalRoyaltiesBasisPoints > math.MaxUint64-bps {
return nil, 0, errors.Wrapf(
RuleErrorAdditionalCoinRoyaltyOverflow,
"additionalRoyaltiesBasisPoints: %v, bps: %v", additionalRoyaltiesBasisPoints, bps)
}
// Add the bps to our total
additionalRoyaltiesBasisPoints += bps
if key == CoinRoyaltiesMapKey {
existingProfileEntry := bav.GetProfileEntryForPublicKey(pkBytess[:])
if existingProfileEntry == nil || existingProfileEntry.isDeleted {
return nil, 0, errors.Wrapf(
RuleErrorAdditionalCoinRoyaltyMustHaveProfile,
"Profile missing for additional Coin NFT royalty pub key: %v",
PkToStringBoth(pkBytess[:]))
}
}
}
}
return additionalRoyalties, additionalRoyaltiesBasisPoints, nil
}
func (bav *UtxoView) _connectCreateNFT(
txn *MsgDeSoTxn, txHash *BlockHash, blockHeight uint32, verifySignatures bool) (
_totalInput uint64, _totalOutput uint64, _utxoOps []*UtxoOperation, _err error) {
if bav.GlobalParamsEntry.MaxCopiesPerNFT == 0 {
return 0, 0, nil, fmt.Errorf("_connectCreateNFT: called with zero MaxCopiesPerNFT")
}
// Check that the transaction has the right TxnType.
if txn.TxnMeta.GetTxnType() != TxnTypeCreateNFT {
return 0, 0, nil, fmt.Errorf("_connectCreateNFT: called with bad TxnType %s",
txn.TxnMeta.GetTxnType().String())
}
txMeta := txn.TxnMeta.(*CreateNFTMetadata)
isBuyNow, buyNowPrice, err := bav._getBuyNowExtraData(txn, blockHeight)
if err != nil {
return 0, 0, nil, errors.Wrapf(err, "_connectCreateNFT: ")
}
// Extract additional DESO royalties
additionalDESONFTRoyalties, additionalDESONFTRoyaltiesBasisPoints, err := bav.extractAdditionalRoyaltyMap(
DESORoyaltiesMapKey, txn.ExtraData, blockHeight)
if err != nil {
return 0, 0, nil, errors.Wrap(err,
"_connectCreateNFT: Problem extract additional DESO Royalties: ")
}
// Extract additional coin royalties
additionalCoinNFTRoyalties, additionalCoinNFTRoyaltiesBasisPoints, err := bav.extractAdditionalRoyaltyMap(
CoinRoyaltiesMapKey, txn.ExtraData, blockHeight)
if err != nil {
return 0, 0, nil, errors.Wrap(err,
"_connectCreateNFT: Problem extract additional Coin Royalties: ")
}
// Validate the txMeta.
if txMeta.NumCopies > bav.GlobalParamsEntry.MaxCopiesPerNFT {
return 0, 0, nil, RuleErrorTooManyNFTCopies
}
if txMeta.NumCopies == 0 {
return 0, 0, nil, RuleErrorNFTMustHaveNonZeroCopies
}
// Make sure we won't overflow when we add the royalty basis points.
if math.MaxUint64-txMeta.NFTRoyaltyToCoinBasisPoints-additionalDESONFTRoyaltiesBasisPoints-
additionalCoinNFTRoyaltiesBasisPoints < txMeta.NFTRoyaltyToCreatorBasisPoints {
return 0, 0, nil, RuleErrorNFTRoyaltyOverflow
}
// Make sure we won't overflow when we add the royalty basis points.
if math.MaxUint64-txMeta.NFTRoyaltyToCreatorBasisPoints-additionalDESONFTRoyaltiesBasisPoints-
additionalCoinNFTRoyaltiesBasisPoints < txMeta.NFTRoyaltyToCoinBasisPoints {
return 0, 0, nil, RuleErrorNFTRoyaltyOverflow
}
// Make sure we won't overflow when we add the royalty basis points.
if math.MaxUint64-txMeta.NFTRoyaltyToCreatorBasisPoints-txMeta.NFTRoyaltyToCoinBasisPoints-
additionalCoinNFTRoyaltiesBasisPoints < additionalDESONFTRoyaltiesBasisPoints {
return 0, 0, nil, RuleErrorNFTRoyaltyOverflow
}
// Make sure we won't overflow when we add the royalty basis points.
if math.MaxUint64-txMeta.NFTRoyaltyToCreatorBasisPoints-txMeta.NFTRoyaltyToCoinBasisPoints-
additionalDESONFTRoyaltiesBasisPoints < additionalCoinNFTRoyaltiesBasisPoints {
return 0, 0, nil, RuleErrorNFTRoyaltyOverflow
}
postEntry := bav.GetPostEntryForPostHash(txMeta.NFTPostHash)
if postEntry == nil || postEntry.isDeleted {
return 0, 0, nil, RuleErrorCreateNFTOnNonexistentPost
}
posterPKID := bav.GetPKIDForPublicKey(postEntry.PosterPublicKey)
if posterPKID == nil || posterPKID.isDeleted {
return 0, 0, nil, fmt.Errorf("_connectCreateNFT: non-existent posterPKID: %s",
PkToString(postEntry.PosterPublicKey, bav.Params))
}
if IsVanillaRepost(postEntry) {
return 0, 0, nil, RuleErrorCreateNFTOnVanillaRepost
}
if !reflect.DeepEqual(postEntry.PosterPublicKey, txn.PublicKey) {
return 0, 0, nil, RuleErrorCreateNFTMustBeCalledByPoster
}
if postEntry.IsNFT {
return 0, 0, nil, RuleErrorCreateNFTOnPostThatAlreadyIsNFT
}
// We can't encrypt unlockable content if Buy Now is enabled.
if txMeta.HasUnlockable && isBuyNow {
return 0, 0, nil, errors.Wrapf(RuleErrorCannotHaveUnlockableAndBuyNowNFT, "_connectCreateNFT: ")
}
// We can't have a Buy Now NFT with a buy now price below min bid amount
if isBuyNow && txMeta.MinBidAmountNanos > buyNowPrice {
return 0, 0, nil, errors.Wrapf(RuleErrorCannotHaveBuyNowPriceBelowMinBidAmountNanos, "_connectCreateNFT: ")
}
// Make sure the creator of the post is not specified in the royalties maps
if _, exists := additionalDESONFTRoyalties[*posterPKID.PKID]; exists {
return 0, 0, nil, errors.Wrapf(RuleErrorCannotSpecifyCreatorAsAdditionalRoyalty,
"_connectCreateNFT: cannot specify the post creator in the additional DESO royalties map")
}
if _, exists := additionalCoinNFTRoyalties[*posterPKID.PKID]; exists {
return 0, 0, nil, errors.Wrapf(RuleErrorCannotSpecifyCreatorAsAdditionalRoyalty,
"_connectCreateNFT: cannot specify the post creator in the additional coin royalties map")
}
creatorRoyaltyBasisPoints := txMeta.NFTRoyaltyToCreatorBasisPoints + txMeta.NFTRoyaltyToCoinBasisPoints
if creatorRoyaltyBasisPoints+additionalCoinNFTRoyaltiesBasisPoints+
additionalDESONFTRoyaltiesBasisPoints > bav.Params.MaxNFTRoyaltyBasisPoints {
return 0, 0, nil, RuleErrorNFTRoyaltyHasTooManyBasisPoints
}
profileEntry := bav.GetProfileEntryForPublicKey(postEntry.PosterPublicKey)
if profileEntry == nil || profileEntry.isDeleted {
return 0, 0, nil, RuleErrorCantCreateNFTWithoutProfileEntry
}
// Connect basic txn to get the total input and the total output without
// considering the transaction metadata.
totalInput, totalOutput, utxoOpsForTxn, err := bav._connectBasicTransfer(
txn, txHash, blockHeight, verifySignatures)
if err != nil {
return 0, 0, nil, errors.Wrapf(err, "_connectCreateNFT: ")
}
// Force the input to be non-zero so that we can prevent replay attacks.
if totalInput == 0 {
return 0, 0, nil, RuleErrorCreateNFTRequiresNonZeroInput
}
if verifySignatures {
// _connectBasicTransfer has already checked that the transaction is
// signed by the top-level public key, which we take to be the poster's
// public key.
}
// Since issuing N copies of an NFT multiplies the downstream processing overhead by N,
// we charge a fee for each additional copy minted.
// We do not need to check for overflow as these values are managed by the ParamUpdater.
nftFee := txMeta.NumCopies * bav.GlobalParamsEntry.CreateNFTFeeNanos
// Sanity check overflow and then ensure that the transaction covers the NFT fee.
if math.MaxUint64-totalOutput < nftFee {
return 0, 0, nil, fmt.Errorf("_connectCreateNFTFee: nft Fee overflow")
}
totalOutput += nftFee
if totalInput < totalOutput {
return 0, 0, nil, RuleErrorCreateNFTWithInsufficientFunds
}
// Save a copy of the post entry so that we can safely modify it.
prevPostEntry := &PostEntry{}
*prevPostEntry = *postEntry
// Update and save the post entry.
postEntry.IsNFT = true
postEntry.NumNFTCopies = txMeta.NumCopies
if txMeta.IsForSale {
postEntry.NumNFTCopiesForSale = txMeta.NumCopies
}
postEntry.HasUnlockable = txMeta.HasUnlockable
postEntry.NFTRoyaltyToCreatorBasisPoints = txMeta.NFTRoyaltyToCreatorBasisPoints
postEntry.NFTRoyaltyToCoinBasisPoints = txMeta.NFTRoyaltyToCoinBasisPoints
postEntry.AdditionalNFTRoyaltiesToCreatorsBasisPoints = additionalDESONFTRoyalties
postEntry.AdditionalNFTRoyaltiesToCoinsBasisPoints = additionalCoinNFTRoyalties
bav._setPostEntryMappings(postEntry)
var extraData map[string][]byte
if blockHeight >= bav.Params.ForkHeights.ExtraDataOnEntriesBlockHeight {
// We don't have a previous entry here because we're creating the
// entry from scratch.
extraData = txn.ExtraData
}
// Add the appropriate NFT entries.
for ii := uint64(1); ii <= txMeta.NumCopies; ii++ {
nftEntry := &NFTEntry{
OwnerPKID: posterPKID.PKID,
NFTPostHash: txMeta.NFTPostHash,
SerialNumber: ii,
IsForSale: txMeta.IsForSale,
MinBidAmountNanos: txMeta.MinBidAmountNanos,
IsBuyNow: isBuyNow,
BuyNowPriceNanos: buyNowPrice,
ExtraData: extraData,
}
bav._setNFTEntryMappings(nftEntry)
}
// Add an operation to the utxoOps list indicating we've created an NFT.
utxoOpsForTxn = append(utxoOpsForTxn, &UtxoOperation{
Type: OperationTypeCreateNFT,
PrevPostEntry: prevPostEntry,
})
return totalInput, totalOutput, utxoOpsForTxn, nil
}
func (bav *UtxoView) _connectUpdateNFT(
txn *MsgDeSoTxn, txHash *BlockHash, blockHeight uint32, verifySignatures bool) (
_totalInput uint64, _totalOutput uint64, _utxoOps []*UtxoOperation, _err error) {
if bav.GlobalParamsEntry.MaxCopiesPerNFT == 0 {
return 0, 0, nil, fmt.Errorf("_connectUpdateNFT: called with zero MaxCopiesPerNFT")
}
// Check that the transaction has the right TxnType.
if txn.TxnMeta.GetTxnType() != TxnTypeUpdateNFT {
return 0, 0, nil, fmt.Errorf("_connectUpdateNFT: called with bad TxnType %s",
txn.TxnMeta.GetTxnType().String())
}
txMeta := txn.TxnMeta.(*UpdateNFTMetadata)
isBuyNow, buyNowPrice, err := bav._getBuyNowExtraData(txn, blockHeight)
if err != nil {
return 0, 0, nil, errors.Wrapf(err, "_connectUpdateNFT: ")
}
// Verify the NFT entry exists.
nftKey := MakeNFTKey(txMeta.NFTPostHash, txMeta.SerialNumber)
prevNFTEntry := bav.GetNFTEntryForNFTKey(&nftKey)
if prevNFTEntry == nil || prevNFTEntry.isDeleted {
return 0, 0, nil, RuleErrorCannotUpdateNonExistentNFT
}
// Verify the NFT is not a pending transfer.
if prevNFTEntry.IsPending {
return 0, 0, nil, RuleErrorCannotUpdatePendingNFTTransfer
}
// Get the postEntry so we can update the number of NFT copies for sale.
postEntry := bav.GetPostEntryForPostHash(txMeta.NFTPostHash)
if postEntry == nil || postEntry.isDeleted {
return 0, 0, nil, fmt.Errorf("_connectUpdateNFT: non-existent postEntry for NFTPostHash: %s",
txMeta.NFTPostHash.String())
}
// We can't encrypt unlockable content if Buy Now is enabled.
if postEntry.HasUnlockable && isBuyNow {
return 0, 0, nil, errors.Wrapf(RuleErrorCannotHaveUnlockableAndBuyNowNFT, "_connectUpdateNFT: ")
}
// We can't have a Buy Now NFT with a buy now price below min bid amount
if isBuyNow && txMeta.MinBidAmountNanos > buyNowPrice {
return 0, 0, nil, errors.Wrapf(RuleErrorCannotHaveBuyNowPriceBelowMinBidAmountNanos, "_connectUpdateNFT: ")
}
// Verify that the updater is the owner of the NFT.
updaterPKID := bav.GetPKIDForPublicKey(txn.PublicKey)
if updaterPKID == nil || updaterPKID.isDeleted {
return 0, 0, nil, fmt.Errorf("_connectUpdateNFT: non-existent updaterPKID: %s",
PkToString(txn.PublicKey, bav.Params))
}
if !reflect.DeepEqual(prevNFTEntry.OwnerPKID, updaterPKID.PKID) {
return 0, 0, nil, RuleErrorUpdateNFTByNonOwner
}
// Sanity check that the NFT entry is correct.
if !reflect.DeepEqual(prevNFTEntry.NFTPostHash, txMeta.NFTPostHash) ||
!reflect.DeepEqual(prevNFTEntry.SerialNumber, txMeta.SerialNumber) {
return 0, 0, nil, fmt.Errorf("_connectUpdateNFT: prevNFTEntry %v is inconsistent with txMeta %v;"+
" this should never happen.", prevNFTEntry, txMeta)
}
// At the moment, updates can only be made if the 'IsForSale' status of the NFT is changing.
// As a result, you cannot change the MinBidAmountNanos of an NFT while it is for sale.
if prevNFTEntry.IsForSale == txMeta.IsForSale {
return 0, 0, nil, RuleErrorNFTUpdateMustUpdateIsForSaleStatus
}
// Connect basic txn to get the total input and the total output without
// considering the transaction metadata.
totalInput, totalOutput, utxoOpsForTxn, err := bav._connectBasicTransfer(
txn, txHash, blockHeight, verifySignatures)
if err != nil {
return 0, 0, nil, errors.Wrapf(err, "_connectUpdateNFT: ")
}
// Force the input to be non-zero so that we can prevent replay attacks.
if totalInput == 0 {
return 0, 0, nil, RuleErrorUpdateNFTRequiresNonZeroInput
}
if verifySignatures {
// _connectBasicTransfer has already checked that the transaction is
// signed by the top-level public key, which we take to be the poster's
// public key.
}
// Now we are ready to update the NFT. Three things must happen:
// (1) Update the NFT entry.
// (2) If the NFT entry is being updated to "is not for sale", kill all the bids.
// (3) Update the number of NFT copies for sale on the post entry.
// Create the updated NFTEntry.
newNFTEntry := &NFTEntry{
LastOwnerPKID: prevNFTEntry.LastOwnerPKID,
OwnerPKID: updaterPKID.PKID,
NFTPostHash: txMeta.NFTPostHash,
SerialNumber: txMeta.SerialNumber,
IsForSale: txMeta.IsForSale,
MinBidAmountNanos: txMeta.MinBidAmountNanos,
UnlockableText: prevNFTEntry.UnlockableText,
IsBuyNow: isBuyNow,
BuyNowPriceNanos: buyNowPrice,
// Keep the last accepted bid amount nanos from the previous entry since this
// value is only updated when a new bid is accepted.
LastAcceptedBidAmountNanos: prevNFTEntry.LastAcceptedBidAmountNanos,
// Just copy the extra data from the previous entry when updating an NFT.
// We do this because you're not allowed to update the ExtraData on an
// NFTEntry.
ExtraData: prevNFTEntry.ExtraData,
}
bav._setNFTEntryMappings(newNFTEntry)
// If we are going from ForSale->NotForSale, delete all the NFTBidEntries for this NFT.
deletedBidEntries := []*NFTBidEntry{}
if prevNFTEntry.IsForSale && !txMeta.IsForSale {
bidEntries := bav.GetAllNFTBidEntries(txMeta.NFTPostHash, txMeta.SerialNumber)
for _, bidEntry := range bidEntries {
deletedBidEntries = append(deletedBidEntries, bidEntry)
bav._deleteNFTBidEntryMappings(bidEntry)
}
}
// Save a copy of the post entry so that we can safely modify it.
prevPostEntry := &PostEntry{}
*prevPostEntry = *postEntry
// Update the number of NFT copies that are for sale.
if prevNFTEntry.IsForSale && !txMeta.IsForSale {
// For sale --> Not for sale.
postEntry.NumNFTCopiesForSale--
} else if !prevNFTEntry.IsForSale && txMeta.IsForSale {
// Not for sale --> For sale.
postEntry.NumNFTCopiesForSale++
}
// Set the new postEntry.
bav._setPostEntryMappings(postEntry)
// Add an operation to the list at the end indicating we've connected an NFT update.
utxoOpsForTxn = append(utxoOpsForTxn, &UtxoOperation{
Type: OperationTypeUpdateNFT,
PrevNFTEntry: prevNFTEntry,
PrevPostEntry: prevPostEntry,
DeletedNFTBidEntries: deletedBidEntries,
})
return totalInput, totalOutput, utxoOpsForTxn, nil
}
func (bav *UtxoView) _connectAcceptNFTBid(
txn *MsgDeSoTxn, txHash *BlockHash, blockHeight uint32, verifySignatures bool) (
_totalInput uint64, _totalOutput uint64, _utxoOps []*UtxoOperation, _err error) {
if bav.GlobalParamsEntry.MaxCopiesPerNFT == 0 {
return 0, 0, nil, fmt.Errorf("_connectAcceptNFTBid: called with zero MaxCopiesPerNFT")
}
// Check that the transaction has the right TxnType.
if txn.TxnMeta.GetTxnType() != TxnTypeAcceptNFTBid {
return 0, 0, nil, fmt.Errorf("_connectAcceptNFTBid: called with bad TxnType %s",
txn.TxnMeta.GetTxnType().String())
}
txMeta := txn.TxnMeta.(*AcceptNFTBidMetadata)
// Verify the NFT entry that is being bid on exists and is on sale.
nftKey := MakeNFTKey(txMeta.NFTPostHash, txMeta.SerialNumber)
prevNFTEntry := bav.GetNFTEntryForNFTKey(&nftKey)
if prevNFTEntry == nil || prevNFTEntry.isDeleted {
// We wrap these errors in order to differentiate versus _connectNFTBid().
return 0, 0, nil, errors.Wrapf(RuleErrorNFTBidOnNonExistentNFTEntry, "_connectAcceptNFTBid: ")
}
if !prevNFTEntry.IsForSale {
return 0, 0, nil, errors.Wrapf(RuleErrorNFTBidOnNFTThatIsNotForSale, "_connectAcceptNFTBid: ")
}
// Verify the NFT is not a pending transfer.
if prevNFTEntry.IsPending {
return 0, 0, nil, RuleErrorCannotAcceptBidForPendingNFTTransfer
}
// Verify that the updater is the owner of the NFT.
updaterPKID := bav.GetPKIDForPublicKey(txn.PublicKey)
if updaterPKID == nil || updaterPKID.isDeleted {
return 0, 0, nil, fmt.Errorf("_connectAcceptNFTBid: non-existent updaterPKID: %s",
PkToString(txn.PublicKey, bav.Params))
}
if !reflect.DeepEqual(prevNFTEntry.OwnerPKID, updaterPKID.PKID) {
return 0, 0, nil, RuleErrorAcceptNFTBidByNonOwner
}
// Get the post entry, verify it exists.
nftPostEntry := bav.GetPostEntryForPostHash(txMeta.NFTPostHash)
// If this is an unlockable NFT, make sure that an unlockable string was provided.
if nftPostEntry == nil || nftPostEntry.isDeleted {
return 0, 0, nil, RuleErrorPostEntryNotFoundForAcceptedNFTBid
}
if nftPostEntry.HasUnlockable && len(txMeta.UnlockableText) == 0 {
return 0, 0, nil, RuleErrorUnlockableNFTMustProvideUnlockableText
}
// Check the length of the UnlockableText.
if uint64(len(txMeta.UnlockableText)) > bav.Params.MaxPrivateMessageLengthBytes {
return 0, 0, nil, errors.Wrapf(
RuleErrorUnlockableTextLengthExceedsMax, "_connectAcceptNFTBid: "+
"UnlockableTextLen = %d; Max length = %d",
len(txMeta.UnlockableText), bav.Params.MaxPrivateMessageLengthBytes)
}
totalInput, totalOutput, utxoOpsForTxn, err := bav._helpConnectNFTSold(HelpConnectNFTSoldStruct{
NFTPostHash: txMeta.NFTPostHash,
SerialNumber: txMeta.SerialNumber,
BidderPKID: txMeta.BidderPKID,
BidAmountNanos: txMeta.BidAmountNanos,
UnlockableText: txMeta.UnlockableText,
BidderInputs: txMeta.BidderInputs,
BlockHeight: blockHeight,
Txn: txn,
TxHash: txHash,
VerifySignatures: verifySignatures,
})
if err != nil {
return 0, 0, nil, errors.Wrapf(err, "_connectAcceptNFTBid")
}
return totalInput, totalOutput, utxoOpsForTxn, nil
}
type HelpConnectNFTSoldStruct struct {
NFTPostHash *BlockHash
SerialNumber uint64
BidderPKID *PKID
BidAmountNanos uint64
UnlockableText []byte
PrevNFTBidEntry *NFTBidEntry
// When an NFT owner accepts a bid, they must specify the bidder's UTXO inputs they will lock up
// as payment for the purchase. This prevents the transaction from accidentally using UTXOs
// that are used by future transactions.
BidderInputs []*DeSoInput
BlockHeight uint32
Txn *MsgDeSoTxn
TxHash *BlockHash
VerifySignatures bool
}
func (bav *UtxoView) _helpConnectNFTSold(args HelpConnectNFTSoldStruct) (
_totalInput uint64, _totalOutput uint64, _utxoOps []*UtxoOperation, _err error) {
if args.Txn.TxnMeta.GetTxnType() != TxnTypeAcceptNFTBid && args.Txn.TxnMeta.GetTxnType() != TxnTypeNFTBid {
return 0, 0, nil, fmt.Errorf("_helpConnectNFTSold: This transaction must be either an AcceptNFTBid txn or a NFTBid txn")
}
nftKey := MakeNFTKey(args.NFTPostHash, args.SerialNumber)
prevNFTEntry := bav.GetNFTEntryForNFTKey(&nftKey)
// Get the post entry, verify it exists.
nftPostEntry := bav.GetPostEntryForPostHash(args.NFTPostHash)
// Get the poster's profile.