-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth256.go
More file actions
663 lines (602 loc) · 20.1 KB
/
Copy pathauth256.go
File metadata and controls
663 lines (602 loc) · 20.1 KB
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
package itb
import (
"crypto/rand"
"encoding/binary"
"fmt"
"math"
"runtime"
"sync"
)
// EncryptAuthenticated3x256Cfg encrypts data with integrity using
// Triple Ouroboros (256-bit variant). Threads cfg through every
// Cfg-aware accessor in the authenticated pipeline. Includes the
// part2-reserves-tag layout and the MAC-over-concatenated-payloads
// invariant. nil cfg falls back to the compile-in defaults.
func EncryptAuthenticated3x256Cfg(cfg *Config, noiseSeed, lockSeed, dataSeed1, dataSeed2, dataSeed3, startSeed1, startSeed2, startSeed3 *Seed256, data []byte, macFunc MACFunc) ([]byte, error) {
if err := checkEightSeeds256(noiseSeed, lockSeed, dataSeed1, dataSeed2, dataSeed3, startSeed1, startSeed2, startSeed3); err != nil {
return nil, err
}
if len(data) == 0 {
return nil, ErrEmptyInput
}
if macFunc == nil {
return nil, fmt.Errorf("itb: macFunc must not be nil")
}
if len(data) > maxDataSize {
return nil, fmt.Errorf("itb: data too large: %d bytes (max %d)", len(data), maxDataSize)
}
if err := validateConfigCfg(cfg); err != nil {
return nil, err
}
tagSize := len(macFunc([]byte{}))
if tagSize == 0 {
return nil, fmt.Errorf("itb: macFunc returned empty tag")
}
nonce, ilNonce, err := generateNoncePairCfg(cfg)
if err != nil {
return nil, err
}
p0, p1, p2 := splitForTriple48LockedCfg(cfg, data, buildLockBatchPRF48_256Cfg(cfg, lockSeed, ilNonce))
// Phase 1: 3 parallel cobsEncode
var encs [3][]byte
{
parts := [3][]byte{p0, p1, p2}
var wg sync.WaitGroup
wg.Add(3)
for i := 0; i < 3; i++ {
go func(i int) {
defer wg.Done()
encs[i] = cobsEncode(parts[i])
}(i)
}
wg.Wait()
}
// part2 COBS length increased by tagSize + 1 for container sizing:
// the +1 mirrors the Streaming AEAD flag-byte slot so the single
// message wire envelope matches the No MAC Encrypt3x envelope
// (which reserves nomacTagStubSizeCfg(cfg) = tagSize + 1 for the
// same mode-ambiguity reason — the zero-value default covers the
// shipped 32-byte tags, and Config.TagStubSize carries a
// custom MAC's tag length). Single messages carry a fixed 0x00 in
// that slot — there is no finalFlag semantic on this path.
cobsLens := [3]int{len(encs[0]), len(encs[1]), len(encs[2]) + tagSize + 1}
width, height := containerSizeAuth3_256Cfg(cfg, noiseSeed, dataSeed1, dataSeed2, dataSeed3, startSeed1, startSeed2, startSeed3, cobsLens)
totalPixels := width * height
third := totalPixels / 3
thirdPixels2 := totalPixels - 2*third
caps := [3]int{
(third * DataBitsPerPixel) / 8,
(third * DataBitsPerPixel) / 8,
(thirdPixels2 * DataBitsPerPixel) / 8,
}
payloadLens := [3]int{caps[0], caps[1], caps[2] - tagSize - 1}
for i := 0; i < 3; i++ {
if len(encs[i])+1 > payloadLens[i] {
return nil, fmt.Errorf("itb: internal error: container third %d too small", i)
}
}
// Build payloads: part0 and part1 full capacity, part2 reserves
// tagSize + 1 (tag slot + fixed 0x00 dummy flag slot).
// Phase 2: 3 parallel payload-build
var payloadPtrs [3]*[]byte
payloads := [3][]byte{}
defer func() {
for i := range payloadPtrs {
if payloadPtrs[i] != nil {
releaseBuffer(payloadPtrs[i], payloads[i])
}
}
}()
{
var errs [3]error
var wg sync.WaitGroup
wg.Add(3)
for i := 0; i < 3; i++ {
go func(i int) {
defer wg.Done()
payloadPtrs[i], payloads[i] = acquireBuffer(payloadLens[i])
copy(payloads[i], encs[i])
payloads[i][len(encs[i])] = 0x00
fillStart := len(encs[i]) + 1
if fillStart < payloadLens[i] {
fillBytes, err := generateRandomBytes(payloadLens[i] - fillStart)
if err != nil {
errs[i] = err
return
}
copy(payloads[i][fillStart:], fillBytes)
}
}(i)
}
wg.Wait()
for _, err := range errs {
if err != nil {
return nil, err
}
}
}
// MAC over concatenated payloads (covers all fill bytes)
tag := macTagCfg(cfg, macFunc, payloads[0], payloads[1], payloads[2])
// full2 = payload2 || tag || 0x00 (single-message dummy flag slot)
full2Ptr, full2 := acquireBuffer(caps[2])
defer releaseBuffer(full2Ptr, full2)
copy(full2, payloads[2])
copy(full2[len(payloads[2]):], tag)
full2[len(payloads[2])+tagSize] = 0x00
// 3×CSPRNG parallel generation
container := make([]byte, totalPixels*Channels)
var wg sync.WaitGroup
var randErr [3]error
wg.Add(3)
go func() { _, randErr[0] = rand.Read(container[0 : third*Channels]); wg.Done() }()
go func() { _, randErr[1] = rand.Read(container[third*Channels : 2*third*Channels]); wg.Done() }()
go func() { _, randErr[2] = rand.Read(container[2*third*Channels : totalPixels*Channels]); wg.Done() }()
wg.Wait()
for _, err := range randErr {
if err != nil {
return nil, fmt.Errorf("itb: crypto/rand: %w", err)
}
}
perThird := runtime.NumCPU() / 3
if perThird < 1 {
perThird = 1
}
offset1 := third * Channels
offset2 := 2 * third * Channels
wg.Add(3)
go func() {
process256Cfg(cfg, noiseSeed, dataSeed1, startSeed1, nonce, container[0:offset1], third, 1, payloads[0], true, perThird)
wg.Done()
}()
go func() {
process256Cfg(cfg, noiseSeed, dataSeed2, startSeed2, nonce, container[offset1:offset2], third, 1, payloads[1], true, perThird)
wg.Done()
}()
go func() {
process256Cfg(cfg, noiseSeed, dataSeed3, startSeed3, nonce, container[offset2:totalPixels*Channels], thirdPixels2, 1, full2, true, perThird)
wg.Done()
}()
wg.Wait()
out := make([]byte, 0, headerSizeCfg(cfg)+len(container))
out = append(out, nonce...)
out = append(out, ilNonce...)
var dim [4]byte
binary.BigEndian.PutUint16(dim[0:], uint16(width))
binary.BigEndian.PutUint16(dim[2:], uint16(height))
out = append(out, dim[:]...)
out = append(out, container...)
return out, nil
}
// DecryptAuthenticated3x256Cfg is the inverse of
// [EncryptAuthenticated3x256Cfg]. nil cfg falls back to the
// compile-in defaults.
func DecryptAuthenticated3x256Cfg(cfg *Config, noiseSeed, lockSeed, dataSeed1, dataSeed2, dataSeed3, startSeed1, startSeed2, startSeed3 *Seed256, fileData []byte, macFunc MACFunc) ([]byte, error) {
if err := checkEightSeeds256(noiseSeed, lockSeed, dataSeed1, dataSeed2, dataSeed3, startSeed1, startSeed2, startSeed3); err != nil {
return nil, err
}
if macFunc == nil {
return nil, fmt.Errorf("itb: macFunc must not be nil")
}
tagSize := len(macFunc([]byte{}))
if tagSize == 0 {
return nil, fmt.Errorf("itb: macFunc returned empty tag")
}
if len(fileData) == 0 {
return nil, ErrEmptyInput
}
if len(fileData) < headerSizeCfg(cfg)+Channels {
return nil, fmt.Errorf("itb: data too short")
}
nonceLen := currentNonceSizeCfg(cfg)
nonce := fileData[:nonceLen]
ilNonce := fileData[nonceLen : 2*nonceLen]
width := int(binary.BigEndian.Uint16(fileData[2*nonceLen:]))
height := int(binary.BigEndian.Uint16(fileData[2*nonceLen+2:]))
container := fileData[headerSizeCfg(cfg):]
if width == 0 || height == 0 {
return nil, fmt.Errorf("itb: invalid dimensions %dx%d", width, height)
}
if width > math.MaxInt/height {
return nil, fmt.Errorf("itb: container dimensions %dx%d overflow int", width, height)
}
totalPixels := width * height
if totalPixels > math.MaxInt/Channels {
return nil, fmt.Errorf("itb: container too large for this platform: %d pixels", totalPixels)
}
if totalPixels > maxTotalPixels {
return nil, fmt.Errorf("itb: container too large: %d pixels exceeds maximum %d", totalPixels, maxTotalPixels)
}
expectedSize := totalPixels * Channels
if len(container) < expectedSize {
return nil, fmt.Errorf("itb: container too short: got %d, need %d", len(container), expectedSize)
}
third := totalPixels / 3
thirdPixels2 := totalPixels - 2*third
caps := [3]int{
(third * DataBitsPerPixel) / 8,
(third * DataBitsPerPixel) / 8,
(thirdPixels2 * DataBitsPerPixel) / 8,
}
if caps[2] <= tagSize+1 {
return nil, fmt.Errorf("itb: container too small for MAC tag")
}
var decodedPtrs [3]*[]byte
decoded := [3][]byte{}
defer func() {
for i := range decodedPtrs {
if decodedPtrs[i] != nil {
releaseBuffer(decodedPtrs[i], decoded[i])
}
}
}()
for i := 0; i < 3; i++ {
decodedPtrs[i], decoded[i] = acquireBuffer(caps[i])
}
perThird := runtime.NumCPU() / 3
if perThird < 1 {
perThird = 1
}
offset1 := third * Channels
offset2 := 2 * third * Channels
var wg sync.WaitGroup
wg.Add(3)
go func() {
process256Cfg(cfg, noiseSeed, dataSeed1, startSeed1, nonce, container[0:offset1], third, 1, decoded[0], false, perThird)
wg.Done()
}()
go func() {
process256Cfg(cfg, noiseSeed, dataSeed2, startSeed2, nonce, container[offset1:offset2], third, 1, decoded[1], false, perThird)
wg.Done()
}()
go func() {
process256Cfg(cfg, noiseSeed, dataSeed3, startSeed3, nonce, container[offset2:totalPixels*Channels], thirdPixels2, 1, decoded[2], false, perThird)
wg.Done()
}()
wg.Wait()
// Split part2 into payload || tag || dummy-flag-byte. The trailing
// byte carries a fixed 0x00 on the encrypt side and is discarded
// here; the null-search skips well before it (the COBS terminator
// lives ahead of the tag region).
payloadLen2 := caps[2] - tagSize - 1
payload2 := decoded[2][:payloadLen2]
tag := decoded[2][payloadLen2 : payloadLen2+tagSize]
// Verify MAC over concatenated payloads
expected := macTagCfg(cfg, macFunc, decoded[0], decoded[1], payload2)
if !constantTimeEqual(tag, expected) {
return nil, ErrMACFailure
}
// 3 parallel null-search + cobsDecode (MAC already verified data integrity)
parts := [3][]byte{}
{
decs := [][]byte{decoded[0], decoded[1], payload2}
var errs [3]error
var wg sync.WaitGroup
wg.Add(3)
for i := 0; i < 3; i++ {
go func(i int) {
defer wg.Done()
dec := decs[i]
nullPos := -1
for j := 0; j < len(dec); j++ {
if dec[j] == 0x00 && nullPos == -1 {
nullPos = j
}
}
if nullPos <= 0 {
errs[i] = fmt.Errorf("itb: no terminator found in third %d", i)
return
}
parts[i] = cobsDecode(dec[:nullPos])
}(i)
}
wg.Wait()
for _, err := range errs {
if err != nil {
return nil, err
}
}
}
return interleaveForTriple48LockedCfg(cfg, parts[0], parts[1], parts[2], buildLockBatchPRF48_256Cfg(cfg, lockSeed, ilNonce)), nil
}
// EncryptStreamAuthenticated3x256Cfg encrypts a single Streaming AEAD
// chunk under Triple Ouroboros with 8 seeds (256-bit variant).
// Threads cfg through every
// Cfg-aware accessor in the Triple Ouroboros Streaming AEAD pipeline.
// Body otherwise identical, including the part2-reserves-tag-and-flag
// layout and the MAC-over-concatenated-payloads-plus-binding invariant.
func EncryptStreamAuthenticated3x256Cfg(cfg *Config, noiseSeed, lockSeed, dataSeed1, dataSeed2, dataSeed3, startSeed1, startSeed2, startSeed3 *Seed256, data []byte, macFunc MACFunc, streamID [32]byte, cumulativePixelOffset uint64, finalFlag bool) ([]byte, error) {
if err := checkEightSeeds256(noiseSeed, lockSeed, dataSeed1, dataSeed2, dataSeed3, startSeed1, startSeed2, startSeed3); err != nil {
return nil, err
}
if len(data) == 0 && !finalFlag {
return nil, ErrEmptyInput
}
if macFunc == nil {
return nil, fmt.Errorf("itb: macFunc must not be nil")
}
if len(data) > maxDataSize {
return nil, fmt.Errorf("itb: data too large: %d bytes (max %d)", len(data), maxDataSize)
}
if err := validateConfigCfg(cfg); err != nil {
return nil, err
}
tagSize := len(macFunc([]byte{}))
if tagSize == 0 {
return nil, fmt.Errorf("itb: macFunc returned empty tag")
}
nonce, ilNonce, err := generateNoncePairCfg(cfg)
if err != nil {
return nil, err
}
p0, p1, p2 := splitForTriple48LockedCfg(cfg, data, buildLockBatchPRF48_256Cfg(cfg, lockSeed, ilNonce))
// Phase 1: 3 parallel cobsEncode
var encs [3][]byte
{
parts := [3][]byte{p0, p1, p2}
var wg sync.WaitGroup
wg.Add(3)
for i := 0; i < 3; i++ {
go func(i int) {
defer wg.Done()
encs[i] = cobsEncode(parts[i])
}(i)
}
wg.Wait()
}
// part2 COBS length increased by tagSize + 1 (flag byte) for container sizing
cobsLens := [3]int{len(encs[0]), len(encs[1]), len(encs[2]) + tagSize + 1}
width, height := containerSizeAuth3_256Cfg(cfg, noiseSeed, dataSeed1, dataSeed2, dataSeed3, startSeed1, startSeed2, startSeed3, cobsLens)
totalPixels := width * height
third := totalPixels / 3
thirdPixels2 := totalPixels - 2*third
caps := [3]int{
(third * DataBitsPerPixel) / 8,
(third * DataBitsPerPixel) / 8,
(thirdPixels2 * DataBitsPerPixel) / 8,
}
payloadLens := [3]int{caps[0], caps[1], caps[2] - tagSize - 1}
for i := 0; i < 3; i++ {
if len(encs[i])+1 > payloadLens[i] {
return nil, fmt.Errorf("itb: internal error: container third %d too small", i)
}
}
// Build payloads: part0 and part1 full capacity, part2 reserves tagSize + 1 (flag)
// Phase 2: 3 parallel payload-build
var payloadPtrs [3]*[]byte
payloads := [3][]byte{}
defer func() {
for i := range payloadPtrs {
if payloadPtrs[i] != nil {
releaseBuffer(payloadPtrs[i], payloads[i])
}
}
}()
{
var errs [3]error
var wg sync.WaitGroup
wg.Add(3)
for i := 0; i < 3; i++ {
go func(i int) {
defer wg.Done()
payloadPtrs[i], payloads[i] = acquireBuffer(payloadLens[i])
copy(payloads[i], encs[i])
payloads[i][len(encs[i])] = 0x00
fillStart := len(encs[i]) + 1
if fillStart < payloadLens[i] {
fillBytes, err := generateRandomBytes(payloadLens[i] - fillStart)
if err != nil {
errs[i] = err
return
}
copy(payloads[i][fillStart:], fillBytes)
}
}(i)
}
wg.Wait()
for _, err := range errs {
if err != nil {
return nil, err
}
}
}
// MAC over concatenated payloads || streamID || uint64_le(offset) || flag
flag := streamFlagByte(finalFlag)
var offsetLE [8]byte
binary.LittleEndian.PutUint64(offsetLE[:], cumulativePixelOffset)
tag := macTagCfg(cfg, macFunc,
payloads[0], payloads[1], payloads[2], streamID[:], offsetLE[:], []byte{flag})
// full2 = payload2 || tag || flag
full2Ptr, full2 := acquireBuffer(caps[2])
defer releaseBuffer(full2Ptr, full2)
copy(full2, payloads[2])
copy(full2[len(payloads[2]):], tag)
full2[len(payloads[2])+tagSize] = flag
// 3×CSPRNG parallel generation
container := make([]byte, totalPixels*Channels)
var wg sync.WaitGroup
var randErr [3]error
wg.Add(3)
go func() { _, randErr[0] = rand.Read(container[0 : third*Channels]); wg.Done() }()
go func() { _, randErr[1] = rand.Read(container[third*Channels : 2*third*Channels]); wg.Done() }()
go func() { _, randErr[2] = rand.Read(container[2*third*Channels : totalPixels*Channels]); wg.Done() }()
wg.Wait()
for _, err := range randErr {
if err != nil {
return nil, fmt.Errorf("itb: crypto/rand: %w", err)
}
}
perThird := runtime.NumCPU() / 3
if perThird < 1 {
perThird = 1
}
offset1 := third * Channels
offset2 := 2 * third * Channels
wg.Add(3)
go func() {
process256Cfg(cfg, noiseSeed, dataSeed1, startSeed1, nonce, container[0:offset1], third, 1, payloads[0], true, perThird)
wg.Done()
}()
go func() {
process256Cfg(cfg, noiseSeed, dataSeed2, startSeed2, nonce, container[offset1:offset2], third, 1, payloads[1], true, perThird)
wg.Done()
}()
go func() {
process256Cfg(cfg, noiseSeed, dataSeed3, startSeed3, nonce, container[offset2:totalPixels*Channels], thirdPixels2, 1, full2, true, perThird)
wg.Done()
}()
wg.Wait()
out := make([]byte, 0, headerSizeCfg(cfg)+len(container))
out = append(out, nonce...)
out = append(out, ilNonce...)
var dim [4]byte
binary.BigEndian.PutUint16(dim[0:], uint16(width))
binary.BigEndian.PutUint16(dim[2:], uint16(height))
out = append(out, dim[:]...)
out = append(out, container...)
return out, nil
}
// DecryptStreamAuthenticated3x256Cfg is the inverse of
// [EncryptStreamAuthenticated3x256Cfg]. nil cfg falls back to the
// compile-in defaults.
func DecryptStreamAuthenticated3x256Cfg(cfg *Config, noiseSeed, lockSeed, dataSeed1, dataSeed2, dataSeed3, startSeed1, startSeed2, startSeed3 *Seed256, chunkData []byte, macFunc MACFunc, streamID [32]byte, cumulativePixelOffset uint64) ([]byte, bool, error) {
if err := checkEightSeeds256(noiseSeed, lockSeed, dataSeed1, dataSeed2, dataSeed3, startSeed1, startSeed2, startSeed3); err != nil {
return nil, false, err
}
if macFunc == nil {
return nil, false, fmt.Errorf("itb: macFunc must not be nil")
}
tagSize := len(macFunc([]byte{}))
if tagSize == 0 {
return nil, false, fmt.Errorf("itb: macFunc returned empty tag")
}
if len(chunkData) == 0 {
return nil, false, ErrEmptyInput
}
if len(chunkData) < headerSizeCfg(cfg)+Channels {
return nil, false, fmt.Errorf("itb: data too short")
}
nonceLen := currentNonceSizeCfg(cfg)
nonce := chunkData[:nonceLen]
ilNonce := chunkData[nonceLen : 2*nonceLen]
width := int(binary.BigEndian.Uint16(chunkData[2*nonceLen:]))
height := int(binary.BigEndian.Uint16(chunkData[2*nonceLen+2:]))
container := chunkData[headerSizeCfg(cfg):]
if width == 0 || height == 0 {
return nil, false, fmt.Errorf("itb: invalid dimensions %dx%d", width, height)
}
if width > math.MaxInt/height {
return nil, false, fmt.Errorf("itb: container dimensions %dx%d overflow int", width, height)
}
totalPixels := width * height
if totalPixels > math.MaxInt/Channels {
return nil, false, fmt.Errorf("itb: container too large for this platform: %d pixels", totalPixels)
}
if totalPixels > maxTotalPixels {
return nil, false, fmt.Errorf("itb: container too large: %d pixels exceeds maximum %d", totalPixels, maxTotalPixels)
}
expectedSize := totalPixels * Channels
if len(container) < expectedSize {
return nil, false, fmt.Errorf("itb: container too short: got %d, need %d", len(container), expectedSize)
}
third := totalPixels / 3
thirdPixels2 := totalPixels - 2*third
caps := [3]int{
(third * DataBitsPerPixel) / 8,
(third * DataBitsPerPixel) / 8,
(thirdPixels2 * DataBitsPerPixel) / 8,
}
if caps[2] <= tagSize+1 {
return nil, false, fmt.Errorf("itb: container too small for MAC tag")
}
var decodedPtrs [3]*[]byte
decoded := [3][]byte{}
defer func() {
for i := range decodedPtrs {
if decodedPtrs[i] != nil {
releaseBuffer(decodedPtrs[i], decoded[i])
}
}
}()
for i := 0; i < 3; i++ {
decodedPtrs[i], decoded[i] = acquireBuffer(caps[i])
}
perThird := runtime.NumCPU() / 3
if perThird < 1 {
perThird = 1
}
offset1 := third * Channels
offset2 := 2 * third * Channels
var wg sync.WaitGroup
wg.Add(3)
go func() {
process256Cfg(cfg, noiseSeed, dataSeed1, startSeed1, nonce, container[0:offset1], third, 1, decoded[0], false, perThird)
wg.Done()
}()
go func() {
process256Cfg(cfg, noiseSeed, dataSeed2, startSeed2, nonce, container[offset1:offset2], third, 1, decoded[1], false, perThird)
wg.Done()
}()
go func() {
process256Cfg(cfg, noiseSeed, dataSeed3, startSeed3, nonce, container[offset2:totalPixels*Channels], thirdPixels2, 1, decoded[2], false, perThird)
wg.Done()
}()
wg.Wait()
// Split part2 into payload || tag || flag
payloadLen2 := caps[2] - tagSize - 1
payload2 := decoded[2][:payloadLen2]
tag := decoded[2][payloadLen2 : payloadLen2+tagSize]
flag := decoded[2][payloadLen2+tagSize]
// Verify MAC over concatenated payloads || streamID || uint64_le(offset) || flag
var offsetLE [8]byte
binary.LittleEndian.PutUint64(offsetLE[:], cumulativePixelOffset)
expected := macTagCfg(cfg, macFunc,
decoded[0], decoded[1], payload2, streamID[:], offsetLE[:], []byte{flag})
if !constantTimeEqual(tag, expected) {
return nil, false, ErrMACFailure
}
finalFlag := flag == 0xFF
// 3 parallel null-search + cobsDecode (MAC already verified data integrity)
parts := [3][]byte{}
emptyThird := [3]bool{}
{
decs := [][]byte{decoded[0], decoded[1], payload2}
var errs [3]error
var wg sync.WaitGroup
wg.Add(3)
for i := 0; i < 3; i++ {
go func(i int) {
defer wg.Done()
dec := decs[i]
nullPos := -1
for j := 0; j < len(dec); j++ {
if dec[j] == 0x00 && nullPos == -1 {
nullPos = j
}
}
if nullPos < 0 {
errs[i] = fmt.Errorf("itb: no terminator found in third %d", i)
return
}
if nullPos == 0 {
if !finalFlag {
errs[i] = fmt.Errorf("itb: no terminator found in third %d", i)
return
}
emptyThird[i] = true
return
}
parts[i] = cobsDecode(dec[:nullPos])
}(i)
}
wg.Wait()
for _, err := range errs {
if err != nil {
return nil, false, err
}
}
}
if emptyThird[0] && emptyThird[1] && emptyThird[2] {
return []byte{}, true, nil
}
return interleaveForTriple48LockedCfg(cfg, parts[0], parts[1], parts[2], buildLockBatchPRF48_256Cfg(cfg, lockSeed, ilNonce)), finalFlag, nil
}