issuance.rs (11932B)
1 use core::num::NonZeroU64; 2 use nostr::JsonUtil; 3 use radroots_signing::{ 4 issuance::{SigningIntent, SigningOutcome}, 5 provider::ProviderError, 6 signer::BoxFuture, 7 }; 8 9 use super::LocalSigner; 10 11 impl LocalSigner { 12 pub(super) fn issue_exact(&self, intent: SigningIntent) -> BoxFuture<'_, SigningOutcome> { 13 Box::pin(async move { 14 let binding = intent.binding(); 15 if intent.author() != self.public_key { 16 return SigningOutcome::not_dispatched(binding, ProviderError::IdentityChanged); 17 } 18 // Conversion/representation errors occur before cryptography. 19 let unsigned = match intent.with_event(crate::plan_signing::unsigned_event_from_fields) 20 { 21 Ok(unsigned) => unsigned, 22 Err(_) => { 23 return SigningOutcome::not_dispatched(binding, ProviderError::InvalidInput); 24 } 25 }; 26 let now = match (self.clock)() { 27 Ok(now) => now, 28 Err(_) => { 29 return SigningOutcome::not_dispatched(binding, ProviderError::ProviderFailure); 30 } 31 }; 32 if let Err(reason) = intent.check_before_effect(self.public_key, now) { 33 return SigningOutcome::not_dispatched(binding, reason); 34 } 35 // After invoking cryptography, an error is uncertain. Never claim 36 // proven non-issuance or fall through to a new captured preimage. 37 let event = match unsigned.sign_with_keys(&self.keys) { 38 Ok(event) => event, 39 Err(_) => return SigningOutcome::unknown(binding, ProviderError::ProviderFailure), 40 }; 41 let observed = (self.clock)().ok().and_then(NonZeroU64::new); 42 // No deadline/cancellation check or fallible clock can discard the 43 // obtained event. Capture verifies its exact fields and signature. 44 SigningOutcome::capture(&intent, event.as_json(), observed) 45 }) 46 } 47 } 48 49 impl LocalSigner { 50 pub(super) fn recover_original( 51 &self, 52 request: radroots_signing::issuance::ExactRecoveryRequest, 53 ) -> BoxFuture<'_, radroots_signing::issuance::ExactRecoveryOutcome> { 54 use radroots_signing::issuance::ExactRecoveryOutcome; 55 Box::pin(async move { 56 let binding = request.binding(); 57 let original = request.original(); 58 if original.author() != self.public_key || request.call().identity() != self.public_key 59 { 60 return ExactRecoveryOutcome::indeterminate( 61 binding, 62 ProviderError::IdentityChanged, 63 ); 64 } 65 let unsigned = 66 match original.with_event(crate::plan_signing::unsigned_event_from_fields) { 67 Ok(unsigned) => unsigned, 68 Err(_) => { 69 return ExactRecoveryOutcome::indeterminate( 70 binding, 71 ProviderError::InvalidInput, 72 ); 73 } 74 }; 75 let now = match (self.clock)() { 76 Ok(now) => now, 77 Err(_) => { 78 return ExactRecoveryOutcome::indeterminate( 79 binding, 80 ProviderError::ProviderFailure, 81 ); 82 } 83 }; 84 // A claim may have committed before its original invocation ever 85 // started. Recomputing after original expiry could then create the 86 // first signature late. A new recovery budget cannot permit that. 87 if let Err(reason) = original.check_before_effect(self.public_key, now) { 88 return ExactRecoveryOutcome::indeterminate(binding, reason); 89 } 90 if let Err(reason) = request.call().check_before_effect(self.public_key, now) { 91 return ExactRecoveryOutcome::indeterminate(binding, reason); 92 } 93 // Only this qualified local adapter performs exact-preimage replay. 94 // Unsupported providers never fall through to legacy signing. 95 let event = match unsigned.sign_with_keys(&self.keys) { 96 Ok(event) => event, 97 Err(_) => { 98 return ExactRecoveryOutcome::indeterminate( 99 binding, 100 ProviderError::ProviderFailure, 101 ); 102 } 103 }; 104 let observed = (self.clock)().ok().and_then(NonZeroU64::new); 105 ExactRecoveryOutcome::from_recovery_verification(SigningOutcome::capture( 106 original, 107 event.as_json(), 108 observed, 109 )) 110 }) 111 } 112 } 113 114 #[cfg(test)] 115 mod tests { 116 use super::*; 117 use crate::key::parse_secret_key; 118 use radroots_event::GenericEventDraft; 119 use radroots_event_codec::authoring::AuthoredEventPlan; 120 use radroots_signing::{ 121 Error as SigningError, 122 error::Kind, 123 issuance::{ArtifactRole, OutcomeKind}, 124 provider::{ParticipantProvider, ProviderCall}, 125 recovery::ReplayCapability, 126 request::CancellationSignal, 127 }; 128 use std::cell::RefCell; 129 const AUTHOR: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; 130 const CREATED: u64 = 1_700_000_000; 131 const DEADLINE: u64 = CREATED * 1000 + 10_000; 132 #[path = "exact_recovery_tests.rs"] 133 mod exact_recovery; 134 #[derive(Default)] 135 struct ClockState { 136 calls: usize, 137 mode: u8, 138 cancellation: Option<CancellationSignal>, 139 } 140 thread_local! { static CLOCK: RefCell<ClockState> = RefCell::default(); } 141 fn clock() -> Result<u64, SigningError> { 142 CLOCK.with(|state| { 143 let mut state = state.borrow_mut(); 144 state.calls += 1; 145 match (state.mode, state.calls) { 146 (8, 1) => Ok(DEADLINE), 147 (9, 2) => Ok(u64::MAX), 148 (1, 2) | (3, 1) => Err(SigningError::new(Kind::InternalError)), 149 (2, 2) => Ok(DEADLINE + 1), 150 (4, 1) | (7, 2) => Ok(0), 151 (5, 1) => Ok(DEADLINE), 152 (6, 2) => { 153 state.cancellation.as_ref().unwrap().cancel(); 154 Ok(CREATED * 1000 + 2) 155 } 156 _ => Ok(CREATED * 1000 + 1), 157 } 158 }) 159 } 160 fn setup(mode: u8) -> (LocalSigner, SigningIntent) { 161 // Published synthetic interoperability identity, never custody material. 162 let signer = LocalSigner::with_clock( 163 parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") 164 .unwrap(), 165 clock, 166 ) 167 .unwrap(); 168 let cancellation = CancellationSignal::new(); 169 CLOCK.with(|state| { 170 *state.borrow_mut() = ClockState { 171 calls: 0, 172 mode, 173 cancellation: Some(cancellation.clone()), 174 } 175 }); 176 let plan = AuthoredEventPlan::from_generic( 177 GenericEventDraft::new( 178 "radroots.social.geochat.v1", 179 20_000, 180 CREATED, 181 vec![], 182 "synthetic unchanged exact preimage", 183 AUTHOR, 184 ) 185 .unwrap(), 186 ) 187 .unwrap(); 188 let intent = SigningIntent::new( 189 "ab".repeat(32).parse().unwrap(), 190 [9; 32], 191 plan, 192 ArtifactRole::PublicEvent, 193 None, 194 ProviderCall::new( 195 signer.public_key(), 196 NonZeroU64::new(DEADLINE).unwrap(), 197 cancellation, 198 ), 199 ) 200 .unwrap(); 201 (signer, intent) 202 } 203 #[tokio::test] 204 async fn exact_native_signatures_survive_missing_late_and_cancelled_completion_observation() { 205 for mode in [0, 1, 2, 6, 7] { 206 let (signer, intent) = setup(mode); 207 let expected = intent.binding(); 208 let length = intent.signed_json_bytes(); 209 let state = signer.provider_state().await.unwrap(); 210 assert_eq!( 211 state.exact_issuance(), 212 Some(ReplayCapability::NonReplayable) 213 ); 214 let outcome = signer.sign_exact(intent).await; 215 assert_eq!(outcome.binding(), expected); 216 let OutcomeKind::Obtained(artifact) = outcome.kind() else { 217 panic!("obtained native signature lost: {outcome:?}"); 218 }; 219 artifact.with_json(|raw| { 220 assert_eq!(raw.len(), length); 221 let event = nostr::Event::from_json(raw).unwrap(); 222 event.verify().unwrap(); 223 assert_eq!(event.pubkey.to_hex(), AUTHOR); 224 assert_eq!(event.content, "synthetic unchanged exact preimage"); 225 }); 226 assert_eq!( 227 artifact.observed_at_unix_ms().is_none(), 228 matches!(mode, 1 | 7) 229 ); 230 if mode == 2 { 231 assert!(artifact.observed_at_unix_ms().unwrap().get() > DEADLINE); 232 } 233 CLOCK.with(|state| assert_eq!(state.borrow().calls, 2)); 234 } 235 } 236 #[tokio::test] 237 async fn failed_zero_and_expired_admission_clocks_do_not_dispatch_a_signature() { 238 for mode in [3, 4, 5] { 239 let (signer, intent) = setup(mode); 240 let outcome = signer.sign_exact(intent).await; 241 assert!(matches!( 242 outcome.kind(), 243 OutcomeKind::NotDispatched( 244 ProviderError::ProviderFailure | ProviderError::DeadlineExceeded 245 ) 246 )); 247 CLOCK.with(|state| assert_eq!(state.borrow().calls, 1)); 248 } 249 } 250 #[tokio::test] 251 async fn wrong_actual_key_and_preexisting_cancellation_refuse_before_crypto() { 252 let (_, intent) = setup(3); 253 let other = LocalSigner::with_clock( 254 parse_secret_key("0000000000000000000000000000000000000000000000000000000000000002") 255 .unwrap(), 256 clock, 257 ) 258 .unwrap(); 259 // An untrusted caller cannot even construct a different captured key. 260 assert!(matches!( 261 SigningIntent::new( 262 intent.binding().operation_id(), 263 [9; 32], 264 intent.with_event(|fields, _| AuthoredEventPlan::from_generic( 265 GenericEventDraft::new( 266 "radroots.social.geochat.v1", 267 fields.kind, 268 fields.created_at, 269 fields.tags.to_vec(), 270 fields.content, 271 fields.author.to_hex() 272 ) 273 .unwrap() 274 ) 275 .unwrap()), 276 ArtifactRole::PublicEvent, 277 None, 278 ProviderCall::new( 279 other.public_key(), 280 NonZeroU64::new(DEADLINE).unwrap(), 281 CancellationSignal::new() 282 ), 283 ), 284 Err(ProviderError::InvalidInput) 285 )); 286 let outcome = other.sign_exact(intent).await; 287 assert!(matches!( 288 outcome.kind(), 289 OutcomeKind::NotDispatched(ProviderError::IdentityChanged) 290 )); 291 CLOCK.with(|state| assert_eq!(state.borrow().calls, 0)); 292 let (signer, intent) = setup(0); 293 CLOCK.with(|state| state.borrow().cancellation.as_ref().unwrap().cancel()); 294 let outcome = signer.sign_exact(intent).await; 295 assert!(matches!( 296 outcome.kind(), 297 OutcomeKind::NotDispatched(ProviderError::Cancelled) 298 )); 299 CLOCK.with(|state| assert_eq!(state.borrow().calls, 1)); 300 } 301 }