encode.rs (2302B)
1 use radroots_events::{job_result::RadrootsJobResult, kinds::is_result_kind}; 2 3 use crate::job::encode::{JobEncodeError, WireEventParts, canonicalize_tags}; 4 use crate::job::util::{job_input_type_tag, push_amount_tag_msat}; 5 6 #[cfg(not(feature = "std"))] 7 use alloc::{ 8 string::{String, ToString}, 9 vec, 10 vec::Vec, 11 }; 12 13 pub fn job_result_build_tags(res: &RadrootsJobResult) -> Vec<Vec<String>> { 14 let mut tags: Vec<Vec<String>> = Vec::with_capacity( 15 2 + res.inputs.len() 16 + usize::from(res.customer_pubkey.is_some()) 17 + usize::from(res.payment.is_some()) 18 + usize::from(res.encrypted), 19 ); 20 21 let mut e = Vec::with_capacity(3); 22 e.push("e".to_string()); 23 e.push(res.request_event.id.clone()); 24 if let Some(r) = &res.request_event.relays { 25 e.push(r.clone()); 26 } 27 tags.push(e); 28 29 if let Some(j) = &res.request_json { 30 tags.push(vec!["request".into(), j.clone()]); 31 } 32 33 if !res.encrypted { 34 for i in &res.inputs { 35 let mut t = Vec::with_capacity(5); 36 t.push("i".to_string()); 37 t.push(i.data.clone()); 38 t.push(job_input_type_tag(i.input_type).to_string()); 39 if let Some(relay) = &i.relay { 40 t.push(relay.clone()); 41 } 42 if let Some(marker) = &i.marker { 43 t.push(marker.clone()); 44 } 45 tags.push(t); 46 } 47 } 48 49 if let Some(p) = &res.customer_pubkey { 50 tags.push(vec!["p".into(), p.clone()]); 51 } 52 53 if let Some(pay) = &res.payment { 54 push_amount_tag_msat(&mut tags, pay.amount_sat, pay.bolt11.clone()); 55 } 56 57 if res.encrypted { 58 tags.push(vec!["encrypted".into()]); 59 } 60 61 tags 62 } 63 64 pub fn to_wire_parts( 65 res: &RadrootsJobResult, 66 content: &str, 67 ) -> Result<WireEventParts, JobEncodeError> { 68 let kind = res.kind as u32; 69 if !is_result_kind(kind) { 70 return Err(JobEncodeError::InvalidKind(kind)); 71 } 72 if res.encrypted && !res.inputs.is_empty() { 73 return Err(JobEncodeError::EmptyRequiredField("inputs-when-encrypted")); 74 } 75 76 let mut tags = job_result_build_tags(res); 77 78 canonicalize_tags(&mut tags); 79 80 Ok(WireEventParts { 81 kind, 82 content: content.to_string(), 83 tags, 84 }) 85 }