commerce_signing.rs (7072B)
1 #![cfg(feature = "commerce")] 2 use radroots_nostr::{key::SecretKey, signing::LocalSigner}; 3 use radroots_protocol::{ 4 command::CapturedOrderAcceptance, 5 commerce::{self, CommerceSeal, CommerceSigningPlan}, 6 intent::SigningReplay, 7 nip59::CapturedDmRoute, 8 }; 9 use radroots_signing::commerce::VerifiedCommerceSigningPlan; 10 use radroots_signing::{ 11 issuance::{OutcomeKind, SigningIntent}, 12 provider::{NonceSource, ParticipantProvider, PrivateText, ProviderCall, ProviderError}, 13 request::CancellationSignal, 14 }; 15 use serde_json::Value; 16 use std::{num::NonZeroU64, sync::Arc}; 17 struct TestNonce; 18 impl NonceSource for TestNonce { 19 fn next_nonce(&self) -> Result<[u8; 32], ProviderError> { 20 Ok([42; 32]) 21 } 22 } 23 fn bytes(hex: &str) -> Vec<u8> { 24 hex.as_bytes() 25 .as_chunks::<2>() 26 .0 27 .iter() 28 .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap()) 29 .collect() 30 } 31 fn hex(bytes: &[u8]) -> String { 32 bytes.iter().map(|byte| format!("{byte:02x}")).collect() 33 } 34 35 #[tokio::test] 36 async fn independent_peer_self_ciphertexts_routes_and_exact_intents_verify_and_actual_signer_matches() 37 { 38 let value: Value = 39 serde_json::from_str(include_str!("fixtures/commerce_signing.v1.json")).unwrap(); 40 let command = 41 CapturedOrderAcceptance::parse(value["command_wire"].as_str().unwrap().as_bytes()).unwrap(); 42 let record = commerce::decode(value["record_wire"].as_str().unwrap().as_bytes()).unwrap(); 43 let rumor = commerce::EncodedCommerceRumor::capture(record.content()).unwrap(); 44 let wire = bytes(value["plan_hex"].as_str().unwrap()); 45 let plan = || { 46 CommerceSigningPlan::parse( 47 command.context().operation_id(), 48 command.digest(), 49 &rumor, 50 &wire, 51 ) 52 .unwrap() 53 }; 54 let provider = 55 LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 1)).unwrap(), || { 56 Ok(451000) 57 }) 58 .unwrap() 59 .with_nonce_source(Arc::new(TestNonce)); 60 let call = || { 61 ProviderCall::new( 62 provider.public_key(), 63 NonZeroU64::new(600000).unwrap(), 64 CancellationSignal::new(), 65 ) 66 }; 67 let verified = VerifiedCommerceSigningPlan::verify(&provider, call(), &rumor, plan()) 68 .await 69 .unwrap(); 70 assert_eq!(verified.plan().protected_wire(), wire); 71 assert_eq!(verified.plan().replay(), SigningReplay::NonReplayable); 72 for (seal, row) in verified 73 .plan() 74 .seals() 75 .iter() 76 .zip(value["seals"].as_array().unwrap()) 77 { 78 let intent = SigningIntent::from_commerce_seal(seal, call()).unwrap(); 79 assert_eq!(hex(intent.binding().digest()), row["intent_digest"]); 80 let outcome = provider.sign_exact(intent).await; 81 let OutcomeKind::Obtained(artifact) = outcome.kind() else { 82 panic!("{outcome:?}"); 83 }; 84 assert_eq!(artifact.event_id().as_bytes(), &seal.event_id()); 85 } 86 let unavailable = 87 LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 1)).unwrap(), || { 88 Ok(451000) 89 }) 90 .unwrap(); 91 assert!( 92 VerifiedCommerceSigningPlan::verify(&unavailable, call(), &rumor, plan()) 93 .await 94 .is_err() 95 ); 96 let mut forged = wire.clone(); 97 let ciphertext = value["seals"][0]["ciphertext"].as_str().unwrap().as_bytes(); 98 let at = forged 99 .windows(ciphertext.len()) 100 .position(|part| part == ciphertext) 101 .unwrap(); 102 forged[at + 50] = if forged[at + 50] == b'A' { b'B' } else { b'A' }; 103 // A stale event ID is refused structurally before any crypto qualification. 104 assert!( 105 CommerceSigningPlan::parse( 106 command.context().operation_id(), 107 command.digest(), 108 &rumor, 109 &forged 110 ) 111 .is_err() 112 ); 113 let rebuild = |first: &str, replay, bad_route| { 114 let seals = value["seals"] 115 .as_array() 116 .unwrap() 117 .iter() 118 .enumerate() 119 .map(|(index, row)| { 120 CommerceSeal::new( 121 command.context().operation_id(), 122 command.digest(), 123 &rumor, 124 row["recipient"].as_str().unwrap().parse().unwrap(), 125 serde_json::from_value(serde_json::json!("450")).unwrap(), 126 if index == 0 { 127 first 128 } else { 129 row["ciphertext"].as_str().unwrap() 130 }, 131 ) 132 .unwrap() 133 }) 134 .collect::<Vec<_>>() 135 .try_into() 136 .unwrap(); 137 let routes = value["seals"] 138 .as_array() 139 .unwrap() 140 .iter() 141 .enumerate() 142 .map(|(index, row)| { 143 CapturedDmRoute::from_observed_descriptor( 144 row["recipient"].as_str().unwrap().parse().unwrap(), 145 row["route"]["event_id"].as_str().unwrap().parse().unwrap(), 146 if index == 0 && bad_route { 147 "{}" 148 } else { 149 row["route"]["raw"].as_str().unwrap() 150 }, 151 &["wss://relay.example".into()], 152 ) 153 .unwrap() 154 }) 155 .collect::<Vec<_>>() 156 .try_into() 157 .unwrap(); 158 CommerceSigningPlan::new( 159 command.context().operation_id(), 160 command.digest(), 161 &rumor, 162 seals, 163 routes, 164 replay, 165 ) 166 .unwrap() 167 }; 168 let peer_cipher = value["seals"][1]["ciphertext"].as_str().unwrap(); 169 assert!( 170 VerifiedCommerceSigningPlan::verify( 171 &provider, 172 call(), 173 &rumor, 174 rebuild(peer_cipher, SigningReplay::NonReplayable, false) 175 ) 176 .await 177 .is_err() 178 ); 179 let wrong = provider 180 .encrypt_private( 181 call(), 182 rumor.recipients()[0], 183 PrivateText::new(&"x".repeat(rumor.protected_wire().len())).unwrap(), 184 ) 185 .await 186 .unwrap(); 187 assert!( 188 VerifiedCommerceSigningPlan::verify( 189 &provider, 190 call(), 191 &rumor, 192 rebuild(wrong.as_str(), SigningReplay::NonReplayable, false) 193 ) 194 .await 195 .is_err() 196 ); 197 let original = value["seals"][0]["ciphertext"].as_str().unwrap(); 198 assert!( 199 VerifiedCommerceSigningPlan::verify( 200 &provider, 201 call(), 202 &rumor, 203 rebuild(original, SigningReplay::NonReplayable, true) 204 ) 205 .await 206 .is_err() 207 ); 208 assert!( 209 VerifiedCommerceSigningPlan::verify( 210 &provider, 211 call(), 212 &rumor, 213 rebuild(original, SigningReplay::LocalReplaySafe, false) 214 ) 215 .await 216 .is_ok() 217 ); 218 }