forked from celestiaorg/rsmt2d
-
Notifications
You must be signed in to change notification settings - Fork 0
/
infectiousRSGF8.go
89 lines (70 loc) · 1.82 KB
/
infectiousRSGF8.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
package rsmt2d
import (
"github.com/vivint/infectious"
)
var _ Codec = &rsGF8Codec{}
func init() {
registerCodec("RSGF8", NewRSGF8Codec())
}
type rsGF8Codec struct {
infectiousCache map[int]*infectious.FEC
}
// NewRSGF8Codec issues a new cached RSGF8Codec
func NewRSGF8Codec() *rsGF8Codec {
return &rsGF8Codec{make(map[int]*infectious.FEC)}
}
func (c *rsGF8Codec) Encode(data [][]byte) ([][]byte, error) {
var fec *infectious.FEC
var err error
// Set up caches.
if value, ok := c.infectiousCache[len(data)]; ok {
fec = value
} else {
fec, err = infectious.NewFEC(len(data), len(data)*2)
if err != nil {
return nil, err
}
c.infectiousCache[len(data)] = fec
}
shares := make([][]byte, len(data))
output := func(s infectious.Share) {
if s.Number >= len(data) {
shareData := make([]byte, len(s.Data))
copy(shareData, s.Data)
shares[s.Number-len(data)] = shareData
}
}
flattened := flattenChunks(data)
err = fec.Encode(flattened, output)
return shares, err
}
func (c *rsGF8Codec) Decode(data [][]byte) ([][]byte, error) {
var fec *infectious.FEC
var err error
// Set up caches.
if value, ok := c.infectiousCache[len(data)/2]; ok {
fec = value
} else {
fec, err = infectious.NewFEC(len(data)/2, len(data))
if err != nil {
return nil, err
}
c.infectiousCache[len(data)/2] = fec
}
rebuiltShares := make([][]byte, len(data)/2)
rebuiltSharesOutput := func(s infectious.Share) {
rebuiltShares[s.Number] = s.DeepCopy().Data
}
shares := []infectious.Share{}
for i, d := range data {
if d != nil {
shares = append(shares, infectious.Share{Number: i, Data: d})
}
}
err = fec.Rebuild(shares, rebuiltSharesOutput)
return rebuiltShares, err
}
// maxChunks returns the max. number of chunks each code supports in a 2D square.
func (c *rsGF8Codec) maxChunks() int {
return 128 * 128
}