native_client.rs (19614B)
1 #![cfg(feature = "native")] 2 3 use futures::{future::poll_fn, task::AtomicWaker}; 4 use radroots::{Client, NativeConfig, StartMode}; 5 use radroots_execution::session::SessionState; 6 use radroots_nostr::{key::parse_secret_key, signing::LocalSigner}; 7 use radroots_signing::{ 8 provider::{ProviderError, SignerCallbacks, SignerHandle}, 9 signer::BoxFuture, 10 }; 11 use radroots_storage::{event::SourceGeneration, status::ShutdownState}; 12 use radroots_storage_sqlite::{OpenMode, OpenOptions, Paths, SqliteStorage}; 13 use std::sync::{ 14 Arc, 15 atomic::{AtomicBool, AtomicUsize, Ordering}, 16 }; 17 18 fn options(root: &std::path::Path) -> OpenOptions { 19 OpenOptions::new(Paths::from_directory(root).unwrap(), OpenMode::Create) 20 .with_source_generation(SourceGeneration::new([17; 32]).unwrap(), 1) 21 .unwrap() 22 } 23 24 #[tokio::test] 25 async fn native_open_start_and_close_own_the_actual_store_without_creating_authority() { 26 let root = tempfile::tempdir().unwrap(); 27 let options = options(root.path()); 28 let client = Client::open(NativeConfig::public_read(options.clone())) 29 .await 30 .unwrap(); 31 let copy = client.clone(); 32 assert_eq!(client.state(), SessionState::Ready); 33 let blocked = match Client::open(NativeConfig::public_read(options.clone())).await { 34 Err(error) => error, 35 Ok(_) => panic!("second writer accepted"), 36 }; 37 assert_eq!(blocked.code(), radroots_execution::Code::StorageFailure); 38 assert!(!format!("{blocked:?}").contains(root.path().to_str().unwrap())); 39 assert_eq!( 40 client.storage_status().await.unwrap().shutdown(), 41 ShutdownState::Open 42 ); 43 assert!(matches!( 44 SqliteStorage::open(options.clone()).await, 45 Err(radroots_storage_sqlite::Error::WriterAlreadyActive { .. }) 46 )); 47 drop(client.start(StartMode::LocalOnly)); 48 assert_eq!(client.state(), SessionState::Ready); 49 client.start(StartMode::LocalOnly).await.unwrap(); 50 assert_eq!(copy.state(), SessionState::Running); 51 drop(client.close()); 52 assert_eq!(copy.state(), SessionState::Running); 53 let receipt = copy.close().await.unwrap(); 54 assert_eq!(receipt.storage().shutdown(), ShutdownState::Closed); 55 assert_eq!(client.state(), SessionState::Closed); 56 assert_eq!(client.close().await.unwrap(), receipt); 57 assert!(client.start(StartMode::LocalOnly).await.is_err()); 58 let reopened = SqliteStorage::open(options).await.unwrap(); 59 reopened.close().await.unwrap(); 60 } 61 62 struct Callbacks { 63 options: OpenOptions, 64 quiesces: AtomicUsize, 65 closes: AtomicUsize, 66 ready: AtomicBool, 67 wake: AtomicWaker, 68 } 69 impl SignerCallbacks for Callbacks { 70 fn quiesce(&self) -> BoxFuture<'_, Result<(), ProviderError>> { 71 Box::pin(async move { 72 self.quiesces.fetch_add(1, Ordering::SeqCst); 73 Ok(()) 74 }) 75 } 76 fn close(&self) -> BoxFuture<'_, Result<(), ProviderError>> { 77 Box::pin(async move { 78 self.closes.fetch_add(1, Ordering::SeqCst); 79 // The real database writer remains owned while callbacks drain. 80 assert!(matches!( 81 SqliteStorage::open(self.options.clone()).await, 82 Err(radroots_storage_sqlite::Error::WriterAlreadyActive { .. }) 83 )); 84 poll_fn(|cx| { 85 self.wake.register(cx.waker()); 86 if self.ready.load(Ordering::SeqCst) { 87 std::task::Poll::Ready(()) 88 } else { 89 std::task::Poll::Pending 90 } 91 }) 92 .await; 93 Ok(()) 94 }) 95 } 96 } 97 fn callbacks(options: OpenOptions, ready: bool) -> Arc<Callbacks> { 98 Arc::new(Callbacks { 99 options, 100 quiesces: AtomicUsize::new(0), 101 closes: AtomicUsize::new(0), 102 ready: AtomicBool::new(ready), 103 wake: AtomicWaker::new(), 104 }) 105 } 106 fn local() -> Arc<LocalSigner> { 107 // Published synthetic interoperability identity, never custody material. 108 Arc::new( 109 LocalSigner::new( 110 parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") 111 .unwrap(), 112 ) 113 .unwrap(), 114 ) 115 } 116 117 #[tokio::test] 118 async fn ordinary_native_scoped_commerce_verification_keeps_the_exact_independent_plan_and_releases_roots() 119 { 120 use radroots_protocol::{ 121 command::CapturedOrderAcceptance, 122 commerce::{self, CommerceSigningPlan, EncodedCommerceRumor}, 123 }; 124 use radroots_signing::{ 125 provider::{NonceSource, ProviderCall}, 126 request::CancellationSignal, 127 }; 128 struct Nonce; 129 impl NonceSource for Nonce { 130 fn next_nonce(&self) -> Result<[u8; 32], ProviderError> { 131 Ok([42; 32]) 132 } 133 } 134 let command = CapturedOrderAcceptance::parse(include_bytes!( 135 "fixtures/commerce_verification/command_wire.json" 136 )) 137 .unwrap(); 138 let record = commerce::decode(include_bytes!( 139 "fixtures/commerce_verification/record_wire.json" 140 )) 141 .unwrap(); 142 let rumor = EncodedCommerceRumor::capture(record.content()).unwrap(); 143 let wire = include_bytes!("fixtures/commerce_verification/plan_wire.bin"); 144 let plan = CommerceSigningPlan::parse( 145 command.context().operation_id(), 146 command.digest(), 147 &rumor, 148 wire, 149 ) 150 .unwrap(); 151 let root = tempfile::tempdir().unwrap(); 152 let selected = options(root.path()); 153 let client = Client::open(NativeConfig::public_read(selected.clone())) 154 .await 155 .unwrap(); 156 let provider = Arc::new( 157 LocalSigner::with_clock( 158 parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") 159 .unwrap(), 160 || Ok(451000), 161 ) 162 .unwrap() 163 .with_nonce_source(Arc::new(Nonce)), 164 ); 165 let author = provider.public_key(); 166 let weak = Arc::downgrade(&provider); 167 let scope = client 168 .attach_signer(SignerHandle::new(provider, callbacks(selected, true))) 169 .await 170 .unwrap(); 171 let call = ProviderCall::new( 172 author, 173 std::num::NonZeroU64::new(600000).unwrap(), 174 CancellationSignal::new(), 175 ); 176 let verified = scope 177 .verify_commerce_plan(call, &rumor, plan) 178 .await 179 .unwrap(); 180 assert_eq!(verified.plan().protected_wire(), wire); 181 assert_eq!(verified.deadline_unix_ms(), 600000); 182 client.close().await.unwrap(); 183 assert!(weak.upgrade().is_none()); 184 assert_eq!( 185 verified.plan().operation_id(), 186 command.context().operation_id() 187 ); 188 // This crypto proof outlives key cleanup; it proves no workspace grant, T1, 189 // first signature, installed order or configured network target. 190 } 191 192 #[tokio::test] 193 async fn ordinary_native_scoped_recovery_keeps_original_fields_and_refuses_expired_original() { 194 use radroots::signing::{ 195 ArtifactRole, ExactRecoveryKind, ExactRecoveryRequest, OutcomeKind, SigningIntent, 196 }; 197 use radroots_event_codec::authoring::AuthoredEventPlan; 198 use radroots_signing::{provider::ProviderCall, request::CancellationSignal}; 199 const CREATED: u64 = 1_700_000_000; 200 const NOW: u64 = CREATED * 1000 + 1; 201 static OBSERVATIONS: AtomicUsize = AtomicUsize::new(0); 202 fn clock() -> Result<u64, radroots_signing::Error> { 203 if OBSERVATIONS 204 .fetch_add(1, Ordering::SeqCst) 205 .is_multiple_of(2) 206 { 207 Ok(NOW) 208 } else { 209 Err(radroots_signing::Error::new( 210 radroots_signing::error::Kind::InternalError, 211 )) 212 } 213 } 214 let root = tempfile::tempdir().unwrap(); 215 let selected = options(root.path()); 216 let client = Client::open(NativeConfig::public_read(selected.clone())) 217 .await 218 .unwrap(); 219 let provider = Arc::new( 220 LocalSigner::with_clock( 221 parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") 222 .unwrap(), 223 clock, 224 ) 225 .unwrap(), 226 ); 227 let author = provider.public_key(); 228 let weak = Arc::downgrade(&provider); 229 let scope = client 230 .attach_signer(SignerHandle::new(provider, callbacks(selected, true))) 231 .await 232 .unwrap(); 233 let call = |deadline| { 234 ProviderCall::new( 235 author, 236 std::num::NonZeroU64::new(deadline).unwrap(), 237 CancellationSignal::new(), 238 ) 239 }; 240 let original = |deadline| { 241 SigningIntent::new( 242 radroots::OperationId::from_bytes([41; 32]), 243 [42; 32], 244 AuthoredEventPlan::from_generic( 245 radroots::event::GenericEventDraft::new( 246 "radroots.social.geochat.v1", 247 20_000, 248 CREATED, 249 vec![], 250 "synthetic scoped original recovery", 251 author.to_hex(), 252 ) 253 .unwrap(), 254 ) 255 .unwrap(), 256 ArtifactRole::PublicEvent, 257 None, 258 call(deadline), 259 ) 260 .unwrap() 261 }; 262 let first = original(CREATED * 1000 + 10_000); 263 let expected = first.binding(); 264 let expected_event = first.with_event(|_, id| id); 265 let issued = scope.sign_exact(first).await; 266 assert!(matches!(issued.kind(), OutcomeKind::Obtained(_))); 267 drop(issued); // Primitive lost observation only; no durable stock claim. 268 let recovered = scope 269 .recover_exact( 270 ExactRecoveryRequest::new( 271 original(CREATED * 1000 + 10_000), 272 call(CREATED * 1000 + 20_000), 273 ) 274 .unwrap(), 275 ) 276 .await; 277 assert_eq!(recovered.binding(), expected); 278 let (_, ExactRecoveryKind::Obtained(bytes)) = recovered.into_parts() else { 279 panic!("real scoped recovery unavailable") 280 }; 281 assert_eq!(bytes.event_id(), expected_event); 282 assert!(bytes.observed_at_unix_ms().is_none()); 283 bytes.with_json(|raw| { 284 let wire = radroots_event::wire::Nip01EventWire::parse_json(raw).unwrap(); 285 assert_eq!(wire.pubkey, author.to_hex()); 286 assert_eq!(wire.content, "synthetic scoped original recovery"); 287 assert_eq!(wire.created_at, CREATED); 288 }); 289 let expired = original(NOW); 290 let expired_binding = expired.binding(); 291 let refused = scope 292 .recover_exact(ExactRecoveryRequest::new(expired, call(CREATED * 1000 + 30_000)).unwrap()) 293 .await; 294 assert_eq!(refused.binding(), expired_binding); 295 assert!(matches!( 296 refused.kind(), 297 ExactRecoveryKind::Indeterminate(ProviderError::DeadlineExceeded) 298 )); 299 assert_eq!(OBSERVATIONS.load(Ordering::SeqCst), 5); 300 client.close().await.unwrap(); 301 assert!(weak.upgrade().is_none()); 302 // Obtained authenticated bytes outlive key/callback cleanup. This proves 303 // neither a protected stock authorization nor durable command capture. 304 assert!(bytes.with_json(|raw| raw.contains("synthetic scoped original recovery"))); 305 } 306 307 #[tokio::test] 308 async fn actual_native_signer_attaches_before_start_and_callbacks_close_before_the_store() { 309 let root = tempfile::tempdir().unwrap(); 310 let options = options(root.path()); 311 let client = Client::open(NativeConfig::public_read(options.clone())) 312 .await 313 .unwrap(); 314 let provider = local(); 315 let weak = Arc::downgrade(&provider); 316 let expected = provider.public_key(); 317 let callbacks = callbacks(options.clone(), true); 318 let signer = client 319 .attach_signer(SignerHandle::new(provider, callbacks.clone())) 320 .await 321 .unwrap(); 322 assert_eq!(signer.observed().unwrap().identity(), expected); 323 assert_eq!(client.state(), SessionState::Ready); 324 assert_eq!(callbacks.quiesces.load(Ordering::SeqCst), 0); 325 client.close().await.unwrap(); 326 assert_eq!(callbacks.quiesces.load(Ordering::SeqCst), 1); 327 assert_eq!(callbacks.closes.load(Ordering::SeqCst), 1); 328 assert!(weak.upgrade().is_none()); 329 assert_eq!(signer.state(), SessionState::Closed); 330 signer.quiesce().await.unwrap(); 331 assert_eq!(callbacks.quiesces.load(Ordering::SeqCst), 1); 332 let reopened = SqliteStorage::open(options).await.unwrap(); 333 reopened.close().await.unwrap(); 334 } 335 336 #[tokio::test] 337 async fn cancelled_client_close_retains_actual_provider_and_writer_until_callback_completion() { 338 use std::{ 339 future::Future, 340 task::{Context, Poll}, 341 }; 342 let root = tempfile::tempdir().unwrap(); 343 let options = options(root.path()); 344 let client = Client::open(NativeConfig::public_read(options.clone())) 345 .await 346 .unwrap(); 347 let provider = local(); 348 let weak = Arc::downgrade(&provider); 349 let callbacks = callbacks(options.clone(), false); 350 client 351 .attach_signer(SignerHandle::new(provider, callbacks.clone())) 352 .await 353 .unwrap(); 354 let mut close = Box::pin(client.close()); 355 assert!(matches!( 356 close 357 .as_mut() 358 .poll(&mut Context::from_waker(futures::task::noop_waker_ref())), 359 Poll::Pending 360 )); 361 drop(close); 362 assert_eq!(client.state(), SessionState::Closing); 363 assert!(weak.upgrade().is_some()); 364 assert!(matches!( 365 SqliteStorage::open(options.clone()).await, 366 Err(radroots_storage_sqlite::Error::WriterAlreadyActive { .. }) 367 )); 368 callbacks.ready.store(true, Ordering::SeqCst); 369 callbacks.wake.wake(); 370 client.close().await.unwrap(); 371 assert!(weak.upgrade().is_none()); 372 assert_eq!(callbacks.quiesces.load(Ordering::SeqCst), 1); 373 let reopened = SqliteStorage::open(options).await.unwrap(); 374 reopened.close().await.unwrap(); 375 } 376 377 #[tokio::test] 378 async fn ordinary_native_signer_scope_returns_real_full_identity_signature_facts() { 379 use radroots::signing::{ArtifactRole, OutcomeKind, SigningIntent}; 380 use radroots_event_codec::authoring::AuthoredEventPlan; 381 use radroots_signing::{provider::ProviderCall, request::CancellationSignal}; 382 fn checked_clock() -> Result<u64, radroots_signing::Error> { 383 Ok(1_700_000_000_001) 384 } 385 let root = tempfile::tempdir().unwrap(); 386 let options = options(root.path()); 387 let client = Client::open(NativeConfig::public_read(options.clone())) 388 .await 389 .unwrap(); 390 let provider = Arc::new( 391 LocalSigner::with_clock( 392 parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") 393 .unwrap(), 394 checked_clock, 395 ) 396 .unwrap(), 397 ); 398 let author = provider.public_key(); 399 let weak = Arc::downgrade(&provider); 400 let callbacks = callbacks(options, true); 401 let scope = client 402 .attach_signer(SignerHandle::new(provider, callbacks)) 403 .await 404 .unwrap(); 405 let plan = AuthoredEventPlan::from_generic( 406 radroots::event::GenericEventDraft::new( 407 "radroots.social.geochat.v1", 408 20_000, 409 1_700_000_000, 410 vec![], 411 "synthetic native retained preimage", 412 author.to_hex(), 413 ) 414 .unwrap(), 415 ) 416 .unwrap(); 417 let operation = radroots::OperationId::from_bytes([31; 32]); 418 let intent = SigningIntent::new( 419 operation, 420 [32; 32], 421 plan, 422 ArtifactRole::PublicEvent, 423 None, 424 ProviderCall::new( 425 author, 426 std::num::NonZeroU64::new(1_700_000_010_000).unwrap(), 427 CancellationSignal::new(), 428 ), 429 ) 430 .unwrap(); 431 let outcome = scope.sign_exact(intent).await; 432 assert_eq!(outcome.binding().operation_id(), operation); 433 let OutcomeKind::Obtained(artifact) = outcome.kind() else { 434 panic!("native signature unavailable: {outcome:?}"); 435 }; 436 artifact.with_json(|raw| { 437 let value = radroots_event::wire::Nip01EventWire::parse_json(raw).unwrap(); 438 assert_eq!(value.pubkey, author.to_hex()); 439 assert_eq!(value.content, "synthetic native retained preimage"); 440 }); 441 assert!(artifact.observed_at_unix_ms().is_some()); 442 client.close().await.unwrap(); 443 assert!(weak.upgrade().is_none()); 444 // Owning authenticated bytes outlive released key/callback roots. This 445 // primitive fact alone does not claim a durable command or publication. 446 artifact.with_json(|raw| assert!(!raw.is_empty())); 447 } 448 449 #[tokio::test] 450 async fn ordinary_scoped_private_crypto_uses_actual_custody_and_nip44() { 451 use radroots_nostr::signing::OsNonceSource; 452 use radroots_signing::provider::{ 453 ParticipantProvider, PrivateText, ProviderCall, ProviderError, 454 }; 455 use radroots_signing::request::CancellationSignal; 456 fn checked_clock() -> Result<u64, radroots_signing::Error> { 457 Ok(1_700_000_000_001) 458 } 459 let root = tempfile::tempdir().unwrap(); 460 let options = options(root.path()); 461 let client = Client::open(NativeConfig::public_read(options.clone())) 462 .await 463 .unwrap(); 464 let owner = Arc::new( 465 LocalSigner::with_clock( 466 parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") 467 .unwrap(), 468 checked_clock, 469 ) 470 .unwrap() 471 .with_nonce_source(Arc::new(OsNonceSource)), 472 ); 473 let peer = LocalSigner::with_clock( 474 parse_secret_key("0000000000000000000000000000000000000000000000000000000000000002") 475 .unwrap(), 476 checked_clock, 477 ) 478 .unwrap() 479 .with_nonce_source(Arc::new(OsNonceSource)); 480 let call = |identity| { 481 ProviderCall::new( 482 identity, 483 std::num::NonZeroU64::new(1_700_000_010_000).unwrap(), 484 CancellationSignal::new(), 485 ) 486 }; 487 let scope = client 488 .attach_signer(SignerHandle::new(owner.clone(), callbacks(options, true))) 489 .await 490 .unwrap(); 491 let text = "scoped private inquiry: apples 🍎 and exact original text"; 492 let ciphertext = scope 493 .encrypt_private( 494 call(owner.public_key()), 495 peer.public_key(), 496 PrivateText::new(text).unwrap(), 497 ) 498 .await 499 .unwrap(); 500 assert_eq!( 501 peer.decrypt_private(call(peer.public_key()), owner.public_key(), ciphertext) 502 .await 503 .unwrap() 504 .expose(), 505 text 506 ); 507 let ciphertext = peer 508 .encrypt_private( 509 call(peer.public_key()), 510 owner.public_key(), 511 PrivateText::new("independent peer response").unwrap(), 512 ) 513 .await 514 .unwrap(); 515 let plaintext = scope 516 .decrypt_private(call(owner.public_key()), peer.public_key(), ciphertext) 517 .await 518 .unwrap(); 519 assert_eq!(plaintext.expose(), "independent peer response"); 520 assert!(!format!("{plaintext:?}").contains("independent peer response")); 521 let cancelled = CancellationSignal::new(); 522 cancelled.cancel(); 523 let denied = scope 524 .encrypt_private( 525 ProviderCall::new( 526 owner.public_key(), 527 std::num::NonZeroU64::new(1_700_000_010_000).unwrap(), 528 cancelled, 529 ), 530 peer.public_key(), 531 PrivateText::new(text).unwrap(), 532 ) 533 .await 534 .unwrap_err(); 535 assert_eq!(denied, ProviderError::Cancelled); 536 client.close().await.unwrap(); 537 assert_eq!( 538 scope 539 .encrypt_private( 540 call(owner.public_key()), 541 peer.public_key(), 542 PrivateText::new(text).unwrap() 543 ) 544 .await 545 .unwrap_err(), 546 ProviderError::CapabilityUnavailable 547 ); 548 }