Debian Codegraph @

msp/msp.go

raw symbols SCIP
1 package msp
2
3 import (
4 "container/heap"
5 "crypto/rand"
6 "errors"
7 "fmt"
8 "strings"
9 )
10
11 // A UserDatabase is an abstraction over the name -> share map returned by the
12 // secret splitter that allows an application to only decrypt or request shares
13 // when needed, rather than re-build a partial map of known data.
14 type UserDatabase interface {
15 ValidUser(name string) bool
16 CanGetShare(name string) bool
17 GetShare(name string) ([][]byte, error)
18 }
19
20 type Condition interface { // Represents one condition in a predicate
21 Ok(UserDatabase) bool
22 }
23
24 type Name struct { // Type of condition
25 string
26 index int
27 }
28
29 func (n Name) Ok(db UserDatabase) bool {
30 return db.CanGetShare(n.string)
31 }
32
33 type TraceElem struct {
34 loc int
35 names []string
36 trace []string
37 }
38
39 type TraceSlice []TraceElem
40
41 func (ts TraceSlice) Len() int { return len(ts) }
42 func (ts TraceSlice) Swap(i, j int) { ts[i], ts[j] = ts[j], ts[i] }
43
44 func (ts TraceSlice) Less(i, j int) bool {
45 return len(ts[i].trace) > len(ts[j].trace)
46 }
47
48 func (ts *TraceSlice) Push(te interface{}) { *ts = append(*ts, te.(TraceElem)) }
49 func (ts *TraceSlice) Pop() interface{} {
50 old := *ts
51 n := len(old)
52
53 *ts = old[0 : n-1]
54 out := old[n-1]
55
56 return out
57 }
58
59 // Compact takes a trace slice and merges all of its fields.
60 //
61 // index: Union of all locations in the slice.
62 // names: Union of all names in the slice.
63 // trace: Union of all the traces in the slice.
64 func (ts TraceSlice) Compact() (index []int, names []string, trace []string) {
65 for _, te := range ts {
66 index = append(index, te.loc)
67 names = append(names, te.names...)
68 trace = append(trace, te.trace...)
69 }
70
71 // This is a QuickSort related algorithm. It makes all the names in the trace unique so we don't double-count people.
72 //
73 // Invariant: There are no duplicates in trace[0:ptr]
74 // Algorithm: Advance ptr by 1 and enforce the invariant.
75 ptr, cutoff := 0, len(trace)
76
77 TopLoop:
78 for ptr < cutoff { // Choose the next un-checked element of the slice.
79 for i := 0; i < ptr; i++ { // Compare it to all elements before it.
80 if trace[i] == trace[ptr] { // If we find a duplicate...
81 trace[ptr], trace[cutoff-1] = trace[cutoff-1], trace[ptr] // Push the dup to the end of the surviving slice.
82 cutoff-- // Mark it for removal.
83
84 continue TopLoop // Because trace[ptr] has been mutated, try to verify the invariant again w/o advancing ptr.
85 }
86 }
87
88 ptr++ // There are no duplicates; move the ptr forward and start again.
89 }
90 trace = trace[0:cutoff]
91
92 return
93 }
94
95 type MSP Formatted
96
97 func StringToMSP(pred string) (m MSP, err error) {
98 var f Formatted
99
100 if -1 == strings.Index(pred, ",") {
101 var r Raw
102 r, err = StringToRaw(pred)
103 if err != nil {
104 return
105 }
106
107 f = r.Formatted()
108 } else {
109 f, err = StringToFormatted(pred)
110 if err != nil {
111 return
112 }
113 }
114
115 return MSP(f), nil
116 }
117
118 // DerivePath returns the cheapest way to satisfy the MSP (the one with the minimal number of delegations).
119 //
120 // ok: True if the MSP can be satisfied with current delegations; false if not.
121 // names: The names in the top-level threshold gate that need to be delegated.
122 // locs: The index in the treshold gate for each name.
123 // trace: All names that must be delegated for for this gate to be satisfied.
124 func (m MSP) DerivePath(db UserDatabase) (ok bool, names []string, locs []int, trace []string) {
125 ts := &TraceSlice{}
126
127 for i, cond := range m.Conds {
128 switch cond := cond.(type) {
129 case Name:
130 if db.CanGetShare(cond.string) {
131 heap.Push(ts, TraceElem{
132 i,
133 []string{cond.string},
134 []string{cond.string},
135 })
136 }
137
138 case Formatted:
139 sok, _, _, strace := MSP(cond).DerivePath(db)
140 if sok {
141 heap.Push(ts, TraceElem{i, []string{}, strace})
142 }
143 }
144
145 if (*ts).Len() > m.Min { // If we can otherwise satisfy the threshold gate
146 heap.Pop(ts) // Drop the TraceElem with the heaviest trace (the one that requires the most delegations).
147 }
148 }
149
150 ok = (*ts).Len() >= m.Min
151 locs, names, trace = ts.Compact()
152 return
153 }
154
155 // DistributeShares takes as input a secret and a user database and returns secret shares according to access structure
156 // described by the MSP.
157 func (m MSP) DistributeShares(sec []byte, db UserDatabase) (map[string][][]byte, error) {
158 out := make(map[string][][]byte)
159
160 // Generate a Vandermonde matrix.
161 height, width := len(m.Conds), m.Min
162 M := Matrix(make([]Row, height))
163
164 for i := 0; i < height; i++ {
165 M[i] = NewRow(width)
166
167 for j := 0; j < width; j++ {
168 M[i][j][0] = byte(i + 1)
169 M[i][j] = M[i][j].Exp(j)
170 }
171 }
172
173 // Convert secret vector.
174 s := NewRow(width)
175 s[0] = FieldElem(sec)
176
177 for i := 1; i < width; i++ {
178 r := NewFieldElem()
179 rand.Read(r)
180
181 s[i] = FieldElem(r)
182 }
183
184 // Calculate shares.
185 shares := M.Mul(s)
186
187 // Distribute the shares.
188 for i, cond := range m.Conds {
189 share := shares[i]
190
191 switch cond := cond.(type) {
192 case Name:
193 name := cond.string
194 if !db.ValidUser(name) {
195 return nil, fmt.Errorf("Unknown user '%s' in predicate.", name)
196 }
197
198 out[name] = append(out[name], share)
199 case Formatted:
200 below := MSP(cond)
201 subOut, err := below.DistributeShares(share, db)
202 if err != nil {
203 return out, err
204 }
205
206 for name, shares := range subOut {
207 out[name] = append(out[name], shares...)
208 }
209 }
210 }
211
212 return out, nil
213 }
214
215 // ErrNotEnoughShares is returned if there aren't enough shares to
216 // decrypt the secret.
217 var ErrNotEnoughShares = errors.New("not enough shares to recover")
218
219 // RecoverSecret takes a user database storing secret shares as input and returns the original secret.
220 func (m MSP) RecoverSecret(db UserDatabase) ([]byte, error) {
221 cache := make(map[string][][]byte, 0) // Caches un-used shares for a user.
222 return m.recoverSecret(db, cache)
223 }
224
225 func (m MSP) recoverSecret(db UserDatabase, cache map[string][][]byte) ([]byte, error) {
226 var (
227 index = []int{} // Indexes where given shares were in the matrix.
228 shares = []FieldElem{} // Contains shares that will be used in reconstruction.
229 )
230
231 ok, names, locs, _ := m.DerivePath(db)
232 if !ok {
233 return nil, ErrNotEnoughShares
234 }
235
236 for _, name := range names {
237 if _, cached := cache[name]; !cached {
238 out, err := db.GetShare(name)
239 if err != nil {
240 return nil, err
241 }
242
243 cache[name] = out
244 }
245 }
246
247 for _, loc := range locs {
248 gate := m.Conds[loc]
249 index = append(index, loc+1)
250
251 switch gate := gate.(type) {
252 case Name:
253 if len(cache[gate.string]) <= gate.index {
254 return nil, errors.New("Predicate / database mismatch!")
255 }
256
257 shares = append(shares, FieldElem(cache[gate.string][gate.index]))
258
259 case Formatted:
260 share, err := MSP(gate).recoverSecret(db, cache)
261 if err != nil {
262 return nil, err
263 }
264
265 shares = append(shares, FieldElem(share))
266 }
267 }
268
269 // Generate the Vandermonde matrix specific to whichever users' shares we're using.
270 MSub := Matrix(make([]Row, m.Min))
271
272 for i := 0; i < m.Min; i++ {
273 MSub[i] = NewRow(m.Min)
274
275 for j := 0; j < m.Min; j++ {
276 MSub[i][j][0] = byte(index[i])
277 MSub[i][j] = MSub[i][j].Exp(j)
278 }
279 }
280
281 // Calculate the reconstruction vector and use it to recover the secret.
282 r, ok := MSub.Recovery()
283 if !ok {
284 return nil, errors.New("Unable to find a reconstruction vector!")
285 }
286
287 // Compute dot product of the shares vector and the reconstruction vector to
288 // recover the secret.
289 s := Row(shares).DotProduct(r)
290
291 return []byte(s), nil
292 }