[dice] Move bcc_main_flow to the library libdiced_open_dice

This cl splits the existing BccMainFlow wrapper with retries
into a raw version and a retry version. The former is
available in both std and nostd environment. The latter
returns a ZerorizeOnDrop struct containing Attestation CDI
and Sealing CDI. This struct is going to replace the
`DiceContext` in microdroid as it is sets all the CDIs to
zero when the struct goes out of scope, which is more secure.

This is part of the project of merging the two existing dice
wrapper libraries into one library libdiced_open_dice.

Test: atest diced_utils_test diced_sample_inputs_test \
diced_test diced_vendor_test diced_open_dice_cbor_test
Test: m pvmfw_img microdroid_manager && atest \
microdroid_manager_test
Bug: 267575445

Change-Id: I94444619fe2dcddf8541a6c9971c7e565c44dda1
diff --git a/diced/src/hal_node.rs b/diced/src/hal_node.rs
index 1efee8b..ca470e5 100644
--- a/diced/src/hal_node.rs
+++ b/diced/src/hal_node.rs
@@ -343,6 +343,16 @@
         bcc: Vec<u8>,
     }
 
+    impl From<dice::OwnedDiceArtifacts> for InsecureSerializableArtifacts {
+        fn from(dice_artifacts: dice::OwnedDiceArtifacts) -> Self {
+            Self {
+                cdi_attest: dice_artifacts.cdi_values.cdi_attest,
+                cdi_seal: dice_artifacts.cdi_values.cdi_seal,
+                bcc: dice_artifacts.bcc[..].to_vec(),
+            }
+        }
+    }
+
     impl DiceArtifacts for InsecureSerializableArtifacts {
         fn cdi_attest(&self) -> &[u8; dice::CDI_SIZE] {
             &self.cdi_attest
@@ -394,10 +404,8 @@
     /// Test the resident artifact batched derivation in process.
     #[test]
     fn derive_with_resident_artifacts() -> Result<()> {
-        let (cdi_attest, cdi_seal, bcc) = diced_sample_inputs::make_sample_bcc_and_cdis()?;
-
-        let artifacts =
-            ResidentArtifacts::new(cdi_attest[..].try_into()?, cdi_seal[..].try_into()?, &bcc)?;
+        let artifacts: ResidentArtifacts =
+            diced_sample_inputs::make_sample_bcc_and_cdis()?.try_into()?;
 
         let input_values = &[
             make_input_values(
@@ -433,18 +441,13 @@
     /// the same test vector as the in process test above.
     #[test]
     fn derive_with_insecure_artifacts() -> Result<()> {
-        let (cdi_attest, cdi_seal, bcc) = diced_sample_inputs::make_sample_bcc_and_cdis()?;
+        let dice_artifacts = diced_sample_inputs::make_sample_bcc_and_cdis()?;
 
         // Safety: ResidentHal can only be used in single threaded environments.
         // On-device Rust tests run each test in a separate process.
-        let hal_impl = unsafe {
-            ResidentHal::new(InsecureSerializableArtifacts {
-                cdi_attest: cdi_attest[..].try_into()?,
-                cdi_seal: cdi_seal[..].try_into()?,
-                bcc,
-            })
-        }
-        .expect("Failed to create ResidentHal.");
+        let hal_impl =
+            unsafe { ResidentHal::new(InsecureSerializableArtifacts::from(dice_artifacts)) }
+                .expect("Failed to create ResidentHal.");
 
         let bcc_handover = hal_impl
             .derive(&[
@@ -474,18 +477,13 @@
     /// must yield the same outcome as three derivations with the same input values.
     #[test]
     fn demote() -> Result<()> {
-        let (cdi_attest, cdi_seal, bcc) = diced_sample_inputs::make_sample_bcc_and_cdis()?;
+        let dice_artifacts = diced_sample_inputs::make_sample_bcc_and_cdis()?;
 
         // Safety: ResidentHal can only be used in single threaded environments.
         // On-device Rust tests run each test in a separate process.
-        let hal_impl = unsafe {
-            ResidentHal::new(InsecureSerializableArtifacts {
-                cdi_attest: cdi_attest[..].try_into()?,
-                cdi_seal: cdi_seal[..].try_into()?,
-                bcc,
-            })
-        }
-        .expect("Failed to create ResidentHal.");
+        let hal_impl =
+            unsafe { ResidentHal::new(InsecureSerializableArtifacts::from(dice_artifacts)) }
+                .expect("Failed to create ResidentHal.");
 
         hal_impl
             .demote(&[
diff --git a/diced/src/resident_node.rs b/diced/src/resident_node.rs
index d65f30c..4d6a7bc 100644
--- a/diced/src/resident_node.rs
+++ b/diced/src/resident_node.rs
@@ -36,21 +36,6 @@
 }
 
 impl ResidentNode {
-    /// Creates a new Resident node with the given dice secrets and certificate chain.
-    pub fn new(
-        cdi_attest: &[u8; dice::CDI_SIZE],
-        cdi_seal: &[u8; dice::CDI_SIZE],
-        bcc: Vec<u8>,
-    ) -> Result<Self> {
-        Ok(ResidentNode {
-            artifacts: RwLock::new(
-                ResidentArtifacts::new(cdi_attest, cdi_seal, &bcc)
-                    .context("In ResidentNode::new: Trying to initialize ResidentArtifacts")?,
-            ),
-            demotion_db: Default::default(),
-        })
-    }
-
     fn get_effective_artifacts(
         &self,
         client: BinderInputValues,
diff --git a/diced/src/sample_inputs.rs b/diced/src/sample_inputs.rs
index 5b61fed..92bdf76 100644
--- a/diced/src/sample_inputs.rs
+++ b/diced/src/sample_inputs.rs
@@ -22,7 +22,6 @@
 use dice::ContextImpl;
 use diced_open_dice_cbor as dice;
 use diced_utils::{cbor, to_dice_input_values};
-use keystore2_crypto::ZVec;
 use std::convert::TryInto;
 use std::ffi::CStr;
 use std::io::Write;
@@ -66,7 +65,7 @@
 
 /// Derives a tuple of (CDI_ATTEST, CDI_SEAL, BCC) derived of the vector of input values returned
 /// by `get_input_values_vector`.
-pub fn make_sample_bcc_and_cdis() -> Result<(ZVec, ZVec, Vec<u8>)> {
+pub fn make_sample_bcc_and_cdis() -> Result<dice::OwnedDiceArtifacts> {
     let mut dice_ctx = dice::OpenDiceCborContext::new();
     let private_key_seed = dice::derive_cdi_private_key_seed(UDS)
         .context("In make_sample_bcc_and_cdis: Trying to derive private key seed.")?;
@@ -93,30 +92,24 @@
 
     bcc.append(&mut cert);
 
-    let (cdi_attest, cdi_seal, bcc) = dice_ctx
-        .bcc_main_flow(
-            &cdi_attest[..].try_into().context(
-                "In make_sample_bcc_and_cdis: Failed to convert cdi_attest to array reference. (1)",
-            )?,
-            &cdi_seal[..].try_into().context(
-                "In make_sample_bcc_and_cdis: Failed to convert cdi_seal to array reference. (1)",
-            )?,
-            &bcc,
-            &to_dice_input_values(&input_values_vector[1]),
-        )
-        .context("In make_sample_bcc_and_cdis: Trying to run first bcc main flow.")?;
-    dice_ctx
-        .bcc_main_flow(
-            &cdi_attest[..].try_into().context(
-                "In make_sample_bcc_and_cdis: Failed to convert cdi_attest to array reference. (2)",
-            )?,
-            &cdi_seal[..].try_into().context(
-                "In make_sample_bcc_and_cdis: Failed to convert cdi_seal to array reference. (2)",
-            )?,
-            &bcc,
-            &to_dice_input_values(&input_values_vector[2]),
-        )
-        .context("In make_sample_bcc_and_cdis: Trying to run second bcc main flow.")
+    let dice_artifacts = dice::retry_bcc_main_flow(
+        &cdi_attest[..].try_into().context(
+            "In make_sample_bcc_and_cdis: Failed to convert cdi_attest to array reference. (1)",
+        )?,
+        &cdi_seal[..].try_into().context(
+            "In make_sample_bcc_and_cdis: Failed to convert cdi_seal to array reference. (1)",
+        )?,
+        &bcc,
+        &to_dice_input_values(&input_values_vector[1]),
+    )
+    .context("In make_sample_bcc_and_cdis: Trying to run first bcc main flow.")?;
+    dice::retry_bcc_main_flow(
+        &dice_artifacts.cdi_values.cdi_attest,
+        &dice_artifacts.cdi_values.cdi_seal,
+        &dice_artifacts.bcc,
+        &to_dice_input_values(&input_values_vector[2]),
+    )
+    .context("In make_sample_bcc_and_cdis: Trying to run second bcc main flow.")
 }
 
 fn make_input_values(
diff --git a/diced/src/utils.rs b/diced/src/utils.rs
index 3d35ae5..c249366 100644
--- a/diced/src/utils.rs
+++ b/diced/src/utils.rs
@@ -19,7 +19,6 @@
     Mode::Mode as BinderMode,
 };
 use anyhow::{Context, Result};
-use dice::{ContextImpl, DiceMode};
 use diced_open_dice_cbor as dice;
 use keystore2_crypto::ZVec;
 use std::convert::TryInto;
@@ -38,13 +37,13 @@
     )
 }
 
-fn to_dice_mode(binder_mode: BinderMode) -> DiceMode {
+fn to_dice_mode(binder_mode: BinderMode) -> dice::DiceMode {
     match binder_mode {
-        BinderMode::NOT_INITIALIZED => DiceMode::kDiceModeNotInitialized,
-        BinderMode::NORMAL => DiceMode::kDiceModeNormal,
-        BinderMode::DEBUG => DiceMode::kDiceModeDebug,
-        BinderMode::RECOVERY => DiceMode::kDiceModeMaintenance,
-        _ => DiceMode::kDiceModeNotInitialized,
+        BinderMode::NOT_INITIALIZED => dice::DiceMode::kDiceModeNotInitialized,
+        BinderMode::NORMAL => dice::DiceMode::kDiceModeNormal,
+        BinderMode::DEBUG => dice::DiceMode::kDiceModeDebug,
+        BinderMode::RECOVERY => dice::DiceMode::kDiceModeMaintenance,
+        _ => dice::DiceMode::kDiceModeNotInitialized,
     }
 }
 
@@ -68,6 +67,18 @@
     bcc: Vec<u8>,
 }
 
+impl TryFrom<dice::OwnedDiceArtifacts> for ResidentArtifacts {
+    type Error = anyhow::Error;
+
+    fn try_from(dice_artifacts: dice::OwnedDiceArtifacts) -> Result<Self, Self::Error> {
+        Ok(ResidentArtifacts {
+            cdi_attest: dice_artifacts.cdi_values.cdi_attest[..].try_into()?,
+            cdi_seal: dice_artifacts.cdi_values.cdi_seal[..].try_into()?,
+            bcc: dice_artifacts.bcc[..].to_vec(),
+        })
+    }
+}
+
 impl ResidentArtifacts {
     /// Create a ResidentArtifacts object. The parameters ensure that the stored secrets
     /// can only have the appropriate size, so that subsequent casts to array references
@@ -125,19 +136,18 @@
     fn execute_step(self, input_values: &BinderInputValues) -> Result<Self> {
         let ResidentArtifacts { cdi_attest, cdi_seal, bcc } = self;
 
-        let (cdi_attest, cdi_seal, bcc) = dice::OpenDiceCborContext::new()
-            .bcc_main_flow(
-                cdi_attest[..].try_into().with_context(|| {
-                    format!("Trying to convert cdi_attest. (length: {})", cdi_attest.len())
-                })?,
-                cdi_seal[..].try_into().with_context(|| {
-                    format!("Trying to convert cdi_seal. (length: {})", cdi_seal.len())
-                })?,
-                &bcc,
-                &to_dice_input_values(input_values),
-            )
-            .context("In ResidentArtifacts::execute_step:")?;
-        Ok(ResidentArtifacts { cdi_attest, cdi_seal, bcc })
+        dice::retry_bcc_main_flow(
+            cdi_attest[..].try_into().with_context(|| {
+                format!("Trying to convert cdi_attest. (length: {})", cdi_attest.len())
+            })?,
+            cdi_seal[..].try_into().with_context(|| {
+                format!("Trying to convert cdi_seal. (length: {})", cdi_seal.len())
+            })?,
+            &bcc,
+            &to_dice_input_values(input_values),
+        )
+        .context("In ResidentArtifacts::execute_step:")?
+        .try_into()
     }
 
     /// Iterate through the iterator of dice input values performing one