This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
generated from mrz1836/go-template
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
beef_tx_sorting.go
74 lines (57 loc) · 2.14 KB
/
beef_tx_sorting.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
package bux
func kahnTopologicalSortTransactions(transactions []*Transaction) []*Transaction {
txByID, incomingEdgesMap, zeroIncomingEdgeQueue := prepareSortStructures(transactions)
result := make([]*Transaction, 0, len(transactions))
for len(zeroIncomingEdgeQueue) > 0 {
txID := zeroIncomingEdgeQueue[0]
zeroIncomingEdgeQueue = zeroIncomingEdgeQueue[1:]
tx := txByID[txID]
result = append(result, tx)
zeroIncomingEdgeQueue = removeTxFromIncomingEdges(tx, incomingEdgesMap, zeroIncomingEdgeQueue)
}
reverseInPlace(result)
return result
}
func prepareSortStructures(dag []*Transaction) (txByID map[string]*Transaction, incomingEdgesMap map[string]int, zeroIncomingEdgeQueue []string) {
dagLen := len(dag)
txByID = make(map[string]*Transaction, dagLen)
incomingEdgesMap = make(map[string]int, dagLen)
for _, tx := range dag {
txByID[tx.ID] = tx
incomingEdgesMap[tx.ID] = 0
}
calculateIncomingEdges(incomingEdgesMap, dag)
zeroIncomingEdgeQueue = getTxWithZeroIncomingEdges(incomingEdgesMap)
return
}
func calculateIncomingEdges(inDegree map[string]int, transactions []*Transaction) {
for _, tx := range transactions {
for _, input := range tx.draftTransaction.Configuration.Inputs {
inDegree[input.UtxoPointer.TransactionID]++
}
}
}
func getTxWithZeroIncomingEdges(incomingEdgesMap map[string]int) []string {
zeroIncomingEdgeQueue := make([]string, 0, len(incomingEdgesMap))
for txID, edgeNum := range incomingEdgesMap {
if edgeNum == 0 {
zeroIncomingEdgeQueue = append(zeroIncomingEdgeQueue, txID)
}
}
return zeroIncomingEdgeQueue
}
func removeTxFromIncomingEdges(tx *Transaction, incomingEdgesMap map[string]int, zeroIncomingEdgeQueue []string) []string {
for _, input := range tx.draftTransaction.Configuration.Inputs {
neighborID := input.UtxoPointer.TransactionID
incomingEdgesMap[neighborID]--
if incomingEdgesMap[neighborID] == 0 {
zeroIncomingEdgeQueue = append(zeroIncomingEdgeQueue, neighborID)
}
}
return zeroIncomingEdgeQueue
}
func reverseInPlace(collection []*Transaction) {
for i, j := 0, len(collection)-1; i < j; i, j = i+1, j-1 {
collection[i], collection[j] = collection[j], collection[i]
}
}