miden-validator 0.17.6

Miden validator
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
//! Tests exercising the administration endpoints end to end.

use axum::Json;
use axum::body::{Body, to_bytes};
use axum::extract::{Path, Query, State};
use axum::http::{Request, StatusCode};
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use golden_ehtdh1::wire::{from_wire_bytes, to_wire_bytes};
use golden_ehtdh1::{Ciphertext, Combiner, DecryptionShare};
use golden_halo2curves::golden_group::Secp256k1GoldenGroup;
use miden_protocol::Word;
use miden_protocol::account::auth::AuthScheme;
use miden_protocol::block::BlockHeader;
use miden_protocol::crypto::dsa::ecdsa_k256_keccak::SigningKey;
use miden_protocol::protocol_config::ProtocolConfig;
use miden_protocol::transaction::{TransactionId, TransactionInputs};
use miden_protocol::utils::serde::{Deserializable, Serializable};
use miden_testing::{Auth, MockChainBuilder};
use rand_chacha_03::ChaCha20Rng;
use rand_chacha_03::rand_core::SeedableRng;
use tower::ServiceExt;

use super::error::ApiError;
use super::get_transaction::get_validated_private_transaction;
use super::issue_decryption_share::{
    IssueDecryptionShareRequest,
    IssueDecryptionShareResponse,
    issue_decryption_share,
};
use super::list_transactions::{
    ListTransactionsQuery,
    ListValidatedPrivateTransactionsResponse,
    MAX_PAGE_LIMIT,
    MAX_RECORD_PAGE_LIMIT,
    list_validated_private_transactions,
};
use super::{ISSUE_SHARE_PATH, LIST_TRANSACTIONS_PATH, ValidatorAdminService, router};
use crate::db::{ValidatorDbReader, ValidatorDbWriter, block_with_header};
use crate::storage_key::tests::operator_keys;
use crate::{
    GoldenOperatorKey,
    PrivateRecordChainId,
    PrivateRecordCombiner,
    PrivateRecordContext,
    PrivateRecordError,
    PrivateRecordId,
    PrivateRecordSealer,
    PrivateRecordShareRequest,
    StorageKeyEpoch,
    StoredPrivateRecord,
};

fn target_record(
    operator_key: &GoldenOperatorKey,
    transaction_id: TransactionId,
    seed: u8,
    plaintext: &[u8],
) -> StoredPrivateRecord {
    let signer = SigningKey::read_from_bytes(&[9; 32]).unwrap();
    let record_id = PrivateRecordId::new(transaction_id, &signer.public_key());
    let context = PrivateRecordContext::new(
        PrivateRecordChainId::new([7; 32]),
        operator_key.key_epoch(),
        transaction_id,
    );
    PrivateRecordSealer::from_operator_key(operator_key)
        .seal(&mut ChaCha20Rng::from_seed([seed; 32]), record_id, context, plaintext)
        .unwrap()
}

fn transaction_inputs() -> TransactionInputs {
    let mut builder = MockChainBuilder::new();
    let account = builder
        .add_existing_wallet(Auth::BasicAuth {
            auth_scheme: AuthScheme::Falcon512Poseidon2,
        })
        .unwrap();
    builder.build().unwrap().get_transaction_inputs(&account, &[], &[]).unwrap()
}

async fn test_database() -> (tempfile::TempDir, ValidatorDbWriter, ValidatorDbReader) {
    let directory = tempfile::tempdir().unwrap();
    let writer = crate::db::setup(directory.path().join("validator.sqlite3")).await.unwrap();
    let reader = writer.reader();
    (directory, writer, reader)
}

fn share_request(record: &StoredPrivateRecord) -> IssueDecryptionShareRequest {
    IssueDecryptionShareRequest {
        ciphertext: hex::encode(record.encrypted_record_key()),
        decryption_context: hex::encode(record.context().to_bytes()),
    }
}

async fn issue(
    service: &ValidatorAdminService,
    request: IssueDecryptionShareRequest,
) -> Result<IssueDecryptionShareResponse, ApiError> {
    issue_decryption_share(State(service.clone()), Json(request))
        .await
        .map(|Json(response)| response)
}

async fn list(
    service: &ValidatorAdminService,
    query: ListTransactionsQuery,
) -> Result<ListValidatedPrivateTransactionsResponse, ApiError> {
    list_validated_private_transactions(State(service.clone()), Query(query))
        .await
        .map(|Json(response)| response)
}

