forked from celestiaorg/rsmt2d
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extendeddatacrossword.go
416 lines (362 loc) · 10.3 KB
/
extendeddatacrossword.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
package rsmt2d
import (
"bytes"
"errors"
"fmt"
"math"
)
const (
row = iota
col
)
// ErrUnrepairableDataSquare is thrown when there is insufficient chunks to repair the square.
var ErrUnrepairableDataSquare = errors.New("failed to solve data square")
// ErrByzantineRow is thrown when a repaired row does not match the expected row Merkle root.
type ErrByzantineRow struct {
RowNumber uint // Row index
Shares [][]byte // Pre-repaired row shares. Missing shares are nil.
}
func (e *ErrByzantineRow) Error() string {
return fmt.Sprintf("byzantine row: %d", e.RowNumber)
}
// ErrByzantineCol is thrown when a repaired column does not match the expected column Merkle root.
type ErrByzantineCol struct {
ColNumber uint // Column index
Shares [][]byte // Pre-repaired column shares. Missing shares are nil.
}
func (e *ErrByzantineCol) Error() string {
return fmt.Sprintf("byzantine column: %d", e.ColNumber)
}
// RepairExtendedDataSquare attempts to repair an incomplete extended data
// square (EDS), comparing repaired rows and columns against expected Merkle
// roots.
//
// Input
//
// Missing shares must be nil.
//
// Output
//
// The EDS is modified in-place. If repairing is successful, the EDS will be
// complete. If repairing is unsuccessful, the EDS will be the most-repaired
// prior to the Byzantine row or column being repaired, and the Byzantine row
// or column prior to repair is returned in the error with missing shares as
// nil.
func RepairExtendedDataSquare(
rowRoots [][]byte,
colRoots [][]byte,
data [][]byte,
codec Codec,
treeCreatorFn TreeConstructorFn,
) (*ExtendedDataSquare, error) {
width := int(math.Ceil(math.Sqrt(float64(len(data)))))
bitMat := newBitMatrix(width)
var chunkSize int
for i := range data {
if data[i] != nil {
bitMat.SetFlat(i)
if chunkSize == 0 {
chunkSize = len(data[i])
}
}
}
if chunkSize == 0 {
return nil, ErrUnrepairableDataSquare
}
fillerChunk := bytes.Repeat([]byte{0}, chunkSize)
for i := range data {
if data[i] == nil {
data[i] = make([]byte, chunkSize)
copy(data[i], fillerChunk)
}
}
eds, err := ImportExtendedDataSquare(data, codec, treeCreatorFn)
if err != nil {
return nil, err
}
err = eds.prerepairSanityCheck(rowRoots, colRoots, bitMat, codec)
if err != nil {
return nil, err
}
err = eds.solveCrossword(rowRoots, colRoots, bitMat, codec)
if err != nil {
return nil, err
}
return eds, err
}
// solveCrossword attempts to iteratively repair an EDS.
func (eds *ExtendedDataSquare) solveCrossword(
rowRoots [][]byte,
colRoots [][]byte,
bitMask bitMatrix,
codec Codec,
) error {
// Keep repeating until the square is solved
for {
// Track if the entire square is completely solved
solved := true
// Track if a single iteration of this loop made progress
progressMade := false
// Loop through every row and column, attempt to rebuild each row or column if incomplete
for i := 0; i < int(eds.width); i++ {
solvedRow, progressMadeRow, err := eds.solveCrosswordRow(i, rowRoots, colRoots, bitMask, codec)
if err != nil {
return err
}
solvedCol, progressMadeCol, err := eds.solveCrosswordCol(i, rowRoots, colRoots, bitMask, codec)
if err != nil {
return err
}
solved = solved && solvedRow && solvedCol
progressMade = progressMade || progressMadeRow || progressMadeCol
}
if solved {
break
}
if !progressMade {
return ErrUnrepairableDataSquare
}
}
return nil
}
// solveCrosswordRow attempts to repair a single row.
// Returns
// - if the row is solved (i.e. complete)
// - if the row was previously unsolved and now solved
// - an error if the repair is unsuccessful
func (eds *ExtendedDataSquare) solveCrosswordRow(
r int,
rowRoots [][]byte,
colRoots [][]byte,
bitMask bitMatrix,
codec Codec,
) (bool, bool, error) {
isComplete := bitMask.RowIsOne(r)
if isComplete {
return true, false, nil
}
// Prepare shares
shares := make([][]byte, eds.width)
for c := 0; c < int(eds.width); c++ {
vectorData := eds.row(uint(r))
if bitMask.Get(r, c) {
// As guaranteed by the bitMask, vectorData can't be nil here:
shares[c] = vectorData[c]
}
}
isExtendedPartIncomplete := !bitMask.RowRangeIsOne(r, int(eds.originalDataWidth), int(eds.width))
// Attempt rebuild
rebuiltShares, isDecoded, err := eds.rebuildShares(isExtendedPartIncomplete, shares, codec)
if err != nil {
return false, false, err
}
if !isDecoded {
return false, false, nil
}
// Check that rebuilt shares matches appropriate root
err = eds.verifyAgainstRowRoots(rowRoots, uint(r), bitMask, rebuiltShares)
if err != nil {
return false, false, err
}
// Check that newly completed orthogonal vectors match their new merkle roots
for c := 0; c < int(eds.width); c++ {
if !bitMask.Get(r, c) &&
bitMask.ColIsOne(c) {
err := eds.verifyAgainstColRoots(colRoots, uint(c), bitMask, rebuiltShares)
if err != nil {
return false, false, err
}
}
}
// Set vector mask to true
for c := 0; c < int(eds.width); c++ {
bitMask.Set(r, c)
}
// Insert rebuilt shares into square.
for c, s := range rebuiltShares {
eds.setCell(uint(r), uint(c), s)
}
return true, true, nil
}
// solveCrosswordCol attempts to repair a single column.
// Returns
// - if the column is solved (i.e. complete)
// - if the column was previously unsolved and now solved
// - an error if the repair is unsuccessful
func (eds *ExtendedDataSquare) solveCrosswordCol(
c int,
rowRoots [][]byte,
colRoots [][]byte,
bitMask bitMatrix,
codec Codec,
) (bool, bool, error) {
isComplete := bitMask.ColIsOne(c)
if isComplete {
return true, false, nil
}
// Prepare shares
shares := make([][]byte, eds.width)
for r := 0; r < int(eds.width); r++ {
vectorData := eds.col(uint(c))
if bitMask.Get(r, c) {
// As guaranteed by the bitMask, vectorData can't be nil here:
shares[r] = vectorData[r]
}
}
isExtendedPartIncomplete := !bitMask.ColRangeIsOne(c, int(eds.originalDataWidth), int(eds.width))
// Attempt rebuild
rebuiltShares, isDecoded, err := eds.rebuildShares(isExtendedPartIncomplete, shares, codec)
if err != nil {
return false, false, err
}
if !isDecoded {
return false, false, nil
}
// Check that rebuilt shares matches appropriate root
err = eds.verifyAgainstColRoots(colRoots, uint(c), bitMask, rebuiltShares)
if err != nil {
return false, false, err
}
// Check that newly completed orthogonal vectors match their new merkle roots
for r := 0; r < int(eds.width); r++ {
if !bitMask.Get(r, c) &&
bitMask.RowIsOne(r) {
err := eds.verifyAgainstRowRoots(rowRoots, uint(r), bitMask, rebuiltShares)
if err != nil {
return false, false, err
}
}
}
// Set vector mask to true
for r := 0; r < int(eds.width); r++ {
bitMask.Set(r, c)
}
// Insert rebuilt shares into square.
for r, s := range rebuiltShares {
eds.setCell(uint(r), uint(c), s)
}
return true, true, nil
}
func (eds *ExtendedDataSquare) rebuildShares(
isExtendedPartIncomplete bool,
shares [][]byte,
codec Codec,
) ([][]byte, bool, error) {
rebuiltShares, err := codec.Decode(shares)
if err != nil {
// repair unsuccessful
return nil, false, nil
}
if isExtendedPartIncomplete {
// If needed, rebuild the parity shares too.
rebuiltExtendedShares, err := codec.Encode(rebuiltShares[0:eds.originalDataWidth])
if err != nil {
return nil, true, err
}
startIndex := len(rebuiltExtendedShares) - int(eds.originalDataWidth)
rebuiltShares = append(
rebuiltShares[0:eds.originalDataWidth],
rebuiltExtendedShares[startIndex:]...,
)
} else {
// Otherwise copy them from the EDS.
startIndex := len(shares) - int(eds.originalDataWidth)
rebuiltShares = append(
rebuiltShares[0:eds.originalDataWidth],
shares[startIndex:]...,
)
}
return rebuiltShares, true, nil
}
func (eds *ExtendedDataSquare) verifyAgainstRowRoots(
rowRoots [][]byte,
r uint,
bitMask bitMatrix,
shares [][]byte,
) error {
root := eds.computeSharesRoot(shares, r)
if !bytes.Equal(root, rowRoots[r]) {
for c := 0; c < int(eds.width); c++ {
if !bitMask.Get(int(r), c) {
shares[c] = nil
}
}
return &ErrByzantineRow{r, shares}
}
return nil
}
func (eds *ExtendedDataSquare) verifyAgainstColRoots(
colRoots [][]byte,
c uint, bitMask bitMatrix,
shares [][]byte,
) error {
root := eds.computeSharesRoot(shares, c)
if !bytes.Equal(root, colRoots[c]) {
for r := 0; r < int(eds.width); r++ {
if !bitMask.Get(r, int(c)) {
shares[r] = nil
}
}
return &ErrByzantineCol{c, shares}
}
return nil
}
func (eds *ExtendedDataSquare) prerepairSanityCheck(
rowRoots [][]byte,
colRoots [][]byte,
bitMask bitMatrix,
codec Codec,
) error {
for i := uint(0); i < eds.width; i++ {
rowIsComplete := bitMask.RowIsOne(int(i))
colIsComplete := bitMask.ColIsOne(int(i))
// if there's no missing data in the this row
if noMissingData(eds.row(i)) {
// ensure that the roots are equal and that rowMask is a vector
if rowIsComplete && !bytes.Equal(rowRoots[i], eds.getRowRoot(i)) {
return fmt.Errorf("bad root input: row %d expected %v got %v", i, rowRoots[i], eds.getRowRoot(i))
}
}
// if there's no missing data in the this col
if noMissingData(eds.col(i)) {
// ensure that the roots are equal and that rowMask is a vector
if colIsComplete && !bytes.Equal(colRoots[i], eds.getColRoot(i)) {
return fmt.Errorf("bad root input: col %d expected %v got %v", i, colRoots[i], eds.getColRoot(i))
}
}
if rowIsComplete {
parityShares, err := codec.Encode(eds.rowSlice(i, 0, eds.originalDataWidth))
if err != nil {
return err
}
if !bytes.Equal(flattenChunks(parityShares), flattenChunks(eds.rowSlice(i, eds.originalDataWidth, eds.originalDataWidth))) {
return &ErrByzantineRow{i, eds.row(i)}
}
}
if colIsComplete {
parityShares, err := codec.Encode(eds.colSlice(0, i, eds.originalDataWidth))
if err != nil {
return err
}
if !bytes.Equal(flattenChunks(parityShares), flattenChunks(eds.colSlice(eds.originalDataWidth, i, eds.originalDataWidth))) {
return &ErrByzantineCol{i, eds.col(i)}
}
}
}
return nil
}
func noMissingData(input [][]byte) bool {
for _, d := range input {
if d == nil {
return false
}
}
return true
}
func (eds *ExtendedDataSquare) computeSharesRoot(shares [][]byte, i uint) []byte {
tree := eds.createTreeFn()
for cell, d := range shares {
tree.Push(d, SquareIndex{Cell: uint(cell), Axis: i})
}
return tree.Root()
}