forked from BuxOrg/bux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeef_tx_sorting_test.go
104 lines (88 loc) · 2.27 KB
/
beef_tx_sorting_test.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
package bux
import (
"fmt"
"math/rand"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_kahnTopologicalSortTransaction(t *testing.T) {
// create related transactions from oldest to newest
txsFromOldestToNewest := []*Transaction{
createTx("0"),
createTx("1", "0"),
createTx("2", "1"),
createTx("3", "2", "1"),
createTx("4", "3", "1"),
createTx("5", "3", "2"),
createTx("6", "4", "2", "0"),
createTx("7", "6", "5", "3", "1"),
createTx("8", "7"),
}
txsFromOldestToNewestWithUnnecessaryInputs := []*Transaction{
createTx("0"),
createTx("1", "0"),
createTx("2", "1", "101", "102"),
createTx("3", "2", "1"),
createTx("4", "3", "1"),
createTx("5", "3", "2", "100"),
createTx("6", "4", "2", "0"),
createTx("7", "6", "5", "3", "1", "103", "105", "106"),
createTx("8", "7"),
}
tCases := []struct {
name string
expectedSortedTransactions []*Transaction
}{{
name: "txs with necessary data only",
expectedSortedTransactions: txsFromOldestToNewest,
},
{
name: "txs with inputs from other txs",
expectedSortedTransactions: txsFromOldestToNewestWithUnnecessaryInputs,
},
}
for _, tc := range tCases {
t.Run(fmt.Sprint("sort from oldest to newest ", tc.name), func(t *testing.T) {
// given
unsortedTxs := shuffleTransactions(tc.expectedSortedTransactions)
// when
sortedGraph := kahnTopologicalSortTransactions(unsortedTxs)
// then
for i, tx := range txsFromOldestToNewest {
assert.Equal(t, tx.ID, sortedGraph[i].ID)
}
})
}
}
func createTx(txID string, inputsTxIDs ...string) *Transaction {
inputs := make([]*TransactionInput, 0)
for _, inTxID := range inputsTxIDs {
in := &TransactionInput{
Utxo: Utxo{
UtxoPointer: UtxoPointer{
TransactionID: inTxID,
},
},
}
inputs = append(inputs, in)
}
transaction := &Transaction{
draftTransaction: &DraftTransaction{
Configuration: TransactionConfig{
Inputs: inputs,
},
},
}
transaction.ID = txID
return transaction
}
func shuffleTransactions(txs []*Transaction) []*Transaction {
n := len(txs)
result := make([]*Transaction, n)
copy(result, txs)
for i := n - 1; i > 0; i-- {
j := rand.Intn(i + 1)
result[i], result[j] = result[j], result[i]
}
return result
}