use alloc::borrow::ToOwned;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use base64::Engine as _;
use serde::{Deserialize, Serialize};
const BASE64: base64::engine::general_purpose::GeneralPurpose =
base64::engine::general_purpose::GeneralPurpose::new(
&base64::alphabet::STANDARD,
base64::engine::general_purpose::GeneralPurposeConfig::new()
.with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent),
);
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedMeterValue {
pub signed_meter_data: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub encoding_method: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signing_method: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub public_key: Option<String>,
}
impl SignedMeterValue {
#[must_use]
pub fn new(signed_meter_data: impl Into<String>) -> Self {
Self {
signed_meter_data: signed_meter_data.into(),
encoding_method: None,
signing_method: None,
public_key: None,
}
}
#[must_use]
pub fn with_encoding_method(mut self, method: impl Into<String>) -> Self {
self.encoding_method = Some(method.into());
self
}
#[must_use]
pub fn with_signing_method(mut self, method: impl Into<String>) -> Self {
self.signing_method = Some(method.into());
self
}
#[must_use]
pub fn with_public_key(mut self, key: impl Into<String>) -> Self {
self.public_key = Some(key.into());
self
}
pub fn from_signed_data(value: &str) -> Result<Self, SignedDataError> {
let parsed: Self = serde_json::from_str(value).map_err(|error| {
SignedDataError::new(alloc::format!("not a SignedMeterValue document: {error}"))
})?;
if parsed.signed_meter_data.is_empty() {
return Err(SignedDataError::new("signedMeterData is empty"));
}
Ok(parsed)
}
pub fn decoded(&self) -> Result<Vec<u8>, SignedDataError> {
self.record().map(|record| record.bytes)
}
pub fn record(&self) -> Result<SignedRecord, SignedDataError> {
let text = self.signed_meter_data.trim();
if text.is_empty() {
return Err(SignedDataError::new("signedMeterData is empty"));
}
let plain = |bytes: &str| SignedRecord {
bytes: bytes.as_bytes().to_vec(),
encoding: RecordEncoding::Plain,
};
if text.starts_with(OCMF_PREFIX) {
return Ok(plain(text));
}
let compact: Vec<u8> = text
.bytes()
.filter(|byte| !byte.is_ascii_whitespace())
.collect();
if !is_base64_alphabet(&compact) {
return Ok(plain(text));
}
BASE64.decode(&compact).map_or_else(
|_| Ok(plain(text)),
|bytes| {
Ok(SignedRecord {
bytes,
encoding: RecordEncoding::Base64,
})
},
)
}
pub fn decoded_str(&self) -> Result<String, SignedDataError> {
String::from_utf8(self.decoded()?)
.map_err(|_| SignedDataError::new("the signed record is not UTF-8 text"))
}
#[must_use]
pub fn to_signed_data(&self) -> String {
serde_json::to_string(self).unwrap_or_else(|_| String::from("{}"))
}
pub fn public_key(&self) -> Option<Result<PublicKey, PublicKeyError>> {
self.public_key.as_deref().map(decode_public_key)
}
pub fn public_key_bytes(&self) -> Option<Result<Vec<u8>, PublicKeyError>> {
self.public_key().map(|result| result.map(|key| key.bytes))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PublicKeyError {
NotBase64,
MalformedEnvelope,
UnsupportedEncoding(String),
MalformedKey,
}
impl fmt::Display for PublicKeyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PublicKeyError::NotBase64 => f.write_str("publicKey is not Base64"),
PublicKeyError::MalformedEnvelope => {
f.write_str("publicKey is an oca: envelope with too few parts")
}
PublicKeyError::UnsupportedEncoding(encoding) => {
write!(f, "publicKey names an unsupported encoding {encoding:?}")
}
PublicKeyError::MalformedKey => f.write_str("publicKey does not spell whole bytes"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for PublicKeyError {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SignedDataError {
reason: String,
}
impl SignedDataError {
fn new(reason: impl Into<String>) -> Self {
Self {
reason: reason.into(),
}
}
#[must_use]
pub fn reason(&self) -> &str {
&self.reason
}
}
impl fmt::Display for SignedDataError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.reason)
}
}
#[cfg(feature = "std")]
impl std::error::Error for SignedDataError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RecordEncoding {
Base64,
Plain,
}
impl RecordEncoding {
#[must_use]
pub const fn is_conforming(self) -> bool {
matches!(self, RecordEncoding::Base64)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SignedRecord {
pub bytes: Vec<u8>,
pub encoding: RecordEncoding,
}
impl SignedRecord {
pub fn as_text(&self) -> Result<String, SignedDataError> {
core::str::from_utf8(&self.bytes)
.map(ToOwned::to_owned)
.map_err(|_| SignedDataError::new("the signed record is not UTF-8 text"))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PublicKeyShape {
Envelope,
PrintedHex,
Opaque,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PublicKey {
pub bytes: Vec<u8>,
pub printed: Option<String>,
pub encoding: Option<String>,
pub content_type: Option<String>,
pub shape: PublicKeyShape,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MissingField {
pub field: &'static str,
pub version: crate::version::Version,
}
impl fmt::Display for MissingField {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"OCPP {} requires signedMeterValue.{}",
self.version, self.field
)
}
}
#[cfg(feature = "std")]
impl std::error::Error for MissingField {}
const OCMF_PREFIX: &str = "OCMF|";
fn is_base64_alphabet(bytes: &[u8]) -> bool {
bytes
.iter()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'='))
}
pub fn decode_public_key(field: &str) -> Result<PublicKey, PublicKeyError> {
let raw = BASE64
.decode(field.trim())
.map_err(|_| PublicKeyError::NotBase64)?;
let Ok(text) = core::str::from_utf8(&raw) else {
return Ok(PublicKey {
bytes: raw,
printed: None,
encoding: None,
content_type: None,
shape: PublicKeyShape::Opaque,
});
};
let text = text.trim();
if let Some(rest) = text.strip_prefix("oca:") {
let mut parts = rest.splitn(3, ':');
let (Some(encoding), Some(content_type), Some(printed)) =
(parts.next(), parts.next(), parts.next())
else {
return Err(PublicKeyError::MalformedEnvelope);
};
let bytes = decode_printed(printed, encoding)?;
return Ok(PublicKey {
bytes,
printed: Some(printed.to_owned()),
encoding: Some(encoding.to_owned()),
content_type: Some(content_type.to_owned()),
shape: PublicKeyShape::Envelope,
});
}
match decode_printed_hex(text) {
Some(bytes) => Ok(PublicKey {
bytes,
printed: Some(text.to_owned()),
encoding: None,
content_type: None,
shape: PublicKeyShape::PrintedHex,
}),
None => Ok(PublicKey {
bytes: raw,
printed: None,
encoding: None,
content_type: None,
shape: PublicKeyShape::Opaque,
}),
}
}
fn decode_printed(printed: &str, encoding: &str) -> Result<Vec<u8>, PublicKeyError> {
if encoding.eq_ignore_ascii_case("base16") || encoding.eq_ignore_ascii_case("hex") {
decode_base16(printed).ok_or(PublicKeyError::MalformedKey)
} else if encoding.eq_ignore_ascii_case("base32") {
decode_base32(printed).ok_or(PublicKeyError::MalformedKey)
} else if encoding.eq_ignore_ascii_case("base64") {
BASE64
.decode(strip_ignored(printed, |byte| {
byte.is_ascii_alphanumeric() || byte == b'+' || byte == b'/' || byte == b'='
}))
.map_err(|_| PublicKeyError::MalformedKey)
} else {
Err(PublicKeyError::UnsupportedEncoding(encoding.to_owned()))
}
}
fn strip_ignored(text: &str, keep: impl Fn(u8) -> bool) -> Vec<u8> {
text.bytes().filter(|byte| keep(*byte)).collect()
}
fn decode_base16(text: &str) -> Option<Vec<u8>> {
let text = text.trim();
let text = text
.strip_prefix("0x")
.or_else(|| text.strip_prefix("0X"))
.unwrap_or(text);
let digits = strip_ignored(text, |byte| byte.is_ascii_hexdigit());
if digits.is_empty() || digits.len() % 2 != 0 {
return None;
}
let mut bytes = Vec::with_capacity(digits.len() / 2);
for pair in digits.chunks(2) {
let high = (pair[0] as char).to_digit(16)?;
let low = (pair[1] as char).to_digit(16)?;
bytes.push(u8::try_from(high * 16 + low).ok()?);
}
Some(bytes)
}
fn decode_printed_hex(text: &str) -> Option<Vec<u8>> {
let trimmed = text.trim();
let body = trimmed
.strip_prefix("0x")
.or_else(|| trimmed.strip_prefix("0X"))
.unwrap_or(trimmed);
if body
.bytes()
.any(|byte| !byte.is_ascii_hexdigit() && !is_separator(byte))
{
return None;
}
decode_base16(trimmed)
}
const fn is_separator(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | b'-' | b':' | b'.')
}
fn decode_base32(text: &str) -> Option<Vec<u8>> {
let mut accumulator: u32 = 0;
let mut bits = 0u32;
let mut bytes = Vec::new();
for byte in text.bytes() {
if byte == b'=' || is_separator(byte) {
continue;
}
let value = match byte {
b'A'..=b'Z' => byte - b'A',
b'a'..=b'z' => byte - b'a',
b'2'..=b'7' => byte - b'2' + 26,
_ => return None,
};
accumulator = (accumulator << 5) | u32::from(value);
bits += 5;
if bits >= 8 {
bits -= 8;
bytes.push(((accumulator >> bits) & 0xff) as u8);
}
}
if accumulator & ((1 << bits) - 1) != 0 || bytes.is_empty() {
return None;
}
Some(bytes)
}
#[cfg(any(feature = "v2_0_1", feature = "v2_1"))]
macro_rules! from_generated {
($module:ident) => {
impl From<&crate::$module::SignedMeterValue> for SignedMeterValue {
fn from(value: &crate::$module::SignedMeterValue) -> Self {
Self {
signed_meter_data: value.signed_meter_data.clone(),
encoding_method: Option::from(value.encoding_method.clone()),
signing_method: Option::from(value.signing_method.clone()),
public_key: Option::from(value.public_key.clone()),
}
}
}
};
}
#[cfg(feature = "v2_0_1")]
from_generated!(v2_0_1);
#[cfg(feature = "v2_1")]
from_generated!(v2_1);
#[cfg(feature = "v2_0_1")]
impl TryFrom<&SignedMeterValue> for crate::v2_0_1::SignedMeterValue {
type Error = MissingField;
fn try_from(value: &SignedMeterValue) -> Result<Self, MissingField> {
let missing = |field| MissingField {
field,
version: crate::version::Version::V2_0_1,
};
Ok(Self::new(
value.signed_meter_data.clone(),
value
.signing_method
.clone()
.ok_or_else(|| missing("signingMethod"))?,
value
.encoding_method
.clone()
.ok_or_else(|| missing("encodingMethod"))?,
value
.public_key
.clone()
.ok_or_else(|| missing("publicKey"))?,
))
}
}
#[cfg(feature = "v2_1")]
impl TryFrom<&SignedMeterValue> for crate::v2_1::SignedMeterValue {
type Error = MissingField;
fn try_from(value: &SignedMeterValue) -> Result<Self, MissingField> {
let mut out = Self::new(
value.signed_meter_data.clone(),
value.encoding_method.clone().ok_or(MissingField {
field: "encodingMethod",
version: crate::version::Version::V2_1,
})?,
);
out.signing_method.clone_from(&value.signing_method);
out.public_key.clone_from(&value.public_key);
Ok(out)
}
}
#[cfg(feature = "v1_6")]
impl crate::v1_6::SampledValue {
#[must_use]
pub fn signed(value: &SignedMeterValue) -> Self {
Self::new(value.to_signed_data()).with_format(crate::v1_6::ValueFormat::SignedData)
}
#[must_use]
pub fn signed_meter_value(&self) -> Option<Result<SignedMeterValue, SignedDataError>> {
if self.format.as_ref()? != &crate::v1_6::ValueFormat::SignedData {
return None;
}
Some(SignedMeterValue::from_signed_data(&self.value))
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
const EXAMPLE_KEY: &str = "MzA1OTMwMTMwNjA3MkE4NjQ4Q0UzRDAyMDEwNjA4MkE4NjQ4Q0UzRDAzMDEwNw==";
const ENVELOPE_KEY: &str =
"b2NhOmJhc2UxNjpzZWNwMjU2cjE6MzAgNTkgMzAgMTMgMDYgMDcgMkEgODYgNDggQ0UgM0QgMDIgMDE=";
#[test]
fn both_shapes_of_the_public_key_field_are_read() {
let bare = decode_public_key(EXAMPLE_KEY).expect("the example message's shape");
assert_eq!(bare.shape, PublicKeyShape::PrintedHex);
assert_eq!(&bare.bytes[..4], &[0x30, 0x59, 0x30, 0x13]);
assert_eq!(bare.printed.as_deref().map(|key| &key[..4]), Some("3059"));
assert_eq!(bare.encoding, None);
let enveloped = decode_public_key(ENVELOPE_KEY).expect("the specified shape");
assert_eq!(enveloped.shape, PublicKeyShape::Envelope);
assert_eq!(&enveloped.bytes[..4], &[0x30, 0x59, 0x30, 0x13]);
assert_eq!(enveloped.encoding.as_deref(), Some("base16"));
assert_eq!(enveloped.content_type.as_deref(), Some("secp256r1"));
assert_eq!(
enveloped.printed.as_deref(),
Some("30 59 30 13 06 07 2A 86 48 CE 3D 02 01"),
"the printed form is what a customer compares with the meter's label"
);
assert_eq!(bare.bytes[..13], enveloped.bytes[..]);
}
#[test]
fn base64_over_key_bytes_is_taken_as_the_key() {
let key = decode_public_key("MFkTAQ==").expect("bytes");
assert_eq!(key.shape, PublicKeyShape::Opaque);
assert_eq!(key.bytes, alloc::vec![0x30, 0x59, 0x13, 0x01]);
assert_eq!(key.printed, None);
}
#[test]
fn a_leading_0x_and_an_odd_digit_count_are_handled_as_the_note_says() {
assert_eq!(decode_base16("0x3059").unwrap(), alloc::vec![0x30, 0x59]);
assert_eq!(decode_base16("30-59:30.13").unwrap().len(), 4);
assert_eq!(decode_base16("305"), None);
assert_eq!(decode_printed_hex("hello dead beef"), None);
}
#[test]
fn an_unreadable_field_says_which_way_it_is_unreadable() {
assert_eq!(decode_public_key("!!!!"), Err(PublicKeyError::NotBase64));
assert_eq!(
decode_public_key("b2NhOmJhc2UxNg=="),
Err(PublicKeyError::MalformedEnvelope)
);
assert_eq!(
decode_public_key("b2NhOmJhc2U5OTp4OjMwNTk="),
Err(PublicKeyError::UnsupportedEncoding("base99".to_string()))
);
}
#[test]
fn base32_and_base64_envelopes_decode_too() {
let field = BASE64.encode("oca:base32:x:GBMTC===");
assert_eq!(
decode_public_key(&field).unwrap().bytes,
alloc::vec![0x30, 0x59, 0x31]
);
let field = BASE64.encode("oca:base64:x:MFkTAQ==");
assert_eq!(
decode_public_key(&field).unwrap().bytes,
alloc::vec![0x30, 0x59, 0x13, 0x01]
);
}
#[test]
fn the_record_comes_out_whether_it_was_base64_or_plain() {
const RECORD: &str = "OCMF|{\"FV\":\"1.0\",\"RD\":[{\"RV\":0.636}]}|{\"SD\":\"304402\"}";
let encoded = SignedMeterValue::new(BASE64.encode(RECORD)).with_encoding_method("OCMF");
assert_eq!(encoded.decoded_str().unwrap(), RECORD);
let plain = SignedMeterValue::new(RECORD).with_encoding_method("OCMF");
assert_eq!(plain.decoded_str().unwrap(), RECORD);
assert_eq!(plain.decoded().unwrap(), RECORD.as_bytes());
let xml = SignedMeterValue::new("<?xml version=\"1.0\"?><edl/>");
assert_eq!(xml.decoded_str().unwrap(), "<?xml version=\"1.0\"?><edl/>");
let binary = SignedMeterValue::new(BASE64.encode([0xff, 0xfe, 0x00]));
assert_eq!(binary.decoded().unwrap(), alloc::vec![0xff, 0xfe, 0x00]);
assert!(binary.decoded_str().is_err());
let wrapped = SignedMeterValue::new(
"T0NNRnx7IkZWIjoiMS4w\nIiwiUkQiOlt7IlJWIjowLjYzNn1dfXx7IlNEIjoiMzA0NDAyIn0=",
);
assert_eq!(wrapped.decoded_str().unwrap(), RECORD);
assert!(SignedMeterValue::new("").decoded().is_err());
assert!(SignedMeterValue::new(" ").decoded().is_err());
}
#[test]
fn which_encoding_the_station_used_is_reported_not_absorbed() {
const RECORD: &str = "OCMF|{\"FV\":\"1.0\"}|{\"SD\":\"3044\"}";
let encoded = SignedMeterValue::new(BASE64.encode(RECORD));
let record = encoded.record().unwrap();
assert_eq!(record.encoding, RecordEncoding::Base64);
assert!(record.encoding.is_conforming());
assert_eq!(record.as_text().unwrap(), RECORD);
let plain = SignedMeterValue::new(RECORD);
let record = plain.record().unwrap();
assert_eq!(record.encoding, RecordEncoding::Plain);
assert!(!record.encoding.is_conforming());
assert_eq!(record.as_text().unwrap(), RECORD);
let xml = SignedMeterValue::new("<?xml version=\"1.0\"?><edl/>");
assert_eq!(xml.record().unwrap().encoding, RecordEncoding::Plain);
assert_eq!(plain.decoded().unwrap(), plain.record().unwrap().bytes);
assert_eq!(encoded.decoded().unwrap(), encoded.record().unwrap().bytes);
}
#[test]
fn a_signed_meter_value_round_trips_through_every_version() {
let record = SignedMeterValue::new("T0NNRnx7fQ==")
.with_encoding_method("OCMF")
.with_signing_method("ECDSA-secp256r1-SHA256")
.with_public_key("MzA1OQ==");
let sample = crate::v1_6::SampledValue::signed(&record);
assert_eq!(sample.format, Some(crate::v1_6::ValueFormat::SignedData));
assert_eq!(sample.signed_meter_value().unwrap().unwrap(), record);
let modern = crate::v2_1::SignedMeterValue::try_from(&record).unwrap();
assert_eq!(SignedMeterValue::from(&modern), record);
let legacy = crate::v2_0_1::SignedMeterValue::try_from(&record).unwrap();
assert_eq!(SignedMeterValue::from(&legacy), record);
let partial = SignedMeterValue::new("T0NNRnx7fQ==").with_encoding_method("OCMF");
let error = crate::v2_0_1::SignedMeterValue::try_from(&partial).unwrap_err();
assert_eq!(error.field, "signingMethod");
assert_eq!(
error.to_string(),
"OCPP 2.0.1 requires signedMeterValue.signingMethod"
);
assert!(crate::v2_1::SignedMeterValue::try_from(&partial).is_ok());
let bare = SignedMeterValue::new("T0NNRnx7fQ==");
assert_eq!(
crate::v2_1::SignedMeterValue::try_from(&bare)
.unwrap_err()
.field,
"encodingMethod"
);
}
#[test]
fn a_16_signed_data_value_is_a_json_document_in_a_string() {
let document = r#"{"signedMeterData":"T0NNRnx7InBhZ2luYXRpb24iOiJUMSJ9",
"encodingMethod":"OCMF","publicKey":"MzA1OQ=="}"#;
let value = SignedMeterValue::from_signed_data(document).expect("the note's document");
assert_eq!(value.signed_meter_data, "T0NNRnx7InBhZ2luYXRpb24iOiJUMSJ9");
assert_eq!(value.encoding_method.as_deref(), Some("OCMF"));
assert_eq!(value.signing_method, None);
assert_eq!(
value.public_key_bytes().unwrap().unwrap(),
alloc::vec![0x30, 0x59]
);
assert!(SignedMeterValue::from_signed_data("12345.6").is_err());
assert!(SignedMeterValue::from_signed_data(r#"{"encodingMethod":"OCMF"}"#).is_err());
}
}