-
Notifications
You must be signed in to change notification settings - Fork 115
/
utxo_dag.go
1306 lines (1088 loc) · 51.8 KB
/
utxo_dag.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 ledgerstate
import (
"container/list"
"fmt"
"strconv"
"sync"
"github.com/cockroachdb/errors"
"github.com/iotaledger/hive.go/byteutils"
"github.com/iotaledger/hive.go/cerrors"
"github.com/iotaledger/hive.go/datastructure/set"
"github.com/iotaledger/hive.go/events"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/hive.go/marshalutil"
"github.com/iotaledger/hive.go/objectstorage"
"github.com/iotaledger/hive.go/stringify"
"github.com/iotaledger/hive.go/types"
"github.com/iotaledger/hive.go/typeutils"
"github.com/iotaledger/goshimmer/packages/consensus/gof"
"github.com/iotaledger/goshimmer/packages/database"
)
// region UTXODAG //////////////////////////////////////////////////////////////////////////////////////////////////////
// IUTXODAG is the interface for UTXODAG which is the core of the ledger state
// that is formed by Transactions consuming Inputs and creating Outputs. It represents all the methods
// that helps to keep track of the balances and the different perceptions of potential conflicts.
type IUTXODAG interface {
// Events returns all events of the UTXODAG
Events() *UTXODAGEvents
// Shutdown shuts down the UTXODAG and persists its state.
Shutdown()
// CheckTransaction contains fast checks that have to be performed before booking a Transaction.
CheckTransaction(transaction *Transaction) (err error)
// BookTransaction books a Transaction into the ledger state.
BookTransaction(transaction *Transaction) (targetBranch BranchID, err error)
// CachedTransaction retrieves the Transaction with the given TransactionID from the object storage.
CachedTransaction(transactionID TransactionID) (cachedTransaction *CachedTransaction)
// Transaction returns a specific transaction, consumed.
Transaction(transactionID TransactionID) (transaction *Transaction)
// Transactions returns all the transactions, consumed.
Transactions() (transactions map[TransactionID]*Transaction)
// CachedTransactionMetadata retrieves the TransactionMetadata with the given TransactionID from the object storage.
CachedTransactionMetadata(transactionID TransactionID) (cachedTransactionMetadata *CachedTransactionMetadata)
// CachedOutput retrieves the Output with the given OutputID from the object storage.
CachedOutput(outputID OutputID) (cachedOutput *CachedOutput)
// CachedOutputMetadata retrieves the OutputMetadata with the given OutputID from the object storage.
CachedOutputMetadata(outputID OutputID) (cachedOutput *CachedOutputMetadata)
// CachedConsumers retrieves the Consumers of the given OutputID from the object storage.
CachedConsumers(outputID OutputID) (cachedConsumers CachedConsumers)
// LoadSnapshot creates a set of outputs in the UTXO-DAG, that are forming the genesis for future transactions.
LoadSnapshot(snapshot *Snapshot)
// CachedAddressOutputMapping retrieves the outputs for the given address.
CachedAddressOutputMapping(address Address) (cachedAddressOutputMappings CachedAddressOutputMappings)
// ConsumedOutputs returns the consumed (cached)Outputs of the given Transaction.
ConsumedOutputs(transaction *Transaction) (cachedInputs CachedOutputs)
// ManageStoreAddressOutputMapping mangages how to store the address-output mapping dependent on which type of output it is.
ManageStoreAddressOutputMapping(output Output)
// StoreAddressOutputMapping stores the address-output mapping.
StoreAddressOutputMapping(address Address, outputID OutputID)
// TransactionGradeOfFinality returns the GradeOfFinality of the Transaction with the given TransactionID.
TransactionGradeOfFinality(transactionID TransactionID) (gradeOfFinality gof.GradeOfFinality, err error)
// BranchGradeOfFinality returns the GradeOfFinality of the Branch with the given BranchID.
BranchGradeOfFinality(branchID BranchID) (gradeOfFinality gof.GradeOfFinality, err error)
// ConflictingTransactions returns the TransactionIDs that are conflicting with the given Transaction.
ConflictingTransactions(transaction *Transaction) (conflictingTransactions TransactionIDs)
}
// UTXODAG represents the DAG that is formed by Transactions consuming Inputs and creating Outputs. It forms the core of
// the ledger state and keeps track of the balances and the different perceptions of potential conflicts.
type UTXODAG struct {
events *UTXODAGEvents
transactionStorage *objectstorage.ObjectStorage
transactionMetadataStorage *objectstorage.ObjectStorage
outputStorage *objectstorage.ObjectStorage
outputMetadataStorage *objectstorage.ObjectStorage
consumerStorage *objectstorage.ObjectStorage
addressOutputMappingStorage *objectstorage.ObjectStorage
branchDAG *BranchDAG
shutdownOnce sync.Once
}
// NewUTXODAG create a new UTXODAG from the given details.
func NewUTXODAG(store kvstore.KVStore, cacheProvider *database.CacheTimeProvider, branchDAG *BranchDAG) (utxoDAG *UTXODAG) {
options := buildObjectStorageOptions(cacheProvider)
osFactory := objectstorage.NewFactory(store, database.PrefixLedgerState)
utxoDAG = &UTXODAG{
events: &UTXODAGEvents{
TransactionBranchIDUpdatedByFork: events.NewEvent(TransactionBranchIDUpdatedByForkEventHandler),
},
transactionStorage: osFactory.New(PrefixTransactionStorage, TransactionFromObjectStorage, options.transactionStorageOptions...),
transactionMetadataStorage: osFactory.New(PrefixTransactionMetadataStorage, TransactionMetadataFromObjectStorage, options.transactionMetadataStorageOptions...),
outputStorage: osFactory.New(PrefixOutputStorage, OutputFromObjectStorage, options.outputStorageOptions...),
outputMetadataStorage: osFactory.New(PrefixOutputMetadataStorage, OutputMetadataFromObjectStorage, options.outputMetadataStorageOptions...),
consumerStorage: osFactory.New(PrefixConsumerStorage, ConsumerFromObjectStorage, options.consumerStorageOptions...),
addressOutputMappingStorage: osFactory.New(PrefixAddressOutputMappingStorage, AddressOutputMappingFromObjectStorage, options.addressOutputMappingStorageOptions...),
branchDAG: branchDAG,
}
return
}
// Events returns all events of the UTXODAG.
func (u *UTXODAG) Events() *UTXODAGEvents {
return u.events
}
// Shutdown shuts down the UTXODAG and persists its state.
func (u *UTXODAG) Shutdown() {
u.shutdownOnce.Do(func() {
u.transactionStorage.Shutdown()
u.transactionMetadataStorage.Shutdown()
u.outputStorage.Shutdown()
u.outputMetadataStorage.Shutdown()
u.consumerStorage.Shutdown()
u.addressOutputMappingStorage.Shutdown()
})
}
// CheckTransaction contains fast checks that have to be performed before booking a Transaction.
func (u *UTXODAG) CheckTransaction(transaction *Transaction) (err error) {
cachedConsumedOutputs := u.ConsumedOutputs(transaction)
defer cachedConsumedOutputs.Release()
consumedOutputs := cachedConsumedOutputs.Unwrap()
// perform cheap checks
if !u.allOutputsExist(consumedOutputs) {
return errors.Errorf("not all consumedOutputs of transaction are solid: %w", ErrTransactionNotSolid)
}
if !TransactionBalancesValid(consumedOutputs, transaction.Essence().Outputs()) {
return errors.Errorf("sum of consumed and spent balances is not 0: %w", ErrTransactionInvalid)
}
if !UnlockBlocksValid(consumedOutputs, transaction) {
return errors.Errorf("spending of referenced consumedOutputs is not authorized: %w", ErrTransactionInvalid)
}
if !AliasInitialStateValid(consumedOutputs, transaction) {
return errors.Errorf("initial state of created alias output is invalid: %w", ErrTransactionInvalid)
}
return nil
}
// BookTransaction books a Transaction into the ledger state.
func (u *UTXODAG) BookTransaction(transaction *Transaction) (targetBranch BranchID, err error) {
cachedConsumedOutputs := u.ConsumedOutputs(transaction)
defer cachedConsumedOutputs.Release()
consumedOutputs := cachedConsumedOutputs.Unwrap()
// store TransactionMetadata
transactionMetadata := NewTransactionMetadata(transaction.ID())
transactionMetadata.SetSolid(true)
newTransaction := false
cachedTransactionMetadata := &CachedTransactionMetadata{CachedObject: u.transactionMetadataStorage.ComputeIfAbsent(transaction.ID().Bytes(), func(key []byte) objectstorage.StorableObject {
newTransaction = true
transactionMetadata.Persist()
transactionMetadata.SetModified()
return transactionMetadata
})}
if !newTransaction {
if !cachedTransactionMetadata.Consume(func(transactionMetadata *TransactionMetadata) {
targetBranch = transactionMetadata.BranchID()
}) {
err = errors.Errorf("failed to load TransactionMetadata with %s: %w", transaction.ID(), cerrors.ErrFatal)
}
return
}
defer cachedTransactionMetadata.Release()
// store Transaction
u.transactionStorage.Store(transaction).Release()
// retrieve the metadata of the Inputs
cachedInputsMetadata := u.transactionInputsMetadata(transaction)
defer cachedInputsMetadata.Release()
inputsMetadata := cachedInputsMetadata.Unwrap()
// check if Transaction is attaching to something invalid
if u.inputsInInvalidBranch(inputsMetadata) {
u.bookInvalidTransaction(transaction, transactionMetadata, inputsMetadata)
targetBranch = InvalidBranchID
return
}
// mark transaction as "permanently rejected"
if !u.consumedOutputsPastConeValid(consumedOutputs, inputsMetadata) {
u.bookInvalidTransaction(transaction, transactionMetadata, inputsMetadata)
targetBranch = InvalidBranchID
return
}
// determine the booking details before we book
branchesOfInputsConflicting, normalizedBranchIDs, conflictingInputs, err := u.determineBookingDetails(inputsMetadata)
if err != nil {
err = errors.Errorf("failed to determine book details of Transaction with %s: %w", transaction.ID(), err)
return
}
// are branches of inputs conflicting
if branchesOfInputsConflicting {
u.bookInvalidTransaction(transaction, transactionMetadata, inputsMetadata)
targetBranch = InvalidBranchID
err = errors.Errorf("branches of inputs are conflicting: %w", err)
return
}
switch len(conflictingInputs) {
case 0:
targetBranch = u.bookNonConflictingTransaction(transaction, transactionMetadata, inputsMetadata, normalizedBranchIDs)
default:
targetBranch = u.bookConflictingTransaction(transaction, transactionMetadata, inputsMetadata, normalizedBranchIDs, conflictingInputs.ByID())
}
return
}
// ConflictingTransactions returns the TransactionIDs that are conflicting with the given Transaction.
func (u *UTXODAG) ConflictingTransactions(transaction *Transaction) (conflictingTransactions TransactionIDs) {
conflictingTransactions = make(TransactionIDs)
for _, input := range transaction.Essence().Inputs() {
u.CachedConsumers(input.(*UTXOInput).ReferencedOutputID()).Consume(func(consumer *Consumer) {
if consumer.TransactionID() == transaction.ID() {
return
}
conflictingTransactions[consumer.TransactionID()] = types.Void
})
}
return
}
// TransactionGradeOfFinality returns the GradeOfFinality of the Transaction with the given TransactionID.
func (u *UTXODAG) TransactionGradeOfFinality(transactionID TransactionID) (gradeOfFinality gof.GradeOfFinality, err error) {
if !u.CachedTransactionMetadata(transactionID).Consume(func(transactionMetadata *TransactionMetadata) {
gradeOfFinality = transactionMetadata.GradeOfFinality()
}) {
return gof.None, errors.Errorf("failed to load TransactionMetadata with %s: %w", transactionID, cerrors.ErrFatal)
}
return
}
// BranchGradeOfFinality returns the GradeOfFinality of the Branch with the given BranchID.
func (u *UTXODAG) BranchGradeOfFinality(branchID BranchID) (gradeOfFinality gof.GradeOfFinality, err error) {
if branchID == MasterBranchID {
return gof.High, nil
}
normalizedBranches, err := u.branchDAG.normalizeBranches(NewBranchIDs(branchID))
if err != nil {
return gof.None, errors.Errorf("failed to normalize %s: %w", branchID, err)
}
gradeOfFinality = gof.High
for conflictBranchID := range normalizedBranches {
conflictBranchGoF, gofErr := u.TransactionGradeOfFinality(conflictBranchID.TransactionID())
if gofErr != nil {
return gof.None, errors.Errorf("failed to normalize %s: %w", branchID, err)
}
if conflictBranchGoF < gradeOfFinality {
gradeOfFinality = conflictBranchGoF
}
}
return gradeOfFinality, nil
}
// CachedTransaction retrieves the Transaction with the given TransactionID from the object storage.
func (u *UTXODAG) CachedTransaction(transactionID TransactionID) (cachedTransaction *CachedTransaction) {
return &CachedTransaction{CachedObject: u.transactionStorage.Load(transactionID.Bytes())}
}
// Transaction returns a specific transaction, consumed.
func (u *UTXODAG) Transaction(transactionID TransactionID) (transaction *Transaction) {
u.CachedTransaction(transactionID).Consume(func(tx *Transaction) {
transaction = tx
})
return transaction
}
// Transactions returns all the transactions, consumed.
func (u *UTXODAG) Transactions() (transactions map[TransactionID]*Transaction) {
transactions = make(map[TransactionID]*Transaction)
u.transactionStorage.ForEach(func(key []byte, cachedObject objectstorage.CachedObject) bool {
(&CachedTransaction{CachedObject: cachedObject}).Consume(func(transaction *Transaction) {
transactions[transaction.ID()] = transaction
})
return true
})
return
}
// CachedTransactionMetadata retrieves the TransactionMetadata with the given TransactionID from the object storage.
func (u *UTXODAG) CachedTransactionMetadata(transactionID TransactionID) (cachedTransactionMetadata *CachedTransactionMetadata) {
return &CachedTransactionMetadata{CachedObject: u.transactionMetadataStorage.Load(transactionID.Bytes())}
}
// CachedOutput retrieves the Output with the given OutputID from the object storage.
func (u *UTXODAG) CachedOutput(outputID OutputID) (cachedOutput *CachedOutput) {
return &CachedOutput{CachedObject: u.outputStorage.Load(outputID.Bytes())}
}
// CachedOutputMetadata retrieves the OutputMetadata with the given OutputID from the object storage.
func (u *UTXODAG) CachedOutputMetadata(outputID OutputID) (cachedOutput *CachedOutputMetadata) {
return &CachedOutputMetadata{CachedObject: u.outputMetadataStorage.Load(outputID.Bytes())}
}
// CachedConsumers retrieves the Consumers of the given OutputID from the object storage.
func (u *UTXODAG) CachedConsumers(outputID OutputID) (cachedConsumers CachedConsumers) {
cachedConsumers = make(CachedConsumers, 0)
u.consumerStorage.ForEach(func(key []byte, cachedObject objectstorage.CachedObject) bool {
cachedConsumers = append(cachedConsumers, &CachedConsumer{CachedObject: cachedObject})
return true
}, objectstorage.WithIteratorPrefix(outputID.Bytes()))
return
}
// LoadSnapshot creates a set of outputs in the UTXO-DAG, that are forming the genesis for future transactions.
func (u *UTXODAG) LoadSnapshot(snapshot *Snapshot) {
for txID, record := range snapshot.Transactions {
transaction := NewTransaction(record.Essence, record.UnlockBlocks)
cached, storedTx := u.transactionStorage.StoreIfAbsent(transaction)
if storedTx {
cached.Release()
}
for i, output := range record.Essence.outputs {
if !record.UnspentOutputs[i] {
continue
}
cachedOutput, stored := u.outputStorage.StoreIfAbsent(output)
if stored {
cachedOutput.Release()
}
// store addressOutputMapping
u.ManageStoreAddressOutputMapping(output)
// store OutputMetadata
metadata := NewOutputMetadata(output.ID())
metadata.SetBranchID(MasterBranchID)
metadata.SetSolid(true)
metadata.SetGradeOfFinality(gof.High)
cachedMetadata, stored := u.outputMetadataStorage.StoreIfAbsent(metadata)
if stored {
cachedMetadata.Release()
}
}
// store TransactionMetadata
txMetadata := NewTransactionMetadata(txID)
txMetadata.SetSolid(true)
txMetadata.SetBranchID(MasterBranchID)
txMetadata.SetGradeOfFinality(gof.High)
(&CachedTransactionMetadata{CachedObject: u.transactionMetadataStorage.ComputeIfAbsent(txID.Bytes(), func(key []byte) objectstorage.StorableObject {
txMetadata.Persist()
txMetadata.SetModified()
return txMetadata
})}).Release()
}
}
// CachedAddressOutputMapping retrieves the outputs for the given address.
func (u *UTXODAG) CachedAddressOutputMapping(address Address) (cachedAddressOutputMappings CachedAddressOutputMappings) {
u.addressOutputMappingStorage.ForEach(func(key []byte, cachedObject objectstorage.CachedObject) bool {
cachedAddressOutputMappings = append(cachedAddressOutputMappings, &CachedAddressOutputMapping{cachedObject})
return true
}, objectstorage.WithIteratorPrefix(address.Bytes()))
return
}
// region booking functions ////////////////////////////////////////////////////////////////////////////////////////////
// bookInvalidTransaction is an internal utility function that books the given Transaction into the Branch identified by
// the InvalidBranchID.
func (u *UTXODAG) bookInvalidTransaction(transaction *Transaction, transactionMetadata *TransactionMetadata, inputsMetadata OutputsMetadata) {
transactionMetadata.SetBranchID(InvalidBranchID)
transactionMetadata.SetSolid(true)
transactionMetadata.SetGradeOfFinality(gof.High)
u.bookConsumers(inputsMetadata, transaction.ID(), types.False)
u.bookOutputs(transaction, InvalidBranchID)
}
// bookNonConflictingTransaction is an internal utility function that books the Transaction into the Branch that is
// determined by aggregating the Branches of the consumed Inputs.
func (u *UTXODAG) bookNonConflictingTransaction(transaction *Transaction, transactionMetadata *TransactionMetadata, inputsMetadata OutputsMetadata, normalizedBranchIDs BranchIDs) (targetBranch BranchID) {
cachedAggregatedBranch, _, err := u.branchDAG.aggregateNormalizedBranches(normalizedBranchIDs)
if err != nil {
panic(fmt.Errorf("failed to aggregate Branches when booking Transaction with %s: %w", transaction.ID(), err))
}
if !cachedAggregatedBranch.Consume(func(branch Branch) {
targetBranch = branch.ID()
transactionMetadata.SetBranchID(targetBranch)
transactionMetadata.SetSolid(true)
u.bookConsumers(inputsMetadata, transaction.ID(), types.True)
u.bookOutputs(transaction, targetBranch)
}) {
panic(fmt.Errorf("failed to load AggregatedBranch with %s", cachedAggregatedBranch.ID()))
}
return
}
// bookConflictingTransaction is an internal utility function that books a Transaction that uses Inputs that have
// already been spent by another Transaction. It create a new ConflictBranch for the new Transaction and "forks" the
// existing consumers of the conflicting Inputs.
func (u *UTXODAG) bookConflictingTransaction(transaction *Transaction, transactionMetadata *TransactionMetadata, inputsMetadata OutputsMetadata, normalizedBranchIDs BranchIDs, conflictingInputs OutputsMetadataByID) (targetBranch BranchID) {
// fork existing consumers
u.walkFutureCone(conflictingInputs.IDs(), func(transactionID TransactionID) (nextOutputsToVisit []OutputID) {
u.forkConsumer(transactionID, conflictingInputs)
return
}, types.True)
// create new ConflictBranch
targetBranch = NewBranchID(transaction.ID())
cachedConflictBranch, _, err := u.branchDAG.CreateConflictBranch(targetBranch, normalizedBranchIDs, conflictingInputs.ConflictIDs())
if err != nil {
panic(fmt.Errorf("failed to create ConflictBranch when booking Transaction with %s: %w", transaction.ID(), err))
}
// book Transaction into new ConflictBranch
if !cachedConflictBranch.Consume(func(branch Branch) {
transactionMetadata.SetBranchID(targetBranch)
transactionMetadata.SetSolid(true)
u.bookConsumers(inputsMetadata, transaction.ID(), types.True)
u.bookOutputs(transaction, targetBranch)
}) {
panic(fmt.Errorf("failed to load ConflictBranch with %s", cachedConflictBranch.ID()))
}
return
}
// forkConsumer is an internal utility function that creates a ConflictBranch for a Transaction that has not been
// conflicting first but now turned out to be conflicting because of a newly booked double spend.
func (u *UTXODAG) forkConsumer(transactionID TransactionID, conflictingInputs OutputsMetadataByID) {
if !u.CachedTransactionMetadata(transactionID).Consume(func(txMetadata *TransactionMetadata) {
conflictBranchID := NewBranchID(transactionID)
conflictBranchParents := NewBranchIDs(txMetadata.BranchID())
conflictIDs := conflictingInputs.Filter(u.consumedOutputIDsOfTransaction(transactionID)).ConflictIDs()
cachedConsumingConflictBranch, _, err := u.branchDAG.CreateConflictBranch(conflictBranchID, conflictBranchParents, conflictIDs)
if err != nil {
panic(fmt.Errorf("failed to create ConflictBranch when forking Transaction with %s: %w", transactionID, err))
}
cachedConsumingConflictBranch.Release()
// We don't need to propagate updates if the branch did already exist.
// Though CreateConflictBranch needs to be called so that conflict sets and conflict membership are properly updated.
if txMetadata.BranchID() == conflictBranchID {
return
}
txMetadata.SetBranchID(conflictBranchID)
u.Events().TransactionBranchIDUpdatedByFork.Trigger(&TransactionBranchIDUpdatedByForkEvent{
TransactionID: transactionID,
NewBranchID: conflictBranchID,
ForkedBranchID: conflictBranchID,
})
outputIds := u.createdOutputIDsOfTransaction(transactionID)
for _, outputID := range outputIds {
if !u.CachedOutputMetadata(outputID).Consume(func(outputMetadata *OutputMetadata) {
outputMetadata.SetBranchID(conflictBranchID)
}) {
panic("failed to load OutputMetadata")
}
}
u.walkFutureCone(outputIds, func(transactionID TransactionID) (updatedOutputs []OutputID) {
return u.propagateBranchUpdates(transactionID, conflictBranchID)
}, types.True)
}) {
panic(fmt.Errorf("failed to load TransactionMetadata of Transaction with %s", transactionID))
}
}
// propagateBranchUpdates is an internal utility function that propagates changes in the perception of the BranchDAG
// after introducing a new ConflictBranch.
func (u *UTXODAG) propagateBranchUpdates(transactionID TransactionID, conflictBranchID BranchID) (updatedOutputs []OutputID) {
if !u.CachedTransactionMetadata(transactionID).Consume(func(transactionMetadata *TransactionMetadata) {
// if the BranchID is the TransactionID we have a ConflictBranch
if transactionMetadata.BranchID() == NewBranchID(transactionID) {
if err := u.branchDAG.UpdateConflictBranchParents(transactionMetadata.BranchID(), u.consumedBranchIDs(transactionID)); err != nil {
panic(fmt.Errorf("failed to update ConflictBranch with %s: %w", transactionMetadata.BranchID(), err))
}
return
}
cachedAggregatedBranch, _, err := u.branchDAG.AggregateBranches(u.consumedBranchIDs(transactionID))
if err != nil {
panic(err)
}
defer cachedAggregatedBranch.Release()
updatedOutputs = u.updateBranchOfTransaction(transactionID, cachedAggregatedBranch.ID(), conflictBranchID)
}) {
panic(fmt.Errorf("failed to load TransactionMetadata of Transaction with %s", transactionID))
}
return
}
// updateBranchOfTransaction is an internal utility function that updates the Branch that a Transaction and its Outputs
// are booked into.
func (u *UTXODAG) updateBranchOfTransaction(transactionID TransactionID, newBranchID, conflictBranchID BranchID) (updatedOutputs []OutputID) {
if !u.CachedTransactionMetadata(transactionID).Consume(func(transactionMetadata *TransactionMetadata) {
if transactionMetadata.SetBranchID(newBranchID) {
updatedOutputs = u.createdOutputIDsOfTransaction(transactionID)
for _, outputID := range updatedOutputs {
if !u.CachedOutputMetadata(outputID).Consume(func(outputMetadata *OutputMetadata) {
outputMetadata.SetBranchID(newBranchID)
}) {
panic(fmt.Errorf("failed to load OutputMetadata with %s", outputID))
}
}
u.Events().TransactionBranchIDUpdatedByFork.Trigger(&TransactionBranchIDUpdatedByForkEvent{
TransactionID: transactionID,
NewBranchID: newBranchID,
ForkedBranchID: conflictBranchID,
})
}
}) {
panic(fmt.Errorf("failed to load TransactionMetadata with %s", transactionID))
}
return
}
// bookConsumers creates the reference between an Output and its spending Transaction. It increases the ConsumerCount if
// the Transaction is a valid spend.
func (u *UTXODAG) bookConsumers(inputsMetadata OutputsMetadata, transactionID TransactionID, valid types.TriBool) {
for _, inputMetadata := range inputsMetadata {
if valid == types.True {
inputMetadata.RegisterConsumer(transactionID)
}
newConsumer := NewConsumer(inputMetadata.ID(), transactionID, valid)
if !(&CachedConsumer{CachedObject: u.consumerStorage.ComputeIfAbsent(newConsumer.ObjectStorageKey(), func(key []byte) objectstorage.StorableObject {
newConsumer.Persist()
newConsumer.SetModified()
return newConsumer
})}).Consume(func(consumer *Consumer) {
consumer.SetValid(valid)
}) {
panic("failed to update valid flag of Consumer")
}
}
}
// bookOutputs creates the Outputs and their corresponding OutputsMetadata in the object storage.
func (u *UTXODAG) bookOutputs(transaction *Transaction, targetBranch BranchID) {
for _, output := range transaction.Essence().Outputs() {
// replace ColorMint color with unique color based on OutputID
updatedOutput := output.UpdateMintingColor()
// store Output
u.outputStorage.Store(updatedOutput).Release()
// store OutputMetadata
metadata := NewOutputMetadata(updatedOutput.ID())
metadata.SetBranchID(targetBranch)
metadata.SetSolid(true)
u.outputMetadataStorage.Store(metadata).Release()
}
}
// determineBookingDetails is an internal utility function that determines the information that are required to fully
// book a newly arrived Transaction into the UTXODAG using the metadata of its referenced Inputs.
func (u *UTXODAG) determineBookingDetails(inputsMetadata OutputsMetadata) (branchesOfInputsConflicting bool, normalizedBranchIDs BranchIDs, conflictingInputs OutputsMetadata, err error) {
conflictingInputs = make(OutputsMetadata, 0)
consumedBranches := make([]BranchID, len(inputsMetadata))
for i, inputMetadata := range inputsMetadata {
consumedBranches[i] = inputMetadata.BranchID()
if inputMetadata.ConsumerCount() >= 1 {
conflictingInputs = append(conflictingInputs, inputMetadata)
}
}
normalizedBranchIDs, err = u.branchDAG.normalizeBranches(NewBranchIDs(consumedBranches...))
if err != nil {
if errors.Is(err, ErrInvalidStateTransition) {
branchesOfInputsConflicting = true
err = nil
return
}
err = errors.Errorf("failed to normalize branches: %w", cerrors.ErrFatal)
return
}
return
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region private utility functions ////////////////////////////////////////////////////////////////////////////////////
// ConsumedOutputs returns the consumed (cached)Outputs of the given Transaction.
func (u *UTXODAG) ConsumedOutputs(transaction *Transaction) (cachedInputs CachedOutputs) {
cachedInputs = make(CachedOutputs, 0)
for _, input := range transaction.Essence().Inputs() {
cachedInputs = append(cachedInputs, u.CachedOutput(input.(*UTXOInput).ReferencedOutputID()))
}
return
}
// allOutputsExist is an internal utility function that checks if all of the given Inputs exist.
func (u *UTXODAG) allOutputsExist(inputs Outputs) (solid bool) {
for _, input := range inputs {
if typeutils.IsInterfaceNil(input) {
return false
}
}
return true
}
// transactionInputsMetadata is an internal utility function that returns the Metadata of the Outputs that are used as
// Inputs by the given Transaction.
func (u *UTXODAG) transactionInputsMetadata(transaction *Transaction) (cachedInputsMetadata CachedOutputsMetadata) {
cachedInputsMetadata = make(CachedOutputsMetadata, 0)
for _, inputMetadata := range transaction.Essence().Inputs() {
cachedInputsMetadata = append(cachedInputsMetadata, u.CachedOutputMetadata(inputMetadata.(*UTXOInput).ReferencedOutputID()))
}
return
}
// inputsInInvalidBranch is an internal utility function that checks if any of the Inputs is booked into the InvalidBranch.
func (u *UTXODAG) inputsInInvalidBranch(inputsMetadata OutputsMetadata) (invalid bool) {
for _, inputMetadata := range inputsMetadata {
if invalid = inputMetadata.BranchID() == InvalidBranchID; invalid {
return
}
}
return
}
// consumedOutputsPastConeValid is an internal utility function that checks if the given Outputs do not directly or
// indirectly reference each other in their own past cone.
func (u *UTXODAG) consumedOutputsPastConeValid(outputs Outputs, outputsMetadata OutputsMetadata) (pastConeValid bool) {
if u.outputsUnspent(outputsMetadata) {
pastConeValid = true
return
}
stack := list.New()
consumedInputIDs := make(map[OutputID]types.Empty)
for _, input := range outputs {
consumedInputIDs[input.ID()] = types.Void
stack.PushBack(input.ID())
}
for stack.Len() > 0 {
firstElement := stack.Front()
stack.Remove(firstElement)
cachedConsumers := u.CachedConsumers(firstElement.Value.(OutputID))
for _, consumer := range cachedConsumers.Unwrap() {
if consumer == nil {
cachedConsumers.Release()
panic("failed to unwrap Consumer")
}
cachedTransaction := u.CachedTransaction(consumer.TransactionID())
transaction := cachedTransaction.Unwrap()
if transaction == nil {
cachedTransaction.Release()
cachedConsumers.Release()
panic("failed to unwrap Transaction")
}
for _, output := range transaction.Essence().Outputs() {
if _, exists := consumedInputIDs[output.ID()]; exists {
cachedTransaction.Release()
cachedConsumers.Release()
return false
}
stack.PushBack(output.ID())
}
cachedTransaction.Release()
}
cachedConsumers.Release()
}
return true
}
// outputsUnspent is an internal utility function that checks if the given outputs are unspent (do not have a valid
// Consumer, yet).
func (u *UTXODAG) outputsUnspent(outputsMetadata OutputsMetadata) (outputsUnspent bool) {
for _, inputMetadata := range outputsMetadata {
if inputMetadata.ConsumerCount() != 0 {
return false
}
}
return true
}
// consumedOutputIDsOfTransaction is an internal utility function returns a list of OutputIDs that were consumed by a
// given Transaction. If the Transaction can not be found, it returns an empty list.
func (u *UTXODAG) consumedOutputIDsOfTransaction(transactionID TransactionID) (inputIDs []OutputID) {
inputIDs = make([]OutputID, 0)
u.CachedTransaction(transactionID).Consume(func(transaction *Transaction) {
for _, input := range transaction.Essence().Inputs() {
inputIDs = append(inputIDs, input.(*UTXOInput).ReferencedOutputID())
}
})
return
}
// createdOutputIDsOfTransaction is an internal utility function that returns the list of OutputIDs that were created by
// the given Transaction. If the Transaction can not be found, it returns an empty list.
func (u *UTXODAG) createdOutputIDsOfTransaction(transactionID TransactionID) (outputIDs []OutputID) {
outputIDs = make([]OutputID, 0)
u.CachedTransaction(transactionID).Consume(func(transaction *Transaction) {
for index := range transaction.Essence().Outputs() {
outputIDs = append(outputIDs, NewOutputID(transactionID, uint16(index)))
}
})
return
}
// walkFutureCone is an internal utility function that walks through the future cone of the given Outputs and calling
// the callback function on each step. It is possible to provide an optional filter for the valid flag of the Consumer
// to only walk through matching Consumers.
func (u *UTXODAG) walkFutureCone(entryPoints []OutputID, callback func(transactionID TransactionID) (nextOutputsToVisit []OutputID), optionalValidFlagFilter ...types.TriBool) {
stack := list.New()
for _, outputID := range entryPoints {
stack.PushBack(outputID)
}
seenTransactions := set.New()
for stack.Len() > 0 {
firstElement := stack.Front()
stack.Remove(firstElement)
u.CachedConsumers(firstElement.Value.(OutputID)).Consume(func(consumer *Consumer) {
if !seenTransactions.Add(consumer.TransactionID()) {
return
}
if len(optionalValidFlagFilter) >= 1 && consumer.Valid() != optionalValidFlagFilter[0] {
return
}
for _, updatedOutputID := range callback(consumer.TransactionID()) {
stack.PushBack(updatedOutputID)
}
})
}
}
// consumedBranchIDs is an internal utility function that determines the list of BranchIDs that were consumed by the
// Inputs of the given Transaction.
func (u *UTXODAG) consumedBranchIDs(transactionID TransactionID) (branchIDs BranchIDs) {
branchIDs = make(BranchIDs)
if !u.CachedTransaction(transactionID).Consume(func(transaction *Transaction) {
for _, input := range transaction.Essence().Inputs() {
if !u.CachedOutputMetadata(input.(*UTXOInput).ReferencedOutputID()).Consume(func(outputMetadata *OutputMetadata) {
branchIDs[outputMetadata.BranchID()] = types.Void
}) {
panic(fmt.Errorf("failed to load OutputMetadata with %s", input.(*UTXOInput).ReferencedOutputID()))
}
}
}) {
panic(fmt.Errorf("failed to load Transaction with %s", transactionID))
}
return
}
// ManageStoreAddressOutputMapping mangages how to store the address-output mapping dependent on which type of output it is.
func (u *UTXODAG) ManageStoreAddressOutputMapping(output Output) {
switch output.Type() {
case AliasOutputType:
castedOutput := output.(*AliasOutput)
// if it is an origin alias output, we don't have the aliasaddress from the parsed bytes.
// that happens in utxodag output booking, so we calculate the alias address here
u.StoreAddressOutputMapping(castedOutput.GetAliasAddress(), output.ID())
u.StoreAddressOutputMapping(castedOutput.GetStateAddress(), output.ID())
if !castedOutput.IsSelfGoverned() {
u.StoreAddressOutputMapping(castedOutput.GetGoverningAddress(), output.ID())
}
case ExtendedLockedOutputType:
castedOutput := output.(*ExtendedLockedOutput)
if castedOutput.FallbackAddress() != nil {
u.StoreAddressOutputMapping(castedOutput.FallbackAddress(), output.ID())
}
u.StoreAddressOutputMapping(output.Address(), output.ID())
default:
u.StoreAddressOutputMapping(output.Address(), output.ID())
}
}
// StoreAddressOutputMapping stores the address-output mapping.
func (u *UTXODAG) StoreAddressOutputMapping(address Address, outputID OutputID) {
result, stored := u.addressOutputMappingStorage.StoreIfAbsent(NewAddressOutputMapping(address, outputID))
if stored {
result.Release()
}
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region UTXODAGEvents ////////////////////////////////////////////////////////////////////////////////////////////////
// UTXODAGEvents is a container for all of the UTXODAG related events.
type UTXODAGEvents struct {
// TransactionBranchIDUpdatedByFork gets triggered when the BranchID of a Transaction is changed after the initial booking.
TransactionBranchIDUpdatedByFork *events.Event
}
// TransactionIDEventHandler is an event handler for an event with a TransactionID.
func TransactionIDEventHandler(handler interface{}, params ...interface{}) {
handler.(func(TransactionID))(params[0].(TransactionID))
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region TransactionBranchIDUpdatedEvent //////////////////////////////////////////////////////////////////////////////
// TransactionBranchIDUpdatedByForkEvent is an event that gets triggered, whenever the BranchID of a Transaction is
// changed.
type TransactionBranchIDUpdatedByForkEvent struct {
TransactionID TransactionID
NewBranchID BranchID
ForkedBranchID BranchID
}
// TransactionBranchIDUpdatedByForkEventHandler is an event handler for an event with a
// TransactionBranchIDUpdatedByForkEvent.
func TransactionBranchIDUpdatedByForkEventHandler(handler interface{}, params ...interface{}) {
handler.(func(*TransactionBranchIDUpdatedByForkEvent))(params[0].(*TransactionBranchIDUpdatedByForkEvent))
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region AddressOutputMapping /////////////////////////////////////////////////////////////////////////////////////////
// AddressOutputMapping represents a mapping between Addresses and their corresponding Outputs. Since an Address can have a
// potentially unbounded amount of Outputs, we store this as a separate k/v pair instead of a marshaled
// list of spending Transactions inside the Output.
type AddressOutputMapping struct {
address Address
outputID OutputID
objectstorage.StorableObjectFlags
}
// NewAddressOutputMapping returns a new AddressOutputMapping.
func NewAddressOutputMapping(address Address, outputID OutputID) *AddressOutputMapping {
return &AddressOutputMapping{
address: address,
outputID: outputID,
}
}
// AddressOutputMappingFromBytes unmarshals a AddressOutputMapping from a sequence of bytes.
func AddressOutputMappingFromBytes(bytes []byte) (addressOutputMapping *AddressOutputMapping, consumedBytes int, err error) {
marshalUtil := marshalutil.New(bytes)
if addressOutputMapping, err = AddressOutputMappingFromMarshalUtil(marshalUtil); err != nil {
err = errors.Errorf("failed to parse AddressOutputMapping from MarshalUtil: %w", err)
return
}
consumedBytes = marshalUtil.ReadOffset()
return
}
// AddressOutputMappingFromMarshalUtil unmarshals an AddressOutputMapping using a MarshalUtil (for easier unmarshaling).
func AddressOutputMappingFromMarshalUtil(marshalUtil *marshalutil.MarshalUtil) (addressOutputMapping *AddressOutputMapping, err error) {
addressOutputMapping = &AddressOutputMapping{}
if addressOutputMapping.address, err = AddressFromMarshalUtil(marshalUtil); err != nil {
err = errors.Errorf("failed to parse consumed Address from MarshalUtil: %w", err)
return
}
if addressOutputMapping.outputID, err = OutputIDFromMarshalUtil(marshalUtil); err != nil {
err = errors.Errorf("failed to parse OutputID from MarshalUtil: %w", err)
return
}
return
}
// AddressOutputMappingFromObjectStorage is a factory method that creates a new AddressOutputMapping instance from a
// storage key of the object storage. It is used by the object storage, to create new instances of this entity.
func AddressOutputMappingFromObjectStorage(key []byte, _ []byte) (result objectstorage.StorableObject, err error) {
if result, _, err = AddressOutputMappingFromBytes(key); err != nil {
err = errors.Errorf("failed to parse AddressOutputMapping from bytes: %w", err)
return
}
return
}
// Address returns the Address of the AddressOutputMapping.
func (a *AddressOutputMapping) Address() Address {
return a.address
}
// OutputID returns the OutputID of the AddressOutputMapping.
func (a *AddressOutputMapping) OutputID() OutputID {
return a.outputID
}
// Bytes marshals the Consumer into a sequence of bytes.
func (a *AddressOutputMapping) Bytes() []byte {
return a.ObjectStorageKey()
}
// String returns a human readable version of the Consumer.
func (a *AddressOutputMapping) String() (humanReadableConsumer string) {
return stringify.Struct("AddressOutputMapping",
stringify.StructField("address", a.address),
stringify.StructField("outputID", a.outputID),
)
}
// Update is disabled and panics if it ever gets called - it is required to match the StorableObject interface.
func (a *AddressOutputMapping) Update(objectstorage.StorableObject) {
panic("updates disabled")
}
// ObjectStorageKey returns the key that is used to store the object in the database. It is required to match the
// StorableObject interface.
func (a *AddressOutputMapping) ObjectStorageKey() []byte {
return byteutils.ConcatBytes(a.address.Bytes(), a.outputID.Bytes())
}
// ObjectStorageValue marshals the Consumer into a sequence of bytes that are used as the value part in the object
// storage.
func (a *AddressOutputMapping) ObjectStorageValue() (value []byte) {
return
}
// code contract (make sure the struct implements all required methods)
var _ objectstorage.StorableObject = &AddressOutputMapping{}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region CachedAddressOutputMapping ///////////////////////////////////////////////////////////////////////////////////
// CachedAddressOutputMapping is a wrapper for the generic CachedObject returned by the object storage that overrides
// the accessor methods with a type-casted one.
type CachedAddressOutputMapping struct {
objectstorage.CachedObject
}
// Retain marks the CachedObject to still be in use by the program.
func (c *CachedAddressOutputMapping) Retain() *CachedAddressOutputMapping {
return &CachedAddressOutputMapping{c.CachedObject.Retain()}
}
// Unwrap is the type-casted equivalent of Get. It returns nil if the object does not exist.
func (c *CachedAddressOutputMapping) Unwrap() *AddressOutputMapping {
untypedObject := c.Get()
if untypedObject == nil {
return nil
}
typedObject := untypedObject.(*AddressOutputMapping)
if typedObject == nil || typedObject.IsDeleted() {
return nil
}
return typedObject
}
// Consume unwraps the CachedObject and passes a type-casted version to the consumer (if the object is not empty - it
// exists). It automatically releases the object when the consumer finishes.
func (c *CachedAddressOutputMapping) Consume(consumer func(addressOutputMapping *AddressOutputMapping), forceRelease ...bool) (consumed bool) {
return c.CachedObject.Consume(func(object objectstorage.StorableObject) {
consumer(object.(*AddressOutputMapping))
}, forceRelease...)