[dice] Create libdiced_open_dice[_nostd] to reuse dice in nostd

Test: atest diced_utils_test diced_sample_inputs_test \
diced_test diced_vendor_test
Bug: 267575445

Change-Id: I3cf1b818938a6b1496657f9391424f2a351148fe
diff --git a/diced/open_dice/Android.bp b/diced/open_dice/Android.bp
new file mode 100644
index 0000000..be8388f
--- /dev/null
+++ b/diced/open_dice/Android.bp
@@ -0,0 +1,36 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_defaults {
+    name: "libdiced_open_dice_defaults",
+    crate_name: "diced_open_dice",
+    srcs: ["src/lib.rs"],
+    static_libs: [
+        "libopen_dice_cbor",
+    ],
+    vendor_available: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.virt",
+    ],
+}
+
+rust_library_rlib {
+    name: "libdiced_open_dice_nostd",
+    defaults: ["libdiced_open_dice_defaults"],
+    rustlibs: [
+        "libopen_dice_cbor_bindgen_nostd",
+    ],
+}
+
+rust_library_rlib {
+    name: "libdiced_open_dice",
+    defaults: ["libdiced_open_dice_defaults"],
+    rustlibs: [
+        "libopen_dice_cbor_bindgen",
+    ],
+    features: [
+        "std",
+    ],
+}
\ No newline at end of file
diff --git a/diced/open_dice/src/dice.rs b/diced/open_dice/src/dice.rs
new file mode 100644
index 0000000..c08cc40
--- /dev/null
+++ b/diced/open_dice/src/dice.rs
@@ -0,0 +1,112 @@
+// Copyright 2023, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Structs and functions about the types used in DICE.
+//! This module mirrors the content in open-dice/include/dice/dice.h
+
+use core::ptr;
+use open_dice_cbor_bindgen::{
+    DiceConfigType, DiceInputValues, DiceMode, DICE_HASH_SIZE, DICE_HIDDEN_SIZE,
+    DICE_INLINE_CONFIG_SIZE,
+};
+
+/// The size of a DICE hash.
+pub const HASH_SIZE: usize = DICE_HASH_SIZE as usize;
+/// The size of the DICE hidden value.
+pub const HIDDEN_SIZE: usize = DICE_HIDDEN_SIZE as usize;
+/// The size of a DICE inline config.
+const INLINE_CONFIG_SIZE: usize = DICE_INLINE_CONFIG_SIZE as usize;
+
+/// Array type of hashes used by DICE.
+pub type Hash = [u8; HASH_SIZE];
+/// Array type of additional input.
+pub type Hidden = [u8; HIDDEN_SIZE];
+/// Array type of inline configuration values.
+pub type InlineConfig = [u8; INLINE_CONFIG_SIZE];
+
+/// Configuration descriptor for DICE input values.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Config<'a> {
+    /// Reference to an inline descriptor.
+    Inline(&'a InlineConfig),
+    /// Reference to a free form descriptor that will be hashed by the implementation.
+    Descriptor(&'a [u8]),
+}
+
+impl Config<'_> {
+    fn dice_config_type(&self) -> DiceConfigType {
+        match self {
+            Self::Inline(_) => DiceConfigType::kDiceConfigTypeInline,
+            Self::Descriptor(_) => DiceConfigType::kDiceConfigTypeDescriptor,
+        }
+    }
+
+    fn inline_config(&self) -> InlineConfig {
+        match self {
+            Self::Inline(inline) => **inline,
+            Self::Descriptor(_) => [0u8; INLINE_CONFIG_SIZE],
+        }
+    }
+
+    fn descriptor_ptr(&self) -> *const u8 {
+        match self {
+            Self::Descriptor(descriptor) => descriptor.as_ptr(),
+            _ => ptr::null(),
+        }
+    }
+
+    fn descriptor_size(&self) -> usize {
+        match self {
+            Self::Descriptor(descriptor) => descriptor.len(),
+            _ => 0,
+        }
+    }
+}
+
+/// Wrap of `DiceInputValues`.
+#[derive(Clone, Debug)]
+pub struct InputValues(DiceInputValues);
+
+impl InputValues {
+    /// Creates a new `InputValues`.
+    pub fn new(
+        code_hash: &Hash,
+        code_descriptor: Option<&[u8]>,
+        config: Config,
+        authority_hash: &Hash,
+        authority_descriptor: Option<&[u8]>,
+        mode: DiceMode,
+        hidden: Option<&Hidden>,
+    ) -> Self {
+        Self(DiceInputValues {
+            code_hash: *code_hash,
+            code_descriptor: code_descriptor.map_or(ptr::null(), |d| d.as_ptr()),
+            code_descriptor_size: code_descriptor.map_or(0, |d| d.len()),
+            config_type: config.dice_config_type(),
+            config_value: config.inline_config(),
+            config_descriptor: config.descriptor_ptr(),
+            config_descriptor_size: config.descriptor_size(),
+            authority_hash: *authority_hash,
+            authority_descriptor: authority_descriptor.map_or(ptr::null(), |d| d.as_ptr()),
+            authority_descriptor_size: authority_descriptor.map_or(0, |d| d.len()),
+            mode,
+            hidden: hidden.map_or([0; HIDDEN_SIZE], |h| *h),
+        })
+    }
+
+    /// Returns a raw pointer to the wrapped `DiceInputValues`.
+    pub fn as_ptr(&self) -> *const DiceInputValues {
+        &self.0 as *const DiceInputValues
+    }
+}
diff --git a/diced/open_dice/src/lib.rs b/diced/open_dice/src/lib.rs
new file mode 100644
index 0000000..96e2569
--- /dev/null
+++ b/diced/open_dice/src/lib.rs
@@ -0,0 +1,22 @@
+// Copyright 2023, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Implements safe wrappers around the public API of libopen-dice for
+//! both std and nostd usages.
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+mod dice;
+
+pub use dice::{Config, Hash, Hidden, InlineConfig, InputValues, HASH_SIZE, HIDDEN_SIZE};
diff --git a/diced/open_dice_cbor/Android.bp b/diced/open_dice_cbor/Android.bp
index a84190a..3a7f04c 100644
--- a/diced/open_dice_cbor/Android.bp
+++ b/diced/open_dice_cbor/Android.bp
@@ -22,6 +22,7 @@
     srcs: ["lib.rs"],
 
     rustlibs: [
+        "libdiced_open_dice",
         // For ZVec
         "libkeystore2_crypto_rust",
         "libopen_dice_bcc_bindgen",
@@ -46,6 +47,7 @@
     test_suites: ["general-tests"],
     auto_gen_config: true,
     rustlibs: [
+        "libdiced_open_dice",
         "libdiced_sample_inputs",
         "libkeystore2_crypto_rust",
         "libopen_dice_bcc_bindgen",
diff --git a/diced/open_dice_cbor/lib.rs b/diced/open_dice_cbor/lib.rs
index 78f5c81..e5bda89 100644
--- a/diced/open_dice_cbor/lib.rs
+++ b/diced/open_dice_cbor/lib.rs
@@ -31,19 +31,18 @@
 //!     .main_flow(&parent_cdi_attest, &parent_cdi_seal, &input_values)?;
 //! ```
 
+use diced_open_dice::InlineConfig;
+pub use diced_open_dice::{Config, Hash, Hidden, HASH_SIZE, HIDDEN_SIZE};
 use keystore2_crypto::{zvec, ZVec};
 use open_dice_bcc_bindgen::BccMainFlow;
 pub use open_dice_cbor_bindgen::DiceMode;
 use open_dice_cbor_bindgen::{
-    DiceConfigType, DiceDeriveCdiCertificateId, DiceDeriveCdiPrivateKeySeed,
-    DiceGenerateCertificate, DiceHash, DiceInputValues, DiceKdf, DiceKeypairFromSeed, DiceMainFlow,
-    DiceResult, DiceSign, DiceVerify, DICE_CDI_SIZE, DICE_HASH_SIZE, DICE_HIDDEN_SIZE,
-    DICE_ID_SIZE, DICE_INLINE_CONFIG_SIZE, DICE_PRIVATE_KEY_SEED_SIZE, DICE_PRIVATE_KEY_SIZE,
+    DiceDeriveCdiCertificateId, DiceDeriveCdiPrivateKeySeed, DiceGenerateCertificate, DiceHash,
+    DiceInputValues, DiceKdf, DiceKeypairFromSeed, DiceMainFlow, DiceResult, DiceSign, DiceVerify,
+    DICE_CDI_SIZE, DICE_ID_SIZE, DICE_PRIVATE_KEY_SEED_SIZE, DICE_PRIVATE_KEY_SIZE,
     DICE_PUBLIC_KEY_SIZE, DICE_SIGNATURE_SIZE,
 };
 use open_dice_cbor_bindgen::{
-    DiceConfigType_kDiceConfigTypeDescriptor as DICE_CONFIG_TYPE_DESCRIPTOR,
-    DiceConfigType_kDiceConfigTypeInline as DICE_CONFIG_TYPE_INLINE,
     DiceResult_kDiceResultBufferTooSmall as DICE_RESULT_BUFFER_TOO_SMALL,
     DiceResult_kDiceResultInvalidInput as DICE_RESULT_INVALID_INPUT,
     DiceResult_kDiceResultOk as DICE_RESULT_OK,
@@ -51,12 +50,6 @@
 };
 use std::ffi::{c_void, NulError};
 
-/// The size of a DICE hash.
-pub const HASH_SIZE: usize = DICE_HASH_SIZE as usize;
-/// The size of the DICE hidden value.
-pub const HIDDEN_SIZE: usize = DICE_HIDDEN_SIZE as usize;
-/// The size of a DICE inline config.
-pub const INLINE_CONFIG_SIZE: usize = DICE_INLINE_CONFIG_SIZE as usize;
 /// The size of a private key seed.
 pub const PRIVATE_KEY_SEED_SIZE: usize = DICE_PRIVATE_KEY_SEED_SIZE as usize;
 /// The size of a CDI.
@@ -119,50 +112,11 @@
     }
 }
 
