-
Notifications
You must be signed in to change notification settings - Fork 14
/
dict.go
434 lines (365 loc) · 11 KB
/
dict.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
// Package dict implements dictionary and run-length addition chain algorithms.
package dict
import (
"errors"
"fmt"
"math/big"
"sort"
"github.com/mmcloughlin/addchain"
"github.com/mmcloughlin/addchain/alg"
"github.com/mmcloughlin/addchain/internal/bigint"
"github.com/mmcloughlin/addchain/internal/bigints"
"github.com/mmcloughlin/addchain/internal/bigvector"
)
// References:
//
// [braueraddsubchains] Martin Otto. Brauer addition-subtraction chains. PhD thesis, Universitat
// Paderborn. 2001.
// http://www.martin-otto.de/publications/docs/2001_MartinOtto_Diplom_BrauerAddition-SubtractionChains.pdf
// [genshortchains] Kunihiro, Noboru and Yamamoto, Hirosuke. New Methods for Generating Short
// Addition Chains. IEICE Transactions on Fundamentals of Electronics
// Communications and Computer Sciences. 2000.
// https://pdfs.semanticscholar.org/b398/d10faca35af9ce5a6026458b251fd0a5640c.pdf
// [hehcc:exp] Christophe Doche. Exponentiation. Handbook of Elliptic and Hyperelliptic Curve
// Cryptography, chapter 9. 2006.
// http://koclab.cs.ucsb.edu/teaching/ecc/eccPapers/Doche-ch09.pdf
// Term represents the integer D * 2ᴱ.
type Term struct {
D *big.Int
E uint
}
// Int converts the term to an integer.
func (t Term) Int() *big.Int {
return new(big.Int).Lsh(t.D, t.E)
}
// Sum is the representation of an integer as a sum of dictionary terms. See
// [hehcc:exp] definition 9.34.
type Sum []Term
// Int computes the dictionary sum as an integer.
func (s Sum) Int() *big.Int {
x := bigint.Zero()
for _, t := range s {
x.Add(x, t.Int())
}
return x
}
// SortByExponent sorts terms in ascending order of the exponent E.
func (s Sum) SortByExponent() {
sort.Slice(s, func(i, j int) bool { return s[i].E < s[j].E })
}
// Dictionary returns the distinct D values in the terms of this sum. The values
// are returned in ascending order.
func (s Sum) Dictionary() []*big.Int {
dict := make([]*big.Int, 0, len(s))
for _, t := range s {
dict = append(dict, t.D)
}
bigints.Sort(dict)
return bigints.Unique(dict)
}
// Decomposer is a method of breaking an integer into a dictionary sum.
type Decomposer interface {
Decompose(x *big.Int) Sum
String() string
}
// FixedWindow breaks integers into k-bit windows.
type FixedWindow struct {
K uint // Window size.
}
func (w FixedWindow) String() string { return fmt.Sprintf("fixed_window(%d)", w.K) }
// Decompose represents x in terms of k-bit windows from left to right.
func (w FixedWindow) Decompose(x *big.Int) Sum {
sum := Sum{}
h := x.BitLen()
for h > 0 {
l := max(h-int(w.K), 0)
d := bigint.Extract(x, uint(l), uint(h))
if bigint.IsNonZero(d) {
sum = append(sum, Term{D: d, E: uint(l)})
}
h = l
}
sum.SortByExponent()
return sum
}
// SlidingWindow breaks integers into k-bit windows, skipping runs of zeros
// where possible. See [hehcc:exp] section 9.1.3 or [braueraddsubchains] section
// 1.2.3.
type SlidingWindow struct {
K uint // Window size.
}
func (w SlidingWindow) String() string { return fmt.Sprintf("sliding_window(%d)", w.K) }
// Decompose represents x in base 2ᵏ.
func (w SlidingWindow) Decompose(x *big.Int) Sum {
sum := Sum{}
h := x.BitLen() - 1
for h >= 0 {
// Find first 1.
for h >= 0 && x.Bit(h) == 0 {
h--
}
if h < 0 {
break
}
// Look down k positions.
l := max(h-int(w.K)+1, 0)
// Advance to the next 1.
for x.Bit(l) == 0 {
l++
}
sum = append(sum, Term{
D: bigint.Extract(x, uint(l), uint(h+1)),
E: uint(l),
})
h = l - 1
}
sum.SortByExponent()
return sum
}
// RunLength decomposes integers in to runs of 1s up to a maximal length. See
// [genshortchains] Section 3.1.
type RunLength struct {
T uint // Maximal run length. Zero means no limit.
}
func (r RunLength) String() string { return fmt.Sprintf("run_length(%d)", r.T) }
// Decompose breaks x into runs of 1 bits.
func (r RunLength) Decompose(x *big.Int) Sum {
sum := Sum{}
i := x.BitLen() - 1
for i >= 0 {
// Find first 1.
for i >= 0 && x.Bit(i) == 0 {
i--
}
if i < 0 {
break
}
// Look for the end of the run.
s := i
for i >= 0 && x.Bit(i) == 1 && (r.T == 0 || uint(s-i) < r.T) {
i--
}
// We have a run from s to i+1.
sum = append(sum, Term{
D: bigint.Ones(uint(s - i)),
E: uint(i + 1),
})
}
sum.SortByExponent()
return sum
}
// Hybrid is a mix of the sliding window and run length decomposition methods,
// similar to the "Hybrid Method" of [genshortchains] Section 3.3.
type Hybrid struct {
K uint // Window size.
T uint // Maximal run length. Zero means no limit.
}
func (h Hybrid) String() string { return fmt.Sprintf("hybrid(%d,%d)", h.K, h.T) }
// Decompose breaks x into k-bit sliding windows or runs of 1s up to length T.
func (h Hybrid) Decompose(x *big.Int) Sum {
sum := Sum{}
// Clone since we'll be modifying it.
y := bigint.Clone(x)
// Process runs of length at least K.
i := y.BitLen() - 1
for i >= 0 {
// Find first 1.
for i >= 0 && y.Bit(i) == 0 {
i--
}
if i < 0 {
break
}
// Look for the end of the run.
s := i
for i >= 0 && y.Bit(i) == 1 && (h.T == 0 || uint(s-i) < h.T) {
i--
}
// We have a run from s to i+1. Skip it if its short.
n := uint(s - i)
if n <= h.K {
continue
}
// Add it to the sum and remove it from the integer.
sum = append(sum, Term{
D: bigint.Ones(n),
E: uint(i + 1),
})
y.Xor(y, bigint.Mask(uint(i+1), uint(s+1)))
}
// Process what remains with a sliding window.
w := SlidingWindow{K: h.K}
rem := w.Decompose(y)
sum = append(sum, rem...)
sum.SortByExponent()
return sum
}
// Algorithm implements a general dictionary-based chain construction algorithm,
// as in [braueraddsubchains] Algorithm 1.26. This operates in three stages:
// decompose the target into a sum of dictionray terms, use a sequence algorithm
// to generate the dictionary, then construct the target from the dictionary
// terms.
type Algorithm struct {
decomp Decomposer
seqalg alg.SequenceAlgorithm
}
// NewAlgorithm builds a dictionary algorithm that breaks up integers using the
// decomposer d and uses the sequence algorithm s to generate dictionary
// entries.
func NewAlgorithm(d Decomposer, a alg.SequenceAlgorithm) *Algorithm {
return &Algorithm{
decomp: d,
seqalg: a,
}
}
func (a Algorithm) String() string {
return fmt.Sprintf("dictionary(%s,%s)", a.decomp, a.seqalg)
}
// FindChain builds an addition chain producing n. This works by using the
// configured Decomposer to represent n as a sum of dictionary terms, then
// delegating to the SequenceAlgorithm to build a chain producing the
// dictionary, and finally using the dictionary terms to construct n. See
// [genshortchains] Section 2 for a full description.
func (a Algorithm) FindChain(n *big.Int) (addchain.Chain, error) {
// Decompose the target.
sum := a.decomp.Decompose(n)
sum.SortByExponent()
// Extract dictionary.
dict := sum.Dictionary()
// Use the sequence algorithm to produce a chain for each element of the dictionary.
c, err := a.seqalg.FindSequence(dict)
if err != nil {
return nil, err
}
// Reduce.
sum, c, err = primitive(sum, c)
if err != nil {
return nil, err
}
// Build chain for n out of the dictionary.
dc := dictsumchain(sum)
c = append(c, dc...)
bigints.Sort(c)
c = addchain.Chain(bigints.Unique(c))
return c, nil
}
// dictsumchain builds a chain for the integer represented by sum, assuming that
// all the terms of the sum are already present. Therefore this is intended to
// be appended to a chain that already contains the dictionary terms.
func dictsumchain(sum Sum) addchain.Chain {
c := addchain.Chain{}
k := len(sum) - 1
cur := bigint.Clone(sum[k].D)
for ; k > 0; k-- {
// Shift until the next exponent.
for i := sum[k].E; i > sum[k-1].E; i-- {
cur.Lsh(cur, 1)
c.AppendClone(cur)
}
// Add in the dictionary term at this position.
cur.Add(cur, sum[k-1].D)
c.AppendClone(cur)
}
for i := sum[0].E; i > 0; i-- {
cur.Lsh(cur, 1)
c.AppendClone(cur)
}
return c
}
// primitive removes terms from the dictionary that are only required once.
//
// The general structure of dictionary based algorithm is to decompose the
// target into a sum of dictionary terms, then create a chain for the
// dictionary, and then create the target from that. In a case where a
// dictionary term is only required once in the target, this can cause extra
// work. In such a case, we will spend operations on creating the dictionary
// term independently, and then later add it into the result. Since it is only
// needed once, we can effectively construct the dictionary term "on the fly" as
// we build up the final target.
//
// This function looks for such opportunities. If it finds them it will produce
// an alternative dictionary sum that replaces that term with a sum of smaller
// terms.
func primitive(sum Sum, c addchain.Chain) (Sum, addchain.Chain, error) {
// This optimization cannot apply if the sum has only one term.
if len(sum) == 1 {
return sum, c, nil
}
n := len(c)
// We'll need a mapping from chain elements to where they appear in the chain.
idx := map[string]int{}
for i, x := range c {
idx[x.String()] = i
}
// Build program for the chain.
p, err := c.Program()
if err != nil {
return nil, nil, err
}
// How many times is each index read during construction, and during its use in the dictionary chain.
reads := p.ReadCounts()
for _, t := range sum {
i := idx[t.D.String()]
reads[i]++
}
// Now, the primitive dictionary elements are those that are read at least twice, and their dependencies.
deps := p.Dependencies()
primitive := make([]bool, n)
for i, numreads := range reads {
if numreads < 2 {
continue
}
primitive[i] = true
for _, j := range bigint.BitsSet(deps[i]) {
primitive[j] = true
}
}
// Express every position in the chain as a linear combination of dictionary
// terms that are used more than once.
vc := []bigvector.Vector{bigvector.NewBasis(n, 0)}
for i, op := range p {
var next bigvector.Vector
if primitive[i+1] {
next = bigvector.NewBasis(n, i+1)
} else {
next = bigvector.Add(vc[op.I], vc[op.J])
}
vc = append(vc, next)
}
// Now express the target sum in terms that are used more than once.
v := bigvector.New(n)
for _, t := range sum {
i := idx[t.D.String()]
v = bigvector.Add(v, bigvector.Lsh(vc[i], t.E))
}
// Rebuild this into a dictionary sum.
out := Sum{}
for i := 0; i < v.Len(); i++ {
for _, e := range bigint.BitsSet(v.Idx(i)) {
out = append(out, Term{
D: c[i],
E: uint(e),
})
}
}
out.SortByExponent()
// We should have not changed the sum.
if !bigint.Equal(out.Int(), sum.Int()) {
return nil, nil, errors.New("reconstruction does not match")
}
// Prune any elements of the chain that are used only once.
pruned := addchain.Chain{}
for i, x := range c {
if primitive[i] {
pruned = append(pruned, x)
}
}
return out, pruned, nil
}
// max returns the maximum of a and b.
func max(a, b int) int {
if a > b {
return a
}
return b
}