1use std::cmp::Ordering;
5use std::num::NonZeroUsize;
6
7use vitaminc_context::Context;
8use vitaminc_hmac::{HmacSha256Prf, WeakKeyError};
9use vitaminc_ore::{OrderKeyInit, OrderPlaintext, OrderQuery, OrderScheme, OrderTarget};
10use vitaminc_prf::{BlockVisitor, Prf, PrfEncoding, PrfKeyInit};
11use vitaminc_protected::Protected;
12use zeroize::{ZeroizeOnDrop, Zeroizing};
13
14use crate::ciphertext::parse_header;
15use crate::scheme::bit2_w6::{OreAes128Bit6, MAX_BYTES};
16use crate::scheme::chained::{Options, OreAes128Bit6Chained, Padding, DEFAULT_MAX_STR_BYTES};
17use crate::{OreError, OreScheme, Query, Term};
18
19pub const ORE_KEY: &str = "vitaminc/ore/block-ore/key/v2";
21
22fn ore_key(prf: &HmacSha256Prf) -> Option<Zeroizing<[u8; 16]>> {
28 let material = prf
29 .prf_bytes_vec(
30 Protected::new(Vec::new()),
31 PrfEncoding::new(ORE_KEY),
32 Context::empty(),
33 BlockVisitor,
34 )
35 .into_result()
36 .ok()
37 .map(Zeroizing::new)?;
38 let mut key = Zeroizing::new([0u8; 16]);
39 key.copy_from_slice(&material[..16]);
40 Some(key)
41}
42
43pub struct BlockOre {
116 key: Option<Zeroizing<[u8; 16]>>,
117 text_padding: Padding,
118 max_bytes: NonZeroUsize,
119}
120
121impl BlockOre {
122 pub fn with_text_padding(mut self, padding: Padding) -> Self {
127 self.text_padding = padding;
128 self
129 }
130
131 pub fn with_max_bytes(mut self, max_bytes: NonZeroUsize) -> Self {
150 self.max_bytes = max_bytes;
151 self
152 }
153
154 pub fn text_padding(&self) -> Padding {
156 self.text_padding
157 }
158
159 pub fn max_bytes(&self) -> NonZeroUsize {
161 self.max_bytes
162 }
163
164 fn key(&self) -> Result<Protected<[u8; 16]>, OreError> {
166 self.key
167 .as_deref()
168 .map(|key| Protected::new(*key))
169 .ok_or(OreError::InitFailed)
170 }
171}
172
173impl std::fmt::Debug for BlockOre {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 f.debug_struct("BlockOre")
177 .field("text_padding", &self.text_padding)
178 .field("max_bytes", &self.max_bytes)
179 .finish_non_exhaustive()
180 }
181}
182
183pub struct BlockOreSpace {
188 engine: Engine,
189 target: OrderTarget,
190}
191
192enum Engine {
193 Bit6(Box<OreAes128Bit6>),
196 Chained(Box<OreAes128Bit6Chained>),
197}
198
199impl ZeroizeOnDrop for BlockOreSpace {}
203
204#[allow(dead_code)]
205fn engines_wipe_on_drop(engine: &Engine) {
206 fn wipes<T: ZeroizeOnDrop>(_: &T) {}
207 match engine {
208 Engine::Bit6(e) => wipes(&**e),
209 Engine::Chained(e) => wipes(&**e),
210 }
211}
212
213impl std::fmt::Debug for BlockOreSpace {
214 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215 let engine = match &self.engine {
216 Engine::Bit6(_) => "Bit6",
217 Engine::Chained(_) => "Chained",
218 };
219 f.debug_struct("BlockOreSpace")
220 .field("engine", &engine)
221 .field("target", &self.target)
222 .finish()
223 }
224}
225
226impl BlockOreSpace {
227 fn check_target(&self, plaintext: &OrderPlaintext) -> Result<(), OreError> {
231 if plaintext.target() == self.target {
232 Ok(())
233 } else {
234 Err(OreError::TargetMismatch)
235 }
236 }
237}
238
239fn engine_for(target: OrderTarget) -> EngineKind {
242 match target.width() {
243 Some(width) if width <= MAX_BYTES => EngineKind::Bit6,
244 _ => EngineKind::Chained,
245 }
246}
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249enum EngineKind {
250 Bit6,
251 Chained,
252}
253
254fn engine_of(bytes: &[u8]) -> Option<EngineKind> {
258 let ((version, scheme_id, _), _) = parse_header(bytes).ok()?;
259 if version != crate::scheme::bit2_w6::WIRE.version {
260 return None;
261 }
262 if scheme_id == crate::scheme::bit2_w6::WIRE.scheme_id {
263 Some(EngineKind::Bit6)
264 } else if scheme_id == crate::scheme::chained::SCHEME_ID {
265 Some(EngineKind::Chained)
266 } else {
267 None
268 }
269}
270
271impl OrderScheme for BlockOre {
272 const NAME: &'static str = "block-ore";
273 type Term = Term;
274 type Error = OreError;
275 type Space = BlockOreSpace;
276
277 fn open(&self, target: OrderTarget, salt: &Context<'_>) -> Result<BlockOreSpace, OreError> {
287 let key = self.key()?;
288 let engine = match engine_for(target) {
289 EngineKind::Bit6 => Engine::Bit6(Box::new(OreAes128Bit6::init_with_salt(key, salt)?)),
290 EngineKind::Chained => {
291 let options = match target {
292 OrderTarget::Bytes => Options::default()
293 .with_salt(salt)
294 .with_padding(Padding::None)
295 .with_max_bytes(self.max_bytes),
296 target if target.width().is_some() => Options::default().with_salt(salt),
300 _ => Options::default()
302 .with_salt(salt)
303 .with_padding(self.text_padding)
304 .with_max_bytes(self.max_bytes),
305 };
306 Engine::Chained(Box::new(OreAes128Bit6Chained::init_with(key, options)?))
307 }
308 };
309 Ok(BlockOreSpace { engine, target })
310 }
311
312 fn encrypt_plaintext(
317 &self,
318 space: &BlockOreSpace,
319 plaintext: &OrderPlaintext,
320 ) -> Result<Term, OreError> {
321 space.check_target(plaintext)?;
322 match &space.engine {
323 Engine::Bit6(engine) => engine.encrypt_plaintext(plaintext),
324 Engine::Chained(engine) => engine.encrypt_plaintext(plaintext),
325 }
326 }
327
328 fn compare(a: &Term, b: &Term) -> Option<Ordering> {
335 match (engine_of(a.as_bytes()), engine_of(b.as_bytes())) {
336 (Some(EngineKind::Bit6), Some(EngineKind::Bit6)) => {
337 OreAes128Bit6::compare_raw_slices(a.as_bytes(), b.as_bytes())
338 }
339 (Some(EngineKind::Chained), Some(EngineKind::Chained)) => {
340 OreAes128Bit6Chained::compare_raw_slices(a.as_bytes(), b.as_bytes())
341 }
342 _ => None,
343 }
344 }
345}
346
347impl OrderQuery for BlockOre {
348 type Query = Query;
349
350 fn encrypt_query(
353 &self,
354 space: &BlockOreSpace,
355 plaintext: &OrderPlaintext,
356 ) -> Result<Query, OreError> {
357 space.check_target(plaintext)?;
358 match &space.engine {
359 Engine::Bit6(engine) => engine.encrypt_query_plaintext(plaintext),
360 Engine::Chained(engine) => engine.encrypt_query_plaintext(plaintext),
361 }
362 }
363
364 fn compare_query(query: &Query, term: &Term) -> Option<Ordering> {
368 match (engine_of(query.as_bytes()), engine_of(term.as_bytes())) {
369 (Some(EngineKind::Bit6), Some(EngineKind::Bit6)) => {
370 OreAes128Bit6::compare_left_to_full(query.as_bytes(), term.as_bytes())
371 }
372 (Some(EngineKind::Chained), Some(EngineKind::Chained)) => {
373 OreAes128Bit6Chained::compare_left_to_full(query.as_bytes(), term.as_bytes())
374 }
375 _ => None,
376 }
377 }
378}
379
380vitaminc_ore::supports_every_target!(BlockOre);
381
382impl OrderKeyInit for BlockOre {
383 type Key = Protected<[u8; 32]>;
384 type KeyError = WeakKeyError;
385
386 fn new(key: Self::Key) -> Self {
387 Self {
388 key: ore_key(&HmacSha256Prf::new(key)),
389 text_padding: Padding::default(),
390 max_bytes: DEFAULT_MAX_STR_BYTES,
391 }
392 }
393
394 fn try_from_bytes(key: Protected<Vec<u8>>) -> Result<Self, WeakKeyError> {
395 Ok(Self {
396 key: ore_key(&HmacSha256Prf::try_from_bytes(key)?),
397 text_padding: Padding::default(),
398 max_bytes: DEFAULT_MAX_STR_BYTES,
399 })
400 }
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406 use crate::scheme::chained::MAX_STR_BYTES;
407 use crate::scheme::decompose::num_blocks_6bit;
408 use crate::testing::{ceiling, fixed_padding, salt, text_pt, u128_pt, u64_pt};
409 use vitaminc_ore::target::{Bytes, Date, Decimal, Text, I32, I64, U128};
410 use vitaminc_ore::{test_support, OrderEncrypt, OrderError, OrderTerm, QueryTerm};
411
412 use OrderTarget as T;
413
414 fn key() -> Protected<[u8; 32]> {
415 Protected::new([7; 32])
416 }
417
418 fn other_key() -> Protected<[u8; 32]> {
419 Protected::new([8; 32])
420 }
421
422 fn scheme() -> BlockOre {
423 BlockOre::new(key())
424 }
425
426 fn engine(bytes: &[u8]) -> EngineKind {
428 engine_of(bytes).expect("a v2 header")
429 }
430
431 #[test]
435 fn the_scheme_keeps_the_order_scheme_contract() {
436 test_support::conformance(&scheme(), &BlockOre::new(other_key()));
437 test_support::query_conformance(&scheme(), &BlockOre::new(other_key()));
438 test_support::static_target::<BlockOre, I32>();
439 test_support::static_target::<BlockOre, Text>();
440 test_support::static_target::<BlockOre, U128>();
441 }
442
443 #[test]
446 fn spaces_are_routed_to_an_engine_by_width() {
447 let s = scheme();
448 let bit6 = [
449 T::I16,
450 T::U16,
451 T::I32,
452 T::U32,
453 T::I64,
454 T::U64,
455 T::F64,
456 T::Date,
457 ];
458 let chained = [
459 T::I128,
460 T::U128,
461 T::Uuid,
462 T::Timestamp,
463 T::Decimal,
464 T::Text,
465 T::Bytes,
466 ];
467 for t in bit6 {
468 assert_eq!(engine_for(t), EngineKind::Bit6, "{t:?}");
469 s.target(t).context("c").open().expect("block ore");
470 }
471 for t in chained {
472 assert_eq!(engine_for(t), EngineKind::Chained, "{t:?}");
473 s.target(t).context("c").open().expect("block ore");
474 }
475 for t in OrderTarget::ALL {
476 assert!(
477 bit6.contains(t) || chained.contains(t),
478 "{:?} is unrouted",
479 t
480 );
481 }
482
483 let i64s = s.target(I64).context("c");
484 let term = i64s.encrypt(42i64).expect("block ore");
485 assert_eq!(engine(term.as_bytes()), EngineKind::Bit6);
486 assert_eq!(term.as_bytes().len(), 295);
487 let query = i64s.encrypt_query(42i64).expect("block ore");
488 assert_eq!(engine(query.as_bytes()), EngineKind::Bit6);
489
490 let wide = s.target(U128).context("c");
491 let term = wide.encrypt(42u128).expect("block ore");
492 assert_eq!(engine(term.as_bytes()), EngineKind::Chained);
493 assert_eq!(term.as_bytes().len(), 7 + 25 * 22 + 16);
494 }
495
496 #[test]
499 fn terms_and_queries_compare_within_a_space() {
500 let s = scheme();
501 let prices = s.target(Decimal).context(("orders", "total"));
502 let values = [
503 rust_decimal::Decimal::MIN,
504 rust_decimal::Decimal::new(-150, 2),
505 rust_decimal::Decimal::ZERO,
506 rust_decimal::Decimal::new(150, 2),
507 rust_decimal::Decimal::MAX,
508 ];
509 let terms: Vec<OrderTerm<Term, Decimal>> = values
510 .iter()
511 .map(|v| prices.encrypt(*v).expect("block ore"))
512 .collect();
513 let queries: Vec<QueryTerm<Query, Decimal>> = values
514 .iter()
515 .map(|v| prices.encrypt_query(*v).expect("block ore"))
516 .collect();
517 for (i, a) in terms.iter().enumerate() {
518 for (j, b) in terms.iter().enumerate() {
519 assert_eq!(prices.compare(a, b), Some(i.cmp(&j)), "{i} vs {j}");
520 assert_eq!(
521 prices.compare_query(&queries[i], b),
522 Some(i.cmp(&j)),
523 "query {i} vs {j}"
524 );
525 }
526 assert_eq!(
527 queries[i],
528 prices.encrypt_query(values[i]).expect("block ore")
529 );
530 assert_ne!(
531 a.as_bytes(),
532 prices.encrypt(values[i]).expect("block ore").as_bytes()
533 );
534 }
535
536 let dates = s.target(Date).context("d");
537 let (a, b) = (
538 dates
539 .encrypt(jiff::civil::date(2022, 1, 1))
540 .expect("block ore"),
541 dates
542 .encrypt(jiff::civil::date(2022, 1, 2))
543 .expect("block ore"),
544 );
545 assert_eq!(dates.compare(&a, &b), Some(Ordering::Less));
546
547 let space = s.open(T::Date, dates.salt()).expect("a date space");
552 for (date, days) in [
553 (jiff::civil::date(1970, 1, 1), 0),
554 (jiff::civil::date(1969, 12, 31), -1),
555 (jiff::civil::date(2022, 1, 1), 18_993),
556 ] {
557 assert_eq!(
558 dates.encrypt_query(date).expect("block ore").as_bytes(),
559 BlockOre::encrypt_query(&s, &space, &crate::testing::date_pt(days))
560 .expect("block ore")
561 .as_bytes(),
562 "{date} is not day {days}"
563 );
564 }
565 }
566
567 #[test]
570 fn comparisons_dispatch_on_the_header_and_refuse_a_mix() {
571 let s = scheme();
572 let narrow = s
573 .target(T::I64)
574 .context("c")
575 .encrypt_checked(1i64)
576 .expect("block ore");
577 let wide = s
578 .target(T::U128)
579 .context("c")
580 .encrypt_checked(1u128)
581 .expect("block ore");
582 let narrow_query = s
583 .target(T::I64)
584 .context("c")
585 .encrypt_query_checked(1i64)
586 .expect("block ore");
587 assert_eq!(BlockOre::compare(narrow.raw(), wide.raw()), None);
588 assert_eq!(BlockOre::compare(wide.raw(), narrow.raw()), None);
589 assert_eq!(
590 BlockOre::compare_query(narrow_query.raw(), wide.raw()),
591 None
592 );
593 assert_eq!(
594 BlockOre::compare(narrow.raw(), narrow.raw()),
595 Some(Ordering::Equal)
596 );
597 assert_eq!(
598 BlockOre::compare_query(narrow_query.raw(), narrow.raw()),
599 Some(Ordering::Equal)
600 );
601 let headerless = Term::from_bytes(vec![0u8; 16]);
602 assert_eq!(BlockOre::compare(&headerless, narrow.raw()), None);
603 assert_eq!(BlockOre::compare(narrow.raw(), &headerless), None);
604 let mut other_version = narrow.raw().clone().into_bytes();
605 other_version[0] = 0x03;
606 assert_eq!(
607 BlockOre::compare(&Term::from_bytes(other_version), narrow.raw()),
608 None
609 );
610 }
611
612 #[test]
615 fn text_is_padded_and_bytes_are_not() {
616 let s = scheme();
617 let text = s.target(Text).context("c");
618 let bytes = s.target(Bytes).context("c");
619 let text_len = |v: &str| text.encrypt_checked(v).expect("block ore").as_bytes().len();
620 let bytes_len = |v: &[u8]| bytes.encrypt(v).expect("block ore").as_bytes().len();
621 let chained_len = |n: usize| 7 + 25 * num_blocks_6bit(n) + 16;
622 assert_eq!(text_len(""), chained_len(16));
624 assert_eq!(text_len("alice"), chained_len(16));
625 assert_eq!(text_len(&"a".repeat(15)), chained_len(16));
626 assert_eq!(text_len(&"a".repeat(16)), chained_len(32));
627 assert_eq!(bytes_len(b""), chained_len(1));
629 assert_eq!(bytes_len(b"alice"), chained_len(6));
630 assert!(bytes.encrypt(&b"x\0"[..]).is_ok());
631 assert!(matches!(
632 text.encrypt_checked("x\0"),
633 Err(OrderError::Backend(OreError::TrailingNul))
634 ));
635
636 let unpadded = BlockOre::new(key()).with_text_padding(Padding::None);
637 assert_eq!(unpadded.text_padding(), Padding::None);
638 let text = unpadded.target(Text).context("c");
639 assert_eq!(
640 text.encrypt_checked("alice")
641 .expect("block ore")
642 .as_bytes()
643 .len(),
644 chained_len(6)
645 );
646
647 let small = BlockOre::new(key()).with_max_bytes(ceiling(8));
648 assert_eq!(small.max_bytes().get(), 8);
649 let text = small.target(Text).context("c");
650 let bytes = small.target(Bytes).context("c");
651 assert!(text.encrypt_checked("1234567").is_ok());
652 assert!(matches!(
653 text.encrypt_checked("12345678"),
654 Err(OrderError::Backend(OreError::TooLong))
655 ));
656 assert!(bytes.encrypt(&[0u8; 7][..]).is_ok());
657 assert!(matches!(
658 bytes.encrypt(&[0u8; 8][..]),
659 Err(OreError::TooLong)
660 ));
661 assert!(small.target(U128).context("c").encrypt(u128::MAX).is_ok());
663 }
664
665 #[test]
669 fn a_ceiling_out_of_range_closes_only_text_and_bytes_spaces() {
670 for max in [MAX_STR_BYTES + 1, 60000] {
671 let s = BlockOre::new(key()).with_max_bytes(ceiling(max));
672 for t in [T::U128, T::I128, T::Uuid, T::Timestamp, T::Decimal] {
673 if let Err(e) = s.target(t).context("c").open() {
674 panic!("{:?} under {}: {:?}", t, max, e);
675 }
676 }
677 assert!(s.target(U128).context("c").encrypt(u128::MAX).is_ok());
678 for t in [T::Text, T::Bytes] {
679 assert!(
680 matches!(s.target(t).context("c").open(), Err(OreError::InitFailed)),
681 "{:?} under {}",
682 t,
683 max
684 );
685 }
686 }
687 let s = BlockOre::new(key()).with_max_bytes(ceiling(MAX_STR_BYTES));
690 s.target(Bytes)
691 .context("c")
692 .open()
693 .expect("bytes at the wire limit");
694 assert!(matches!(
695 s.target(Text).context("c").open(),
696 Err(OreError::InitFailed)
697 ));
698 let s = BlockOre::new(key()).with_max_bytes(ceiling(32768));
699 s.target(Text).context("c").open().expect("text at 32768");
700 let s = BlockOre::new(key()).with_max_bytes(ceiling(32769));
701 assert!(matches!(
702 s.target(Text).context("c").open(),
703 Err(OreError::InitFailed)
704 ));
705 }
706
707 #[test]
711 fn the_text_padding_closes_only_text_spaces() {
712 let s = BlockOre::new(key()).with_text_padding(Padding::PowerOfTwo {
713 min_bytes: u16::MAX,
714 });
715 assert!(matches!(
716 s.target(Text).context("c").open(),
717 Err(OreError::InitFailed)
718 ));
719 for t in [
720 T::Bytes,
721 T::U128,
722 T::I128,
723 T::Uuid,
724 T::Timestamp,
725 T::Decimal,
726 ] {
727 if let Err(e) = s.target(t).context("c").open() {
728 panic!("{:?} under an unpaddable text policy: {:?}", t, e);
729 }
730 }
731
732 let s = BlockOre::new(key())
733 .with_text_padding(fixed_padding(8))
734 .with_max_bytes(ceiling(60000));
735 let text = s.target(Text).context("c");
736 assert!(text.encrypt_checked("1234567").is_ok());
737 assert!(matches!(
738 text.encrypt_checked("12345678"),
739 Err(OrderError::Backend(OreError::ExceedsPadding))
740 ));
741 }
742
743 #[test]
747 fn a_space_refuses_a_plaintext_of_another_target() {
748 let s = BlockOre::new(key()).with_text_padding(fixed_padding(64));
749 let ctx = salt(b"c");
750 let wide = OrderScheme::open(&s, T::U128, &ctx).unwrap();
751 let narrow = OrderScheme::open(&s, T::I64, &ctx).unwrap();
752 let text = OrderScheme::open(&s, T::Text, &ctx).unwrap();
753 for space in [&wide, &narrow] {
754 assert!(matches!(
755 s.encrypt_plaintext(space, &text_pt("alice")),
756 Err(OreError::TargetMismatch)
757 ));
758 assert!(matches!(
759 s.encrypt_query(space, &text_pt("alice")),
760 Err(OreError::TargetMismatch)
761 ));
762 }
763 assert!(matches!(
764 s.encrypt_plaintext(&text, &u128_pt(5)),
765 Err(OreError::TargetMismatch)
766 ));
767 assert!(matches!(
768 s.encrypt_plaintext(&narrow, &u64_pt(5)),
769 Err(OreError::TargetMismatch)
770 ));
771 assert!(s.encrypt_plaintext(&wide, &u128_pt(5)).is_ok());
772 assert!(s.encrypt_query(&wide, &u128_pt(5)).is_ok());
773 assert!(s.encrypt_plaintext(&text, &text_pt("alice")).is_ok());
774 }
775
776 #[test]
778 fn text_and_bytes_are_refused_past_1023_bytes() {
779 let s = scheme();
780 let text = s.target(Text).context("c");
781 let bytes = s.target(Bytes).context("c");
782 assert!(text.encrypt_checked("a".repeat(1023).as_str()).is_ok());
783 assert!(matches!(
784 text.encrypt_checked("a".repeat(1024).as_str()),
785 Err(OrderError::Backend(OreError::TooLong))
786 ));
787 assert!(bytes.encrypt(&vec![1u8; 1023][..]).is_ok());
788 assert!(matches!(
789 bytes.encrypt(&vec![1u8; 1024][..]),
790 Err(OreError::TooLong)
791 ));
792 }
793
794 #[test]
798 fn terms_compare_only_within_one_scheme_key_target_and_context() {
799 let s = scheme();
800 let a = s
801 .target(T::I32)
802 .context("c")
803 .encrypt_checked(1i32)
804 .expect("block ore");
805 let other_target = s
806 .target(T::U32)
807 .context("c")
808 .encrypt_checked(1u32)
809 .expect("block ore");
810 let other_context = s
811 .target(T::I32)
812 .context("d")
813 .encrypt_checked(1i32)
814 .expect("block ore");
815 let other_key = BlockOre::new(other_key())
816 .target(T::I32)
817 .context("c")
818 .encrypt_checked(1i32)
819 .expect("block ore");
820 for other in [&other_target, &other_context, &other_key] {
821 assert_ne!(
822 BlockOre::compare(a.raw(), other.raw()),
823 Some(Ordering::Equal)
824 );
825 }
826 let same = s
827 .target(T::I32)
828 .context("c")
829 .encrypt_checked(1i32)
830 .expect("block ore");
831 assert_eq!(
832 BlockOre::compare(a.raw(), same.raw()),
833 Some(Ordering::Equal)
834 );
835 }
836
837 #[test]
841 fn queries_under_a_fixed_key_are_pinned() {
842 let s = scheme();
843 let narrow = s
844 .target(I32)
845 .context("pinned")
846 .encrypt_query(1i32)
847 .expect("block ore");
848 let wide = s
849 .target(U128)
850 .context("pinned")
851 .encrypt_query(1u128)
852 .expect("block ore");
853 assert_eq!(hex::encode(narrow.as_bytes()), PINNED_BIT6_QUERY);
854 assert_eq!(hex::encode(wide.as_bytes()), PINNED_CHAINED_QUERY);
855 }
856
857 const PINNED_BIT6_QUERY: &str = "0202000634253e3a0f361d11a1e27e55c72c1525ac3ffe1a36a3bbb1bb643141e98603df6b5a25da12f46901b6b637bb7aed66d4d4a76be3ce72496bc48fa83d17112c74f7a61caa32d176ae7eeb5471898519f199ae79a74418ca5b9717455df9637516f3fe3a60b4de";
858 const PINNED_CHAINED_QUERY: &str = "0203001600000033112033270b3037360909143b3315002330121f171068031d6c3431c9e1c1daf685de3fb173bb12f9c71ea7c9f565e9cb85fc2cc3646b890ce0b376aba6a79411da2b86ca300c8b4ba04b50c8740751b104772292236a5dc099d4fe537cadcdc048d70da884a4220976c3337777023933f38b33280b9ca99619da619597f5ee558913b5a1ce3a02a91c2c550c2488c6ba9ac71017bb1598978b2a991d82bbfeed0155b8fc616cf7f4c58a191b85d42d74383089ae8a9a2d930ca7495b3c8b9c4282e01cbacbbe98aa38d6ade89c6288479cf2ae0ecfd1abda089bf13b91b3506967dc6b4b2acdf366442f8c3c39df57b1a1be6745a445c79c24a71a2a7a175e06d2f67e375b08b6f5c854d132cc954d447dc6abfd05da818a58fa1852b8fc936633aced31052f4caf9a5373d238f7ba3fd6f38d147caaab184ffb50dc125d447e1ca3153321eb76ec4e6414e6e3ec566a2992add3ee02f5d0a68123b708c25fe675521ea600188475076ff3de8effb700c603df81b7";
859
860 #[test]
863 fn a_scheme_is_keyed_like_a_prf() {
864 assert!(BlockOre::try_from_bytes(Protected::new(vec![7u8; 8])).is_err());
865 let from_bytes = BlockOre::try_from_bytes(Protected::new(vec![7u8; 32])).expect("32 bytes");
866 let a = scheme()
867 .target(I32)
868 .context("c")
869 .encrypt_query(1i32)
870 .expect("block ore");
871 let b = from_bytes
872 .target(I32)
873 .context("c")
874 .encrypt_query(1i32)
875 .expect("block ore");
876 assert_eq!(a, b, "the same key material keys the same scheme");
877
878 let keyless = BlockOre {
879 key: None,
880 text_padding: Padding::default(),
881 max_bytes: DEFAULT_MAX_STR_BYTES,
882 };
883 assert!(matches!(
884 keyless.target(I32).context("c").open(),
885 Err(OreError::InitFailed)
886 ));
887 assert!(matches!(
888 keyless.target(I32).context("c").encrypt(1i32),
889 Err(OreError::InitFailed)
890 ));
891 }
892
893 #[test]
896 fn a_space_is_shared_across_threads_and_debugs_without_the_key() {
897 fn is_send_sync<X: Send + Sync>(_: &X) {}
898 let s = scheme();
899 is_send_sync(&s);
900 let space = s.target(I64).context("c");
901 is_send_sync(&space);
902 space.open().expect("block ore");
903 let shared = &space;
904 let terms: Vec<_> = std::thread::scope(|scope| {
905 let handles: Vec<_> = (0..4i64)
906 .map(|i| scope.spawn(move || shared.encrypt(i).expect("block ore")))
907 .collect();
908 handles
909 .into_iter()
910 .map(|h| h.join().expect("a thread"))
911 .collect()
912 });
913 for pair in terms.windows(2) {
914 assert_eq!(space.compare(&pair[0], &pair[1]), Some(Ordering::Less));
915 }
916 let shown = format!("{s:?} {space:?}");
917 assert!(!shown.contains("key"), "{}", shown);
918 assert!(shown.contains("BlockOre"), "{}", shown);
919 }
920
921 #[test]
924 fn a_value_with_no_term_is_refused() {
925 let s = scheme();
926 assert!(matches!(
927 s.target(T::I32).context("c").encrypt_checked(true),
928 Err(OrderError::Term(_))
929 ));
930 assert!(matches!(
931 s.target(Date).context("c").encrypt_checked("not a date"),
932 Err(OrderError::Term(_))
933 ));
934 }
935}