native_stock_terms_tests.rs (9280B)
1 //! Ordinary client ownership of an actual complete replacement installation. 2 use super::*; 3 use nostr::JsonUtil; 4 use radroots_domain::{ 5 AgreedFixedPrice, AgreementLine, AgreementPrice, CommerceContent, CommerceHeader, 6 CommercePayload, RecordId, Sequence, SourceId, Terms, TermsAuthorization, TermsProposal, 7 }; 8 use radroots_protocol::{ 9 command::CapturedTermsInstallation, 10 commerce::{DecodedRecord, EncodedCommerceRumor, EncodedRecord}, 11 terms::EncodedTerms, 12 }; 13 use radroots_signing::request::CancellationSignal; 14 15 async fn incoming(r: &Rig, content: &CommerceContent, scalar: u8) -> DecodedRecord { 16 let encoded = EncodedRecord::capture(content).unwrap(); 17 let decoded = radroots_protocol::commerce::decode(encoded.protected_wire()).unwrap(); 18 let rumor = EncodedCommerceRumor::capture(content).unwrap(); 19 let keys = nostr::Keys::new(nostr::SecretKey::from_hex(&format!("{scalar:064x}")).unwrap()); 20 let receiver = 21 nostr::PublicKey::from_hex(&r.enrollment.input().participant().to_hex()).unwrap(); 22 let wrap = nostr::EventBuilder::gift_wrap( 23 &keys, 24 &receiver, 25 nostr::UnsignedEvent::from_json(rumor.protected_wire()).unwrap(), 26 Vec::<nostr::Tag>::new(), 27 ) 28 .await 29 .unwrap(); 30 let provider = 31 LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 3)).unwrap(), || { 32 Ok(150000) 33 }) 34 .unwrap(); 35 let opening = radroots_nostr::commerce::open( 36 &provider, 37 ProviderCall::new( 38 provider.public_key(), 39 NonZeroU64::new(230000).unwrap(), 40 CancellationSignal::new(), 41 ), 42 &wrap.as_json(), 43 ) 44 .await 45 .unwrap(); 46 let capture = radroots_storage_sqlite::workspace::StockSourceCapture::prepare( 47 SellerAuthoritySelection::from_attachment(r.enrollment.input()), 48 &opening, 49 ) 50 .unwrap(); 51 let (sources, _, _) = r.minima().await; 52 r.native 53 .retain_stock_source( 54 r.scope.binding().clone(), 55 sources, 56 &capture, 57 r.enrollment.proof(), 58 ) 59 .await 60 .unwrap(); 61 decoded 62 } 63 64 async fn exercise(quantity: &str, remaining: u64, available: u64) { 65 let r = Rig::new().await; 66 let request = r.request().await; 67 let old = request.terms(); 68 let line = &old.lines()[0]; 69 let AgreementPrice::Fixed(old_price) = line.price() else { 70 panic!("fixed fixture") 71 }; 72 let price = AgreedFixedPrice::new( 73 old_price.rate(), 74 old_price.basis(), 75 old_price.discount_bps(), 76 None, 77 ); 78 let quantity = quantity.parse().unwrap(); 79 let total = price.total(quantity).unwrap(); 80 let line = AgreementLine::new( 81 line.id(), 82 line.source(), 83 line.option_id(), 84 line.product().clone(), 85 line.option().clone(), 86 quantity, 87 line.fulfillment_group(), 88 line.source_lot_label(), 89 AgreementPrice::Fixed(price), 90 total, 91 ) 92 .unwrap(); 93 let terms = Terms::new( 94 old.buyer(), 95 old.seller(), 96 vec![line], 97 old.fulfillment().to_vec(), 98 old.fulfillment_charge(), 99 old.fulfillment_charge().checked_add(total).unwrap(), 100 old.supply().clone(), 101 ) 102 .unwrap(); 103 let (_, initial) = r.accept().await; 104 assert!(initial.installation().is_some()); 105 let scope = request.scope(); 106 let make = |author, previous, sequence, payload, extra: &[RecordId]| { 107 let mut parents: Vec<_> = terms 108 .lines() 109 .iter() 110 .map(|line| SourceId::from_bytes(line.source().event_id().into_bytes())) 111 .collect(); 112 parents.extend( 113 [initial.record_id(), previous] 114 .into_iter() 115 .chain(extra.iter().copied()) 116 .map(|id| SourceId::from_bytes(id.into_bytes())), 117 ); 118 parents.sort(); 119 parents.dedup(); 120 CommerceContent::new( 121 CommerceHeader::new( 122 scope.thread_id(), 123 Some(scope.order_id()), 124 author, 125 scope.buyer(), 126 scope.seller(), 127 UnixSeconds::new(150).unwrap(), 128 Sequence::new(sequence).unwrap(), 129 Some(previous), 130 parents, 131 ) 132 .unwrap(), 133 payload, 134 ) 135 .unwrap() 136 }; 137 let proposal = make( 138 scope.seller(), 139 initial.record_id(), 140 2, 141 CommercePayload::TermsProposed( 142 TermsProposal::new( 143 Some(initial.record_id()), 144 terms.clone(), 145 UnixSeconds::new(230).unwrap(), 146 "complete replacement", 147 ) 148 .unwrap(), 149 ), 150 &[], 151 ); 152 let proposal = incoming(&r, &proposal, 3).await; 153 let authorization = make( 154 scope.buyer(), 155 request.request(), 156 2, 157 CommercePayload::TermsAuthorized(TermsAuthorization::new( 158 proposal.record_id(), 159 EncodedTerms::capture(&terms).unwrap().digest(), 160 UnixSeconds::new(230).unwrap(), 161 )), 162 &[proposal.record_id()], 163 ); 164 let authorization = incoming(&r, &authorization, 2).await; 165 let (sources, listings, minimum) = r.minima().await; 166 let history = r 167 .native 168 .stock_order_history( 169 r.scope.binding().clone(), 170 minimum, 171 sources, 172 listings, 173 scope, 174 r.enrollment.proof(), 175 ) 176 .await 177 .unwrap(); 178 let mut wire = serde_json::json!({"type":"orders.install_terms","context":r.context(110),"input":{"proposal":proposal.record_id(),"authorization":authorization.record_id(),"terms_digest":EncodedTerms::capture(&terms).unwrap().digest(),"allocation":{"type":"automatic"}}}); 179 wire["context"]["expected"] = serde_json::json!({"agreement":initial.record_id(),"buyer_head":history.analysis().buyer_head(),"checkpoint":history.checkpoint().unwrap(),"order_id":scope.order_id(),"seller_sequence":"1"}); 180 let command = CapturedTermsInstallation::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); 181 wire["context"]["approval"] = serde_json::json!({"intent_digest":command.approval_intent_digest(),"scope":"orders.install_terms","expires_at":"230"}); 182 let command = CapturedTermsInstallation::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); 183 let context = r 184 .scope 185 .command_context( 186 command.context().operation_id(), 187 command.context().expected().cloned(), 188 command.context().approval().cloned(), 189 UnixSeconds::new(230).unwrap(), 190 ) 191 .unwrap(); 192 let consent = StockConsentCapture::prepare( 193 SellerAuthoritySelection::from_attachment(r.enrollment.input()), 194 r.enrollment.input().grant_id(), 195 StockConsentMode::ExecuteAndRecover, 196 StockResources::all_pools(), 197 UnixSeconds::new(230).unwrap(), 198 CapturedTermsInstallation::parse(command.protected_wire()).unwrap(), 199 ) 200 .unwrap(); 201 let (_, _, minimum) = r.minima().await; 202 r.native 203 .issue_stock_consent( 204 r.scope.binding().clone(), 205 minimum, 206 &consent, 207 r.enrollment.proof(), 208 ) 209 .await 210 .unwrap(); 211 let (sources, listings, minimum) = r.minima().await; 212 let input = crate::orders::InstallTermsInput::new( 213 proposal.record_id(), 214 authorization.record_id(), 215 command.input().terms_digest(), 216 AllocationSelection::automatic(), 217 ); 218 let installed = r 219 .client 220 .orders(&r.scope) 221 .install_terms(context, minimum, sources, listings, input) 222 .await 223 .unwrap(); 224 assert!(installed.installation().is_some()); 225 assert_eq!(installed.attempt().command_digest(), command.digest()); 226 assert_ne!(installed.record_id(), initial.record_id()); 227 assert_eq!(r.control.signs.load(Ordering::SeqCst), 4); 228 assert_eq!(r.io.sent.lock().unwrap().len(), 4); 229 let (_, _, minimum) = r.minima().await; 230 let current = r 231 .client 232 .stock(&r.scope) 233 .inspect(minimum, PoolId::from_bytes([80; 32])) 234 .await 235 .unwrap() 236 .unwrap(); 237 assert_eq!(current.installed_obligations().remaining().get(), remaining); 238 assert_eq!( 239 current 240 .pool() 241 .snapshot() 242 .balances() 243 .physical() 244 .available 245 .get(), 246 available 247 ); 248 let resumed = r 249 .client 250 .orders(&r.scope) 251 .resume_acceptance(minimum, command.context().operation_id(), command.digest()) 252 .await 253 .unwrap(); 254 assert_eq!(resumed.record_id(), installed.record_id()); 255 assert_eq!(r.control.signs.load(Ordering::SeqCst), 4); 256 let (_, _, after) = r.minima().await; 257 assert_eq!(after, minimum); 258 r.client.close().await.unwrap(); 259 } 260 261 #[tokio::test] 262 async fn ordinary_install_terms_uses_the_same_owner_and_resumes_without_extra_signatures_or_stock() 263 { 264 exercise("5", 5, 5).await; 265 } 266 267 #[tokio::test] 268 async fn ordinary_negative_install_terms_finishes_self_copy_after_original_release() { 269 exercise("1", 1, 9).await; 270 }