/// Commits `transactions`, in that order, in a signed block at `block_num`. Only committed
/// transactions are listed, so listing tests have to place their records in a block.
async fn commit(writer: &ValidatorDbWriter, block_num: u32, transactions: &[TransactionId]) {
    writer
        .insert_signed_block(
            block_with_header(BlockHeader::mock(block_num, None, None, &[])),
            ProtocolConfig::mock(),
            transactions.to_vec(),
        )
        .await
        .unwrap();
}

#[tokio::test]
async fn listed_record_drives_threshold_recovery() {
    let mut keys = operator_keys();
    let record_owner = keys.pop().unwrap();
    let second = keys.pop().unwrap();
    let first = keys.pop().unwrap();
    let public_key_set = record_owner.public_key_set().clone();
    let setup_context = record_owner.setup_context().clone();
    let (_directory, writer, reader) = test_database().await;
    let first_service = ValidatorAdminService::new(first, reader.clone());
    let second_service = ValidatorAdminService::new(second, reader);
    let inputs = transaction_inputs();
    let transaction_id = TransactionId::from_raw(Word::from([8u32, 7, 6, 5]));
    let record = target_record(&record_owner, transaction_id, 10, &inputs.to_bytes());
    writer.insert_validated_private_transaction(record.clone()).await.unwrap();
    commit(&writer, 4, &[transaction_id]).await;

    let response = list(
        &first_service,
        ListTransactionsQuery {
            include_records: true,
            ..ListTransactionsQuery::default()
        },
    )
    .await
    .unwrap();
    let [listed] = response.transactions.as_slice() else {
        panic!("expected one listed transaction");
    };
    assert_eq!(listed.transaction_id, hex::encode(transaction_id.to_bytes()));
    assert_eq!((listed.block_num, listed.block_tx_index), (4, 0));
    assert_eq!(listed.key_epoch, hex::encode(record.context().key_epoch().as_bytes()));
    assert_eq!(listed.setup_context_id, hex::encode(record.setup_context_id()));
    let payload = listed.record.as_ref().expect("include_records must attach the record");
    assert_eq!(payload.final_ciphertext, hex::encode(record.encrypted_record()));
    assert_eq!(payload.cipher_nonce, hex::encode(record.nonce()));
    assert_eq!(payload.encrypted_record_key, hex::encode(record.encrypted_record_key()));
    assert_eq!(payload.decryption_context, hex::encode(record.context().to_bytes()));

    let request = share_request(&record);
    let share_bytes = [
        issue(&first_service, request.clone()).await.unwrap().decryption_share,
        issue(&second_service, request).await.unwrap().decryption_share,
    ];
    let ciphertext: Ciphertext<Secp256k1GoldenGroup> =
        from_wire_bytes(record.encrypted_record_key()).unwrap();
    let shares = share_bytes
        .iter()
        .map(|share| {
            let bytes = hex::decode(share).unwrap();
            from_wire_bytes::<DecryptionShare<Secp256k1GoldenGroup>>(&bytes).unwrap()
        })
        .collect::<Vec<_>>();
    let context = record.context().to_bytes();
    let content_key = Combiner::new(public_key_set, setup_context)
        .unwrap()
        .combine_exact_with_associated_data(&ciphertext, &context, &context, &shares)
        .unwrap();
    let plaintext = XChaCha20Poly1305::new_from_slice(&content_key)
        .unwrap()
        .decrypt(
            &XNonce::from(*record.nonce()),
            Payload {
                msg: record.encrypted_record(),
                aad: &context,
            },
        )
        .unwrap();

    assert_eq!(TransactionInputs::read_from_bytes(&plaintext).unwrap(), inputs);
}

/// Metadata-only listing (the default) omits the sealed record payload entirely.
#[tokio::test]
async fn list_returns_metadata_only_by_default() {
    let mut keys = operator_keys();
    let (_directory, writer, reader) = test_database().await;
    let transaction_id = TransactionId::from_raw(Word::from([3u32, 0, 0, 0]));
    let record = target_record(&keys[0], transaction_id, 21, b"record");
    writer.insert_validated_private_transaction(record).await.unwrap();
    commit(&writer, 1, &[transaction_id]).await;

    let service = ValidatorAdminService::new(keys.remove(0), reader);
    let response = list(&service, ListTransactionsQuery::default()).await.unwrap();
    let [listed] = response.transactions.as_slice() else {
        panic!("expected one listed transaction");
    };
    assert_eq!(listed.transaction_id, hex::encode(transaction_id.to_bytes()));
    assert!(listed.record.is_none());
}

