-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol_test_util.go
91 lines (78 loc) · 1.95 KB
/
protocol_test_util.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
package test
import (
"fmt"
dbm "github.com/tendermint/tmlibs/db"
"github.com/bytom-gm/protocol"
"github.com/bytom-gm/protocol/bc/types"
)
func declChain(name string, baseChain *protocol.Chain, baseHeight uint64, height uint64) (*protocol.Chain, error) {
chainDB := dbm.NewDB(name, "leveldb", name)
chain, _, _, err := MockChain(chainDB)
if err != nil {
return nil, err
}
if baseChain == nil {
if err := AppendBlocks(chain, height); err != nil {
return nil, err
}
return chain, nil
}
for i := uint64(1); i <= baseHeight; i++ {
block, err := baseChain.GetBlockByHeight(i)
if err != nil {
return nil, err
}
if err := SolveAndUpdate(chain, block); err != nil {
return nil, err
}
}
err = AppendBlocks(chain, height-baseHeight)
return chain, err
}
func ancestorOf(c1 *protocol.Chain, c2 *protocol.Chain) (*types.Block, error) {
start := c1.BestBlockHeight()
if c2.BestBlockHeight() < c1.BestBlockHeight() {
start = c2.BestBlockHeight()
}
for i := start; i >= 0; i-- {
b1, err := c1.GetBlockByHeight(i)
if err != nil {
return nil, err
}
b2, err := c2.GetBlockByHeight(i)
if err != nil {
return nil, err
}
if b1.Hash() == b2.Hash() {
return b1, nil
}
}
return nil, fmt.Errorf("can't find ancestor")
}
func merge(c1 *protocol.Chain, c2 *protocol.Chain) error {
// c1 and c2 are same
if c1.BestBlockHeight() == c2.BestBlockHeight() && *c1.BestBlockHash() == *c2.BestBlockHash() {
return nil
}
ancestor, err := ancestorOf(c1, c2)
if err != nil {
return err
}
processBlocks := func(dest *protocol.Chain, src *protocol.Chain, height uint64) error {
for h := src.BestBlockHeight(); h > height; h-- {
block, err := src.GetBlockByHeight(h)
if err != nil {
return err
}
_, err = dest.ProcessBlock(block)
if err != nil {
return err
}
}
return nil
}
if err := processBlocks(c1, c2, ancestor.Height); err != nil {
return err
}
return processBlocks(c2, c1, ancestor.Height)
}