-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathdelegate_interface.rs
More file actions
1118 lines (1001 loc) · 34.6 KB
/
delegate_interface.rs
File metadata and controls
1118 lines (1001 loc) · 34.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
borrow::{Borrow, Cow},
fmt::Display,
fs::File,
io::Read,
ops::Deref,
path::Path,
};
use blake3::{traits::digest::Digest, Hasher as Blake3};
use serde::{Deserialize, Deserializer, Serialize};
use serde_with::serde_as;
use crate::generated::client_request::{
DelegateKey as FbsDelegateKey, InboundDelegateMsg as FbsInboundDelegateMsg,
InboundDelegateMsgType,
};
use crate::common_generated::common::SecretsId as FbsSecretsId;
use crate::client_api::{TryFromFbs, WsApiError};
use crate::contract_interface::{RelatedContracts, UpdateData};
use crate::prelude::{ContractInstanceId, WrappedState};
use crate::versioning::ContractContainer;
use crate::{code_hash::CodeHash, prelude::Parameters};
const DELEGATE_HASH_LENGTH: usize = 32;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Delegate<'a> {
#[serde(borrow)]
parameters: Parameters<'a>,
#[serde(borrow)]
pub data: DelegateCode<'a>,
key: DelegateKey,
}
impl Delegate<'_> {
pub fn key(&self) -> &DelegateKey {
&self.key
}
pub fn code(&self) -> &DelegateCode<'_> {
&self.data
}
pub fn code_hash(&self) -> &CodeHash {
&self.data.code_hash
}
pub fn params(&self) -> &Parameters<'_> {
&self.parameters
}
pub fn into_owned(self) -> Delegate<'static> {
Delegate {
parameters: self.parameters.into_owned(),
data: self.data.into_owned(),
key: self.key,
}
}
pub fn size(&self) -> usize {
self.parameters.size() + self.data.size()
}
pub(crate) fn deserialize_delegate<'de, D>(deser: D) -> Result<Delegate<'static>, D::Error>
where
D: Deserializer<'de>,
{
let data: Delegate<'de> = Deserialize::deserialize(deser)?;
Ok(data.into_owned())
}
}
impl PartialEq for Delegate<'_> {
fn eq(&self, other: &Self) -> bool {
self.key == other.key
}
}
impl Eq for Delegate<'_> {}
impl<'a> From<(&DelegateCode<'a>, &Parameters<'a>)> for Delegate<'a> {
fn from((data, parameters): (&DelegateCode<'a>, &Parameters<'a>)) -> Self {
Self {
key: DelegateKey::from_params_and_code(parameters, data),
parameters: parameters.clone(),
data: data.clone(),
}
}
}
/// Executable delegate
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde_as]
pub struct DelegateCode<'a> {
#[serde_as(as = "serde_with::Bytes")]
#[serde(borrow)]
pub(crate) data: Cow<'a, [u8]>,
// todo: skip serializing and instead compute it
pub(crate) code_hash: CodeHash,
}
impl DelegateCode<'static> {
/// Loads the contract raw wasm module, without any version.
pub fn load_raw(path: &Path) -> Result<Self, std::io::Error> {
let contract_data = Self::load_bytes(path)?;
Ok(DelegateCode::from(contract_data))
}
pub(crate) fn load_bytes(path: &Path) -> Result<Vec<u8>, std::io::Error> {
let mut contract_file = File::open(path)?;
let mut contract_data = if let Ok(md) = contract_file.metadata() {
Vec::with_capacity(md.len() as usize)
} else {
Vec::new()
};
contract_file.read_to_end(&mut contract_data)?;
Ok(contract_data)
}
}
impl DelegateCode<'_> {
/// Delegate code hash.
pub fn hash(&self) -> &CodeHash {
&self.code_hash
}
/// Returns the `Base58` string representation of the delegate key.
pub fn hash_str(&self) -> String {
Self::encode_hash(&self.code_hash.0)
}
/// Reference to delegate code.
pub fn data(&self) -> &[u8] {
&self.data
}
/// Returns the `Base58` string representation of a hash.
pub fn encode_hash(hash: &[u8; DELEGATE_HASH_LENGTH]) -> String {
bs58::encode(hash)
.with_alphabet(bs58::Alphabet::BITCOIN)
.into_string()
}
pub fn into_owned(self) -> DelegateCode<'static> {
DelegateCode {
code_hash: self.code_hash,
data: Cow::from(self.data.into_owned()),
}
}
pub fn size(&self) -> usize {
self.data.len()
}
}
impl PartialEq for DelegateCode<'_> {
fn eq(&self, other: &Self) -> bool {
self.code_hash == other.code_hash
}
}
impl Eq for DelegateCode<'_> {}
impl AsRef<[u8]> for DelegateCode<'_> {
fn as_ref(&self) -> &[u8] {
self.data.borrow()
}
}
impl From<Vec<u8>> for DelegateCode<'static> {
fn from(data: Vec<u8>) -> Self {
let key = CodeHash::from_code(data.as_slice());
DelegateCode {
data: Cow::from(data),
code_hash: key,
}
}
}
impl<'a> From<&'a [u8]> for DelegateCode<'a> {
fn from(code: &'a [u8]) -> Self {
let key = CodeHash::from_code(code);
DelegateCode {
data: Cow::from(code),
code_hash: key,
}
}
}
#[serde_as]
#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub struct DelegateKey {
#[serde_as(as = "[_; DELEGATE_HASH_LENGTH]")]
key: [u8; DELEGATE_HASH_LENGTH],
code_hash: CodeHash,
}
impl From<DelegateKey> for SecretsId {
fn from(key: DelegateKey) -> SecretsId {
SecretsId {
hash: key.key,
key: vec![],
}
}
}
impl DelegateKey {
pub const fn new(key: [u8; DELEGATE_HASH_LENGTH], code_hash: CodeHash) -> Self {
Self { key, code_hash }
}
fn from_params_and_code<'a>(
params: impl Borrow<Parameters<'a>>,
wasm_code: impl Borrow<DelegateCode<'a>>,
) -> Self {
let code = wasm_code.borrow();
let key = generate_id(params.borrow(), code);
Self {
key,
code_hash: *code.hash(),
}
}
pub fn encode(&self) -> String {
bs58::encode(self.key)
.with_alphabet(bs58::Alphabet::BITCOIN)
.into_string()
}
pub fn code_hash(&self) -> &CodeHash {
&self.code_hash
}
pub fn bytes(&self) -> &[u8] {
self.key.as_ref()
}
pub fn from_params(
code_hash: impl Into<String>,
parameters: &Parameters,
) -> Result<Self, bs58::decode::Error> {
let mut code_key = [0; DELEGATE_HASH_LENGTH];
bs58::decode(code_hash.into())
.with_alphabet(bs58::Alphabet::BITCOIN)
.onto(&mut code_key)?;
let mut hasher = Blake3::new();
hasher.update(code_key.as_slice());
hasher.update(parameters.as_ref());
let full_key_arr = hasher.finalize();
debug_assert_eq!(full_key_arr[..].len(), DELEGATE_HASH_LENGTH);
let mut key = [0; DELEGATE_HASH_LENGTH];
key.copy_from_slice(&full_key_arr);
Ok(Self {
key,
code_hash: CodeHash(code_key),
})
}
}
impl Deref for DelegateKey {
type Target = [u8; DELEGATE_HASH_LENGTH];
fn deref(&self) -> &Self::Target {
&self.key
}
}
impl Display for DelegateKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.encode())
}
}
impl<'a> TryFromFbs<&FbsDelegateKey<'a>> for DelegateKey {
fn try_decode_fbs(key: &FbsDelegateKey<'a>) -> Result<Self, WsApiError> {
let mut key_bytes = [0; DELEGATE_HASH_LENGTH];
key_bytes.copy_from_slice(key.key().bytes().iter().as_ref());
Ok(DelegateKey {
key: key_bytes,
code_hash: CodeHash::from_code(key.code_hash().bytes()),
})
}
}
/// Type of errors during interaction with a delegate.
#[derive(Debug, thiserror::Error, Serialize, Deserialize)]
pub enum DelegateError {
#[error("de/serialization error: {0}")]
Deser(String),
#[error("{0}")]
Other(String),
}
fn generate_id<'a>(
parameters: &Parameters<'a>,
code_data: &DelegateCode<'a>,
) -> [u8; DELEGATE_HASH_LENGTH] {
let contract_hash = code_data.hash();
let mut hasher = Blake3::new();
hasher.update(contract_hash.0.as_slice());
hasher.update(parameters.as_ref());
let full_key_arr = hasher.finalize();
debug_assert_eq!(full_key_arr[..].len(), DELEGATE_HASH_LENGTH);
let mut key = [0; DELEGATE_HASH_LENGTH];
key.copy_from_slice(&full_key_arr);
key
}
#[serde_as]
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct SecretsId {
#[serde_as(as = "serde_with::Bytes")]
key: Vec<u8>,
#[serde_as(as = "[_; 32]")]
hash: [u8; 32],
}
impl SecretsId {
pub fn new(key: Vec<u8>) -> Self {
let mut hasher = Blake3::new();
hasher.update(&key);
let hashed = hasher.finalize();
let mut hash = [0; 32];
hash.copy_from_slice(&hashed);
Self { key, hash }
}
pub fn encode(&self) -> String {
bs58::encode(self.hash)
.with_alphabet(bs58::Alphabet::BITCOIN)
.into_string()
}
pub fn hash(&self) -> &[u8; 32] {
&self.hash
}
pub fn key(&self) -> &[u8] {
self.key.as_slice()
}
}
impl Display for SecretsId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.encode())
}
}
impl<'a> TryFromFbs<&FbsSecretsId<'a>> for SecretsId {
fn try_decode_fbs(key: &FbsSecretsId<'a>) -> Result<Self, WsApiError> {
let mut key_hash = [0; 32];
key_hash.copy_from_slice(key.hash().bytes().iter().as_ref());
Ok(SecretsId {
key: key.key().bytes().to_vec(),
hash: key_hash,
})
}
}
/// Identifies where an inbound application message originated from.
///
/// When a web app sends a message to a delegate through the WebSocket API with
/// an authentication token, the runtime resolves the token to the originating
/// contract and wraps it in `MessageOrigin::WebApp`. Delegates receive this as
/// the `origin` parameter of [`DelegateInterface::process`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum MessageOrigin {
/// The message was sent by a web application backed by the given contract.
WebApp(ContractInstanceId),
}
/// A Delegate is a webassembly code designed to act as an agent for the user on
/// Freenet. Delegates can:
///
/// * Store private data on behalf of the user
/// * Create, read, and modify contracts
/// * Create other delegates
/// * Send and receive messages from other delegates and user interfaces
/// * Ask the user questions and receive answers
///
/// Example use cases:
///
/// * A delegate stores a private key for the user, other components can ask
/// the delegate to sign messages, it will ask the user for permission
/// * A delegate monitors an inbox contract and downloads new messages when
/// they arrive
///
/// # Example
///
/// ```ignore
/// use freenet_stdlib::prelude::*;
///
/// struct MyDelegate;
///
/// #[delegate]
/// impl DelegateInterface for MyDelegate {
/// fn process(
/// ctx: &mut DelegateCtx,
/// _params: Parameters<'static>,
/// _origin: Option<MessageOrigin>,
/// message: InboundDelegateMsg,
/// ) -> Result<Vec<OutboundDelegateMsg>, DelegateError> {
/// // Access secrets synchronously - no round-trip needed!
/// if let Some(key) = ctx.get_secret(b"private_key") {
/// // use key...
/// }
/// ctx.set_secret(b"new_key", b"value");
///
/// // Read/write context for temporary state within a batch
/// ctx.write(b"some state");
///
/// Ok(vec![])
/// }
/// }
/// ```
pub trait DelegateInterface {
/// Process inbound message, producing zero or more outbound messages in response.
///
/// # Arguments
/// - `ctx`: Mutable handle to the delegate's execution environment. Provides:
/// - **Context** (temporary): `read()`, `write()`, `len()`, `clear()` - state within a batch
/// - **Secrets** (persistent): `get_secret()`, `set_secret()`, `has_secret()`, `remove_secret()`
/// - `parameters`: The delegate's initialization parameters.
/// - `origin`: An optional [`MessageOrigin`] identifying where the message came from.
/// For messages sent by web applications, this is `MessageOrigin::WebApp(contract_id)`.
/// - `message`: The inbound message to process.
fn process(
ctx: &mut crate::delegate_host::DelegateCtx,
parameters: Parameters<'static>,
origin: Option<MessageOrigin>,
message: InboundDelegateMsg,
) -> Result<Vec<OutboundDelegateMsg>, DelegateError>;
}
#[serde_as]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct DelegateContext(#[serde_as(as = "serde_with::Bytes")] Vec<u8>);
impl DelegateContext {
pub const MAX_SIZE: usize = 4096 * 10 * 10;
pub fn new(bytes: Vec<u8>) -> Self {
assert!(bytes.len() < Self::MAX_SIZE);
Self(bytes)
}
pub fn append(&mut self, bytes: &mut Vec<u8>) {
assert!(self.0.len() + bytes.len() < Self::MAX_SIZE);
self.0.append(bytes)
}
pub fn replace(&mut self, bytes: Vec<u8>) {
assert!(bytes.len() < Self::MAX_SIZE);
let _ = std::mem::replace(&mut self.0, bytes);
}
}
impl AsRef<[u8]> for DelegateContext {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum InboundDelegateMsg<'a> {
ApplicationMessage(ApplicationMessage),
UserResponse(#[serde(borrow)] UserInputResponse<'a>),
GetContractResponse(GetContractResponse),
PutContractResponse(PutContractResponse),
UpdateContractResponse(UpdateContractResponse),
SubscribeContractResponse(SubscribeContractResponse),
ContractNotification(ContractNotification),
DelegateMessage(DelegateMessage),
}
impl InboundDelegateMsg<'_> {
pub fn into_owned(self) -> InboundDelegateMsg<'static> {
match self {
InboundDelegateMsg::ApplicationMessage(r) => InboundDelegateMsg::ApplicationMessage(r),
InboundDelegateMsg::UserResponse(r) => InboundDelegateMsg::UserResponse(r.into_owned()),
InboundDelegateMsg::GetContractResponse(r) => {
InboundDelegateMsg::GetContractResponse(r)
}
InboundDelegateMsg::PutContractResponse(r) => {
InboundDelegateMsg::PutContractResponse(r)
}
InboundDelegateMsg::UpdateContractResponse(r) => {
InboundDelegateMsg::UpdateContractResponse(r)
}
InboundDelegateMsg::SubscribeContractResponse(r) => {
InboundDelegateMsg::SubscribeContractResponse(r)
}
InboundDelegateMsg::ContractNotification(r) => {
InboundDelegateMsg::ContractNotification(r)
}
InboundDelegateMsg::DelegateMessage(r) => InboundDelegateMsg::DelegateMessage(r),
}
}
pub fn get_context(&self) -> Option<&DelegateContext> {
match self {
InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
Some(context)
}
InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
Some(context)
}
InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
Some(context)
}
InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
context, ..
}) => Some(context),
InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
context,
..
}) => Some(context),
InboundDelegateMsg::ContractNotification(ContractNotification { context, .. }) => {
Some(context)
}
InboundDelegateMsg::DelegateMessage(DelegateMessage { context, .. }) => Some(context),
_ => None,
}
}
pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
match self {
InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
Some(context)
}
InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
Some(context)
}
InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
Some(context)
}
InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
context, ..
}) => Some(context),
InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
context,
..
}) => Some(context),
InboundDelegateMsg::ContractNotification(ContractNotification { context, .. }) => {
Some(context)
}
InboundDelegateMsg::DelegateMessage(DelegateMessage { context, .. }) => Some(context),
_ => None,
}
}
}
impl From<ApplicationMessage> for InboundDelegateMsg<'_> {
fn from(value: ApplicationMessage) -> Self {
Self::ApplicationMessage(value)
}
}
impl<'a> TryFromFbs<&FbsInboundDelegateMsg<'a>> for InboundDelegateMsg<'a> {
fn try_decode_fbs(msg: &FbsInboundDelegateMsg<'a>) -> Result<Self, WsApiError> {
match msg.inbound_type() {
InboundDelegateMsgType::common_ApplicationMessage => {
let app_msg = msg.inbound_as_common_application_message().unwrap();
let app_msg = ApplicationMessage {
payload: app_msg.payload().bytes().to_vec(),
context: DelegateContext::new(app_msg.context().bytes().to_vec()),
processed: app_msg.processed(),
};
Ok(InboundDelegateMsg::ApplicationMessage(app_msg))
}
InboundDelegateMsgType::UserInputResponse => {
let user_response = msg.inbound_as_user_input_response().unwrap();
let user_response = UserInputResponse {
request_id: user_response.request_id(),
response: ClientResponse::new(user_response.response().data().bytes().to_vec()),
context: DelegateContext::new(
user_response.delegate_context().bytes().to_vec(),
),
};
Ok(InboundDelegateMsg::UserResponse(user_response))
}
_ => unreachable!("invalid inbound delegate message type"),
}
}
}
#[non_exhaustive]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ApplicationMessage {
pub payload: Vec<u8>,
pub context: DelegateContext,
pub processed: bool,
}
impl ApplicationMessage {
pub fn new(payload: Vec<u8>) -> Self {
Self {
payload,
context: DelegateContext::default(),
processed: false,
}
}
pub fn with_context(mut self, context: DelegateContext) -> Self {
self.context = context;
self
}
pub fn processed(mut self, p: bool) -> Self {
self.processed = p;
self
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UserInputResponse<'a> {
pub request_id: u32,
#[serde(borrow)]
pub response: ClientResponse<'a>,
pub context: DelegateContext,
}
impl UserInputResponse<'_> {
pub fn into_owned(self) -> UserInputResponse<'static> {
UserInputResponse {
request_id: self.request_id,
response: self.response.into_owned(),
context: self.context,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum OutboundDelegateMsg {
// for the apps
ApplicationMessage(ApplicationMessage),
RequestUserInput(
#[serde(deserialize_with = "OutboundDelegateMsg::deser_user_input_req")]
UserInputRequest<'static>,
),
// todo: remove when context can be accessed from the delegate environment and we pass it as reference
ContextUpdated(DelegateContext),
GetContractRequest(GetContractRequest),
PutContractRequest(PutContractRequest),
UpdateContractRequest(UpdateContractRequest),
SubscribeContractRequest(SubscribeContractRequest),
SendDelegateMessage(DelegateMessage),
}
impl From<ApplicationMessage> for OutboundDelegateMsg {
fn from(req: ApplicationMessage) -> Self {
Self::ApplicationMessage(req)
}
}
impl From<GetContractRequest> for OutboundDelegateMsg {
fn from(req: GetContractRequest) -> Self {
Self::GetContractRequest(req)
}
}
impl From<PutContractRequest> for OutboundDelegateMsg {
fn from(req: PutContractRequest) -> Self {
Self::PutContractRequest(req)
}
}
impl From<UpdateContractRequest> for OutboundDelegateMsg {
fn from(req: UpdateContractRequest) -> Self {
Self::UpdateContractRequest(req)
}
}
impl From<SubscribeContractRequest> for OutboundDelegateMsg {
fn from(req: SubscribeContractRequest) -> Self {
Self::SubscribeContractRequest(req)
}
}
impl From<DelegateMessage> for OutboundDelegateMsg {
fn from(msg: DelegateMessage) -> Self {
Self::SendDelegateMessage(msg)
}
}
impl OutboundDelegateMsg {
fn deser_user_input_req<'de, D>(deser: D) -> Result<UserInputRequest<'static>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = <UserInputRequest<'de> as Deserialize>::deserialize(deser)?;
Ok(value.into_owned())
}
pub fn processed(&self) -> bool {
match self {
OutboundDelegateMsg::ApplicationMessage(msg) => msg.processed,
OutboundDelegateMsg::GetContractRequest(msg) => msg.processed,
OutboundDelegateMsg::PutContractRequest(msg) => msg.processed,
OutboundDelegateMsg::UpdateContractRequest(msg) => msg.processed,
OutboundDelegateMsg::SubscribeContractRequest(msg) => msg.processed,
OutboundDelegateMsg::SendDelegateMessage(msg) => msg.processed,
OutboundDelegateMsg::RequestUserInput(_) => true,
OutboundDelegateMsg::ContextUpdated(_) => true,
}
}
pub fn get_context(&self) -> Option<&DelegateContext> {
match self {
OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
Some(context)
}
OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
Some(context)
}
OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
Some(context)
}
OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
context, ..
}) => Some(context),
OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
context,
..
}) => Some(context),
OutboundDelegateMsg::SendDelegateMessage(DelegateMessage { context, .. }) => {
Some(context)
}
_ => None,
}
}
pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
match self {
OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
Some(context)
}
OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
Some(context)
}
OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
Some(context)
}
OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
context, ..
}) => Some(context),
OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
context,
..
}) => Some(context),
OutboundDelegateMsg::SendDelegateMessage(DelegateMessage { context, .. }) => {
Some(context)
}
_ => None,
}
}
}
/// Request to get contract state from within a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct GetContractRequest {
pub contract_id: ContractInstanceId,
pub context: DelegateContext,
pub processed: bool,
}
impl GetContractRequest {
pub fn new(contract_id: ContractInstanceId) -> Self {
Self {
contract_id,
context: Default::default(),
processed: false,
}
}
}
/// Response containing contract state for a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct GetContractResponse {
pub contract_id: ContractInstanceId,
/// The contract state, or None if the contract was not found locally.
pub state: Option<WrappedState>,
pub context: DelegateContext,
}
/// Request to store a new contract from within a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PutContractRequest {
/// The contract code and parameters.
pub contract: ContractContainer,
/// The initial state for the contract.
pub state: WrappedState,
/// Related contracts that this contract depends on.
#[serde(deserialize_with = "RelatedContracts::deser_related_contracts")]
pub related_contracts: RelatedContracts<'static>,
/// Context for the delegate.
pub context: DelegateContext,
/// Whether this request has been processed.
pub processed: bool,
}
impl PutContractRequest {
pub fn new(
contract: ContractContainer,
state: WrappedState,
related_contracts: RelatedContracts<'static>,
) -> Self {
Self {
contract,
state,
related_contracts,
context: Default::default(),
processed: false,
}
}
}
/// Response after attempting to store a contract from a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PutContractResponse {
/// The ID of the contract that was (attempted to be) stored.
pub contract_id: ContractInstanceId,
/// Success (Ok) or error message (Err).
pub result: Result<(), String>,
/// Context for the delegate.
pub context: DelegateContext,
}
/// Request to update an existing contract's state from within a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UpdateContractRequest {
/// The contract to update.
pub contract_id: ContractInstanceId,
/// The update to apply (full state or delta).
#[serde(deserialize_with = "UpdateContractRequest::deser_update_data")]
pub update: UpdateData<'static>,
/// Context for the delegate.
pub context: DelegateContext,
/// Whether this request has been processed.
pub processed: bool,
}
impl UpdateContractRequest {
pub fn new(contract_id: ContractInstanceId, update: UpdateData<'static>) -> Self {
Self {
contract_id,
update,
context: Default::default(),
processed: false,
}
}
fn deser_update_data<'de, D>(deser: D) -> Result<UpdateData<'static>, D::Error>
where
D: Deserializer<'de>,
{
let value = <UpdateData<'de> as Deserialize>::deserialize(deser)?;
Ok(value.into_owned())
}
}
/// Response after attempting to update a contract from a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UpdateContractResponse {
/// The contract that was updated.
pub contract_id: ContractInstanceId,
/// Success (Ok) or error message (Err).
pub result: Result<(), String>,
/// Context for the delegate.
pub context: DelegateContext,
}
/// Request to subscribe to a contract's state changes from within a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SubscribeContractRequest {
/// The contract to subscribe to.
pub contract_id: ContractInstanceId,
/// Context for the delegate.
pub context: DelegateContext,
/// Whether this request has been processed.
pub processed: bool,
}
impl SubscribeContractRequest {
pub fn new(contract_id: ContractInstanceId) -> Self {
Self {
contract_id,
context: Default::default(),
processed: false,
}
}
}
/// Response after attempting to subscribe to a contract from a delegate.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SubscribeContractResponse {
/// The contract subscribed to.
pub contract_id: ContractInstanceId,
/// Success (Ok) or error message (Err).
pub result: Result<(), String>,
/// Context for the delegate.
pub context: DelegateContext,
}
/// A message sent from one delegate to another.
///
/// Delegates can communicate with each other by emitting
/// `OutboundDelegateMsg::SendDelegateMessage` with a `DelegateMessage` targeting
/// another delegate. The runtime delivers it as `InboundDelegateMsg::DelegateMessage`
/// to the target delegate's `process()` function.
///
/// The `sender` field is overwritten by the runtime with the actual sender's key
/// (sender attestation), so delegates cannot spoof their identity.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DelegateMessage {
/// The delegate to deliver this message to.
pub target: DelegateKey,
/// The delegate that sent this message (overwritten by runtime for attestation).
pub sender: DelegateKey,
/// Arbitrary message payload.
pub payload: Vec<u8>,
/// Delegate context, carried through the processing pipeline.
pub context: DelegateContext,
/// Runtime protocol flag indicating whether this message has been delivered.
pub processed: bool,
}
impl DelegateMessage {
pub fn new(target: DelegateKey, sender: DelegateKey, payload: Vec<u8>) -> Self {
Self {
target,
sender,
payload,
context: DelegateContext::default(),
processed: false,
}
}
}
/// Notification delivered to a delegate when a subscribed contract's state changes.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ContractNotification {
/// The contract whose state changed.
pub contract_id: ContractInstanceId,
/// The new state of the contract.
pub new_state: WrappedState,
/// Context for the delegate.
pub context: DelegateContext,
}
#[serde_as]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NotificationMessage<'a>(
#[serde_as(as = "serde_with::Bytes")]
#[serde(borrow)]
Cow<'a, [u8]>,
);
impl TryFrom<&serde_json::Value> for NotificationMessage<'static> {
type Error = ();
fn try_from(json: &serde_json::Value) -> Result<NotificationMessage<'static>, ()> {
// todo: validate format when we have a better idea of what we want here
let bytes = serde_json::to_vec(json).unwrap();
Ok(Self(Cow::Owned(bytes)))
}
}
impl NotificationMessage<'_> {
pub fn into_owned(self) -> NotificationMessage<'static> {
NotificationMessage(self.0.into_owned().into())
}
pub fn bytes(&self) -> &[u8] {
self.0.as_ref()
}
}
#[serde_as]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ClientResponse<'a>(
#[serde_as(as = "serde_with::Bytes")]
#[serde(borrow)]
Cow<'a, [u8]>,
);
impl Deref for ClientResponse<'_> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ClientResponse<'_> {