-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdag.go
934 lines (761 loc) · 22.4 KB
/
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
package dag
import (
"fmt"
"io/fs"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
merkle_tree "github.com/HORNET-Storage/Scionic-Merkle-Tree/tree"
cbor "github.com/fxamacker/cbor/v2"
)
type fileInfoDirEntry struct {
fileInfo os.FileInfo
}
func (e fileInfoDirEntry) Name() string {
return e.fileInfo.Name()
}
func (e fileInfoDirEntry) IsDir() bool {
return e.fileInfo.IsDir()
}
func (e fileInfoDirEntry) Type() fs.FileMode {
return e.fileInfo.Mode().Type()
}
func (e fileInfoDirEntry) Info() (fs.FileInfo, error) {
return e.fileInfo, nil
}
func newDirEntry(path string) (fs.DirEntry, error) {
fileInfo, err := os.Stat(path)
if err != nil {
return nil, err
}
return fileInfoDirEntry{fileInfo: fileInfo}, nil
}
func CreateDag(path string, timestampRoot bool) (*Dag, error) {
var additionalData map[string]string = nil
if timestampRoot {
currentTime := time.Now().UTC()
timeString := currentTime.Format(time.RFC3339)
additionalData = map[string]string{
"timestamp": timeString,
}
}
dag, err := createDag(path, additionalData)
if err != nil {
return nil, err
}
return dag, nil
}
func CreateDagAdvanced(path string, additionalData map[string]string) (*Dag, error) {
dag, err := createDag(path, additionalData)
if err != nil {
return nil, err
}
return dag, nil
}
func createDag(path string, additionalData map[string]string) (*Dag, error) {
dag := CreateDagBuilder()
fileInfo, err := os.Stat(path)
if err != nil {
return nil, err
}
dirEntry, err := newDirEntry(path)
if err != nil {
return nil, err
}
parentPath := filepath.Dir(path)
var leaf *DagLeaf
if fileInfo.IsDir() {
leaf, err = processDirectory(dirEntry, &parentPath, dag, true, additionalData)
} else {
leaf, err = processFile(dirEntry, &parentPath, dag, true, additionalData)
}
if err != nil {
return nil, err
}
dag.AddLeaf(leaf, nil)
rootHash := leaf.Hash
return dag.BuildDag(rootHash), nil
}
func processEntry(entry fs.DirEntry, path *string, dag *DagBuilder) (*DagLeaf, error) {
var result *DagLeaf
var err error
if entry.IsDir() {
result, err = processDirectory(entry, path, dag, false, nil)
} else {
result, err = processFile(entry, path, dag, false, nil)
}
if err != nil {
return nil, err
}
return result, nil
}
func processDirectory(entry fs.DirEntry, path *string, dag *DagBuilder, isRoot bool, additionalData map[string]string) (*DagLeaf, error) {
entryPath := filepath.Join(*path, entry.Name())
relPath, err := filepath.Rel(*path, entryPath)
if err != nil {
return nil, err
}
builder := CreateDagLeafBuilder(relPath)
builder.SetType(DirectoryLeafType)
entries, err := os.ReadDir(entryPath)
if err != nil {
return nil, err
}
var result *DagLeaf
for _, entry := range entries {
leaf, err := processEntry(entry, &entryPath, dag)
if err != nil {
return nil, err
}
label := dag.GetNextAvailableLabel()
builder.AddLink(label, leaf.Hash)
leaf.SetLabel(label)
dag.AddLeaf(leaf, nil)
}
if isRoot {
result, err = builder.BuildRootLeaf(dag, additionalData)
} else {
result, err = builder.BuildLeaf(nil)
}
if err != nil {
return nil, err
}
return result, nil
}
func processFile(entry fs.DirEntry, path *string, dag *DagBuilder, isRoot bool, additionalData map[string]string) (*DagLeaf, error) {
entryPath := filepath.Join(*path, entry.Name())
relPath, err := filepath.Rel(*path, entryPath)
if err != nil {
return nil, err
}
var result *DagLeaf
builder := CreateDagLeafBuilder(relPath)
builder.SetType(FileLeafType)
fileData, err := os.ReadFile(entryPath)
if err != nil {
return nil, err
}
builder.SetType(FileLeafType)
fileChunks := chunkFile(fileData, ChunkSize)
if len(fileChunks) == 1 {
builder.SetData(fileChunks[0])
} else {
for i, chunk := range fileChunks {
chunkEntryPath := filepath.Join(relPath, strconv.Itoa(i))
chunkBuilder := CreateDagLeafBuilder(chunkEntryPath)
chunkBuilder.SetType(ChunkLeafType)
chunkBuilder.SetData(chunk)
chunkLeaf, err := chunkBuilder.BuildLeaf(nil)
if err != nil {
return nil, err
}
label := dag.GetNextAvailableLabel()
builder.AddLink(label, chunkLeaf.Hash)
chunkLeaf.SetLabel(label)
dag.AddLeaf(chunkLeaf, nil)
}
}
if isRoot {
result, err = builder.BuildRootLeaf(dag, additionalData)
} else {
result, err = builder.BuildLeaf(nil)
}
if err != nil {
return nil, err
}
return result, nil
}
func chunkFile(fileData []byte, chunkSize int) [][]byte {
var chunks [][]byte
fileSize := len(fileData)
for i := 0; i < fileSize; i += chunkSize {
end := i + chunkSize
if end > fileSize {
end = fileSize
}
chunks = append(chunks, fileData[i:end])
}
return chunks
}
func CreateDagBuilder() *DagBuilder {
return &DagBuilder{
Leafs: map[string]*DagLeaf{},
}
}
func (b *DagBuilder) AddLeaf(leaf *DagLeaf, parentLeaf *DagLeaf) error {
if parentLeaf != nil {
label := GetLabel(leaf.Hash)
_, exists := parentLeaf.Links[label]
if !exists {
parentLeaf.AddLink(leaf.Hash)
}
// If parent has more than one link, rebuild its merkle tree
if len(parentLeaf.Links) > 1 {
builder := merkle_tree.CreateTree()
for _, link := range parentLeaf.Links {
builder.AddLeaf(GetLabel(link), link)
}
merkleTree, leafMap, err := builder.Build()
if err == nil {
parentLeaf.MerkleTree = merkleTree
parentLeaf.LeafMap = leafMap
parentLeaf.ClassicMerkleRoot = merkleTree.Root
}
}
}
b.Leafs[leaf.Hash] = leaf
return nil
}
func (b *DagBuilder) BuildDag(root string) *Dag {
return &Dag{
Leafs: b.Leafs,
Root: root,
}
}
// verifyFullDag verifies a complete DAG by checking parent-child relationships
func (d *Dag) verifyFullDag() error {
return d.IterateDag(func(leaf *DagLeaf, parent *DagLeaf) error {
if leaf.Hash == d.Root {
err := leaf.VerifyRootLeaf()
if err != nil {
return err
}
} else {
err := leaf.VerifyLeaf()
if err != nil {
return err
}
if !parent.HasLink(leaf.Hash) {
return fmt.Errorf("parent %s does not contain link to child %s", parent.Hash, leaf.Hash)
}
}
return nil
})
}
// verifyWithProofs verifies a partial DAG using stored Merkle proofs
func (d *Dag) verifyWithProofs() error {
// First verify the root leaf
rootLeaf := d.Leafs[d.Root]
if err := rootLeaf.VerifyRootLeaf(); err != nil {
return fmt.Errorf("root leaf failed to verify: %w", err)
}
// Verify each non-root leaf
for _, leaf := range d.Leafs {
if leaf.Hash == d.Root {
continue
}
// First verify the leaf itself
if err := leaf.VerifyLeaf(); err != nil {
return fmt.Errorf("leaf %s failed to verify: %w", leaf.Hash, err)
}
// Then verify the path to root
current := leaf
for current.Hash != d.Root {
// Find parent in this partial DAG
var parent *DagLeaf
for _, potential := range d.Leafs {
if potential.HasLink(current.Hash) {
parent = potential
break
}
}
if parent == nil {
return fmt.Errorf("broken path to root for leaf %s", leaf.Hash)
}
// Verify parent leaf
if parent.Hash != d.Root {
if err := parent.VerifyLeaf(); err != nil {
return fmt.Errorf("parent leaf %s failed to verify: %w", parent.Hash, err)
}
}
// Only verify merkle proof if parent has multiple children
// according to its CurrentLinkCount (which is part of its hash)
if parent.CurrentLinkCount > 1 {
// Try both the full hash and the hash without label
var proof *ClassicTreeBranch
var hasProof bool
proof, hasProof = parent.Proofs[current.Hash]
if !hasProof {
return fmt.Errorf("missing merkle proof for node %s in partial DAG", current.Hash)
}
err := parent.VerifyBranch(proof)
if err != nil {
return fmt.Errorf("invalid merkle proof for node %s: %w", current.Hash, err)
}
}
current = parent
}
}
return nil
}
// Verify checks the integrity of the DAG, automatically choosing between full and partial verification
func (d *Dag) Verify() error {
if d.IsPartial() {
// Use more thorough verification with proofs for partial DAGs
return d.verifyWithProofs()
}
// Use simpler verification for full DAGs
return d.verifyFullDag()
}
func (dag *Dag) CreateDirectory(path string) error {
rootHash := dag.Root
rootLeaf := dag.Leafs[rootHash]
err := rootLeaf.CreateDirectoryLeaf(path, dag)
if err != nil {
return err
}
return nil
}
func ReadDag(path string) (*Dag, error) {
fileData, err := ioutil.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("could not read file: %w", err)
}
var result Dag
if err := cbor.Unmarshal(fileData, &result); err != nil {
return nil, fmt.Errorf("could not decode Dag: %w", err)
}
return &result, nil
}
func (dag *Dag) GetContentFromLeaf(leaf *DagLeaf) ([]byte, error) {
var content []byte
if len(leaf.Links) > 0 {
// For chunked files, concatenate content from all chunks
for _, link := range leaf.Links {
childLeaf := dag.Leafs[link]
if childLeaf == nil {
return nil, fmt.Errorf("invalid link: %s", link)
}
content = append(content, childLeaf.Content...)
}
} else if len(leaf.Content) > 0 {
// For single-chunk files, return content directly
content = leaf.Content
}
return content, nil
}
func (d *Dag) IterateDag(processLeaf func(leaf *DagLeaf, parent *DagLeaf) error) error {
var iterate func(leafHash string, parentHash *string) error
iterate = func(leafHash string, parentHash *string) error {
leaf, exists := d.Leafs[leafHash]
if !exists {
return fmt.Errorf("child is missing when iterating dag")
}
var parent *DagLeaf
if parentHash != nil {
parent = d.Leafs[*parentHash]
}
err := processLeaf(leaf, parent)
if err != nil {
return err
}
childHashes := []string{}
for _, childHash := range leaf.Links {
childHashes = append(childHashes, childHash)
}
sort.Slice(childHashes, func(i, j int) bool {
numI, _ := strconv.Atoi(strings.Split(childHashes[i], ":")[0])
numJ, _ := strconv.Atoi(strings.Split(childHashes[j], ":")[0])
return numI < numJ
})
for _, childHash := range childHashes {
err := iterate(childHash, &leaf.Hash)
if err != nil {
return err
}
}
return nil
}
return iterate(d.Root, nil)
}
// IsPartial returns true if this DAG is a partial DAG (has fewer leaves than the total count)
func (d *Dag) IsPartial() bool {
// Get the root leaf
rootLeaf := d.Leafs[d.Root]
if rootLeaf == nil {
return true // If root leaf is missing, it's definitely partial
}
// Check if the number of leaves in the DAG matches the total leaf count
return len(d.Leafs) < rootLeaf.LeafCount
}
// pruneIrrelevantLinks removes links that aren't needed for partial verification
func (d *Dag) pruneIrrelevantLinks(relevantHashes map[string]bool) {
for _, leaf := range d.Leafs {
// Create new map for relevant links
prunedLinks := make(map[string]string)
// Only keep links that are relevant
for label, hash := range leaf.Links {
if relevantHashes[GetHash(hash)] {
prunedLinks[label] = hash
}
}
// Only modify the Links map, keep everything else as is
// since they're part of the leaf's identity
leaf.Links = prunedLinks
}
}
// findParent searches the DAG for a leaf's parent
func (d *Dag) findParent(leaf *DagLeaf) *DagLeaf {
for _, potential := range d.Leafs {
if potential.HasLink(leaf.Hash) {
return potential
}
}
return nil
}
// buildVerificationBranch creates a branch containing the leaf and its verification path
func (d *Dag) buildVerificationBranch(leaf *DagLeaf) (*DagBranch, error) {
// Clone the root leaf first to ensure it has all fields
rootLeaf := d.Leafs[d.Root].Clone()
branch := &DagBranch{
Leaf: leaf.Clone(),
Path: make([]*DagLeaf, 0),
}
// Always add root leaf to path
branch.Path = append(branch.Path, rootLeaf)
// Find path to root through parent nodes
current := leaf
for current.Hash != d.Root {
// Find parent in this partial DAG, not the original
var parent *DagLeaf
for _, potential := range d.Leafs {
if potential.HasLink(current.Hash) {
parent = potential
break
}
}
if parent == nil {
return nil, fmt.Errorf("failed to find parent for leaf %s", current.Hash)
}
// Clone parent before any modifications
parentClone := parent.Clone()
// If parent has multiple children according to CurrentLinkCount,
// we must generate and store a proof since this is our only chance
if parent.CurrentLinkCount > 1 {
// Find the label for current in parent's links
var label string
for l, h := range parent.Links {
if h == current.Hash {
label = l
break
}
}
if label == "" {
return nil, fmt.Errorf("unable to find label for key")
}
// Build merkle tree with all current links
builder := merkle_tree.CreateTree()
for l, h := range parent.Links {
builder.AddLeaf(l, h)
}
merkleTree, _, err := builder.Build()
if err != nil {
return nil, err
}
// Get proof for the current leaf
index, exists := merkleTree.GetIndexForKey(label)
if !exists {
return nil, fmt.Errorf("unable to find index for key %s", label)
}
// Store proof in parent clone
if parentClone.Proofs == nil {
parentClone.Proofs = make(map[string]*ClassicTreeBranch)
}
proof := &ClassicTreeBranch{
Leaf: current.Hash,
Proof: merkleTree.Proofs[index],
}
// Store proof using the hash
parentClone.Proofs[current.Hash] = proof
}
// Always add parent to path so its proofs get merged
branch.Path = append(branch.Path, parentClone)
current = parent
}
return branch, nil
}
// addBranchToPartial adds a branch to the partial DAG
func (d *Dag) addBranchToPartial(branch *DagBranch, partial *Dag) error {
// Add leaf if not present
if _, exists := partial.Leafs[branch.Leaf.Hash]; !exists {
partial.Leafs[branch.Leaf.Hash] = branch.Leaf
}
// Add all path nodes (including root) and merge their proofs
for i := 0; i < len(branch.Path); i++ {
pathNode := branch.Path[i]
if existingNode, exists := partial.Leafs[pathNode.Hash]; exists {
// Create a new node with merged proofs
mergedNode := existingNode.Clone()
if mergedNode.Proofs == nil {
mergedNode.Proofs = make(map[string]*ClassicTreeBranch)
}
if pathNode.Proofs != nil {
for k, v := range pathNode.Proofs {
mergedNode.Proofs[k] = v
}
}
// Update the node in the map
partial.Leafs[pathNode.Hash] = mergedNode
} else {
partial.Leafs[pathNode.Hash] = pathNode
}
}
return nil
}
// GetPartial returns a new DAG containing only the requested leaves and their verification paths
func (d *Dag) GetPartial(start, end int) (*Dag, error) {
if start == end {
return nil, fmt.Errorf("invalid range: indices cannot be the same")
}
if start < 0 || end < 0 {
return nil, fmt.Errorf("invalid range: indices cannot be negative")
}
if start > end {
return nil, fmt.Errorf("invalid range: start cannot be greater than end")
}
rootLeaf := d.Leafs[d.Root]
if start >= rootLeaf.LeafCount || end > rootLeaf.LeafCount {
return nil, fmt.Errorf("invalid range: indices cannot be greater than the overall leaf count")
}
partialDag := &Dag{
Leafs: make(map[string]*DagLeaf),
Root: d.Root,
}
// Track hashes that are relevant for verification
relevantHashes := make(map[string]bool)
relevantHashes[GetHash(d.Root)] = true
// Process each requested leaf
for i := start; i <= end; i++ {
// Find and validate leaf
var targetLeaf *DagLeaf
if i == 0 {
targetLeaf = d.Leafs[d.Root]
} else {
label := strconv.Itoa(i)
for _, leaf := range d.Leafs {
if GetLabel(leaf.Hash) == label {
targetLeaf = leaf
break
}
}
}
if targetLeaf == nil {
continue
}
// Add target leaf hash to relevant hashes
relevantHashes[GetHash(targetLeaf.Hash)] = true
// Build verification path
branch, err := d.buildVerificationBranch(targetLeaf)
if err != nil {
return nil, err
}
// Track hashes from verification path
for _, pathNode := range branch.Path {
relevantHashes[GetHash(pathNode.Hash)] = true
}
// Track hashes from Merkle proofs
for _, proof := range branch.MerkleProofs {
// Add the leaf hash
relevantHashes[GetHash(proof.Leaf)] = true
// Add all sibling hashes from the proof
for _, sibling := range proof.Proof.Siblings {
relevantHashes[string(sibling)] = true
}
}
// Add branch to partial DAG
err = d.addBranchToPartial(branch, partialDag)
if err != nil {
return nil, err
}
}
// Prune irrelevant links from the partial DAG
partialDag.pruneIrrelevantLinks(relevantHashes)
return partialDag, nil
}
// getPartialLeafSequence returns an ordered sequence of leaves for transmission from a partial DAG
// This is an internal method used by GetLeafSequence when dealing with partial DAGs
func (d *Dag) getPartialLeafSequence() []*TransmissionPacket {
var sequence []*TransmissionPacket
// Get the root leaf
rootLeaf := d.Leafs[d.Root]
if rootLeaf == nil {
return sequence // Return empty sequence if root leaf is missing
}
// First, build a map of proofs organized by parent hash and child hash
// This will allow us to look up the proof for a specific child when creating its packet
proofMap := make(map[string]map[string]*ClassicTreeBranch)
// Populate the proof map from all leaves in the partial DAG
for _, leaf := range d.Leafs {
if len(leaf.Proofs) > 0 {
// Create an entry for this parent if it doesn't exist
if _, exists := proofMap[leaf.Hash]; !exists {
proofMap[leaf.Hash] = make(map[string]*ClassicTreeBranch)
}
// Add all proofs from this leaf to the map
for childHash, proof := range leaf.Proofs {
proofMap[leaf.Hash][childHash] = proof
}
}
}
// Now perform BFS traversal similar to the full DAG method
visited := make(map[string]bool)
// Start with the root
rootLeafClone := rootLeaf.Clone()
// We need to preserve the original links for the root leaf
// because they're part of its identity and hash calculation
originalLinks := make(map[string]string)
for k, v := range rootLeaf.Links {
originalLinks[k] = v
}
// Clear links for transmission (they'll be reconstructed on the receiving end)
rootLeafClone.Links = make(map[string]string)
// We need to preserve these fields for verification
// but clear proofs for the root packet - they'll be sent with child packets
originalMerkleRoot := rootLeafClone.ClassicMerkleRoot
originalLatestLabel := rootLeafClone.LatestLabel
originalLeafCount := rootLeafClone.LeafCount
rootLeafClone.Proofs = nil
// Restore the critical fields
rootLeafClone.ClassicMerkleRoot = originalMerkleRoot
rootLeafClone.LatestLabel = originalLatestLabel
rootLeafClone.LeafCount = originalLeafCount
rootPacket := &TransmissionPacket{
Leaf: rootLeafClone,
ParentHash: "", // Root has no parent
Proofs: make(map[string]*ClassicTreeBranch),
}
sequence = append(sequence, rootPacket)
visited[d.Root] = true
// Restore the original links for the root leaf in the DAG
rootLeaf.Links = originalLinks
// BFS traversal
queue := []string{d.Root}
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
currentLeaf := d.Leafs[current]
// Sort links for deterministic order
var sortedLinks []string
for _, link := range currentLeaf.Links {
sortedLinks = append(sortedLinks, link)
}
sort.Strings(sortedLinks)
// Process each child
for _, childHash := range sortedLinks {
if !visited[childHash] {
childLeaf := d.Leafs[childHash]
if childLeaf == nil {
continue // Skip if child leaf doesn't exist in this partial DAG
}
// Clone the leaf and clear its links for transmission
leafClone := childLeaf.Clone()
leafClone.Links = make(map[string]string)
leafClone.Proofs = nil // Clear proofs from the leaf
packet := &TransmissionPacket{
Leaf: leafClone,
ParentHash: current,
Proofs: make(map[string]*ClassicTreeBranch),
}
// Add the proof for this specific child from the proof map
if parentProofs, exists := proofMap[current]; exists {
if proof, hasProof := parentProofs[childHash]; hasProof {
packet.Proofs[childHash] = proof
}
}
sequence = append(sequence, packet)
visited[childHash] = true
queue = append(queue, childHash)
}
}
}
return sequence
}
// GetLeafSequence returns an ordered sequence of leaves for transmission
// Each packet contains a leaf, its parent hash, and any proofs needed for verification
func (d *Dag) GetLeafSequence() []*TransmissionPacket {
// Check if this is a partial DAG
if d.IsPartial() {
// Use specialized method for partial DAGs
return d.getPartialLeafSequence()
}
// Original implementation for complete DAGs
var sequence []*TransmissionPacket
visited := make(map[string]bool)
rootLeaf := d.Leafs[d.Root]
if rootLeaf == nil {
return sequence
}
totalLeafCount := rootLeaf.LeafCount
rootLeafClone := rootLeaf.Clone()
rootLeafClone.Links = make(map[string]string)
rootPacket := &TransmissionPacket{
Leaf: rootLeafClone,
ParentHash: "",
Proofs: make(map[string]*ClassicTreeBranch),
}
sequence = append(sequence, rootPacket)
visited[d.Root] = true
queue := []string{d.Root}
for len(queue) > 0 && len(sequence) <= totalLeafCount {
current := queue[0]
queue = queue[1:]
currentLeaf := d.Leafs[current]
var sortedLinks []string
for _, link := range currentLeaf.Links {
sortedLinks = append(sortedLinks, link)
}
sort.Strings(sortedLinks)
for _, childHash := range sortedLinks {
if !visited[childHash] && len(sequence) <= totalLeafCount {
branch, err := d.buildVerificationBranch(d.Leafs[childHash])
if err != nil {
continue
}
leafClone := d.Leafs[childHash].Clone()
leafClone.Links = make(map[string]string)
packet := &TransmissionPacket{
Leaf: leafClone,
ParentHash: current,
Proofs: make(map[string]*ClassicTreeBranch),
}
for _, pathNode := range branch.Path {
if pathNode.Proofs != nil {
for k, v := range pathNode.Proofs {
packet.Proofs[k] = v
}
}
}
sequence = append(sequence, packet)
visited[childHash] = true
queue = append(queue, childHash)
}
}
}
return sequence
}
func (d *Dag) ApplyTransmissionPacket(packet *TransmissionPacket) {
d.Leafs[packet.Leaf.Hash] = packet.Leaf
if packet.ParentHash != "" {
if parent, exists := d.Leafs[packet.ParentHash]; exists {
label := GetLabel(packet.Leaf.Hash)
if label != "" {
parent.Links[label] = packet.Leaf.Hash
}
}
}
for leafHash, proof := range packet.Proofs {
for _, leaf := range d.Leafs {
if leaf.HasLink(leafHash) {
if leaf.Proofs == nil {
leaf.Proofs = make(map[string]*ClassicTreeBranch)
}
leaf.Proofs[leafHash] = proof
break
}
}
}
}