1use 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#[derive(Clone)]
20pub struct SigningKey {
21 secret: SecretKey,
22 key_id: String,
23}
24
25impl SigningKey {
26 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 pub fn public_key(&self) -> [u8; 32] {
35 self.secret.public
36 }
37
38 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#[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 pub fn new() -> ReceiptBuilder {
81 ReceiptBuilder::default()
82 }
83
84 pub fn cell(mut self, cell: Cell) -> Self {
86 self.cell = Some(cell);
87 self
88 }
89
90 pub fn value(mut self, value: Scalar) -> Self {
92 self.value = Some(value);
93 self
94 }
95
96 pub fn valid(mut self, valid: Args) -> Self {
98 self.valid = Some(valid);
99 self
100 }
101
102 pub fn asof(mut self, asof: impl Into<String>) -> Self {
104 self.asof = Some(asof.into());
105 self
106 }
107
108 pub fn tx(mut self, tx: impl Into<String>) -> Self {
110 self.tx = Some(tx.into());
111 self
112 }
113
114 pub fn issued(mut self, issued: impl Into<String>) -> Self {
116 self.issued = Some(issued.into());
117 self
118 }
119
120 pub fn publisher(mut self, publisher: impl Into<String>) -> Self {
122 self.publisher = Some(publisher.into());
123 self
124 }
125
126 pub fn signer_host(mut self, host: impl Into<String>) -> Self {
128 self.signer_host = Some(host.into());
129 self
130 }
131
132 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 pub fn licence(mut self, licence: impl Into<String>) -> Self {
145 self.licence = Some(licence.into());
146 self
147 }
148
149 pub fn summary(mut self, summary: impl Into<String>) -> Self {
151 self.summary = Some(summary.into());
152 self
153 }
154
155 pub fn source(mut self, source: Source) -> Self {
158 self.source = Some(source);
159 self
160 }
161
162 pub fn withdrawn(mut self, reason: &str) -> Self {
166 self.withdrawn = Some(reason.into());
167 self
168 }
169
170 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 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 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 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}