use rusty_esp_core::error::{Error, Result};
use sha2::Digest;
use crate::did::Did;
use crate::signer::{DeviceSigner, verify_prehash};
pub const STATUS_DOMAIN: &[u8] = b"janus-status-v1\n";
pub const STATUS_VERSION: u8 = 1;
pub const KIND_ADOPTION_V1: &str = "janus-adoption-v1";
pub const KIND_MATA_STATEMENT: &str = "mata-statement-v1";
pub const NO_ADOPTION: [u8; 32] = [0; 32];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StatusProof<'a> {
pub nonce: &'a [u8; 32],
pub device_did: &'a str,
pub owner_did: &'a str,
pub adoption_kind: &'a str,
pub adoption_hash: [u8; 32],
}
impl<'a> StatusProof<'a> {
#[must_use]
pub const fn unadopted(nonce: &'a [u8; 32], device_did: &'a str) -> Self {
Self {
nonce,
device_did,
owner_did: "",
adoption_kind: "",
adoption_hash: NO_ADOPTION,
}
}
#[must_use]
pub fn adopted(
nonce: &'a [u8; 32],
device_did: &'a str,
owner_did: &'a str,
adoption_kind: &'a str,
adoption: &[u8],
) -> Self {
Self {
nonce,
device_did,
owner_did,
adoption_kind,
adoption_hash: crate::sha256(adoption),
}
}
#[must_use]
pub fn len(&self) -> usize {
STATUS_DOMAIN.len()
+ 1
+ 32
+ 2
+ self.device_did.len()
+ 2
+ self.owner_did.len()
+ 2
+ self.adoption_kind.len()
+ 32
}
#[must_use]
pub fn is_empty(&self) -> bool {
false
}
fn fields(&self, mut put: impl FnMut(&[u8])) -> Result<()> {
let str16 = |s: &str| -> Result<[u8; 2]> {
let n = u16::try_from(s.len()).map_err(|_| Error::InvalidFormat)?;
Ok(n.to_be_bytes())
};
let (dev, own, kind) = (
str16(self.device_did)?,
str16(self.owner_did)?,
str16(self.adoption_kind)?,
);
put(STATUS_DOMAIN);
put(&[STATUS_VERSION]);
put(self.nonce);
put(&dev);
put(self.device_did.as_bytes());
put(&own);
put(self.owner_did.as_bytes());
put(&kind);
put(self.adoption_kind.as_bytes());
put(&self.adoption_hash);
Ok(())
}
pub fn write(&self, out: &mut [u8]) -> Result<usize> {
let needed = self.len();
if out.len() < needed {
return Err(Error::BufferTooSmall { needed });
}
let mut at = 0;
self.fields(|b| {
out[at..at + b.len()].copy_from_slice(b);
at += b.len();
})?;
Ok(at)
}
pub fn prehash(&self) -> Result<[u8; 32]> {
let mut h = sha2::Sha256::new();
self.fields(|b| h.update(b))?;
Ok(h.finalize().into())
}
pub fn sign(&self, signer: &impl DeviceSigner) -> Result<[u8; 64]> {
Ok(signer.sign_prehash(&self.prehash()?))
}
pub fn verify(&self, signature: &[u8; 64]) -> Result<()> {
let did = Did::parse(self.device_did)?;
verify_prehash(did.pubkey(), &self.prehash()?, signature)
}
}
pub fn parse_nonce_hex(s: &str) -> Result<[u8; 32]> {
let b = s.as_bytes();
if b.len() != 64 {
return Err(Error::InvalidFormat);
}
let nibble = |c: u8| -> Result<u8> {
match c {
b'0'..=b'9' => Ok(c - b'0'),
b'a'..=b'f' => Ok(c - b'a' + 10),
_ => Err(Error::InvalidFormat),
}
};
let mut out = [0u8; 32];
for (i, o) in out.iter_mut().enumerate() {
*o = (nibble(b[2 * i])? << 4) | nibble(b[2 * i + 1])?;
}
Ok(out)
}
#[cfg(feature = "alloc")]
pub use document::{Adoption, StatusDocument};
#[cfg(feature = "alloc")]
mod document {
use alloc::string::{String, ToString};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde_json::{Map, Value, json};
use super::StatusProof;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Adoption<'a> {
pub owner_did: &'a str,
pub kind: &'a str,
pub bytes: &'a [u8],
}
#[derive(Debug, Clone, PartialEq)]
pub struct StatusDocument<'a> {
pub device_did: &'a str,
pub maker_did: Option<&'a str>,
pub model: &'a str,
pub node_id: Option<&'a str>,
pub adoption: Option<Adoption<'a>>,
pub extra: Map<String, Value>,
}
const FIELDS: [&str; 9] = [
"pair",
"maker_did",
"model",
"device_did",
"node_id",
"owner_did",
"adoption_kind",
"adoption",
"device_sig",
];
impl StatusDocument<'_> {
fn pair(&self) -> Value {
match &self.adoption {
None => Value::from("ready"),
Some(a) => json!({ "paired": { "owner_did": a.owner_did } }),
}
}
#[must_use]
pub fn plain(&self) -> Value {
json!({
"pair": self.pair(),
"maker_did": self.maker_did,
"model": self.model,
"device_did": self.device_did,
"node_id": self.node_id,
})
}
pub fn signed(
&self,
nonce: &[u8; 32],
sign: impl FnOnce(&[u8; 32]) -> [u8; 64],
) -> rusty_esp_core::error::Result<Value> {
let proof = match &self.adoption {
None => StatusProof::unadopted(nonce, self.device_did),
Some(a) => {
StatusProof::adopted(nonce, self.device_did, a.owner_did, a.kind, a.bytes)
}
};
let sig = sign(&proof.prehash()?);
let mut out = Map::new();
for (k, v) in &self.extra {
if !FIELDS.contains(&k.as_str()) {
out.insert(k.clone(), v.clone());
}
}
if let Value::Object(plain) = self.plain() {
out.extend(plain);
}
if let Some(a) = &self.adoption {
out.insert("owner_did".to_string(), a.owner_did.into());
out.insert("adoption_kind".to_string(), a.kind.into());
out.insert(
"adoption".to_string(),
URL_SAFE_NO_PAD.encode(a.bytes).into(),
);
}
out.insert("device_sig".to_string(), URL_SAFE_NO_PAD.encode(sig).into());
Ok(Value::Object(out))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::key::DeviceKey;
const NONCE: [u8; 32] = [
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
0x1e, 0x1f,
];
fn did_of(key: &DeviceKey) -> ([u8; 64], usize) {
let mut buf = [0u8; 64];
let n = key.did().write(&mut buf).expect("did fits").len();
(buf, n)
}
fn by_hand(device: &str, owner: &str, kind: &str, hash: &[u8; 32]) -> Vec<u8> {
let mut m = Vec::new();
m.extend_from_slice(b"janus-status-v1\n");
m.push(1);
m.extend_from_slice(&NONCE);
for s in [device, owner, kind] {
m.extend_from_slice(&(s.len() as u16).to_be_bytes());
m.extend_from_slice(s.as_bytes());
}
m.extend_from_slice(hash);
m
}
#[test]
fn the_message_is_laid_out_as_the_contract_says() {
let key = DeviceKey::from_seed_for_tests("status-vector-device", "dev-1");
let (buf, n) = did_of(&key);
let device = core::str::from_utf8(&buf[..n]).unwrap();
let owner = "did:mata:owner-for-the-layout-test";
let adoption = b"an adoption's raw bytes";
let p = StatusProof::adopted(&NONCE, device, owner, KIND_ADOPTION_V1, adoption);
let mut out = [0u8; 256];
let len = p.write(&mut out).unwrap();
assert_eq!(len, p.len());
let expected = by_hand(device, owner, KIND_ADOPTION_V1, &crate::sha256(adoption));
assert_eq!(&out[..len], &expected[..]);
assert_eq!(p.prehash().unwrap(), crate::sha256(&expected));
}
#[test]
fn unadopted_is_empty_strings_and_a_zero_hash() {
let p = StatusProof::unadopted(&NONCE, "did:mata:x");
let mut out = [0u8; 128];
let len = p.write(&mut out).unwrap();
assert_eq!(&out[..len], &by_hand("did:mata:x", "", "", &[0; 32])[..]);
assert_ne!(NO_ADOPTION, crate::sha256(b""));
}
#[test]
fn a_short_buffer_says_what_it_needed() {
let p = StatusProof::unadopted(&NONCE, "did:mata:x");
assert_eq!(
p.write(&mut [0u8; 8]),
Err(Error::BufferTooSmall { needed: p.len() })
);
}
#[test]
fn signed_by_the_device_verifies_and_nothing_else_does() {
let key = DeviceKey::from_seed_for_tests("status-vector-device", "dev-1");
let (buf, n) = did_of(&key);
let device = core::str::from_utf8(&buf[..n]).unwrap();
let p = StatusProof::adopted(&NONCE, device, "did:mata:o", KIND_MATA_STATEMENT, b"h.p.s");
let sig = p.sign(&key).unwrap();
assert_eq!(p.verify(&sig), Ok(()));
let other_nonce = [9u8; 32];
assert!(
StatusProof {
nonce: &other_nonce,
..p
}
.verify(&sig)
.is_err()
);
assert!(
StatusProof {
owner_did: "did:mata:p",
..p
}
.verify(&sig)
.is_err()
);
assert!(
StatusProof {
adoption_kind: KIND_ADOPTION_V1,
..p
}
.verify(&sig)
.is_err()
);
assert!(
StatusProof {
adoption_hash: NO_ADOPTION,
..p
}
.verify(&sig)
.is_err()
);
let other = DeviceKey::from_seed_for_tests("someone-else", "dev-2");
assert!(p.verify(&p.sign(&other).unwrap()).is_err());
use p256::elliptic_curve::PrimeField;
let mut high = sig;
let mut s_bytes = p256::FieldBytes::default();
s_bytes.copy_from_slice(&sig[32..]);
let s = p256::Scalar::from_repr(s_bytes).into_option().unwrap();
high[32..].copy_from_slice(&(-s).to_bytes());
assert!(p.verify(&high).is_err());
}
#[test]
fn the_nonce_is_64_lowercase_hex() {
let hex: String = NONCE.iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(parse_nonce_hex(&hex), Ok(NONCE));
assert!(parse_nonce_hex(&hex.to_uppercase()).is_err());
assert!(parse_nonce_hex(&hex[..62]).is_err());
assert!(parse_nonce_hex(&format!("{hex}00")).is_err());
assert!(parse_nonce_hex(&format!("{}zz", &hex[..62])).is_err());
}
}
#[cfg(test)]
mod vector {
use super::*;
use crate::key::DeviceKey;
pub const SECRET: &str = "b2f00d8c0abf7e2cffa4dcad2d2b27cf47656e2b97eb19e787c5f69ec0572e67";
pub const DEVICE_DID: &str = "did:mata:huF8W8oTSzSJybQztujeQc5BLiiMXYG7xUtXgkEkXjYj";
pub const NONCE: [u8; 32] = [
0, 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,
];
pub const OWNER_DID: &str = "did:mata:zOwnerForTheVector";
pub const ADOPTION: &[u8] = b"janus-adoption-v1 vector bytes";
pub const MESSAGE: &str = "6a616e75732d7374617475732d76310a01000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f00356469643a6d6174613a6875463857386f54537a534a7962517a74756a65516335424c69694d5859473778557458676b456b586a596a001b6469643a6d6174613a7a4f776e6572466f72546865566563746f7200116a616e75732d61646f7074696f6e2d7631cc0fe955facc03fe83d5c98365c445eea2f021139e78ec8cfbd120c991f9bb1e";
pub const PREHASH: &str = "ff77b0f7d0d4433bac8c76ddafbb4c1f9257a803a59fdc4efb3622c5567079ba";
pub const SIGNATURE: &str = "af346d509a8ec6e32161250a41c9ee4f88197c136c3f977132964f4d542a9ffb068d86182fafa42a2a44787f0c107f71ec553f1a0414292948848ae8bf4d25df";
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
#[test]
fn the_chip_produces_exactly_the_vector() {
let key = DeviceKey::from_seed_for_tests("janus-status-v1-vector", "vector");
assert_eq!(hex(&key.secret_bytes()), SECRET);
let mut buf = [0u8; 64];
assert_eq!(key.did().write(&mut buf).unwrap(), DEVICE_DID);
let p = StatusProof::adopted(&NONCE, DEVICE_DID, OWNER_DID, KIND_ADOPTION_V1, ADOPTION);
let mut out = [0u8; 256];
let n = p.write(&mut out).unwrap();
assert_eq!(hex(&out[..n]), MESSAGE);
assert_eq!(hex(&p.prehash().unwrap()), PREHASH);
let sig = p.sign(&key).unwrap();
assert_eq!(hex(&sig), SIGNATURE);
assert_eq!(p.verify(&sig), Ok(()));
}
#[test]
fn the_document_carries_the_vector() {
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use mid_signer::DeviceSigner;
use serde_json::{Map, Value, json};
let key = DeviceKey::from_seed_for_tests("janus-status-v1-vector", "vector");
let mut extra = Map::new();
extra.insert("boots".into(), 7.into());
extra.insert("device_did".into(), "did:mata:someoneElse".into());
let doc = StatusDocument {
device_did: DEVICE_DID,
maker_did: Some("did:mata:maker"),
model: "XIAO ESP32-S3 Sense camera",
node_id: None,
adoption: Some(Adoption {
owner_did: OWNER_DID,
kind: KIND_ADOPTION_V1,
bytes: ADOPTION,
}),
extra,
};
let plain = doc.plain();
assert_eq!(
plain,
json!({
"pair": { "paired": { "owner_did": OWNER_DID } },
"maker_did": "did:mata:maker",
"model": "XIAO ESP32-S3 Sense camera",
"device_did": DEVICE_DID,
"node_id": null,
})
);
let signed = doc.signed(&NONCE, |h| key.sign_prehash(h)).unwrap();
let s = |k: &str| signed[k].as_str().unwrap().to_owned();
assert_eq!(
hex(&URL_SAFE_NO_PAD.decode(s("device_sig")).unwrap()),
SIGNATURE
);
assert_eq!(URL_SAFE_NO_PAD.decode(s("adoption")).unwrap(), ADOPTION);
assert_eq!(s("owner_did"), OWNER_DID);
assert_eq!(s("adoption_kind"), KIND_ADOPTION_V1);
assert_eq!(s("device_did"), DEVICE_DID);
assert_eq!(signed["boots"], 7);
assert_eq!(signed["node_id"], Value::Null);
let doc = StatusDocument {
adoption: None,
extra: Map::new(),
..doc
};
assert_eq!(doc.plain()["pair"], "ready");
let signed = doc.signed(&NONCE, |h| key.sign_prehash(h)).unwrap();
for k in ["owner_did", "adoption_kind", "adoption"] {
assert!(signed.get(k).is_none(), "{k}");
}
let sig: [u8; 64] = URL_SAFE_NO_PAD
.decode(signed["device_sig"].as_str().unwrap())
.unwrap()
.try_into()
.unwrap();
assert_eq!(
StatusProof::unadopted(&NONCE, DEVICE_DID).verify(&sig),
Ok(())
);
}
}