/// A validated transaction that is not in a signed block is not listed, but is still retrievable by
/// id.
#[tokio::test]
async fn list_omits_uncommitted_transactions() {
    let mut keys = operator_keys();
    let (_directory, writer, reader) = test_database().await;
    let transaction_id = TransactionId::from_raw(Word::from([4u32, 0, 0, 0]));
    let record = target_record(&keys[0], transaction_id, 23, b"record");
    writer.insert_validated_private_transaction(record).await.unwrap();
    let service = ValidatorAdminService::new(keys.remove(0), reader);

    let response = list(&service, ListTransactionsQuery::default()).await.unwrap();
    assert!(response.transactions.is_empty());
    assert_eq!(response.pagination.block_num, None);

    let Json(fetched) = get_validated_private_transaction(
        State(service),
        Path(hex::encode(transaction_id.to_bytes())),
    )
    .await
    .unwrap();
    assert_eq!(fetched.transaction_id, hex::encode(transaction_id.to_bytes()));
}

/// A paged sweep returns committed rows in committed order, honoring the row limit exactly, and
/// terminates with an empty page reporting no position. A block range restricts results to the rows
/// committed in range.
#[tokio::test]
async fn list_pages_in_committed_order_and_filters_by_block_range() {
    let mut keys = operator_keys();
    let (_directory, writer, reader) = test_database().await;
    let transaction_ids = (1u64..=5)
        .map(|i| TransactionId::from_raw(Word::try_from([i, i, i, i]).unwrap()))
        .collect::<Vec<_>>();
    for (seed, transaction_id) in (31u8..=35).zip(&transaction_ids) {
        let record = target_record(&keys[0], *transaction_id, seed, b"record");
        writer.insert_validated_private_transaction(record).await.unwrap();
    }
    // Blocks 1 and 2 include two transactions each; the fifth is never committed. Block 1 includes
    // a later insertion first, to prove committed order wins over insertion order.
    commit(&writer, 1, &[transaction_ids[3], transaction_ids[0]]).await;
    commit(&writer, 2, &[transaction_ids[1], transaction_ids[2]]).await;
    let service = ValidatorAdminService::new(keys.remove(0), reader);
    let expected_sweep = [
        (transaction_ids[3], 1, 0),
        (transaction_ids[0], 1, 1),
        (transaction_ids[1], 2, 0),
        (transaction_ids[2], 2, 1),
    ]
    .map(|(id, block_num, index)| (hex::encode(id.to_bytes()), block_num, index));

    // Sweep asking for a single row per page: each page returns exactly one row, and the next page
    // is the same request resumed one position past the row just reported.
    let mut swept = Vec::new();
    let mut block_from = None;
    let mut tx_index_from = None;
    loop {
        let response = list(
            &service,
            ListTransactionsQuery {
                block_from,
                tx_index_from,
                limit: Some(1),
                ..ListTransactionsQuery::default()
            },
        )
        .await
        .unwrap();
        assert_eq!(response.pagination.chain_tip, 2, "the tip is reported on every page");
        let (Some(last_block), Some(last_index)) =
            (response.pagination.block_num, response.pagination.block_tx_index)
        else {
            assert!(response.transactions.is_empty(), "a page with rows must report its position");
            break;
        };
        assert_eq!(response.transactions.len(), 1, "a page must honor the row limit");
        block_from = Some(last_block);
        tx_index_from = Some(last_index + 1);
        swept.extend(
            response
                .transactions
                .into_iter()
                .map(|item| (item.transaction_id, item.block_num, item.block_tx_index)),
        );
    }
    assert_eq!(swept, expected_sweep);

    // A block filter excludes block 1, and the never-committed transaction is absent regardless of
    // the filter.
    let response = list(
        &service,
        ListTransactionsQuery {
            block_from: Some(2),
            block_to: Some(9),
            ..ListTransactionsQuery::default()
        },
    )
    .await
    .unwrap();
    assert_eq!(
        response
            .transactions
            .iter()
            .map(|item| item.transaction_id.as_str())
            .collect::<Vec<_>>(),
        vec![
            hex::encode(transaction_ids[1].to_bytes()),
            hex::encode(transaction_ids[2].to_bytes()),
        ],
    );
}