-/// Configuration descriptor for dice input values.
-#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
-pub enum Config<'a> {
-    /// A reference to an inline descriptor.
-    Inline(&'a [u8; INLINE_CONFIG_SIZE]),
-    /// A reference to a free form descriptor that will be hashed by the implementation.
-    Descriptor(&'a [u8]),
-}
-
 enum ConfigOwned {
-    Inline([u8; INLINE_CONFIG_SIZE]),
+    Inline(InlineConfig),
     Descriptor(Vec<u8>),
 }
 
-impl Config<'_> {
-    fn get_type(&self) -> DiceConfigType {
-        match self {
-            Self::Inline(_) => DICE_CONFIG_TYPE_INLINE,
-            Self::Descriptor(_) => DICE_CONFIG_TYPE_DESCRIPTOR,
-        }
-    }
-
-    fn get_inline(&self) -> [u8; INLINE_CONFIG_SIZE] {
-        match self {
-            Self::Inline(inline) => **inline,
-            _ => [0u8; INLINE_CONFIG_SIZE],
-        }
-    }
-
-    fn get_descriptor_as_ptr(&self) -> *const u8 {
-        match self {
-            Self::Descriptor(descriptor) => descriptor.as_ptr(),
-            _ => std::ptr::null(),
-        }
-    }
-
-    fn get_descriptor_size(&self) -> usize {
-        match self {
-            Self::Descriptor(descriptor) => descriptor.len(),
-            _ => 0,
-        }
-    }
-}
-
 impl From<Config<'_>> for ConfigOwned {
     fn from(config: Config) -> Self {
         match config {
@@ -175,38 +129,38 @@
 /// This trait allows API users to supply DICE input values without copying.
 pub trait InputValues {
     /// Returns the code hash.
-    fn code_hash(&self) -> &[u8; HASH_SIZE];
+    fn code_hash(&self) -> &Hash;
     /// Returns the config.
     fn config(&self) -> Config;
     /// Returns the authority hash.
-    fn authority_hash(&self) -> &[u8; HASH_SIZE];
+    fn authority_hash(&self) -> &Hash;
     /// Returns the authority descriptor.
     fn authority_descriptor(&self) -> Option<&[u8]>;
     /// Returns the mode.
     fn mode(&self) -> DiceMode;
     /// Returns the hidden value.
-    fn hidden(&self) -> &[u8; HIDDEN_SIZE];
+    fn hidden(&self) -> &Hidden;
 }
 
 /// An owning convenience type implementing `InputValues`.
 pub struct InputValuesOwned {
-    code_hash: [u8; HASH_SIZE],
+    code_hash: Hash,
     config: ConfigOwned,
-    authority_hash: [u8; HASH_SIZE],
+    authority_hash: Hash,
     authority_descriptor: Option<Vec<u8>>,
     mode: DiceMode,
-    hidden: [u8; HIDDEN_SIZE],
+    hidden: Hidden,
 }
 
 impl InputValuesOwned {
     /// Construct a new instance of InputValuesOwned.
     pub fn new(
-        code_hash: [u8; HASH_SIZE],
+        code_hash: Hash,
         config: Config,
-        authority_hash: [u8; HASH_SIZE],
+        authority_hash: Hash,
         authority_descriptor: Option<Vec<u8>>,
         mode: DiceMode,
-        hidden: [u8; HIDDEN_SIZE],
+        hidden: Hidden,
     ) -> Self {
         Self {
             code_hash,
@@ -220,7 +174,7 @@
 }
 
 impl InputValues for InputValuesOwned {
-    fn code_hash(&self) -> &[u8; HASH_SIZE] {
+    fn code_hash(&self) -> &Hash {
         &self.code_hash
     }
     fn config(&self) -> Config {
@@ -229,7 +183,7 @@
             ConfigOwned::Descriptor(descriptor) => Config::Descriptor(descriptor.as_slice()),
         }
     }
-    fn authority_hash(&self) -> &[u8; HASH_SIZE] {
+    fn authority_hash(&self) -> &Hash {
         &self.authority_hash
     }
     fn authority_descriptor(&self) -> Option<&[u8]> {
@@ -238,7 +192,7 @@
     fn mode(&self) -> DiceMode {
         self.mode
     }
-    fn hidden(&self) -> &[u8; HIDDEN_SIZE] {
+    fn hidden(&self) -> &Hidden {
         &self.hidden
     }
 }
@@ -247,24 +201,16 @@
 where
     F: FnOnce(*const DiceInputValues) -> Result<R>,
 {
-    let input_values = DiceInputValues {
-        code_hash: *input_values.code_hash(),
-        code_descriptor: std::ptr::null(),
-        code_descriptor_size: 0,
-        config_type: input_values.config().get_type(),
-        config_value: input_values.config().get_inline(),
-        config_descriptor: input_values.config().get_descriptor_as_ptr(),
-        config_descriptor_size: input_values.config().get_descriptor_size(),
-        authority_hash: *input_values.authority_hash(),
-        authority_descriptor: input_values
-            .authority_descriptor()
-            .map_or_else(std::ptr::null, <[u8]>::as_ptr),
-        authority_descriptor_size: input_values.authority_descriptor().map_or(0, <[u8]>::len),
-        mode: input_values.mode(),
-        hidden: *input_values.hidden(),
-    };
-
-    f(&input_values as *const DiceInputValues)
+    let input_values = diced_open_dice::InputValues::new(
+        input_values.code_hash(),
+        None, // code_descriptor
+        input_values.config(),
+        input_values.authority_hash(),
+        input_values.authority_descriptor(),
+        input_values.mode(),
+        Some(input_values.hidden()),
+    );
+    f(input_values.as_ptr())
 }
 
 /// Multiple of the open dice function required preallocated output buffer
diff --git a/diced/src/sample_inputs.rs b/diced/src/sample_inputs.rs
index bab296a..14e0efa 100644
--- a/diced/src/sample_inputs.rs
+++ b/diced/src/sample_inputs.rs
@@ -121,13 +121,13 @@
 }
 
 fn make_input_values(
-    code_hash: &[u8; dice::HASH_SIZE],
-    authority_hash: &[u8; dice::HASH_SIZE],
+    code_hash: &dice::Hash,
+    authority_hash: &dice::Hash,
     config_name: &str,
     config_version: u64,
     config_resettable: bool,
     mode: Mode,
-    hidden: &[u8; dice::HIDDEN_SIZE],
+    hidden: &dice::Hidden,
 ) -> Result<BinderInputValues> {
     Ok(BinderInputValues {
         codeHash: *code_hash,
diff --git a/diced/src/utils.rs b/diced/src/utils.rs
index da39f8f..05702ad 100644
--- a/diced/src/utils.rs
+++ b/diced/src/utils.rs
@@ -19,7 +19,7 @@
     Mode::Mode as BinderMode,
 };
 use anyhow::{Context, Result};
-use dice::{ContextImpl, DiceMode};
+use dice::{ContextImpl, DiceMode, Hash, Hidden};
 use diced_open_dice_cbor as dice;
 use keystore2_crypto::ZVec;
 use std::convert::TryInto;
@@ -47,7 +47,7 @@
 }
 
 impl dice::InputValues for InputValues<'_> {
-    fn code_hash(&self) -> &[u8; dice::HASH_SIZE] {
+    fn code_hash(&self) -> &Hash {
         &self.0.codeHash
     }
 
@@ -55,7 +55,7 @@
         dice::Config::Descriptor(self.0.config.desc.as_slice())
     }
 
-    fn authority_hash(&self) -> &[u8; dice::HASH_SIZE] {
+    fn authority_hash(&self) -> &Hash {
         &self.0.authorityHash
     }
 
@@ -73,7 +73,7 @@
         }
     }
 
-    fn hidden(&self) -> &[u8; dice::HIDDEN_SIZE] {
+    fn hidden(&self) -> &Hidden {
         // If `self` was created using try_from the length was checked and this cannot panic.
         &self.0.hidden
     }