/
chunkVerifier_test.go
348 lines (300 loc) · 10.3 KB
/
chunkVerifier_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
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
package chunks_test
import (
"fmt"
"math/rand"
"testing"
"time"
"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
executionState "github.com/onflow/flow-go/engine/execution/state"
"github.com/onflow/flow-go/fvm"
fvmErrors "github.com/onflow/flow-go/fvm/errors"
"github.com/onflow/flow-go/fvm/programs"
"github.com/onflow/flow-go/fvm/state"
"github.com/onflow/flow-go/ledger"
completeLedger "github.com/onflow/flow-go/ledger/complete"
"github.com/onflow/flow-go/ledger/complete/wal/fixtures"
chunksmodels "github.com/onflow/flow-go/model/chunks"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/model/verification"
"github.com/onflow/flow-go/module/chunks"
"github.com/onflow/flow-go/module/metrics"
"github.com/onflow/flow-go/utils/unittest"
)
var eventsList = flow.EventsList{
{
Type: "event.someType",
TransactionID: flow.Identifier{2, 3, 2, 3},
TransactionIndex: 1,
EventIndex: 2,
Payload: []byte{7, 3, 1, 2},
},
{
Type: "event.otherType",
TransactionID: flow.Identifier{3, 3, 3},
TransactionIndex: 4,
EventIndex: 4,
Payload: []byte{7, 3, 1, 2},
},
}
type ChunkVerifierTestSuite struct {
suite.Suite
verifier *chunks.ChunkVerifier
}
// Make sure variables are set properly
// SetupTest is executed prior to each individual test in this test suite
func (s *ChunkVerifierTestSuite) SetupTest() {
// seed the RNG
rand.Seed(time.Now().UnixNano())
vm := new(vmMock)
vmCtx := fvm.NewContext(zerolog.Nop())
s.verifier = chunks.NewChunkVerifier(vm, vmCtx)
}
// TestChunkVerifier invokes all the tests in this test suite
func TestChunkVerifier(t *testing.T) {
suite.Run(t, new(ChunkVerifierTestSuite))
}
// TestHappyPath tests verification of the baseline verifiable chunk
func (s *ChunkVerifierTestSuite) TestHappyPath() {
vch := GetBaselineVerifiableChunk(s.T(), "")
assert.NotNil(s.T(), vch)
spockSecret, chFaults, err := s.verifier.Verify(vch)
assert.Nil(s.T(), err)
assert.Nil(s.T(), chFaults)
assert.NotNil(s.T(), spockSecret)
}
// TestMissingRegisterTouchForUpdate tests verification given a chunkdatapack missing a register touch (update)
func (s *ChunkVerifierTestSuite) TestMissingRegisterTouchForUpdate() {
s.T().Skip("Check new partial ledger for missing keys")
vch := GetBaselineVerifiableChunk(s.T(), "")
assert.NotNil(s.T(), vch)
// remove the second register touch
//vch.ChunkDataPack.RegisterTouches = vch.ChunkDataPack.RegisterTouches[:1]
spockSecret, chFaults, err := s.verifier.Verify(vch)
assert.Nil(s.T(), err)
assert.NotNil(s.T(), chFaults)
assert.Nil(s.T(), spockSecret)
_, ok := chFaults.(*chunksmodels.CFMissingRegisterTouch)
assert.True(s.T(), ok)
}
// TestMissingRegisterTouchForRead tests verification given a chunkdatapack missing a register touch (read)
func (s *ChunkVerifierTestSuite) TestMissingRegisterTouchForRead() {
s.T().Skip("Check new partial ledger for missing keys")
vch := GetBaselineVerifiableChunk(s.T(), "")
assert.NotNil(s.T(), vch)
// remove the second register touch
//vch.ChunkDataPack.RegisterTouches = vch.ChunkDataPack.RegisterTouches[1:]
spockSecret, chFaults, err := s.verifier.Verify(vch)
assert.Nil(s.T(), err)
assert.NotNil(s.T(), chFaults)
assert.Nil(s.T(), spockSecret)
_, ok := chFaults.(*chunksmodels.CFMissingRegisterTouch)
assert.True(s.T(), ok)
}
// TestWrongEndState tests verification covering the case
// the state commitment computed after updating the partial trie
// doesn't match the one provided by the chunks
func (s *ChunkVerifierTestSuite) TestWrongEndState() {
vch := GetBaselineVerifiableChunk(s.T(), "wrongEndState")
assert.NotNil(s.T(), vch)
spockSecret, chFaults, err := s.verifier.Verify(vch)
assert.Nil(s.T(), err)
assert.NotNil(s.T(), chFaults)
assert.Nil(s.T(), spockSecret)
_, ok := chFaults.(*chunksmodels.CFNonMatchingFinalState)
assert.True(s.T(), ok)
}
// TestFailedTx tests verification behavior in case
// of failed transaction. if a transaction fails, it should
// still change the state commitment.
func (s *ChunkVerifierTestSuite) TestFailedTx() {
vch := GetBaselineVerifiableChunk(s.T(), "failedTx")
assert.NotNil(s.T(), vch)
spockSecret, chFaults, err := s.verifier.Verify(vch)
assert.Nil(s.T(), err)
assert.Nil(s.T(), chFaults)
assert.NotNil(s.T(), spockSecret)
}
// TestEventsMismatch tests verification behavior in case
// of emitted events not matching chunks
func (s *ChunkVerifierTestSuite) TestEventsMismatch() {
vch := GetBaselineVerifiableChunk(s.T(), "eventsMismatch")
assert.NotNil(s.T(), vch)
_, chFault, err := s.verifier.Verify(vch)
assert.Nil(s.T(), err)
assert.NotNil(s.T(), chFault)
assert.IsType(s.T(), &chunksmodels.CFInvalidEventsCollection{}, chFault)
}
// TestVerifyWrongChunkType evaluates that following invocations return an error:
// - verifying a system chunk with Verify method.
// - verifying a non-system chunk with SystemChunkVerify method.
func (s *ChunkVerifierTestSuite) TestVerifyWrongChunkType() {
// defines verifiable chunk for a system chunk
svc := &verification.VerifiableChunkData{
IsSystemChunk: true,
}
// invoking Verify method with system chunk should return an error
_, _, err := s.verifier.Verify(svc)
require.Error(s.T(), err)
// defines verifiable chunk for a non-system chunk
vc := &verification.VerifiableChunkData{
IsSystemChunk: false,
}
// invoking SystemChunkVerify method with a non-system chunk should return an error
_, _, err = s.verifier.SystemChunkVerify(vc)
require.Error(s.T(), err)
}
// TestEmptyCollection tests verification behaviour if a
// collection doesn't have any transaction.
func (s *ChunkVerifierTestSuite) TestEmptyCollection() {
vch := GetBaselineVerifiableChunk(s.T(), "")
assert.NotNil(s.T(), vch)
col := unittest.CollectionFixture(0)
vch.Collection = &col
vch.EndState = vch.ChunkDataPack.StartState
emptyListHash, _ := flow.EventsList{}.Hash()
vch.Chunk.EventCollection = emptyListHash //empty collection emits no events
spockSecret, chFaults, err := s.verifier.Verify(vch)
assert.Nil(s.T(), err)
assert.Nil(s.T(), chFaults)
assert.NotNil(s.T(), spockSecret)
}
// GetBaselineVerifiableChunk returns a verifiable chunk and sets the script
// of a transaction in the middle of the collection to some value to signal the
// mocked vm on what to return as tx exec outcome.
func GetBaselineVerifiableChunk(t *testing.T, script string) *verification.VerifiableChunkData {
// Collection setup
collectionSize := 5
magicTxIndex := 3
coll := unittest.CollectionFixture(collectionSize)
coll.Transactions[magicTxIndex] = &flow.TransactionBody{Script: []byte(script)}
guarantee := coll.Guarantee()
// Block setup
payload := flow.Payload{
Guarantees: []*flow.CollectionGuarantee{&guarantee},
}
header := unittest.BlockHeaderFixture()
header.PayloadHash = payload.Hash()
block := flow.Block{
Header: &header,
Payload: &payload,
}
blockID := block.ID()
// registerTouch and State setup
id1 := flow.NewRegisterID("00", "", "")
value1 := []byte{'a'}
id2Bytes := make([]byte, 32)
id2Bytes[0] = byte(5)
id2 := flow.NewRegisterID("05", "", "")
value2 := []byte{'b'}
UpdatedValue2 := []byte{'B'}
ids := make([]flow.RegisterID, 0)
values := make([]flow.RegisterValue, 0)
ids = append(ids, id1, id2)
values = append(values, value1, value2)
var verifiableChunkData verification.VerifiableChunkData
metricsCollector := &metrics.NoopCollector{}
f, _ := completeLedger.NewLedger(&fixtures.NoopWAL{}, 1000, metricsCollector, zerolog.Nop(), completeLedger.DefaultPathFinderVersion)
keys := executionState.RegisterIDSToKeys(ids)
update, err := ledger.NewUpdate(
f.InitialState(),
keys,
executionState.RegisterValuesToValues(values),
)
require.NoError(t, err)
startState, err := f.Set(update)
require.NoError(t, err)
query, err := ledger.NewQuery(startState, keys)
require.NoError(t, err)
proof, err := f.Prove(query)
require.NoError(t, err)
ids = []flow.RegisterID{id2}
values = [][]byte{UpdatedValue2}
keys = executionState.RegisterIDSToKeys(ids)
update, err = ledger.NewUpdate(
startState,
keys,
executionState.RegisterValuesToValues(values),
)
require.NoError(t, err)
endState, err := f.Set(update)
require.NoError(t, err)
// events
chunkEvents := make(flow.EventsList, 0)
for i := 0; i < collectionSize; i++ {
if i == magicTxIndex {
switch script {
case "failedTx":
continue
}
}
chunkEvents = append(chunkEvents, eventsList...)
}
eventsListHash, err := chunkEvents.Hash()
require.NoError(t, err)
// Chunk setup
chunk := flow.Chunk{
ChunkBody: flow.ChunkBody{
CollectionIndex: 0,
StartState: flow.StateCommitment(startState),
BlockID: blockID,
EventCollection: eventsListHash,
},
Index: 0,
}
chunkDataPack := flow.ChunkDataPack{
ChunkID: chunk.ID(),
StartState: flow.StateCommitment(startState),
Proof: proof,
}
// ExecutionResult setup
result := flow.ExecutionResult{
BlockID: blockID,
Chunks: flow.ChunkList{&chunk},
}
verifiableChunkData = verification.VerifiableChunkData{
IsSystemChunk: false,
Chunk: &chunk,
Header: &header,
Result: &result,
Collection: &coll,
ChunkDataPack: &chunkDataPack,
EndState: flow.StateCommitment(endState),
}
return &verifiableChunkData
}
type vmMock struct{}
func (vm *vmMock) Run(ctx fvm.Context, proc fvm.Procedure, led state.View, programs *programs.Programs) error {
tx, ok := proc.(*fvm.TransactionProcedure)
if !ok {
return fmt.Errorf("invokable is not a transaction")
}
switch string(tx.Transaction.Script) {
case "wrongEndState":
// add updates to the ledger
_ = led.Set("00", "", "", []byte{'F'})
tx.Logs = []string{"log1", "log2"}
tx.Events = eventsList
case "failedTx":
// add updates to the ledger
_ = led.Set("05", "", "", []byte{'B'})
tx.Err = &fvmErrors.CadenceRuntimeError{} // inside the runtime (e.g. div by zero, access account)
case "eventsMismatch":
tx.Events = append(eventsList, flow.Event{
Type: "event.Extra",
TransactionID: flow.Identifier{2, 3},
TransactionIndex: 0,
EventIndex: 0,
Payload: []byte{88},
})
default:
_, _ = led.Get("00", "", "")
_, _ = led.Get("05", "", "")
_ = led.Set("05", "", "", []byte{'B'})
tx.Logs = []string{"log1", "log2"}
tx.Events = eventsList
}
return nil
}