/// A replacement of the tip block gives the block's positions to its own transactions. A sweep that
/// resumes after the last position it read does not see them. A sweep that reads the tip block
/// again from its first position does.
#[tokio::test]
async fn list_serves_a_replaced_tip_block_from_its_first_position() {
    let mut keys = operator_keys();
    let (_directory, writer, reader) = test_database().await;
    let transaction_ids = (1u64..=3)
        .map(|i| TransactionId::from_raw(Word::try_from([i, i, i, i]).unwrap()))
        .collect::<Vec<_>>();
    for (seed, transaction_id) in (41u8..=43).zip(&transaction_ids) {
        let record = target_record(&keys[0], *transaction_id, seed, b"record");
        writer.insert_validated_private_transaction(record).await.unwrap();
    }
    commit(&writer, 1, &[transaction_ids[0], transaction_ids[1]]).await;
    let service = ValidatorAdminService::new(keys.remove(0), reader);

    let page = list(&service, ListTransactionsQuery::default()).await.unwrap();
    assert_eq!(page.transactions.len(), 2);
    let pagination = page.pagination;
    assert_eq!(
        (pagination.chain_tip, pagination.block_num, pagination.block_tx_index),
        (1, Some(1), Some(1))
    );

    writer
        .replace_signed_block(
            block_with_header(BlockHeader::mock(1, None, None, &[])),
            ProtocolConfig::mock(),
            vec![transaction_ids[2]],
        )
        .await
        .unwrap();

    let resumed = list(
        &service,
        ListTransactionsQuery {
            block_from: pagination.block_num,
            tx_index_from: pagination.block_tx_index.map(|index| index + 1),
            ..ListTransactionsQuery::default()
        },
    )
    .await
    .unwrap();
    assert!(resumed.transactions.is_empty());

    let reread = list(
        &service,
        ListTransactionsQuery {
            block_from: Some(pagination.chain_tip),
            ..ListTransactionsQuery::default()
        },
    )
    .await
    .unwrap();
    assert_eq!(
        reread
            .transactions
            .iter()
            .map(|item| (item.transaction_id.as_str(), item.block_num, item.block_tx_index))
            .collect::<Vec<_>>(),
        vec![(hex::encode(transaction_ids[2].to_bytes()).as_str(), 1, 0)],
    );
}

#[tokio::test]
async fn list_rejects_invalid_parameters() {
    let mut keys = operator_keys();
    let (_directory, _writer, reader) = test_database().await;
    let service = ValidatorAdminService::new(keys.remove(0), reader);

    for query in [
        ListTransactionsQuery {
            limit: Some(0),
            ..ListTransactionsQuery::default()
        },
        ListTransactionsQuery {
            limit: Some(MAX_PAGE_LIMIT + 1),
            ..ListTransactionsQuery::default()
        },
        ListTransactionsQuery {
            limit: Some(MAX_RECORD_PAGE_LIMIT + 1),
            include_records: true,
            ..ListTransactionsQuery::default()
        },
        ListTransactionsQuery {
            block_from: Some(3),
            block_to: Some(2),
            ..ListTransactionsQuery::default()
        },
        ListTransactionsQuery {
            tx_index_from: Some(1),
            ..ListTransactionsQuery::default()
        },
    ] {
        let error = list(&service, query).await.unwrap_err();
        assert_eq!(error.status, StatusCode::BAD_REQUEST);
    }
}

#[tokio::test]
async fn get_transaction_returns_the_full_record() {
    let mut keys = operator_keys();
    let (_directory, writer, reader) = test_database().await;
    let transaction_id = TransactionId::from_raw(Word::from([6u32, 6, 6, 6]));
    let record = target_record(&keys[0], transaction_id, 22, b"record");
    writer.insert_validated_private_transaction(record.clone()).await.unwrap();
    let service = ValidatorAdminService::new(keys.remove(0), reader);

    let Json(fetched) = get_validated_private_transaction(
        State(service.clone()),
        Path(hex::encode(transaction_id.to_bytes())),
    )
    .await
    .unwrap();
    assert_eq!(fetched.transaction_id, hex::encode(transaction_id.to_bytes()));
    assert_eq!(fetched.final_ciphertext, hex::encode(record.encrypted_record()));
    assert_eq!(fetched.cipher_nonce, hex::encode(record.nonce()));
    assert_eq!(fetched.encrypted_record_key, hex::encode(record.encrypted_record_key()));
    assert_eq!(fetched.decryption_context, hex::encode(record.context().to_bytes()));

    let unknown_id = TransactionId::from_raw(Word::from([9u32, 9, 9, 9]));
    let error = get_validated_private_transaction(
        State(service.clone()),
        Path(hex::encode(unknown_id.to_bytes())),
    )
    .await
    .unwrap_err();
    assert_eq!(error.status, StatusCode::NOT_FOUND);

    let error =
        get_validated_private_transaction(State(service.clone()), Path("not hex".to_owned()))
            .await
            .unwrap_err();
    assert_eq!(error.status, StatusCode::BAD_REQUEST);

    // An id with bytes after the 32-byte transaction id does not name the stored transaction.
    let error = get_validated_private_transaction(
        State(service),
        Path(format!("{}00", hex::encode(transaction_id.to_bytes()))),
    )
    .await
    .unwrap_err();
    assert_eq!(error.status, StatusCode::BAD_REQUEST);
}

