forked from ipfs/go-graphsync
/
testchain.go
273 lines (246 loc) · 10 KB
/
testchain.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
package testutil
import (
"context"
"io"
"testing"
blocks "github.com/ipfs/go-block-format"
cid "github.com/ipfs/go-cid"
"github.com/ipld/go-ipld-prime"
_ "github.com/ipld/go-ipld-prime/codec/dagcbor"
"github.com/ipld/go-ipld-prime/datamodel"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
"github.com/ipld/go-ipld-prime/node/basicnode"
"github.com/ipld/go-ipld-prime/traversal/selector"
"github.com/ipld/go-ipld-prime/traversal/selector/builder"
mh "github.com/multiformats/go-multihash"
"github.com/stretchr/testify/require"
graphsync "github.com/filecoin-project/boost-graphsync"
"github.com/filecoin-project/boost-graphsync/testutil/chaintypes"
)
const blockChainTraversedNodesPerBlock = 2
// TestBlockChain is a simulated data structure similar to a blockchain
// which graphsync is uniquely suited for
type TestBlockChain struct {
t testing.TB
blockChainLength int
loader ipld.BlockReadOpener
GenisisNode ipld.Node
GenisisLink ipld.Link
MiddleNodes []ipld.Node
MiddleLinks []ipld.Link
TipNode ipld.Node
TipLink ipld.Link
}
func createBlock(parents []ipld.Link, size uint64) (ipld.Node, error) {
blknb := chaintypes.Type.Block.NewBuilder()
blknbmnb, err := blknb.BeginMap(2)
if err != nil {
return nil, err
}
entnb, err := blknbmnb.AssembleEntry("Parents")
if err != nil {
return nil, err
}
pnblnb, err := entnb.BeginList(int64(len(parents)))
if err != nil {
return nil, err
}
for _, parent := range parents {
err := pnblnb.AssembleValue().AssignLink(parent)
if err != nil {
return nil, err
}
}
err = pnblnb.Finish()
if err != nil {
return nil, err
}
entnb, err = blknbmnb.AssembleEntry("Messages")
if err != nil {
return nil, err
}
mnblnb, err := entnb.BeginList(1)
if err != nil {
return nil, err
}
err = mnblnb.AssembleValue().AssignBytes(RandomBytes(int64(size)))
if err != nil {
return nil, err
}
err = mnblnb.Finish()
if err != nil {
return nil, err
}
err = blknbmnb.Finish()
if err != nil {
return nil, err
}
return blknb.Build(), nil
}
// SetupBlockChain creates a new test block chain with the given height
func SetupBlockChain(
ctx context.Context,
t testing.TB,
lsys ipld.LinkSystem,
size uint64,
blockChainLength int) *TestBlockChain {
linkPrototype := cidlink.LinkPrototype{Prefix: cid.NewPrefixV1(cid.DagCBOR, mh.SHA2_256)}
genisisNode, err := createBlock([]ipld.Link{}, size)
require.NoError(t, err, "Error creating genesis block")
genesisLink, err := lsys.Store(ipld.LinkContext{Ctx: ctx}, linkPrototype, genisisNode)
require.NoError(t, err, "Error creating link to genesis block")
parent := genesisLink
middleNodes := make([]ipld.Node, 0, blockChainLength-2)
middleLinks := make([]ipld.Link, 0, blockChainLength-2)
for i := 0; i < blockChainLength-2; i++ {
node, err := createBlock([]ipld.Link{parent}, size)
require.NoError(t, err, "Error creating middle block")
middleNodes = append(middleNodes, node)
link, err := lsys.Store(ipld.LinkContext{Ctx: ctx}, linkPrototype, node)
require.NoError(t, err, "Error creating link to middle block")
middleLinks = append(middleLinks, link)
parent = link
}
tipNode, err := createBlock([]ipld.Link{parent}, size)
require.NoError(t, err, "Error creating tip block")
tipLink, err := lsys.Store(ipld.LinkContext{Ctx: ctx}, linkPrototype, tipNode)
require.NoError(t, err, "Error creating link to tip block")
return &TestBlockChain{t, blockChainLength, lsys.StorageReadOpener, genisisNode, genesisLink, middleNodes, middleLinks, tipNode, tipLink}
}
// Selector returns the selector to recursive traverse the block chain parent links
func (tbc *TestBlockChain) Selector() ipld.Node {
ssb := builder.NewSelectorSpecBuilder(basicnode.Prototype.Any)
return ssb.ExploreRecursive(selector.RecursionLimitDepth(int64(tbc.blockChainLength)),
ssb.ExploreFields(func(efsb builder.ExploreFieldsSpecBuilder) {
efsb.Insert("Parents", ssb.ExploreAll(
ssb.ExploreRecursiveEdge()))
})).Node()
}
// LinkTipIndex returns a link to the block at the given index from the tip
func (tbc *TestBlockChain) LinkTipIndex(fromTip int) ipld.Link {
switch height := tbc.blockChainLength - 1 - fromTip; {
case height == 0:
return tbc.GenisisLink
case height == tbc.blockChainLength-1:
return tbc.TipLink
default:
return tbc.MiddleLinks[height-1]
}
}
// NodeTipIndex returns the node to the block at the given index from the tip
func (tbc *TestBlockChain) NodeTipIndex(fromTip int) ipld.Node {
switch height := tbc.blockChainLength - 1 - fromTip; {
case height == 0:
return tbc.GenisisNode
case height == tbc.blockChainLength-1:
return tbc.TipNode
default:
return tbc.MiddleNodes[height-1]
}
}
// PathTipIndex returns the path to the block at the given index from the tip
func (tbc *TestBlockChain) PathTipIndex(fromTip int) ipld.Path {
expectedPath := make([]datamodel.PathSegment, 0, 2*fromTip)
for i := 0; i < fromTip; i++ {
expectedPath = append(expectedPath, datamodel.PathSegmentOfString("Parents"), datamodel.PathSegmentOfInt(0))
}
return datamodel.NewPath(expectedPath)
}
func (tbc *TestBlockChain) checkResponses(responses []graphsync.ResponseProgress, start int, end int, verifyTypes bool) {
require.Len(tbc.t, responses, (end-start)*blockChainTraversedNodesPerBlock, "traverses all nodes")
expectedPath := tbc.PathTipIndex(start).String()
for i, response := range responses {
require.Equal(tbc.t, expectedPath, response.Path.String(), "response has correct path")
if i%2 == 0 {
if verifyTypes {
_, ok := response.Node.(chaintypes.Block)
require.True(tbc.t, ok, "nodes in response should have correct type")
}
if expectedPath == "" {
expectedPath = "Parents"
} else {
expectedPath = expectedPath + "/Parents"
}
} else {
if verifyTypes {
_, ok := response.Node.(chaintypes.Parents)
require.True(tbc.t, ok, "nodes in response should have correct type")
}
expectedPath = expectedPath + "/0"
}
if response.LastBlock.Path.String() != response.Path.String() {
continue
}
if response.LastBlock.Link == nil {
continue
}
expectedLink := tbc.LinkTipIndex((i / 2) + start)
require.Equal(tbc.t, expectedLink, response.LastBlock.Link, "response has correct link")
}
}
// VerifyWholeChain verifies the given response channel returns the expected responses for the whole chain
func (tbc *TestBlockChain) VerifyWholeChain(ctx context.Context, responseChan <-chan graphsync.ResponseProgress) {
tbc.VerifyRemainder(ctx, responseChan, 0)
}
// VerifyRemainder verifies the given response channel returns the remainder of the chain starting at the nth block from the tip
func (tbc *TestBlockChain) VerifyRemainder(ctx context.Context, responseChan <-chan graphsync.ResponseProgress, from int) {
responses := CollectResponses(ctx, tbc.t, responseChan)
tbc.checkResponses(responses, from, tbc.blockChainLength, false)
}
// VerifyResponseRange verifies the given response channel returns the given range of respnses, indexed from the tip
// (with possibly more data left in the channel)
func (tbc *TestBlockChain) VerifyResponseRange(ctx context.Context, responseChan <-chan graphsync.ResponseProgress, from int, to int) {
responses := ReadNResponses(ctx, tbc.t, responseChan, (to-from)*blockChainTraversedNodesPerBlock)
tbc.checkResponses(responses, from, to, false)
}
// VerifyWholeChainSync verifies the given set of read responses are the expected responses for the whole chain
func (tbc *TestBlockChain) VerifyWholeChainSync(responses []graphsync.ResponseProgress) {
tbc.VerifyRemainderSync(responses, 0)
}
// VerifyRemainderSync verifies the given set of read responses are the remainder of the chain starting at the nth block from the tip
func (tbc *TestBlockChain) VerifyRemainderSync(responses []graphsync.ResponseProgress, from int) {
tbc.checkResponses(responses, from, tbc.blockChainLength, false)
}
// VerifyResponseRangeSync verifies given set of read responses match responses for the given range of the blockchain, indexed from the tip
// (with possibly more data left in the channel)
func (tbc *TestBlockChain) VerifyResponseRangeSync(responses []graphsync.ResponseProgress, from int, to int) {
tbc.checkResponses(responses, from, to, false)
}
// VerifyWholeChainWithTypes verifies the given response channel returns the expected responses for the whole chain
// and that the types in the response are the expected types for a block chain
func (tbc *TestBlockChain) VerifyWholeChainWithTypes(ctx context.Context, responseChan <-chan graphsync.ResponseProgress) {
tbc.VerifyRemainderWithTypes(ctx, responseChan, 0)
}
// VerifyRemainderWithTypes verifies the given response channel returns the remainder of the chain starting at the nth block from the tip
// and that the types in the response are the expected types for a block chain
func (tbc *TestBlockChain) VerifyRemainderWithTypes(ctx context.Context, responseChan <-chan graphsync.ResponseProgress, from int) {
responses := CollectResponses(ctx, tbc.t, responseChan)
tbc.checkResponses(responses, from, tbc.blockChainLength, true)
}
// Blocks Returns the given raw blocks for the block chain for the given range, indexed from the tip
func (tbc *TestBlockChain) Blocks(from int, to int) []blocks.Block {
var blks []blocks.Block
for i := from; i < to; i++ {
link := tbc.LinkTipIndex(i)
reader, err := tbc.loader(ipld.LinkContext{}, link)
require.NoError(tbc.t, err)
data, err := io.ReadAll(reader)
require.NoError(tbc.t, err)
blk, err := blocks.NewBlockWithCid(data, link.(cidlink.Link).Cid)
require.NoError(tbc.t, err)
blks = append(blks, blk)
}
return blks
}
// AllBlocks returns all blocks for a blockchain
func (tbc *TestBlockChain) AllBlocks() []blocks.Block {
return tbc.Blocks(0, tbc.blockChainLength)
}
// RemainderBlocks returns the remaining blocks for a blockchain, indexed from tip
func (tbc *TestBlockChain) RemainderBlocks(from int) []blocks.Block {
return tbc.Blocks(from, tbc.blockChainLength)
}
// Chooser is a NodeBuilderChooser function that always returns the block chain
func (tbc *TestBlockChain) Chooser(ipld.Link, ipld.LinkContext) (ipld.NodePrototype, error) {
return chaintypes.Type.Block, nil
}