1use std::{
2 borrow::{Borrow, Cow},
3 fmt::Display,
4 fs::File,
5 io::Read,
6 ops::Deref,
7 path::Path,
8};
9
10use blake3::{traits::digest::Digest, Hasher as Blake3};
11use serde::{Deserialize, Deserializer, Serialize};
12use serde_with::serde_as;
13
14use crate::generated::client_request::{
15 DelegateKey as FbsDelegateKey, InboundDelegateMsg as FbsInboundDelegateMsg,
16 InboundDelegateMsgType,
17};
18
19use crate::common_generated::common::SecretsId as FbsSecretsId;
20
21use crate::client_api::{TryFromFbs, WsApiError};
22use crate::contract_interface::{RelatedContracts, UpdateData};
23use crate::prelude::{ContractInstanceId, WrappedState, CONTRACT_KEY_SIZE};
24use crate::versioning::ContractContainer;
25use crate::{code_hash::CodeHash, prelude::Parameters};
26
27const DELEGATE_HASH_LENGTH: usize = 32;
28
29#[derive(Clone, Debug, Serialize, Deserialize)]
30pub struct Delegate<'a> {
31 #[serde(borrow)]
32 parameters: Parameters<'a>,
33 #[serde(borrow)]
34 pub data: DelegateCode<'a>,
35 key: DelegateKey,
36}
37
38impl Delegate<'_> {
39 pub fn key(&self) -> &DelegateKey {
40 &self.key
41 }
42
43 pub fn code(&self) -> &DelegateCode<'_> {
44 &self.data
45 }
46
47 pub fn code_hash(&self) -> &CodeHash {
48 &self.data.code_hash
49 }
50
51 pub fn params(&self) -> &Parameters<'_> {
52 &self.parameters
53 }
54
55 pub fn into_owned(self) -> Delegate<'static> {
56 Delegate {
57 parameters: self.parameters.into_owned(),
58 data: self.data.into_owned(),
59 key: self.key,
60 }
61 }
62
63 pub fn size(&self) -> usize {
64 self.parameters.size() + self.data.size()
65 }
66
67 pub(crate) fn deserialize_delegate<'de, D>(deser: D) -> Result<Delegate<'static>, D::Error>
68 where
69 D: Deserializer<'de>,
70 {
71 let data: Delegate<'de> = Deserialize::deserialize(deser)?;
72 Ok(data.into_owned())
73 }
74}
75
76impl PartialEq for Delegate<'_> {
77 fn eq(&self, other: &Self) -> bool {
78 self.key == other.key
79 }
80}
81
82impl Eq for Delegate<'_> {}
83
84impl<'a> From<(&DelegateCode<'a>, &Parameters<'a>)> for Delegate<'a> {
85 fn from((data, parameters): (&DelegateCode<'a>, &Parameters<'a>)) -> Self {
86 Self {
87 key: DelegateKey::from_params_and_code(parameters, data),
88 parameters: parameters.clone(),
89 data: data.clone(),
90 }
91 }
92}
93
94#[derive(Debug, Serialize, Deserialize, Clone)]
96#[serde_as]
97pub struct DelegateCode<'a> {
98 #[serde_as(as = "serde_with::Bytes")]
99 #[serde(borrow)]
100 pub(crate) data: Cow<'a, [u8]>,
101 pub(crate) code_hash: CodeHash,
103}
104
105impl DelegateCode<'static> {
106 pub fn load_raw(path: &Path) -> Result<Self, std::io::Error> {
108 let contract_data = Self::load_bytes(path)?;
109 Ok(DelegateCode::from(contract_data))
110 }
111
112 pub(crate) fn load_bytes(path: &Path) -> Result<Vec<u8>, std::io::Error> {
113 let mut contract_file = File::open(path)?;
114 let mut contract_data = if let Ok(md) = contract_file.metadata() {
115 Vec::with_capacity(md.len() as usize)
116 } else {
117 Vec::new()
118 };
119 contract_file.read_to_end(&mut contract_data)?;
120 Ok(contract_data)
121 }
122}
123
124impl DelegateCode<'_> {
125 pub fn hash(&self) -> &CodeHash {
127 &self.code_hash
128 }
129
130 pub fn hash_str(&self) -> String {
132 Self::encode_hash(&self.code_hash.0)
133 }
134
135 pub fn data(&self) -> &[u8] {
137 &self.data
138 }
139
140 pub fn encode_hash(hash: &[u8; DELEGATE_HASH_LENGTH]) -> String {
142 bs58::encode(hash)
143 .with_alphabet(bs58::Alphabet::BITCOIN)
144 .into_string()
145 }
146
147 pub fn into_owned(self) -> DelegateCode<'static> {
148 DelegateCode {
149 code_hash: self.code_hash,
150 data: Cow::from(self.data.into_owned()),
151 }
152 }
153
154 pub fn size(&self) -> usize {
155 self.data.len()
156 }
157}
158
159impl PartialEq for DelegateCode<'_> {
160 fn eq(&self, other: &Self) -> bool {
161 self.code_hash == other.code_hash
162 }
163}
164
165impl Eq for DelegateCode<'_> {}
166
167impl AsRef<[u8]> for DelegateCode<'_> {
168 fn as_ref(&self) -> &[u8] {
169 self.data.borrow()
170 }
171}
172
173impl From<Vec<u8>> for DelegateCode<'static> {
174 fn from(data: Vec<u8>) -> Self {
175 let key = CodeHash::from_code(data.as_slice());
176 DelegateCode {
177 data: Cow::from(data),
178 code_hash: key,
179 }
180 }
181}
182
183impl<'a> From<&'a [u8]> for DelegateCode<'a> {
184 fn from(code: &'a [u8]) -> Self {
185 let key = CodeHash::from_code(code);
186 DelegateCode {
187 data: Cow::from(code),
188 code_hash: key,
189 }
190 }
191}
192
193#[serde_as]
194#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
195pub struct DelegateKey {
196 #[serde_as(as = "[_; DELEGATE_HASH_LENGTH]")]
197 key: [u8; DELEGATE_HASH_LENGTH],
198 code_hash: CodeHash,
199}
200
201impl From<DelegateKey> for SecretsId {
202 fn from(key: DelegateKey) -> SecretsId {
203 SecretsId {
204 hash: key.key,
205 key: vec![],
206 }
207 }
208}
209
210impl DelegateKey {
211 pub const fn new(key: [u8; DELEGATE_HASH_LENGTH], code_hash: CodeHash) -> Self {
212 Self { key, code_hash }
213 }
214
215 fn from_params_and_code<'a>(
216 params: impl Borrow<Parameters<'a>>,
217 wasm_code: impl Borrow<DelegateCode<'a>>,
218 ) -> Self {
219 let code = wasm_code.borrow();
220 let key = generate_id(params.borrow(), code);
221 Self {
222 key,
223 code_hash: *code.hash(),
224 }
225 }
226
227 pub fn encode(&self) -> String {
228 bs58::encode(self.key)
229 .with_alphabet(bs58::Alphabet::BITCOIN)
230 .into_string()
231 }
232
233 pub fn code_hash(&self) -> &CodeHash {
234 &self.code_hash
235 }
236
237 pub fn bytes(&self) -> &[u8] {
238 self.key.as_ref()
239 }
240
241 pub fn from_params(
242 code_hash: impl Into<String>,
243 parameters: &Parameters,
244 ) -> Result<Self, bs58::decode::Error> {
245 let mut code_key = [0; DELEGATE_HASH_LENGTH];
246 bs58::decode(code_hash.into())
247 .with_alphabet(bs58::Alphabet::BITCOIN)
248 .onto(&mut code_key)?;
249 let mut hasher = Blake3::new();
250 hasher.update(code_key.as_slice());
251 hasher.update(parameters.as_ref());
252 let full_key_arr = hasher.finalize();
253
254 debug_assert_eq!(full_key_arr[..].len(), DELEGATE_HASH_LENGTH);
255 let mut key = [0; DELEGATE_HASH_LENGTH];
256 key.copy_from_slice(&full_key_arr);
257
258 Ok(Self {
259 key,
260 code_hash: CodeHash(code_key),
261 })
262 }
263}
264
265impl Deref for DelegateKey {
266 type Target = [u8; DELEGATE_HASH_LENGTH];
267
268 fn deref(&self) -> &Self::Target {
269 &self.key
270 }
271}
272
273impl Display for DelegateKey {
274 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275 write!(f, "{}", self.encode())
276 }
277}
278
279impl<'a> TryFromFbs<&FbsDelegateKey<'a>> for DelegateKey {
280 fn try_decode_fbs(key: &FbsDelegateKey<'a>) -> Result<Self, WsApiError> {
281 let mut key_bytes = [0; DELEGATE_HASH_LENGTH];
282 key_bytes.copy_from_slice(key.key().bytes().iter().as_ref());
283 Ok(DelegateKey {
284 key: key_bytes,
285 code_hash: CodeHash::from_code(key.code_hash().bytes()),
286 })
287 }
288}
289
290#[derive(Debug, thiserror::Error, Serialize, Deserialize)]
292pub enum DelegateError {
293 #[error("de/serialization error: {0}")]
294 Deser(String),
295 #[error("{0}")]
296 Other(String),
297}
298
299fn generate_id<'a>(
300 parameters: &Parameters<'a>,
301 code_data: &DelegateCode<'a>,
302) -> [u8; DELEGATE_HASH_LENGTH] {
303 let contract_hash = code_data.hash();
304
305 let mut hasher = Blake3::new();
306 hasher.update(contract_hash.0.as_slice());
307 hasher.update(parameters.as_ref());
308 let full_key_arr = hasher.finalize();
309
310 debug_assert_eq!(full_key_arr[..].len(), DELEGATE_HASH_LENGTH);
311 let mut key = [0; DELEGATE_HASH_LENGTH];
312 key.copy_from_slice(&full_key_arr);
313 key
314}
315
316#[serde_as]
317#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
318pub struct SecretsId {
319 #[serde_as(as = "serde_with::Bytes")]
320 key: Vec<u8>,
321 #[serde_as(as = "[_; 32]")]
322 hash: [u8; 32],
323}
324
325impl SecretsId {
326 pub fn new(key: Vec<u8>) -> Self {
327 let mut hasher = Blake3::new();
328 hasher.update(&key);
329 let hashed = hasher.finalize();
330 let mut hash = [0; 32];
331 hash.copy_from_slice(&hashed);
332 Self { key, hash }
333 }
334
335 pub fn encode(&self) -> String {
336 bs58::encode(self.hash)
337 .with_alphabet(bs58::Alphabet::BITCOIN)
338 .into_string()
339 }
340
341 pub fn hash(&self) -> &[u8; 32] {
342 &self.hash
343 }
344 pub fn key(&self) -> &[u8] {
345 self.key.as_slice()
346 }
347}
348
349impl Display for SecretsId {
350 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
351 write!(f, "{}", self.encode())
352 }
353}
354
355impl<'a> TryFromFbs<&FbsSecretsId<'a>> for SecretsId {
356 fn try_decode_fbs(key: &FbsSecretsId<'a>) -> Result<Self, WsApiError> {
357 let mut key_hash = [0; 32];
358 key_hash.copy_from_slice(key.hash().bytes().iter().as_ref());
359 Ok(SecretsId {
360 key: key.key().bytes().to_vec(),
361 hash: key_hash,
362 })
363 }
364}
365
366pub trait DelegateInterface {
411 fn process(
422 ctx: &mut crate::delegate_host::DelegateCtx,
423 parameters: Parameters<'static>,
424 attested: Option<&'static [u8]>,
425 message: InboundDelegateMsg,
426 ) -> Result<Vec<OutboundDelegateMsg>, DelegateError>;
427}
428
429#[serde_as]
430#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
431pub struct DelegateContext(#[serde_as(as = "serde_with::Bytes")] Vec<u8>);
432
433impl DelegateContext {
434 pub const MAX_SIZE: usize = 4096 * 10 * 10;
435
436 pub fn new(bytes: Vec<u8>) -> Self {
437 assert!(bytes.len() < Self::MAX_SIZE);
438 Self(bytes)
439 }
440
441 pub fn append(&mut self, bytes: &mut Vec<u8>) {
442 assert!(self.0.len() + bytes.len() < Self::MAX_SIZE);
443 self.0.append(bytes)
444 }
445
446 pub fn replace(&mut self, bytes: Vec<u8>) {
447 assert!(bytes.len() < Self::MAX_SIZE);
448 let _ = std::mem::replace(&mut self.0, bytes);
449 }
450}
451
452impl AsRef<[u8]> for DelegateContext {
453 fn as_ref(&self) -> &[u8] {
454 &self.0
455 }
456}
457
458#[derive(Serialize, Deserialize, Debug, Clone)]
459pub enum InboundDelegateMsg<'a> {
460 ApplicationMessage(ApplicationMessage),
461 UserResponse(#[serde(borrow)] UserInputResponse<'a>),
462 GetContractResponse(GetContractResponse),
463 PutContractResponse(PutContractResponse),
464 UpdateContractResponse(UpdateContractResponse),
465 SubscribeContractResponse(SubscribeContractResponse),
466 ContractNotification(ContractNotification),
467}
468
469impl InboundDelegateMsg<'_> {
470 pub fn into_owned(self) -> InboundDelegateMsg<'static> {
471 match self {
472 InboundDelegateMsg::ApplicationMessage(r) => InboundDelegateMsg::ApplicationMessage(r),
473 InboundDelegateMsg::UserResponse(r) => InboundDelegateMsg::UserResponse(r.into_owned()),
474 InboundDelegateMsg::GetContractResponse(r) => {
475 InboundDelegateMsg::GetContractResponse(r)
476 }
477 InboundDelegateMsg::PutContractResponse(r) => {
478 InboundDelegateMsg::PutContractResponse(r)
479 }
480 InboundDelegateMsg::UpdateContractResponse(r) => {
481 InboundDelegateMsg::UpdateContractResponse(r)
482 }
483 InboundDelegateMsg::SubscribeContractResponse(r) => {
484 InboundDelegateMsg::SubscribeContractResponse(r)
485 }
486 InboundDelegateMsg::ContractNotification(r) => {
487 InboundDelegateMsg::ContractNotification(r)
488 }
489 }
490 }
491
492 pub fn get_context(&self) -> Option<&DelegateContext> {
493 match self {
494 InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
495 Some(context)
496 }
497 InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
498 Some(context)
499 }
500 InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
501 Some(context)
502 }
503 InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
504 context, ..
505 }) => Some(context),
506 InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
507 context,
508 ..
509 }) => Some(context),
510 InboundDelegateMsg::ContractNotification(ContractNotification { context, .. }) => {
511 Some(context)
512 }
513 _ => None,
514 }
515 }
516
517 pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
518 match self {
519 InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
520 Some(context)
521 }
522 InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
523 Some(context)
524 }
525 InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
526 Some(context)
527 }
528 InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
529 context, ..
530 }) => Some(context),
531 InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
532 context,
533 ..
534 }) => Some(context),
535 InboundDelegateMsg::ContractNotification(ContractNotification { context, .. }) => {
536 Some(context)
537 }
538 _ => None,
539 }
540 }
541}
542
543impl From<ApplicationMessage> for InboundDelegateMsg<'_> {
544 fn from(value: ApplicationMessage) -> Self {
545 Self::ApplicationMessage(value)
546 }
547}
548
549impl<'a> TryFromFbs<&FbsInboundDelegateMsg<'a>> for InboundDelegateMsg<'a> {
550 fn try_decode_fbs(msg: &FbsInboundDelegateMsg<'a>) -> Result<Self, WsApiError> {
551 match msg.inbound_type() {
552 InboundDelegateMsgType::common_ApplicationMessage => {
553 let app_msg = msg.inbound_as_common_application_message().unwrap();
554 let mut instance_key_bytes = [0; CONTRACT_KEY_SIZE];
555 instance_key_bytes
556 .copy_from_slice(app_msg.app().data().bytes().to_vec().as_slice());
557 let app_msg = ApplicationMessage {
558 app: ContractInstanceId::new(instance_key_bytes),
559 payload: app_msg.payload().bytes().to_vec(),
560 context: DelegateContext::new(app_msg.context().bytes().to_vec()),
561 processed: app_msg.processed(),
562 };
563 Ok(InboundDelegateMsg::ApplicationMessage(app_msg))
564 }
565 InboundDelegateMsgType::UserInputResponse => {
566 let user_response = msg.inbound_as_user_input_response().unwrap();
567 let user_response = UserInputResponse {
568 request_id: user_response.request_id(),
569 response: ClientResponse::new(user_response.response().data().bytes().to_vec()),
570 context: DelegateContext::new(
571 user_response.delegate_context().bytes().to_vec(),
572 ),
573 };
574 Ok(InboundDelegateMsg::UserResponse(user_response))
575 }
576 _ => unreachable!("invalid inbound delegate message type"),
577 }
578 }
579}
580
581#[non_exhaustive]
582#[derive(Serialize, Deserialize, Debug, Clone)]
583pub struct ApplicationMessage {
584 pub app: ContractInstanceId,
585 pub payload: Vec<u8>,
586 pub context: DelegateContext,
587 pub processed: bool,
588}
589
590impl ApplicationMessage {
591 pub fn new(app: ContractInstanceId, payload: Vec<u8>) -> Self {
592 Self {
593 app,
594 payload,
595 context: DelegateContext::default(),
596 processed: false,
597 }
598 }
599
600 pub fn with_context(mut self, context: DelegateContext) -> Self {
601 self.context = context;
602 self
603 }
604
605 pub fn processed(mut self, p: bool) -> Self {
606 self.processed = p;
607 self
608 }
609}
610
611#[derive(Serialize, Deserialize, Debug, Clone)]
612pub struct UserInputResponse<'a> {
613 pub request_id: u32,
614 #[serde(borrow)]
615 pub response: ClientResponse<'a>,
616 pub context: DelegateContext,
617}
618
619impl UserInputResponse<'_> {
620 pub fn into_owned(self) -> UserInputResponse<'static> {
621 UserInputResponse {
622 request_id: self.request_id,
623 response: self.response.into_owned(),
624 context: self.context,
625 }
626 }
627}
628
629#[derive(Serialize, Deserialize, Debug, Clone)]
630pub enum OutboundDelegateMsg {
631 ApplicationMessage(ApplicationMessage),
633 RequestUserInput(
634 #[serde(deserialize_with = "OutboundDelegateMsg::deser_user_input_req")]
635 UserInputRequest<'static>,
636 ),
637 ContextUpdated(DelegateContext),
639 GetContractRequest(GetContractRequest),
640 PutContractRequest(PutContractRequest),
641 UpdateContractRequest(UpdateContractRequest),
642 SubscribeContractRequest(SubscribeContractRequest),
643}
644
645impl From<ApplicationMessage> for OutboundDelegateMsg {
646 fn from(req: ApplicationMessage) -> Self {
647 Self::ApplicationMessage(req)
648 }
649}
650
651impl From<GetContractRequest> for OutboundDelegateMsg {
652 fn from(req: GetContractRequest) -> Self {
653 Self::GetContractRequest(req)
654 }
655}
656
657impl From<PutContractRequest> for OutboundDelegateMsg {
658 fn from(req: PutContractRequest) -> Self {
659 Self::PutContractRequest(req)
660 }
661}
662
663impl From<UpdateContractRequest> for OutboundDelegateMsg {
664 fn from(req: UpdateContractRequest) -> Self {
665 Self::UpdateContractRequest(req)
666 }
667}
668
669impl From<SubscribeContractRequest> for OutboundDelegateMsg {
670 fn from(req: SubscribeContractRequest) -> Self {
671 Self::SubscribeContractRequest(req)
672 }
673}
674
675impl OutboundDelegateMsg {
676 fn deser_user_input_req<'de, D>(deser: D) -> Result<UserInputRequest<'static>, D::Error>
677 where
678 D: serde::Deserializer<'de>,
679 {
680 let value = <UserInputRequest<'de> as Deserialize>::deserialize(deser)?;
681 Ok(value.into_owned())
682 }
683
684 pub fn processed(&self) -> bool {
685 match self {
686 OutboundDelegateMsg::ApplicationMessage(msg) => msg.processed,
687 OutboundDelegateMsg::GetContractRequest(msg) => msg.processed,
688 OutboundDelegateMsg::PutContractRequest(msg) => msg.processed,
689 OutboundDelegateMsg::UpdateContractRequest(msg) => msg.processed,
690 OutboundDelegateMsg::SubscribeContractRequest(msg) => msg.processed,
691 OutboundDelegateMsg::RequestUserInput(_) => true,
692 OutboundDelegateMsg::ContextUpdated(_) => true,
693 }
694 }
695
696 pub fn get_context(&self) -> Option<&DelegateContext> {
697 match self {
698 OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
699 Some(context)
700 }
701 OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
702 Some(context)
703 }
704 OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
705 Some(context)
706 }
707 OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
708 context, ..
709 }) => Some(context),
710 OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
711 context,
712 ..
713 }) => Some(context),
714 _ => None,
715 }
716 }
717
718 pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
719 match self {
720 OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
721 Some(context)
722 }
723 OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
724 Some(context)
725 }
726 OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
727 Some(context)
728 }
729 OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
730 context, ..
731 }) => Some(context),
732 OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
733 context,
734 ..
735 }) => Some(context),
736 _ => None,
737 }
738 }
739}
740
741#[derive(Serialize, Deserialize, Debug, Clone)]
743pub struct GetContractRequest {
744 pub contract_id: ContractInstanceId,
745 pub context: DelegateContext,
746 pub processed: bool,
747}
748
749impl GetContractRequest {
750 pub fn new(contract_id: ContractInstanceId) -> Self {
751 Self {
752 contract_id,
753 context: Default::default(),
754 processed: false,
755 }
756 }
757}
758
759#[derive(Serialize, Deserialize, Debug, Clone)]
761pub struct GetContractResponse {
762 pub contract_id: ContractInstanceId,
763 pub state: Option<WrappedState>,
765 pub context: DelegateContext,
766}
767
768#[derive(Serialize, Deserialize, Debug, Clone)]
770pub struct PutContractRequest {
771 pub contract: ContractContainer,
773 pub state: WrappedState,
775 #[serde(deserialize_with = "RelatedContracts::deser_related_contracts")]
777 pub related_contracts: RelatedContracts<'static>,
778 pub context: DelegateContext,
780 pub processed: bool,
782}
783
784impl PutContractRequest {
785 pub fn new(
786 contract: ContractContainer,
787 state: WrappedState,
788 related_contracts: RelatedContracts<'static>,
789 ) -> Self {
790 Self {
791 contract,
792 state,
793 related_contracts,
794 context: Default::default(),
795 processed: false,
796 }
797 }
798}
799
800#[derive(Serialize, Deserialize, Debug, Clone)]
802pub struct PutContractResponse {
803 pub contract_id: ContractInstanceId,
805 pub result: Result<(), String>,
807 pub context: DelegateContext,
809}
810
811#[derive(Serialize, Deserialize, Debug, Clone)]
813pub struct UpdateContractRequest {
814 pub contract_id: ContractInstanceId,
816 #[serde(deserialize_with = "UpdateContractRequest::deser_update_data")]
818 pub update: UpdateData<'static>,
819 pub context: DelegateContext,
821 pub processed: bool,
823}
824
825impl UpdateContractRequest {
826 pub fn new(contract_id: ContractInstanceId, update: UpdateData<'static>) -> Self {
827 Self {
828 contract_id,
829 update,
830 context: Default::default(),
831 processed: false,
832 }
833 }
834
835 fn deser_update_data<'de, D>(deser: D) -> Result<UpdateData<'static>, D::Error>
836 where
837 D: Deserializer<'de>,
838 {
839 let value = <UpdateData<'de> as Deserialize>::deserialize(deser)?;
840 Ok(value.into_owned())
841 }
842}
843
844#[derive(Serialize, Deserialize, Debug, Clone)]
846pub struct UpdateContractResponse {
847 pub contract_id: ContractInstanceId,
849 pub result: Result<(), String>,
851 pub context: DelegateContext,
853}
854
855#[derive(Serialize, Deserialize, Debug, Clone)]
857pub struct SubscribeContractRequest {
858 pub contract_id: ContractInstanceId,
860 pub context: DelegateContext,
862 pub processed: bool,
864}
865
866impl SubscribeContractRequest {
867 pub fn new(contract_id: ContractInstanceId) -> Self {
868 Self {
869 contract_id,
870 context: Default::default(),
871 processed: false,
872 }
873 }
874}
875
876#[derive(Serialize, Deserialize, Debug, Clone)]
878pub struct SubscribeContractResponse {
879 pub contract_id: ContractInstanceId,
881 pub result: Result<(), String>,
883 pub context: DelegateContext,
885}
886
887#[derive(Serialize, Deserialize, Debug, Clone)]
889pub struct ContractNotification {
890 pub contract_id: ContractInstanceId,
892 pub new_state: WrappedState,
894 pub context: DelegateContext,
896}
897
898#[serde_as]
899#[derive(Serialize, Deserialize, Debug, Clone)]
900pub struct NotificationMessage<'a>(
901 #[serde_as(as = "serde_with::Bytes")]
902 #[serde(borrow)]
903 Cow<'a, [u8]>,
904);
905
906impl TryFrom<&serde_json::Value> for NotificationMessage<'static> {
907 type Error = ();
908
909 fn try_from(json: &serde_json::Value) -> Result<NotificationMessage<'static>, ()> {
910 let bytes = serde_json::to_vec(json).unwrap();
912 Ok(Self(Cow::Owned(bytes)))
913 }
914}
915
916impl NotificationMessage<'_> {
917 pub fn into_owned(self) -> NotificationMessage<'static> {
918 NotificationMessage(self.0.into_owned().into())
919 }
920 pub fn bytes(&self) -> &[u8] {
921 self.0.as_ref()
922 }
923}
924
925#[serde_as]
926#[derive(Serialize, Deserialize, Debug, Clone)]
927pub struct ClientResponse<'a>(
928 #[serde_as(as = "serde_with::Bytes")]
929 #[serde(borrow)]
930 Cow<'a, [u8]>,
931);
932
933impl Deref for ClientResponse<'_> {
934 type Target = [u8];
935
936 fn deref(&self) -> &Self::Target {
937 &self.0
938 }
939}
940
941impl ClientResponse<'_> {
942 pub fn new(response: Vec<u8>) -> Self {
943 Self(response.into())
944 }
945 pub fn into_owned(self) -> ClientResponse<'static> {
946 ClientResponse(self.0.into_owned().into())
947 }
948 pub fn bytes(&self) -> &[u8] {
949 self.0.as_ref()
950 }
951}
952
953#[derive(Serialize, Deserialize, Debug, Clone)]
954pub struct UserInputRequest<'a> {
955 pub request_id: u32,
956 #[serde(borrow)]
957 pub message: NotificationMessage<'a>,
959 pub responses: Vec<ClientResponse<'a>>,
961}
962
963impl UserInputRequest<'_> {
964 pub fn into_owned(self) -> UserInputRequest<'static> {
965 UserInputRequest {
966 request_id: self.request_id,
967 message: self.message.into_owned(),
968 responses: self.responses.into_iter().map(|r| r.into_owned()).collect(),
969 }
970 }
971}
972
973#[doc(hidden)]
974pub(crate) mod wasm_interface {
975 use super::*;
978 use crate::memory::WasmLinearMem;
979
980 #[repr(C)]
981 #[derive(Debug, Clone, Copy)]
982 pub struct DelegateInterfaceResult {
983 ptr: i64,
984 size: u32,
985 }
986
987 impl DelegateInterfaceResult {
988 pub unsafe fn from_raw(ptr: i64, mem: &WasmLinearMem) -> Self {
989 let result = Box::leak(Box::from_raw(crate::memory::buf::compute_ptr(
990 ptr as *mut Self,
991 mem,
992 )));
993 #[cfg(feature = "trace")]
994 {
995 tracing::trace!(
996 "got FFI result @ {ptr} ({:p}) -> {result:?}",
997 ptr as *mut Self
998 );
999 }
1000 *result
1001 }
1002
1003 #[cfg(feature = "contract")]
1004 pub fn into_raw(self) -> i64 {
1005 #[cfg(feature = "trace")]
1006 {
1007 tracing::trace!("returning FFI -> {self:?}");
1008 }
1009 let ptr = Box::into_raw(Box::new(self));
1010 #[cfg(feature = "trace")]
1011 {
1012 tracing::trace!("FFI result ptr: {ptr:p} ({}i64)", ptr as i64);
1013 }
1014 ptr as _
1015 }
1016
1017 pub unsafe fn unwrap(
1018 self,
1019 mem: WasmLinearMem,
1020 ) -> Result<Vec<OutboundDelegateMsg>, DelegateError> {
1021 let ptr = crate::memory::buf::compute_ptr(self.ptr as *mut u8, &mem);
1022 let serialized = std::slice::from_raw_parts(ptr as *const u8, self.size as _);
1023 let value: Result<Vec<OutboundDelegateMsg>, DelegateError> =
1024 bincode::deserialize(serialized)
1025 .map_err(|e| DelegateError::Other(format!("{e}")))?;
1026 #[cfg(feature = "trace")]
1027 {
1028 tracing::trace!(
1029 "got result through FFI; addr: {:p} ({}i64, mapped: {ptr:p})
1030 serialized: {serialized:?}
1031 value: {value:?}",
1032 self.ptr as *mut u8,
1033 self.ptr
1034 );
1035 }
1036 value
1037 }
1038 }
1039
1040 impl From<Result<Vec<OutboundDelegateMsg>, DelegateError>> for DelegateInterfaceResult {
1041 fn from(value: Result<Vec<OutboundDelegateMsg>, DelegateError>) -> Self {
1042 let serialized = bincode::serialize(&value).unwrap();
1043 let size = serialized.len() as _;
1044 let ptr = serialized.as_ptr();
1045 #[cfg(feature = "trace")]
1046 {
1047 tracing::trace!(
1048 "sending result through FFI; addr: {ptr:p} ({}),\n serialized: {serialized:?}\n value: {value:?}",
1049 ptr as i64
1050 );
1051 }
1052 std::mem::forget(serialized);
1053 Self {
1054 ptr: ptr as i64,
1055 size,
1056 }
1057 }
1058 }
1059}