/// The share endpoint refuses to act as a decryption oracle: it only issues shares whose decryption
/// context references a transaction this validator itself validated.
#[tokio::test]
async fn share_refused_for_unvalidated_transaction() {
    let mut keys = operator_keys();
    let record_owner = keys.pop().unwrap();
    let (_directory, _writer, reader) = test_database().await;
    let service = ValidatorAdminService::new(keys.pop().unwrap(), reader);
    let transaction_id = TransactionId::from_raw(Word::from([2u32, 4, 6, 8]));
    let record = target_record(&record_owner, transaction_id, 30, b"record");

    let error = issue(&service, share_request(&record)).await.unwrap_err();

    assert_eq!(error.status, StatusCode::NOT_FOUND);
}

/// A share from this validator's key opens only records sealed under the same key epoch, so the
/// share endpoint refuses a context that names another epoch.
#[tokio::test]
async fn share_refused_for_another_key_epoch() {
    let mut keys = operator_keys();
    let transaction_id = TransactionId::from_raw(Word::from([1u32, 2, 3, 4]));
    let record = target_record(&keys[0], transaction_id, 6, b"record");
    let (_directory, writer, reader) = test_database().await;
    writer.insert_validated_private_transaction(record.clone()).await.unwrap();

    // The transaction is validated and the ciphertext is bound to the context, so the request fails
    // only on the epoch that the context names.
    let other_epoch = StorageKeyEpoch::new([0xaa; 32]);
    assert_ne!(other_epoch, keys[0].key_epoch());
    let context =
        PrivateRecordContext::new(record.context().chain_id(), other_epoch, transaction_id)
            .to_bytes();
    let ciphertext = keys[0]
        .sealing_key()
        .seal_bytes_with_associated_data(&mut ChaCha20Rng::from_seed([7; 32]), &[0; 32], &context)
        .unwrap();
    let request = IssueDecryptionShareRequest {
        ciphertext: hex::encode(to_wire_bytes(&ciphertext)),
        decryption_context: hex::encode(context),
    };

    let error = issue(&ValidatorAdminService::new(keys.remove(0), reader), request)
        .await
        .unwrap_err();

    assert_eq!(error.status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn shares_for_different_ciphertexts_are_not_reusable() {
    let mut keys = operator_keys();
    let record_owner = keys.pop().unwrap();
    let transaction_id = TransactionId::from_raw(Word::from([1u32, 2, 3, 4]));
    let first_record = target_record(&record_owner, transaction_id, 2, b"same plaintext");
    let second_record = target_record(&record_owner, transaction_id, 3, b"same plaintext");
    assert_eq!(first_record.context(), second_record.context());
    assert_ne!(first_record.encrypted_record_key(), second_record.encrypted_record_key());
    // Each validator has validated (and stored its own record for) the transaction.
    let (_first_dir, first_writer, first_reader) = test_database().await;
    first_writer
        .insert_validated_private_transaction(first_record.clone())
        .await
        .unwrap();
    let (_second_dir, second_writer, second_reader) = test_database().await;
    second_writer
        .insert_validated_private_transaction(second_record.clone())
        .await
        .unwrap();
    let second = ValidatorAdminService::new(keys.pop().unwrap(), second_reader);
    let first = ValidatorAdminService::new(keys.pop().unwrap(), first_reader);

    let shares = [
        issue(&first, share_request(&first_record)).await.unwrap().decryption_share,
        issue(&second, share_request(&second_record)).await.unwrap().decryption_share,
    ]
    .map(|share| hex::decode(share).unwrap());
    let request = PrivateRecordShareRequest::for_record(&first_record);
    let result = PrivateRecordCombiner::from_operator_key(&record_owner).unwrap().open(
        &request,
        &first_record,
        &shares,
    );

    assert!(matches!(result, Err(PrivateRecordError::ShareCombination(_))));
}

#[tokio::test]
async fn invalid_share_requests_return_bad_request() {
    let mut keys = operator_keys();
    let transaction_id = TransactionId::from_raw(Word::from([1u32, 2, 3, 4]));
    let record = target_record(&keys[0], transaction_id, 4, b"record");
    let context = record.context().to_bytes();
    let (_directory, writer, reader) = test_database().await;
    // The referenced transaction is validated, so these requests fail on their own defects rather
    // than on the validated-transaction check.
    writer.insert_validated_private_transaction(record.clone()).await.unwrap();

    let invalid_hex = IssueDecryptionShareRequest {
        ciphertext: "not hex".to_owned(),
        decryption_context: hex::encode(&context),
    };
    let error = issue(&ValidatorAdminService::new(keys.remove(0), reader.clone()), invalid_hex)
        .await
        .unwrap_err();
    assert_eq!(error.status, StatusCode::BAD_REQUEST);

    let mut short_rng = ChaCha20Rng::from_seed([5; 32]);
    let short_ciphertext = keys[0]
        .sealing_key()
        .seal_bytes_with_associated_data(&mut short_rng, &[0; 31], &context)
        .unwrap();
    let wrong_size = IssueDecryptionShareRequest {
        ciphertext: hex::encode(to_wire_bytes(&short_ciphertext)),
        decryption_context: hex::encode(context),
    };
    let error = issue(&ValidatorAdminService::new(keys.remove(0), reader.clone()), wrong_size)
        .await
        .unwrap_err();
    assert_eq!(error.status, StatusCode::BAD_REQUEST);

    let wrong_context = IssueDecryptionShareRequest {
        ciphertext: hex::encode(record.encrypted_record_key()),
        decryption_context: hex::encode(b"wrong context"),
    };
    let error =
        issue(&ValidatorAdminService::new(operator_keys().remove(0), reader), wrong_context)
            .await
            .unwrap_err();
    assert_eq!(error.status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn router_exposes_only_the_json_admin_routes() {
    let (_directory, _writer, reader) = test_database().await;
    let app = router(operator_keys().remove(0), reader);

    let response = app
        .clone()
        .oneshot(Request::get(LIST_TRANSACTIONS_PATH).body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.headers().get("content-type").unwrap(), "application/json",);
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    assert_eq!(
        body.as_ref(),
        br#"{"transactions":[],"pagination":{"chain_tip":0,"block_num":null,"block_tx_index":null}}"#
    );

    let response = app
        .clone()
        .oneshot(
            Request::get(format!("{LIST_TRANSACTIONS_PATH}/{}", hex::encode([1u8; 32])))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
    assert_eq!(response.headers().get("content-type").unwrap(), "application/json",);

    let response = app
        .clone()
        .oneshot(
            Request::post(ISSUE_SHARE_PATH)
                .header("content-type", "application/json")
                .body(Body::from(r#"{"ciphertext":"not hex","decryption_context":""}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);

    let response = app.oneshot(Request::get("/").body(Body::empty()).unwrap()).await.unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

/// Request parsing errors use plain text, while handler validation errors use the JSON envelope.
#[tokio::test]
async fn router_distinguishes_extractor_and_handler_errors() {
    let (_directory, _writer, reader) = test_database().await;
    let app = router(operator_keys().remove(0), reader);
    let cases = [
        (
            Request::get(format!("{LIST_TRANSACTIONS_PATH}?limit=abc"))
                .body(Body::empty())
                .unwrap(),
            StatusCode::BAD_REQUEST,
            "text/plain; charset=utf-8",
        ),
        (
            Request::post(ISSUE_SHARE_PATH)
                .header("content-type", "application/json")
                .body(Body::from("{"))
                .unwrap(),
            StatusCode::BAD_REQUEST,
            "text/plain; charset=utf-8",
        ),
        (
            Request::post(ISSUE_SHARE_PATH)
                .header("content-type", "application/json")
                .body(Body::from("{}"))
                .unwrap(),
            StatusCode::UNPROCESSABLE_ENTITY,
            "text/plain; charset=utf-8",
        ),
        (
            Request::post(ISSUE_SHARE_PATH).body(Body::from("{}")).unwrap(),
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            "text/plain; charset=utf-8",
        ),
        (
            Request::get(format!("{LIST_TRANSACTIONS_PATH}?limit=0"))
                .body(Body::empty())
                .unwrap(),
            StatusCode::BAD_REQUEST,
            "application/json",
        ),
    ];
    for (request, status, content_type) in cases {
        let response = app.clone().oneshot(request).await.unwrap();
        assert_eq!(response.status(), status);
        assert_eq!(response.headers().get("content-type").unwrap(), content_type);
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        assert!(!body.is_empty());
        if content_type == "application/json" {
            assert_eq!(body.as_ref(), br#"{"error":"limit must be between 1 and 1000"}"#);
        }
    }
}

/// Shares issued by two validators recover a third validator's stored record over HTTP.
#[tokio::test]
async fn http_private_record_recovery() {
    let mut keys = operator_keys();
    let owner = keys.pop().unwrap();
    let second = keys.pop().unwrap();
    let first = keys.pop().unwrap();
    let (_dir, writer, reader) = test_database().await;
    let tx = TransactionId::from_raw(Word::from([8u32, 7, 6, 5]));
    let inputs = transaction_inputs();
    let record = target_record(&owner, tx, 10, &inputs.to_bytes());
    writer.insert_validated_private_transaction(record.clone()).await.unwrap();
    let request = share_request(&record);
    let issue_body = format!(
        r#"{{"ciphertext":"{}","decryption_context":"{}"}}"#,
        request.ciphertext, request.decryption_context,
    );
    let mut shares = Vec::new();
    for key in [first, second] {
        let response = router(key, reader.clone())
            .oneshot(
                Request::post(ISSUE_SHARE_PATH)
                    .header("content-type", "application/json")
                    .body(Body::from(issue_body.clone()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let response: IssueDecryptionShareResponse = serde_json::from_slice(&body).unwrap();
        shares.push(response.decryption_share);
    }
    let response = router(owner, reader.clone())
        .oneshot(
            Request::post(format!("/admin/v1/transactions/{}/decrypt", hex::encode(tx.to_bytes())))
                .header("content-type", "application/json")
                .body(Body::from(format!(
                    r#"{{"decryption_shares":["{}","{}"]}}"#,
                    shares[0], shares[1],
                )))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    let response: serde_json::Value = serde_json::from_slice(&body).unwrap();
    let plaintext = hex::decode(response["plaintext"].as_str().unwrap()).unwrap();
    assert_eq!(plaintext, inputs.to_bytes());
    assert_eq!(reader.load_private_record(tx).await.unwrap().unwrap(), record);
}

/// Posts real share bytes through the decryption route and decodes its public JSON response.
async fn decrypt_http(
    app: axum::Router,
    transaction_id: &str,
    shares: &[String],
) -> (StatusCode, serde_json::Value) {
    let response = app
        .oneshot(
            Request::post(format!("/admin/v1/transactions/{transaction_id}/decrypt"))
                .header("content-type", "application/json")
                .body(Body::from(serde_json::json!({"decryption_shares": shares}).to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    let status = response.status();
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    (status, serde_json::from_slice(&body).unwrap())
}

/// Invalid shares cannot recover plaintext or alter the stored record.
#[tokio::test]
async fn decrypt_rejects_invalid_share_sets() {
    let keys = operator_keys();
    let (_dir, writer, reader) = test_database().await;
    let tx = TransactionId::from_raw(Word::from([8u32, 7, 6, 5]));
    let record = target_record(&keys[2], tx, 10, b"private record");
    writer.insert_validated_private_transaction(record.clone()).await.unwrap();
    let shares = keys
        .iter()
        .map(|key| {
            hex::encode(
                key.issue_private_record_share(
                    &mut rand_core_06::OsRng,
                    &PrivateRecordShareRequest::for_record(&record),
                    &record,
                )
                .unwrap(),
            )
        })
        .collect::<Vec<_>>();
    let other = target_record(&keys[2], tx, 11, b"private record");
    let other_share = hex::encode(
        keys[0]
            .issue_private_record_share(
                &mut rand_core_06::OsRng,
                &PrivateRecordShareRequest::for_record(&other),
                &other,
            )
            .unwrap(),
    );
    let app = router(operator_keys().remove(2), reader.clone());
    for (name, shares) in [
        ("empty", vec![]),
        ("insufficient", vec![shares[0].clone()]),
        ("duplicate", vec![shares[0].clone(), shares[0].clone()]),
        ("excess", shares.clone()),
        ("invalid hex", vec!["zz".into(), shares[1].clone()]),
        ("invalid encoding", vec!["00".into(), shares[1].clone()]),
        ("wrong ciphertext", vec![other_share, shares[1].clone()]),
    ] {
        let (status, body) = decrypt_http(app.clone(), &hex::encode(tx.to_bytes()), &shares).await;
        assert_eq!(status, StatusCode::BAD_REQUEST, "{name}: {body}");
        assert!(body.get("plaintext").is_none(), "{name}");
        assert!(body["error"].is_string(), "{name}");
    }
    assert_eq!(reader.load_private_record(tx).await.unwrap().unwrap(), record);
}

/// Transaction selection rejects malformed identifiers and distinguishes absent records.
#[tokio::test]
async fn decrypt_validates_transaction_selection() {
    let (_dir, _writer, reader) = test_database().await;
    let app = router(operator_keys().remove(0), reader);
    let tx = hex::encode(TransactionId::from_raw(Word::from([8u32, 7, 6, 5])).to_bytes());
    for (id, expected) in [
        ("zz".to_owned(), StatusCode::BAD_REQUEST),
        (format!("{tx}00"), StatusCode::BAD_REQUEST),
        (tx, StatusCode::NOT_FOUND),
    ] {
        let (status, body) = decrypt_http(app.clone(), &id, &[]).await;
        assert_eq!(status, expected);
        assert!(body.get("plaintext").is_none());
    }
}

/// Incompatible setup metadata is actionable; authenticated payload corruption is internal.
#[rstest::rstest]
#[case::epoch("epoch", StatusCode::BAD_REQUEST)]
#[case::setup("setup", StatusCode::BAD_REQUEST)]
#[case::corrupt_payload("payload", StatusCode::INTERNAL_SERVER_ERROR)]
#[tokio::test]
async fn decrypt_classifies_record_failures(#[case] defect: &str, #[case] expected: StatusCode) {
    let keys = operator_keys();
    let (_dir, writer, reader) = test_database().await;
    let tx = TransactionId::from_raw(Word::from([8u32, 7, 6, 5]));
    let record = target_record(&keys[2], tx, 10, b"secret plaintext");
    let shares = keys[..2]
        .iter()
        .map(|key| {
            hex::encode(
                key.issue_private_record_share(
                    &mut rand_core_06::OsRng,
                    &PrivateRecordShareRequest::for_record(&record),
                    &record,
                )
                .unwrap(),
            )
        })
        .collect::<Vec<_>>();
    let mut fields = record.into_storage_fields();
    match defect {
        "epoch" => {
            // Seal a valid record under a different epoch, so decoding succeeds before
            // compatibility with the active operator key is checked.
            let context = PrivateRecordContext::new(
                PrivateRecordChainId::new([7; 32]),
                StorageKeyEpoch::new([99; 32]),
                tx,
            );
            let sealer = crate::private_record::test_private_record_sealer(
                context.key_epoch(),
                keys[2].setup_context_id(),
            );
            fields = sealer
                .seal(&mut rand_core_06::OsRng, fields.record_id, context, b"secret plaintext")
                .unwrap()
                .into_storage_fields();
        },
        "setup" => fields.setup_context_id = [99; 32],
        "payload" => fields.encrypted_record[0] ^= 1,
        _ => unreachable!(),
    }
    let record = StoredPrivateRecord::from_storage_fields(fields).unwrap();
    writer.insert_validated_private_transaction(record.clone()).await.unwrap();
    let (status, body) = decrypt_http(
        router(operator_keys().remove(2), reader.clone()),
        &hex::encode(tx.to_bytes()),
        &shares,
    )
    .await;
    assert_eq!(status, expected);
    assert!(body.get("plaintext").is_none());
    assert!(!body.to_string().contains("secret plaintext"));
    for share in shares {
        assert!(!body.to_string().contains(&share));
    }
    if expected == StatusCode::INTERNAL_SERVER_ERROR {
        assert_eq!(body["error"], "failed to decrypt private record");
    }
    assert_eq!(reader.load_private_record(tx).await.unwrap().unwrap(), record);
}