Skip to main content

datumesh_core/
sign.rs

1//! Signing receipts (feature `sign`): [`SigningKey`] and [`ReceiptBuilder`].
2//!
3//! Ed25519 is RFC 8032 pure Ed25519, deterministic, built on the crate's existing
4//! `curve25519-dalek` and `sha2`. The seed is not zeroised when a key is dropped (that would
5//! need another dependency); keep keys in memory only as long as needed.
6
7use core::fmt;
8
9use crate::crypto::{key_id, SecretKey};
10use crate::error::{err, ErrorCode, Result};
11use crate::json::Value;
12use crate::lexical::to_hex;
13use crate::model::{args_to_value, Args, Cell, Scalar};
14use crate::receipt::{Receipt, Source, Withdrawal};
15
16/// An Ed25519 signing key, from its 32-byte seed (RFC 8032 5.1.5).
17///
18/// `Debug` shows the key id, never the seed.
19#[derive(Clone)]
20pub struct SigningKey {
21    secret: SecretKey,
22    key_id: String,
23}
24
25impl SigningKey {
26    /// The key whose seed is `seed`.
27    pub fn from_seed(seed: &[u8; 32]) -> SigningKey {
28        let secret = SecretKey::from_seed(seed);
29        let key_id = key_id(&secret.public);
30        SigningKey { secret, key_id }
31    }
32
33    /// The 32-byte public key, as a key document's `public` holds it in hex (9.2).
34    pub fn public_key(&self) -> [u8; 32] {
35        self.secret.public
36    }
37
38    /// The key id (9.1): the first 16 hex digits of SHA-256 over the public key.
39    pub fn key_id(&self) -> &str {
40        &self.key_id
41    }
42}
43
44impl fmt::Debug for SigningKey {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        f.debug_struct("SigningKey").field("key_id", &self.key_id).finish_non_exhaustive()
47    }
48}
49
50/// The members of a receipt before it is signed; [`sign`](Self::sign) is the only way to
51/// turn it into a [`Receipt`].
52///
53/// Every member of 8.1 has a setter except `proto` (always `datumesh/1`), `type` (the
54/// value's type), `sig` (made by `sign`) and `computed_by`: that one is derived, as
55/// `<signer host>#<key id of the signing key>`, so a receipt naming another key than the
56/// one that signed it cannot be built. `inputs` defaults to empty (a stored cell); every
57/// other member must be set.
58///
59/// Nothing is repaired: `sign` checks the members exactly as [`Receipt::from_json`] checks a
60/// parsed receipt (steps 2-4 of 10.1) and returns the error it would report.
61#[derive(Clone, Debug, Default)]
62pub struct ReceiptBuilder {
63    cell: Option<Cell>,
64    value: Option<Scalar>,
65    valid: Option<Args>,
66    asof: Option<String>,
67    tx: Option<String>,
68    issued: Option<String>,
69    publisher: Option<String>,
70    signer_host: Option<String>,
71    inputs: Vec<String>,
72    licence: Option<String>,
73    summary: Option<String>,
74    source: Option<Source>,
75    withdrawn: Option<String>,
76}
77
78impl ReceiptBuilder {
79    /// A builder with no members set.
80    pub fn new() -> ReceiptBuilder {
81        ReceiptBuilder::default()
82    }
83
84    /// The cell answered (no slices).
85    pub fn cell(mut self, cell: Cell) -> Self {
86        self.cell = Some(cell);
87        self
88    }
89
90    /// The value; also sets `type`.
91    pub fn value(mut self, value: Scalar) -> Self {
92        self.value = Some(value);
93        self
94    }
95
96    /// The valid-time arguments, echoed from the cell's arguments (`{}` if none).
97    pub fn valid(mut self, valid: Args) -> Self {
98        self.valid = Some(valid);
99        self
100    }
101
102    /// The transaction time answered as of.
103    pub fn asof(mut self, asof: impl Into<String>) -> Self {
104        self.asof = Some(asof.into());
105        self
106    }
107
108    /// When the value was recorded.
109    pub fn tx(mut self, tx: impl Into<String>) -> Self {
110        self.tx = Some(tx.into());
111        self
112    }
113
114    /// When the receipt is signed.
115    pub fn issued(mut self, issued: impl Into<String>) -> Self {
116        self.issued = Some(issued.into());
117        self
118    }
119
120    /// The namespace that owns the function; must equal the cell's `ns`.
121    pub fn publisher(mut self, publisher: impl Into<String>) -> Self {
122        self.publisher = Some(publisher.into());
123        self
124    }
125
126    /// The host publishing the signing key: `computed_by` is `<host>#<key id>`.
127    pub fn signer_host(mut self, host: impl Into<String>) -> Self {
128        self.signer_host = Some(host.into());
129        self
130    }
131
132    /// The inputs entries, receipt hashes and slice entries (`slice:<slice id>:<members
133    /// hash>`, see [`crate::Manifest::entry`]); must be strictly ascending.
134    pub fn inputs<I, S>(mut self, inputs: I) -> Self
135    where
136        I: IntoIterator<Item = S>,
137        S: Into<String>,
138    {
139        self.inputs = inputs.into_iter().map(Into::into).collect();
140        self
141    }
142
143    /// An SPDX identifier or an https URL.
144    pub fn licence(mut self, licence: impl Into<String>) -> Self {
145        self.licence = Some(licence.into());
146        self
147    }
148
149    /// One human sentence saying what the value is.
150    pub fn summary(mut self, summary: impl Into<String>) -> Self {
151        self.summary = Some(summary.into());
152        self
153    }
154
155    /// The `source` member (8.1, `spec-0.6.0`): where the value was taken from. Only with no
156    /// inputs; `sign` refuses it otherwise (`E_SCHEMA`).
157    pub fn source(mut self, source: Source) -> Self {
158        self.source = Some(source);
159        self
160    }
161
162    /// `withdrawn` (8.1, `spec-0.7.0`, R1): the reason the cell is withdrawn, the null version of
163    /// the cell. Only [`sign_withdrawal`](Self::sign_withdrawal) signs it; [`sign`](Self::sign)
164    /// refuses a builder that has it. It replaces `value`.
165    pub fn withdrawn(mut self, reason: &str) -> Self {
166        self.withdrawn = Some(reason.into());
167        self
168    }
169
170    /// Checks the members as [`Receipt::from_json`] does, then signs the payload (8.3) with
171    /// `key`. The receipt's `computed_by` is `<signer host>#<key.key_id()>`.
172    ///
173    /// Errors: `E_SCHEMA` for a member not set (path `$`), otherwise the code and path
174    /// `from_json` reports for the same members. A builder with `withdrawn` is `E_SCHEMA`: it
175    /// signs with [`sign_withdrawal`](Self::sign_withdrawal).
176    pub fn sign(&self, key: &SigningKey) -> Result<Receipt> {
177        if self.withdrawn.is_some() {
178            return err(ErrorCode::Schema, "$", "a withdrawal is signed by sign_withdrawal, not sign");
179        }
180        let s = |x: &Option<String>| x.as_ref().map(|t| Value::String(t.clone()));
181        let computed_by = self.signer_host.as_ref().map(|h| Value::String(format!("{h}#{}", key.key_id())));
182        let (ty, value) = match &self.value {
183            Some(v) => {
184                let raw = match v {
185                    Scalar::Boolean(b) => Value::Bool(*b),
186                    other => Value::String(other.lexical().to_string()),
187                };
188                (Some(Value::String(v.ty().as_str().into())), Some(raw))
189            }
190            None => (None, None),
191        };
192        // Any well-formed placeholder: `sig` is not part of the payload.
193        let placeholder = "0".repeat(128);
194        let members: Vec<(&str, Option<Value>)> = vec![
195            ("asof", s(&self.asof)),
196            ("cell", self.cell.as_ref().map(Cell::to_value)),
197            ("computed_by", computed_by),
198            ("inputs", Some(Value::Array(self.inputs.iter().map(|h| Value::String(h.clone())).collect()))),
199            ("issued", s(&self.issued)),
200            ("licence", s(&self.licence)),
201            ("proto", Some(Value::String("datumesh/1".into()))),
202            ("publisher", s(&self.publisher)),
203            ("sig", Some(Value::String(placeholder))),
204            ("source", self.source.as_ref().map(Source::to_value)),
205            ("summary", s(&self.summary)),
206            ("tx", s(&self.tx)),
207            ("type", ty),
208            ("valid", self.valid.as_ref().map(args_to_value)),
209            ("value", value),
210        ];
211        let object = members.into_iter().filter_map(|(k, v)| v.map(|v| (k.to_string(), v))).collect();
212        let unsigned = Receipt::from_value(&Value::Object(object))?;
213        let sig = key.secret.sign(unsigned.payload());
214        Ok(unsigned.with_sig(to_hex(&sig)))
215    }
216
217    /// Checks the members as [`Withdrawal::from_json`] does, then signs the payload (8.3) with
218    /// `key`. The withdrawal's `computed_by` is `<signer host>#<key.key_id()>`.
219    ///
220    /// The builder is a withdrawal's: `withdrawn` is set, `value` is not (`E_SCHEMA`), and `inputs`
221    /// is empty (`E_SCHEMA`, a stored cell's only). Every other member is as for [`sign`](Self::sign):
222    /// an unset one is `E_SCHEMA`, and a publisher or time order that breaks 10.1 steps 4 is its
223    /// code. The reason follows the summary rules (`E_SCHEMA` when empty, `E_CANON_STRING` or
224    /// `E_CANON_LIMIT` otherwise).
225    pub fn sign_withdrawal(&self, key: &SigningKey) -> Result<Withdrawal> {
226        let Some(reason) = &self.withdrawn else {
227            return err(ErrorCode::Schema, "$.withdrawn", "sign_withdrawal needs withdrawn");
228        };
229        if self.value.is_some() {
230            return err(ErrorCode::Schema, "$.value", "a withdrawal has no value");
231        }
232        if !self.inputs.is_empty() {
233            return err(ErrorCode::Schema, "$.inputs", "a withdrawal is a stored cell's: inputs is empty");
234        }
235        let s = |x: &Option<String>| x.as_ref().map(|t| Value::String(t.clone()));
236        let members = |sig: String| -> Value {
237            let computed_by = self.signer_host.as_ref().map(|h| Value::String(format!("{h}#{}", key.key_id())));
238            let list: Vec<(&str, Option<Value>)> = vec![
239                ("asof", s(&self.asof)),
240                ("cell", self.cell.as_ref().map(Cell::to_value)),
241                ("computed_by", computed_by),
242                ("inputs", Some(Value::Array(Vec::new()))),
243                ("issued", s(&self.issued)),
244                ("licence", s(&self.licence)),
245                ("proto", Some(Value::String("datumesh/1".into()))),
246                ("publisher", s(&self.publisher)),
247                ("sig", Some(Value::String(sig))),
248                ("source", self.source.as_ref().map(Source::to_value)),
249                ("summary", s(&self.summary)),
250                ("tx", s(&self.tx)),
251                ("valid", self.valid.as_ref().map(args_to_value)),
252                ("withdrawn", Some(Value::String(reason.clone()))),
253            ];
254            Value::Object(list.into_iter().filter_map(|(k, v)| v.map(|v| (k.to_string(), v))).collect())
255        };
256        // Pass one: the payload, which does not cover `sig`; pass two: the signed withdrawal.
257        let unsigned = Withdrawal::from_value(&members("0".repeat(128)))?;
258        let sig = key.secret.sign(unsigned.payload());
259        Withdrawal::from_value(&members(to_hex(&sig)))
260    }
261}