forked from deso-protocol/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock_view.go
7414 lines (6389 loc) · 295 KB
/
block_view.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 (
"encoding/hex"
"fmt"
"math"
"math/big"
"reflect"
"sort"
"strings"
"time"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/davecgh/go-spew/spew"
"github.com/dgraph-io/badger/v3"
"github.com/golang/glog"
merkletree "github.com/laser/go-merkle-tree"
"github.com/pkg/errors"
)
// block_view.go is the main work-horse for validating transactions in blocks.
// It generally works by creating an "in-memory view" of the current tip and
// then applying a transaction's operations to the view to see if those operations
// are allowed and consistent with the blockchain's current state. Generally,
// every transaction we define has a corresponding connect() and disconnect()
// function defined here that specifies what operations that transaction applies
// to the view and ultimately to the database. If you want to know how any
// particular transaction impacts the database, you've found the right file. A
// good place to start in this file is ConnectTransaction and DisconnectTransaction.
// ConnectBlock is also good.
type UtxoType uint8
const (
// UTXOs can come from different sources. We document all of those sources
// in the UTXOEntry using these types.
UtxoTypeOutput UtxoType = 0
UtxoTypeBlockReward UtxoType = 1
UtxoTypeBitcoinBurn UtxoType = 2
// TODO(DELETEME): Remove the StakeReward txn type
UtxoTypeStakeReward UtxoType = 3
UtxoTypeCreatorCoinSale UtxoType = 4
UtxoTypeCreatorCoinFounderReward UtxoType = 5
// NEXT_TAG = 6
)
func (mm UtxoType) String() string {
if mm == UtxoTypeOutput {
return "UtxoTypeOutput"
} else if mm == UtxoTypeBlockReward {
return "UtxoTypeBlockReward"
} else if mm == UtxoTypeBitcoinBurn {
return "UtxoTypeBitcoinBurn"
} else if mm == UtxoTypeStakeReward {
return "UtxoTypeStakeReward"
}
return "UtxoTypeUnknown"
}
// UtxoEntry identifies the data associated with a UTXO.
type UtxoEntry struct {
AmountNanos uint64
PublicKey []byte
BlockHeight uint32
UtxoType UtxoType
// The fields below aren't serialized or hashed. They are only kept
// around for in-memory bookkeeping purposes.
// Whether or not the UTXO is spent. This is not used by the database,
// (in fact it's not even stored in the db) it's used
// only by the in-memory data structure. The database is simple: A UTXO
// is unspent if and only if it exists in the db. However, for the view,
// a UTXO is unspent if it (exists in memory and is unspent) OR (it does not
// exist in memory at all but does exist in the database).
//
// Note that we are relying on the code that serializes the entry to the
// db to ignore private fields, which is why this variable is lowerCamelCase
// rather than UpperCamelCase. We are also relying on it defaulting to
// false when newly-read from the database.
isSpent bool
// A back-reference to the utxo key associated with this entry.
UtxoKey *UtxoKey
}
func (utxoEntry *UtxoEntry) String() string {
return fmt.Sprintf("< PublicKey: %v, BlockHeight: %d, AmountNanos: %d, UtxoType: %v, "+
"isSpent: %v, utxoKey: %v>", PkToStringMainnet(utxoEntry.PublicKey),
utxoEntry.BlockHeight, utxoEntry.AmountNanos,
utxoEntry.UtxoType, utxoEntry.isSpent, utxoEntry.UtxoKey)
}
// Have to define these because Go doesn't let you use raw byte slices as map keys.
// This needs to be in-sync with BitCloutMainnetParams.MaxUsernameLengthBytes
type UsernameMapKey [MaxUsernameLengthBytes]byte
func MakeUsernameMapKey(nonLowercaseUsername []byte) UsernameMapKey {
// Always lowercase the username when we use it as a key in our map. This allows
// us to check uniqueness in a case-insensitive way.
lowercaseUsername := []byte(strings.ToLower(string(nonLowercaseUsername)))
usernameMapKey := UsernameMapKey{}
copy(usernameMapKey[:], lowercaseUsername)
return usernameMapKey
}
type PkMapKey [btcec.PubKeyBytesLenCompressed]byte
func (mm PkMapKey) String() string {
return PkToStringBoth(mm[:])
}
func MakePkMapKey(pk []byte) PkMapKey {
pkMapKey := PkMapKey{}
copy(pkMapKey[:], pk)
return pkMapKey
}
func MakeMessageKey(pk []byte, tstampNanos uint64) MessageKey {
return MessageKey{
PublicKey: MakePkMapKey(pk),
TstampNanos: tstampNanos,
}
}
type MessageKey struct {
PublicKey PkMapKey
BlockHeight uint32
TstampNanos uint64
}
func (mm *MessageKey) String() string {
return fmt.Sprintf("<Public Key: %s, TstampNanos: %d>",
PkToStringMainnet(mm.PublicKey[:]), mm.TstampNanos)
}
// StringKey is useful for creating maps that need to be serialized to JSON.
func (mm *MessageKey) StringKey(params *BitCloutParams) string {
return PkToString(mm.PublicKey[:], params) + "_" + fmt.Sprint(mm.TstampNanos)
}
// MessageEntry stores the essential content of a message transaction.
type MessageEntry struct {
SenderPublicKey []byte
RecipientPublicKey []byte
EncryptedText []byte
// TODO: Right now a sender can fake the timestamp and make it appear to
// the recipient that she sent messages much earlier than she actually did.
// This isn't a big deal because there is generally not much to gain from
// faking a timestamp, and it's still impossible for a user to impersonate
// another user, which is the important thing. Moreover, it is easy to fix
// the timestamp spoofing issue: You just need to make it so that the nodes
// index messages based on block height in addition to on the tstamp. The
// reason I didn't do it yet is because it adds some complexity around
// detecting duplicates, particularly if a transaction is allowed to have
// zero inputs/outputs, which is advantageous for various reasons.
TstampNanos uint64
isDeleted bool
}
// Entry for a public key forbidden from signing blocks.
type ForbiddenPubKeyEntry struct {
PubKey []byte
// Whether or not this entry is deleted in the view.
isDeleted bool
}
func MakeLikeKey(userPk []byte, LikedPostHash BlockHash) LikeKey {
return LikeKey{
LikerPubKey: MakePkMapKey(userPk),
LikedPostHash: LikedPostHash,
}
}
type LikeKey struct {
LikerPubKey PkMapKey
LikedPostHash BlockHash
}
// LikeEntry stores the content of a like transaction.
type LikeEntry struct {
LikerPubKey []byte
LikedPostHash *BlockHash
// Whether or not this entry is deleted in the view.
isDeleted bool
}
func MakeFollowKey(followerPKID *PKID, followedPKID *PKID) FollowKey {
return FollowKey{
FollowerPKID: *followerPKID,
FollowedPKID: *followedPKID,
}
}
type FollowKey struct {
FollowerPKID PKID
FollowedPKID PKID
}
// FollowEntry stores the content of a follow transaction.
type FollowEntry struct {
// Note: It's a little redundant to have these in the entry because they're
// already used as the key in the DB but it doesn't hurt for now.
FollowerPKID *PKID
FollowedPKID *PKID
// Whether or not this entry is deleted in the view.
isDeleted bool
}
type DiamondKey struct {
SenderPKID PKID
ReceiverPKID PKID
DiamondPostHash BlockHash
}
func MakeDiamondKey(senderPKID *PKID, receiverPKID *PKID, diamondPostHash *BlockHash) DiamondKey {
return DiamondKey{
SenderPKID: *senderPKID,
ReceiverPKID: *receiverPKID,
DiamondPostHash: *diamondPostHash,
}
}
func (mm *DiamondKey) String() string {
return fmt.Sprintf("<SenderPKID: %v, ReceiverPKID: %v, DiamondPostHash: %v>",
PkToStringMainnet(mm.SenderPKID[:]), PkToStringMainnet(mm.ReceiverPKID[:]),
hex.EncodeToString(mm.DiamondPostHash[:]))
}
// DiamondEntry stores the number of diamonds given by a sender to a post.
type DiamondEntry struct {
SenderPKID *PKID
ReceiverPKID *PKID
DiamondPostHash *BlockHash
DiamondLevel int64
// Whether or not this entry is deleted in the view.
isDeleted bool
}
func MakeRecloutKey(userPk []byte, RecloutedPostHash BlockHash) RecloutKey {
return RecloutKey{
ReclouterPubKey: MakePkMapKey(userPk),
RecloutedPostHash: RecloutedPostHash,
}
}
type RecloutKey struct {
ReclouterPubKey PkMapKey
// Post Hash of post that was reclouted
RecloutedPostHash BlockHash
}
// RecloutEntry stores the content of a Reclout transaction.
type RecloutEntry struct {
ReclouterPubKey []byte
// BlockHash of the reclout
RecloutPostHash *BlockHash
// Post Hash of post that was reclouted
RecloutedPostHash *BlockHash
// Whether or not this entry is deleted in the view.
isDeleted bool
}
type GlobalParamsEntry struct {
// The new exchange rate to set.
USDCentsPerBitcoin uint64
// The new create profile fee
CreateProfileFeeNanos uint64
// The new minimum fee the network will accept
MinimumNetworkFeeNanosPerKB uint64
}
// The blockchain used to store the USD to BTC exchange rate in bav.USDCentsPerBitcoin, which was set by a
// UPDATE_BITCOIN_USD_EXCHANGE_RATE txn, but has since moved to the GlobalParamsEntry, which is set by a
// UPDATE_GLOBAL_PARAMS txn.
func (bav *UtxoView) GetCurrentUSDCentsPerBitcoin() uint64 {
usdCentsPerBitcoin := bav.USDCentsPerBitcoin
if bav.GlobalParamsEntry.USDCentsPerBitcoin != 0 {
usdCentsPerBitcoin = bav.GlobalParamsEntry.USDCentsPerBitcoin
}
return usdCentsPerBitcoin
}
// This struct holds info on a readers interactions (e.g. likes) with a post.
// It is added to a post entry response in the frontend server api.
type PostEntryReaderState struct {
// This is true if the reader has liked the associated post.
LikedByReader bool
// The number of diamonds that the reader has given this post.
DiamondLevelBestowed int64
// This is true if the reader has reclouted the associated post.
RecloutedByReader bool
// This is the post hash hex of the reclout
RecloutPostHashHex string
}
func (bav *UtxoView) GetPostEntryReaderState(
readerPK []byte, postEntry *PostEntry) *PostEntryReaderState {
postEntryReaderState := &PostEntryReaderState{}
// Get like state.
likeKey := MakeLikeKey(readerPK, *postEntry.PostHash)
likeEntry := bav._getLikeEntryForLikeKey(&likeKey)
if likeEntry != nil && !likeEntry.isDeleted {
postEntryReaderState.LikedByReader = true
}
// Get reclout state.
recloutKey := MakeRecloutKey(readerPK, *postEntry.PostHash)
recloutEntry := bav._getRecloutEntryForRecloutKey(&recloutKey)
if recloutEntry != nil {
recloutPostEntry := bav.GetPostEntryForPostHash(recloutEntry.RecloutPostHash)
if recloutPostEntry == nil {
glog.Errorf("Could not find reclout post entry from post hash: %v", recloutEntry.RecloutedPostHash)
return nil
}
// If the user's reclout of this post is hidden, we set RecloutedByReader to false.
postEntryReaderState.RecloutedByReader = !recloutPostEntry.IsHidden
// We include the PostHashHex of this user's post that reclouts the current post to
// handle undo-ing (AKA hiding) a reclout.
postEntryReaderState.RecloutPostHashHex = hex.EncodeToString(recloutEntry.RecloutPostHash[:])
}
// Get diamond state.
senderPKID := bav.GetPKIDForPublicKey(readerPK)
receiverPKID := bav.GetPKIDForPublicKey(postEntry.PosterPublicKey)
if senderPKID == nil || receiverPKID == nil {
glog.Debugf(
"GetPostEntryReaderState: Could not find PKID for reader PK: %s or poster PK: %s",
PkToString(readerPK, bav.Params), PkToString(postEntry.PosterPublicKey, bav.Params))
} else {
diamondKey := MakeDiamondKey(senderPKID.PKID, receiverPKID.PKID, postEntry.PostHash)
diamondEntry := bav.GetDiamondEntryForDiamondKey(&diamondKey)
if diamondEntry != nil {
postEntryReaderState.DiamondLevelBestowed = diamondEntry.DiamondLevel
}
}
return postEntryReaderState
}
type SingleStake struct {
// Just save the data from the initial stake for posterity.
InitialStakeNanos uint64
BlockHeight uint64
InitialStakeMultipleBasisPoints uint64
// The amount distributed to previous users can be computed by
// adding the creator percentage and the burn fee and then
// subtracting that total percentage off of the InitialStakeNanos.
// Example:
// - InitialStakeNanos = 100
// - CreatorPercentage = 15%
// - BurnFeePercentage = 10%
// - Amount to pay to previous users = 100 - 15 - 10 = 75
InitialCreatorPercentageBasisPoints uint64
// These fields are what we actually use to pay out the user who staked.
//
// The initial RemainingAmountOwedNanos is computed by simply multiplying
// the InitialStakeNanos by the InitialStakeMultipleBasisPoints.
RemainingStakeOwedNanos uint64
PublicKey []byte
}
type StakeEntry struct {
StakeList []*SingleStake
// Computed for profiles to cache how much has been staked to
// their posts in total. When a post is staked to, this value
// gets incremented on the profile. It gets reverted on the
// profile when the post stake is reverted.
TotalPostStake uint64
}
func NewStakeEntry() *StakeEntry {
return &StakeEntry{
StakeList: []*SingleStake{},
}
}
func StakeEntryCopy(stakeEntry *StakeEntry) *StakeEntry {
newStakeEntry := NewStakeEntry()
for _, singleStake := range stakeEntry.StakeList {
singleStakeCopy := *singleStake
newStakeEntry.StakeList = append(newStakeEntry.StakeList, &singleStakeCopy)
}
newStakeEntry.TotalPostStake = stakeEntry.TotalPostStake
return newStakeEntry
}
type StakeEntryStats struct {
TotalStakeNanos uint64
TotalStakeOwedNanos uint64
TotalCreatorEarningsNanos uint64
TotalFeesBurnedNanos uint64
TotalPostStakeNanos uint64
}
func GetStakeEntryStats(stakeEntry *StakeEntry, params *BitCloutParams) *StakeEntryStats {
stakeEntryStats := &StakeEntryStats{}
for _, singleStake := range stakeEntry.StakeList {
stakeEntryStats.TotalStakeNanos += singleStake.InitialStakeNanos
stakeEntryStats.TotalStakeOwedNanos += singleStake.RemainingStakeOwedNanos
// Be careful when computing these values in order to avoid overflow.
stakeEntryStats.TotalCreatorEarningsNanos += big.NewInt(0).Div(
big.NewInt(0).Mul(
big.NewInt(int64(singleStake.InitialStakeNanos)),
big.NewInt(int64(singleStake.InitialCreatorPercentageBasisPoints))),
big.NewInt(100*100)).Uint64()
stakeEntryStats.TotalFeesBurnedNanos += big.NewInt(0).Div(
big.NewInt(0).Mul(
big.NewInt(int64(singleStake.InitialStakeNanos)),
big.NewInt(int64(params.StakeFeeBasisPoints))),
big.NewInt(100*100)).Uint64()
}
stakeEntryStats.TotalPostStakeNanos = stakeEntry.TotalPostStake
return stakeEntryStats
}
type StakeIDType uint8
const (
StakeIDTypePost StakeIDType = 0
StakeIDTypeProfile StakeIDType = 1
)
func (ss StakeIDType) String() string {
if ss == StakeIDTypePost {
return "post"
} else if ss == StakeIDTypeProfile {
return "profile"
} else {
return "unknown"
}
}
type PostEntry struct {
// The hash of this post entry. Used as the ID for the entry.
PostHash *BlockHash
// The public key of the user who made the post.
PosterPublicKey []byte
// The parent post. This is used for comments.
ParentStakeID []byte
// The body of this post.
Body []byte
// The PostHash of the post this post reclouts
RecloutedPostHash *BlockHash
// Indicator if this PostEntry is a quoted reclout or not
IsQuotedReclout bool
// The amount the creator of the post gets when someone stakes
// to the post.
CreatorBasisPoints uint64
// The multiple of the payout when a user stakes to a post.
// 2x multiple = 200% = 20,000bps
StakeMultipleBasisPoints uint64
// The block height when the post was confirmed.
ConfirmationBlockHeight uint32
// A timestamp used for ordering messages when displaying them to
// users. The timestamp must be unique. Note that we use a nanosecond
// timestamp because it makes it easier to deal with the uniqueness
// constraint technically (e.g. If one second spacing is required
// as would be the case with a standard Unix timestamp then any code
// that generates these transactions will need to potentially wait
// or else risk a timestamp collision. This complexity is avoided
// by just using a nanosecond timestamp). Note that the timestamp is
// an unsigned int as opposed to a signed int, which means times
// before the zero time are not represented which doesn't matter
// for our purposes. Restricting the timestamp in this way makes
// lexicographic sorting based on bytes easier in our database which
// is one of the reasons we do it.
TimestampNanos uint64
// Users can "delete" posts, but right now we just implement this as
// setting a flag on the post to hide it rather than actually deleting
// it. This simplifies the implementation and makes it easier to "undelete"
// posts in certain situations.
IsHidden bool
// Every post has a StakeEntry that keeps track of all the stakes that
// have been applied to this post.
StakeEntry *StakeEntry
// Counter of users that have liked this post.
LikeCount uint64
// Counter of users that have reclouted this post.
RecloutCount uint64
// Counter of diamonds that the post has received.
DiamondCount uint64
// The private fields below aren't serialized or hashed. They are only kept
// around for in-memory bookkeeping purposes.
// Used to sort posts by their stake. Generally not set.
stakeStats *StakeEntryStats
// Whether or not this entry is deleted in the view.
isDeleted bool
// How many comments this post has
CommentCount uint64
// Indicator if a post is pinned or not.
IsPinned bool
// ExtraData map to hold arbitrary attributes of a post. Holds non-consensus related information about a post.
PostExtraData map[string][]byte
}
func (pe *PostEntry) IsDeleted() bool {
return pe.isDeleted
}
// Return true if postEntry is a vanilla reclout. A vanilla reclout is a post that reclouts another post,
// but does not have a body.
func IsVanillaReclout(postEntry *PostEntry) bool {
if !postEntry.IsQuotedReclout && postEntry.RecloutedPostHash != nil {
return true
}
return false
}
type BalanceEntryMapKey struct {
HODLerPKID PKID
CreatorPKID PKID
}
func MakeCreatorCoinBalanceKey(hodlerPKID *PKID, creatorPKID *PKID) BalanceEntryMapKey {
return BalanceEntryMapKey{
HODLerPKID: *hodlerPKID,
CreatorPKID: *creatorPKID,
}
}
func (mm BalanceEntryMapKey) String() string {
return fmt.Sprintf("BalanceEntryMapKey: <HODLer Pub Key: %v, Creator Pub Key: %v>",
PkToStringBoth(mm.HODLerPKID[:]), PkToStringBoth(mm.CreatorPKID[:]))
}
// This struct is mainly used to track a user's balance of a particular
// creator coin. In the database, we store it as the value in a mapping
// that looks as follows:
// <HodlerPKID, CreatorPKID> -> HODLerEntry
type BalanceEntry struct {
// The PKID of the HODLer. This should never change after it's set initially.
HODLerPKID *PKID
// The PKID of the creator. This should never change after it's set initially.
CreatorPKID *PKID
// How much this HODLer owns of a particular creator coin.
BalanceNanos uint64
// Has the hodler purchased any amount of this user's coin
HasPurchased bool
// Whether or not this entry is deleted in the view.
isDeleted bool
}
// This struct contains all the information required to support coin
// buy/sell transactions on profiles.
type CoinEntry struct {
// The amount the owner of this profile receives when there is a
// "net new" purchase of their coin.
CreatorBasisPoints uint64
// The amount of BitClout backing the coin. Whenever a user buys a coin
// from the protocol this amount increases, and whenever a user sells a
// coin to the protocol this decreases.
BitCloutLockedNanos uint64
// The number of public keys who have holdings in this creator coin.
// Due to floating point truncation, it can be difficult to simultaneously
// reset CoinsInCirculationNanos and BitCloutLockedNanos to zero after
// everyone has sold all their creator coins. Initially NumberOfHolders
// is set to zero. Once it returns to zero after a series of buys & sells
// we reset the BitCloutLockedNanos and CoinsInCirculationNanos to prevent
// abnormal bancor curve behavior.
NumberOfHolders uint64
// The number of coins currently in circulation. Whenever a user buys a
// coin from the protocol this increases, and whenever a user sells a
// coin to the protocol this decreases.
CoinsInCirculationNanos uint64
// This field keeps track of the highest number of coins that has ever
// been in circulation. It is used to determine when a creator should
// receive a "founder reward." In particular, whenever the number of
// coins being minted would push the number of coins in circulation
// beyond the watermark, we allocate a percentage of the coins being
// minted to the creator as a "founder reward."
CoinWatermarkNanos uint64
}
type PKIDEntry struct {
PKID *PKID
// We add the public key only so we can reuse this struct to store the reverse
// mapping of pkid -> public key.
PublicKey []byte
isDeleted bool
}
type ProfileEntry struct {
// PublicKey is the key used by the user to sign for things and generally
// verify her identity.
PublicKey []byte
// Username is a unique human-readable identifier associated with a profile.
Username []byte
// Some text describing the profile.
Description []byte
// The profile pic string encoded as a link e.g.
// data:image/png;base64,<data in base64>
ProfilePic []byte
// Users can "delete" profiles, but right now we just implement this as
// setting a flag on the post to hide it rather than actually deleting
// it. This simplifies the implementation and makes it easier to "undelete"
// profiles in certain situations.
IsHidden bool
// CoinEntry tracks the information required to buy/sell coins on a user's
// profile. We "embed" it here for convenience so we can access the fields
// directly on the ProfileEntry object. Embedding also makes it so that we
// don't need to initialize it explicitly.
CoinEntry
// Whether or not this entry should be deleted when the view is flushed
// to the db. This is initially set to false, but can become true if for
// example we update a user entry and need to delete the data associated
// with the old entry.
isDeleted bool
// TODO(DELETEME): This field is deprecated. It was relevant back when
// we wanted to allow people to stake to profiles, which isn't something
// we want to support going forward.
//
// The multiple of the payout when a user stakes to this profile. If
// unset, a sane default is set when the first person stakes to this
// profile.
// 2x multiple = 200% = 20,000bps
StakeMultipleBasisPoints uint64
// TODO(DELETEME): This field is deprecated. It was relevant back when
// we wanted to allow people to stake to profiles, which isn't something
// we want to support going forward.
//
// Every provile has a StakeEntry that keeps track of all the stakes that
// have been applied to it.
StakeEntry *StakeEntry
// The private fields below aren't serialized or hashed. They are only kept
// around for in-memory bookkeeping purposes.
// TODO(DELETEME): This field is deprecated. It was relevant back when
// we wanted to allow people to stake to profiles, which isn't something
// we want to support going forward.
//
// Used to sort profiles by their stake. Generally not set.
stakeStats *StakeEntryStats
}
func (pe *ProfileEntry) IsDeleted() bool {
return pe.isDeleted
}
type UtxoView struct {
// Utxo data
NumUtxoEntries uint64
UtxoKeyToUtxoEntry map[UtxoKey]*UtxoEntry
// BitcoinExchange data
NanosPurchased uint64
USDCentsPerBitcoin uint64
GlobalParamsEntry *GlobalParamsEntry
BitcoinBurnTxIDs map[BlockHash]bool
// Forbidden block signature pubkeys
ForbiddenPubKeyToForbiddenPubKeyEntry map[PkMapKey]*ForbiddenPubKeyEntry
// Messages data
MessageKeyToMessageEntry map[MessageKey]*MessageEntry
// Follow data
FollowKeyToFollowEntry map[FollowKey]*FollowEntry
// Diamond data
DiamondKeyToDiamondEntry map[DiamondKey]*DiamondEntry
// Like data
LikeKeyToLikeEntry map[LikeKey]*LikeEntry
// Reclout data
RecloutKeyToRecloutEntry map[RecloutKey]*RecloutEntry
// Post data
PostHashToPostEntry map[BlockHash]*PostEntry
// Profile data
PublicKeyToPKIDEntry map[PkMapKey]*PKIDEntry
// The PKIDEntry is only used here to store the public key.
PKIDToPublicKey map[PKID]*PKIDEntry
ProfilePKIDToProfileEntry map[PKID]*ProfileEntry
ProfileUsernameToProfileEntry map[UsernameMapKey]*ProfileEntry
// Coin balance entries
HODLerPKIDCreatorPKIDToBalanceEntry map[BalanceEntryMapKey]*BalanceEntry
// The hash of the tip the view is currently referencing. Mainly used
// for error-checking when doing a bulk operation on the view.
TipHash *BlockHash
BitcoinManager *BitcoinManager
Handle *badger.DB
Params *BitCloutParams
}
type OperationType uint
const (
// Every operation has a type that we document here. This information is
// used when rolling back a txn to determine what kind of operations need
// to be performed. For example, rolling back a BitcoinExchange may require
// rolling back an AddUtxo operation.
OperationTypeAddUtxo OperationType = 0
OperationTypeSpendUtxo OperationType = 1
OperationTypeBitcoinExchange OperationType = 2
OperationTypePrivateMessage OperationType = 3
OperationTypeSubmitPost OperationType = 4
OperationTypeUpdateProfile OperationType = 5
OperationTypeDeletePost OperationType = 7
OperationTypeUpdateBitcoinUSDExchangeRate OperationType = 8
OperationTypeFollow OperationType = 9
OperationTypeLike OperationType = 10
OperationTypeCreatorCoin OperationType = 11
OperationTypeSwapIdentity OperationType = 12
OperationTypeUpdateGlobalParams OperationType = 13
OperationTypeCreatorCoinTransfer OperationType = 14
// NEXT_TAG = 15
)
func (op OperationType) String() string {
switch op {
case OperationTypeAddUtxo:
{
return "OperationTypeAddUtxo"
}
case OperationTypeSpendUtxo:
{
return "OperationTypeSpendUtxo"
}
case OperationTypeBitcoinExchange:
{
return "OperationTypeBitcoinExchange"
}
case OperationTypePrivateMessage:
{
return "OperationTypePrivateMessage"
}
case OperationTypeSubmitPost:
{
return "OperationTypeSubmitPost"
}
case OperationTypeUpdateProfile:
{
return "OperationTypeUpdateProfile"
}
case OperationTypeDeletePost:
{
return "OperationTypeDeletePost"
}
case OperationTypeUpdateBitcoinUSDExchangeRate:
{
return "OperationTypeUpdateBitcoinUSDExchangeRate"
}
case OperationTypeFollow:
{
return "OperationTypeFollow"
}
case OperationTypeCreatorCoin:
{
return "OperationTypeCreatorCoin"
}
}
return "OperationTypeUNKNOWN"
}
type UtxoOperation struct {
Type OperationType
// Only set for OperationTypeSpendUtxo
//
// When we SPEND a UTXO entry we delete it from the utxo set but we still
// store its info in case we want to reverse
// it in the future. This information is not needed for ADD since
// reversing an ADD just means deleting an entry from the end of our list.
//
// SPEND works by swapping the UTXO we want to spend with the UTXO at
// the end of the list and then deleting from the end of the list. Obviously
// this is more efficient than deleting the element in-place and then shifting
// over everything after it. In order to be able to undo this operation,
// however, we need to store the original index of the item we are
// spending/deleting. Reversing the operation then amounts to adding a utxo entry
// at the end of the list and swapping with this index. Given this, the entry
// we store here has its position set to the position it was at right before the
// SPEND operation was performed.
Entry *UtxoEntry
// Only set for OperationTypeSpendUtxo
//
// Store the UtxoKey as well. This isn't necessary but it helps
// with error-checking during a roll-back so we just keep it.
//
// TODO: We can probably delete this at some point and save some space. UTXOs
// are probably our biggest disk hog so getting rid of this should materially
// improve disk usage.
Key *UtxoKey
// Used to revert BitcoinExchange transaction.
PrevNanosPurchased uint64
// Used to revert UpdateBitcoinUSDExchangeRate transaction.
PrevUSDCentsPerBitcoin uint64
// Save the previous post entry when making an update to a post.
PrevPostEntry *PostEntry
PrevParentPostEntry *PostEntry
PrevGrandparentPostEntry *PostEntry
PrevRecloutedPostEntry *PostEntry
// Save the previous profile entry when making an update.
PrevProfileEntry *ProfileEntry
// Save the previous like entry and like count when making an update.
PrevLikeEntry *LikeEntry
PrevLikeCount uint64
// For disconnecting diamonds.
PrevDiamondEntry *DiamondEntry
// Save the previous reclout entry and reclout count when making an update.
PrevRecloutEntry *RecloutEntry
PrevRecloutCount uint64
// Save the state of a creator coin prior to updating it due to a
// buy/sell/add transaction.
PrevCoinEntry *CoinEntry
// Save the creator coin balance of both the transactor and the creator.
// We modify the transactor's balances when they buys/sell a creator coin
// and we modify the creator's balance when we pay them a founder reward.
PrevTransactorBalanceEntry *BalanceEntry
PrevCreatorBalanceEntry *BalanceEntry
// We use this to revert founder's reward UTXOs created by creator coin buys.
FounderRewardUtxoKey *UtxoKey
// Save balance entries for the sender and receiver when creator coins are transferred.
PrevSenderBalanceEntry *BalanceEntry
PrevReceiverBalanceEntry *BalanceEntry
// Save the global params when making an update.
PrevGlobalParamsEntry *GlobalParamsEntry
PrevForbiddenPubKeyEntry *ForbiddenPubKeyEntry
}
// Assumes the db Handle is already set on the view, but otherwise the
// initialization is full.
func (bav *UtxoView) _ResetViewMappingsAfterFlush() {
// Utxo data
bav.UtxoKeyToUtxoEntry = make(map[UtxoKey]*UtxoEntry)
bav.NumUtxoEntries = GetUtxoNumEntries(bav.Handle)
// BitcoinExchange data
bav.NanosPurchased = DbGetNanosPurchased(bav.Handle)
bav.USDCentsPerBitcoin = DbGetUSDCentsPerBitcoinExchangeRate(bav.Handle)
bav.GlobalParamsEntry = DbGetGlobalParamsEntry(bav.Handle)
bav.BitcoinBurnTxIDs = make(map[BlockHash]bool)
// Forbidden block signature pub key info.
bav.ForbiddenPubKeyToForbiddenPubKeyEntry = make(map[PkMapKey]*ForbiddenPubKeyEntry)
// Post and profile data
bav.PostHashToPostEntry = make(map[BlockHash]*PostEntry)
bav.PublicKeyToPKIDEntry = make(map[PkMapKey]*PKIDEntry)
bav.PKIDToPublicKey = make(map[PKID]*PKIDEntry)
bav.ProfilePKIDToProfileEntry = make(map[PKID]*ProfileEntry)
bav.ProfileUsernameToProfileEntry = make(map[UsernameMapKey]*ProfileEntry)
// Messages data
bav.MessageKeyToMessageEntry = make(map[MessageKey]*MessageEntry)
// Follow data
bav.FollowKeyToFollowEntry = make(map[FollowKey]*FollowEntry)
// Diamond data
bav.DiamondKeyToDiamondEntry = make(map[DiamondKey]*DiamondEntry)
// Like data
bav.LikeKeyToLikeEntry = make(map[LikeKey]*LikeEntry)
// Reclout data
bav.RecloutKeyToRecloutEntry = make(map[RecloutKey]*RecloutEntry)
// Coin balance entries
bav.HODLerPKIDCreatorPKIDToBalanceEntry = make(map[BalanceEntryMapKey]*BalanceEntry)
}
func (bav *UtxoView) CopyUtxoView() (*UtxoView, error) {
newView, err := NewUtxoView(bav.Handle, bav.Params, bav.BitcoinManager)
if err != nil {
return nil, err
}
// Copy the UtxoEntry data
// Note that using _setUtxoMappings is dangerous because the Pos within
// the UtxoEntrys is off.
newView.UtxoKeyToUtxoEntry = make(map[UtxoKey]*UtxoEntry, len(bav.UtxoKeyToUtxoEntry))
for utxoKey, utxoEntry := range bav.UtxoKeyToUtxoEntry {
newUtxoEntry := *utxoEntry
newView.UtxoKeyToUtxoEntry[utxoKey] = &newUtxoEntry
}
newView.NumUtxoEntries = bav.NumUtxoEntries
// Copy the BitcoinExchange data
newView.BitcoinBurnTxIDs = make(map[BlockHash]bool, len(bav.BitcoinBurnTxIDs))
for bh := range bav.BitcoinBurnTxIDs {
newView.BitcoinBurnTxIDs[bh] = true
}
newView.NanosPurchased = bav.NanosPurchased
newView.USDCentsPerBitcoin = bav.USDCentsPerBitcoin
// Copy the GlobalParamsEntry
newGlobalParamsEntry := *bav.GlobalParamsEntry
newView.GlobalParamsEntry = &newGlobalParamsEntry
// Copy the post data
newView.PostHashToPostEntry = make(map[BlockHash]*PostEntry, len(bav.PostHashToPostEntry))
for postHash, postEntry := range bav.PostHashToPostEntry {
newPostEntry := *postEntry
newView.PostHashToPostEntry[postHash] = &newPostEntry
}
// Copy the PKID data
newView.PublicKeyToPKIDEntry = make(map[PkMapKey]*PKIDEntry, len(bav.PublicKeyToPKIDEntry))
for pkMapKey, pkid := range bav.PublicKeyToPKIDEntry {
newPKID := *pkid
newView.PublicKeyToPKIDEntry[pkMapKey] = &newPKID
}
newView.PKIDToPublicKey = make(map[PKID]*PKIDEntry, len(bav.PKIDToPublicKey))
for pkid, pkidEntry := range bav.PKIDToPublicKey {
newPKIDEntry := *pkidEntry
newView.PKIDToPublicKey[pkid] = &newPKIDEntry
}
// Copy the profile data
newView.ProfilePKIDToProfileEntry = make(map[PKID]*ProfileEntry, len(bav.ProfilePKIDToProfileEntry))
for profilePKID, profileEntry := range bav.ProfilePKIDToProfileEntry {
newProfileEntry := *profileEntry
newView.ProfilePKIDToProfileEntry[profilePKID] = &newProfileEntry
}
newView.ProfileUsernameToProfileEntry = make(map[UsernameMapKey]*ProfileEntry, len(bav.ProfileUsernameToProfileEntry))
for profilePKID, profileEntry := range bav.ProfileUsernameToProfileEntry {
newProfileEntry := *profileEntry
newView.ProfileUsernameToProfileEntry[profilePKID] = &newProfileEntry
}