hyli-contract-sdk 0.15.0

Hyli smart contract SDK
Documentation
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
use crate::{
    alloc::string::{String, ToString},
    caller::ExecutionContext,
    Identity, StructuredBlobData,
};
use alloc::{format, vec};
use borsh::{BorshDeserialize, BorshSerialize};
use core::result::Result;

use hyli_model::{
    Blob, BlobIndex, Calldata, DropEndOfReader, HyliOutput, IndexedBlobs, StateCommitment,
    StructuredBlob,
};

/// This function is used to parse the contract input blob data into a given template `Action`
/// It assumes that the blob data is the `Action` serialized with borsh.
/// It returns a tuple with the parsed `Action` and an [ExecutionContext] that can be used
/// by the contract, and will be needed by the sdk to build the [HyliOutput].
///
/// Alternative: [parse_calldata]
pub fn parse_raw_calldata<Action>(calldata: &Calldata) -> Result<(Action, ExecutionContext), String>
where
    Action: BorshDeserialize,
{
    let blobs = &calldata.blobs;
    let index = &calldata.index;

    let blob = match blobs.get(index) {
        Some(v) => v,
        None => {
            return Err(format!("Could not find Blob at index {index}"));
        }
    };

    let Ok(parameters) = borsh::from_slice::<Action>(blob.data.0.as_slice()) else {
        return Err(format!("Could not deserialize Blob at index {index}"));
    };

    let exec_ctx = ExecutionContext::new(calldata.identity.clone(), blob.contract_name.clone());
    Ok((parameters, exec_ctx))
}

/// This function is used to parse the contract input blob data.
/// It assumes that the blob data is a [StructuredBlobData] serialized with borsh.
/// It returns a tuple with the parsed `Action` and an [ExecutionContext] that can be used
/// by the contract, and will be needed by the sdk to build the [HyliOutput].
///
/// The [ExecutionContext] will holds the caller/callees information.
/// See [StructuredBlobData] page for more information on caller/callees.
///
/// Alternative: [parse_raw_calldata]
pub fn parse_calldata<Action>(calldata: &Calldata) -> Result<(Action, ExecutionContext), String>
where
    Action: BorshSerialize + BorshDeserialize,
{
    let parsed_blob = parse_structured_blob::<Action>(&calldata.blobs, &calldata.index);

    let parsed_blob = parsed_blob.ok_or("Failed to parse input blob".to_string())?;

    let caller = check_caller_callees::<Action>(calldata, &parsed_blob)?;

    let mut callees_blobs = vec::Vec::new();
    for (_, blob) in &calldata.blobs {
        if let Ok(structured_blob) = blob.data.clone().try_into() {
            let structured_blob: StructuredBlobData<DropEndOfReader> = structured_blob; // for type inference
            if structured_blob.caller == Some(calldata.index) {
                callees_blobs.push(blob.clone());
            }
        };
    }

    let ctx = ExecutionContext {
        callees_blobs,
        caller,
        contract_name: parsed_blob.contract_name.clone(),
    };

    Ok((parsed_blob.data.parameters, ctx))
}

pub fn parse_blob<Action>(blobs: &[Blob], index: &BlobIndex) -> Option<Action>
where
    Action: BorshDeserialize,
{
    let blob = match blobs.get(index.0) {
        Some(v) => v,
        None => {
            return None;
        }
    };

    let Ok(parameters) = borsh::from_slice::<Action>(blob.data.0.as_slice()) else {
        return None;
    };

    Some(parameters)
}

pub fn parse_structured_blob<Action>(
    blobs: &IndexedBlobs,
    index: &BlobIndex,
) -> Option<StructuredBlob<Action>>
where
    Action: BorshDeserialize,
{
    let blob = match blobs.get(index) {
        Some(v) => v,
        None => {
            return None;
        }
    };

    let parsed_blob: StructuredBlob<Action> = match StructuredBlob::try_from(blob.clone()) {
        Ok(v) => v,
        Err(_) => {
            return None;
        }
    };
    Some(parsed_blob)
}

fn fail(
    calldata: &Calldata,
    initial_state_commitment: StateCommitment,
    message: &str,
) -> HyliOutput {
    HyliOutput {
        version: 1,
        initial_state: initial_state_commitment.clone(),
        next_state: initial_state_commitment,
        identity: calldata.identity.clone(),
        index: calldata.index,
        blobs: calldata.blobs.clone(),
        tx_blob_count: calldata.tx_blob_count,
        success: false,
        tx_hash: calldata.tx_hash.clone(),
        state_reads: vec![],
        tx_ctx: calldata.tx_ctx.clone(),
        onchain_effects: vec![],
        program_outputs: message.to_string().into_bytes(),
    }
}

pub fn as_hyli_output(
    initial_state_commitment: StateCommitment,
    next_state_commitment: StateCommitment,
    calldata: &Calldata,
    res: &mut crate::RunResult,
) -> HyliOutput {
    match res {
        Ok((ref mut program_output, execution_context, ref mut onchain_effects)) => {
            if !execution_context.callees_blobs.is_empty() {
                return fail(
                    calldata,
                    initial_state_commitment,
                    &format!(
                        "Execution context has not been fully consumed {:?}",
                        execution_context.callees_blobs
                    ),
                );
            }
            HyliOutput {
                version: 1,
                initial_state: initial_state_commitment,
                next_state: next_state_commitment,
                identity: calldata.identity.clone(),
                index: calldata.index,
                blobs: calldata.blobs.clone(),
                tx_blob_count: calldata.tx_blob_count,
                success: true,
                tx_hash: calldata.tx_hash.clone(),
                state_reads: vec![],
                tx_ctx: calldata.tx_ctx.clone(),
                onchain_effects: core::mem::take(onchain_effects),
                program_outputs: core::mem::take(program_output),
            }
        }
        Err(message) => fail(calldata, initial_state_commitment, message),
    }
}

/// This function checks that the caller and callees of a blob are correct.
/// It is written defensively, so it's both checking our callees and our caller.
/// If another contract is written incorrectly, we still will reject incorrect blobs.
pub fn check_caller_callees<Action>(
    calldata: &Calldata,
    parameters: &StructuredBlob<Action>,
) -> Result<Identity, String>
where
    Action: BorshSerialize + BorshDeserialize,
{
    // Check that callees has this blob as caller
    if let Some(callees) = parameters.data.callees.as_ref() {
        // Check that the number of callees matches the number of blobs that have this blob as caller
        let blobs_with_this_as_caller = calldata.blobs.iter().filter_map(|(i, blob)| {
            if let Ok(structured_blob) =
                blob.data.clone().try_into() as Result<StructuredBlobData<DropEndOfReader>, _>
            {
                match structured_blob.caller == Some(calldata.index) {
                    true => Some(i),
                    false => None,
                }
            } else {
                None
            }
        });
        if !callees.iter().eq(blobs_with_this_as_caller) {
            return Err("Blob callees do not match actual callees".to_string());
        }
    }
    // Extract the correct caller
    if let Some(caller_index) = parameters.data.caller.as_ref() {
        if *caller_index == calldata.index {
            return Err("Self-reference as callee is forbidden".to_string());
        }

        // TODO: Have to clone to parse into StructuredBlobData
        if let Some(caller_blob) = calldata.blobs.get(caller_index).cloned() {
            let caller_structured_blob: StructuredBlobData<DropEndOfReader> = caller_blob
                .data
                .try_into()
                .map_err(|_| format!("Could not parse blob {caller_index} as a StructuredBlob"))?;
            // Check that caller has this blob as callee
            let Some(caller_callees) = caller_structured_blob.callees else {
                return Err("Caller does not have any callees".to_string());
            };
            if !caller_callees.contains(&calldata.index) {
                return Err("Incorrect Caller for this blob".to_string());
            }
            return Ok(caller_blob.contract_name.0.clone().into());
        } else {
            return Err(format!("Caller index {caller_index} not found in blobs"));
        }
        // TODO: have to clone to parse into StructuredBlobData
    } else if calldata.blobs.clone().into_iter().any(|(_, blob)| {
        if let Ok(structured_blob) =
            blob.data.clone().try_into() as Result<StructuredBlobData<DropEndOfReader>, _>
        {
            structured_blob.callees.is_some_and(|callees| {
                // Check that this blob is not in callees
                callees.contains(&calldata.index)
            })
        } else {
            false
        }
    }) {
        return Err("Blob has no caller but another blob claims it as a callee".to_string());
    }

    // No callers detected, use the identity
    Ok(calldata.identity.clone())
}

#[cfg(test)]
mod tests {
    use super::*;
    use hyli_model::{Blob, BlobData, ContractName, TxHash};

    fn make_calldata(
        identity: Identity,
        index: BlobIndex,
        blobs: IndexedBlobs,
        tx_blob_count: usize,
    ) -> Calldata {
        Calldata {
            identity,
            index,
            blobs,
            tx_blob_count,
            tx_hash: TxHash::default(),
            tx_ctx: None,
            private_input: vec![],
        }
    }

    fn make_blob(
        contract: &str,
        caller: Option<BlobIndex>,
        callees: Option<Vec<BlobIndex>>,
    ) -> Blob {
        Blob {
            contract_name: ContractName::new(contract),
            data: BlobData(
                borsh::to_vec(&StructuredBlobData {
                    caller,
                    callees,
                    parameters: (),
                })
                .unwrap(),
            ),
        }
    }

    type TestCase<'a> = (
        BlobIndex,
        &'a str,
        Option<BlobIndex>,
        Option<Vec<BlobIndex>>,
    );
    fn make_test_case(
        blob_specs: Vec<TestCase>,
        test_index: BlobIndex,
    ) -> (Calldata, StructuredBlob<()>) {
        let blobs: Vec<(BlobIndex, Blob)> = blob_specs
            .iter()
            .map(|(idx, contract, caller, callees)| {
                (*idx, make_blob(contract, *caller, callees.clone()))
            })
            .collect();
        let calldata = make_calldata(Identity::new("user"), test_index, IndexedBlobs(blobs), 2);
        // Find the blob spec for test_index
        let (_, _, caller, callees) = blob_specs
            .iter()
            .find(|(idx, _, _, _)| *idx == test_index)
            .expect("test_index must be present in blob_specs");
        let parameters = StructuredBlob {
            contract_name: ContractName::new("test"),
            data: StructuredBlobData {
                caller: *caller,
                callees: callees.clone(),
                parameters: (),
            },
        };
        (calldata, parameters)
    }

    fn expect_error(blob_specs: Vec<TestCase>, test_index: BlobIndex, expected_error: &str) {
        let (calldata, parameters) = make_test_case(blob_specs, test_index);
        let result = check_caller_callees(&calldata, &parameters);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), expected_error);
    }

    fn expect_ok(blob_specs: Vec<TestCase>, test_index: BlobIndex) {
        let (calldata, parameters) = make_test_case(blob_specs, test_index);
        let result = check_caller_callees(&calldata, &parameters);
        assert!(result.is_ok());
    }

    #[test]
    fn test_valid_caller_and_callee() {
        expect_ok(
            vec![
                (BlobIndex(0), "caller", None, Some(vec![BlobIndex(1)])),
                (BlobIndex(1), "callee", Some(BlobIndex(0)), None),
            ],
            BlobIndex(0),
        );
        expect_ok(
            vec![
                (BlobIndex(0), "caller", None, Some(vec![BlobIndex(1)])),
                (BlobIndex(1), "callee", Some(BlobIndex(0)), None),
            ],
            BlobIndex(1),
        );
    }
    #[test]
    fn test_valid_with_nothing() {
        expect_ok(
            vec![
                (BlobIndex(0), "caller", None, None),
                (BlobIndex(1), "callee", None, None),
            ],
            BlobIndex(0),
        );
        expect_ok(
            vec![
                (BlobIndex(0), "caller", None, None),
                (BlobIndex(1), "callee", None, None),
            ],
            BlobIndex(1),
        );
    }

    #[test]
    fn test_callee_does_not_have_this_blob_as_caller() {
        expect_error(
            vec![
                (BlobIndex(0), "caller", None, Some(vec![BlobIndex(1)])),
                (BlobIndex(1), "callee", None, None),
            ],
            BlobIndex(0),
            "Blob callees do not match actual callees",
        );
        // Inverse - check no-one claims to be our caller
        expect_error(
            vec![
                (BlobIndex(0), "caller", None, Some(vec![BlobIndex(1)])),
                (BlobIndex(1), "callee", None, None),
            ],
            BlobIndex(1),
            "Blob has no caller but another blob claims it as a callee",
        );
    }

    #[test]
    fn test_caller_does_not_have_this_blob_as_callee() {
        expect_error(
            vec![
                (BlobIndex(0), "caller", None, Some(vec![BlobIndex(2)])),
                (BlobIndex(1), "callee", Some(BlobIndex(0)), None),
            ],
            BlobIndex(1),
            "Incorrect Caller for this blob",
        );
    }

    #[test]
    fn test_callee_index_does_not_exist() {
        expect_error(
            vec![(BlobIndex(0), "caller", None, Some(vec![BlobIndex(1)]))],
            BlobIndex(0),
            "Blob callees do not match actual callees",
        );
    }

    #[test]
    fn test_caller_index_does_not_exist() {
        expect_error(
            vec![(BlobIndex(1), "callee", Some(BlobIndex(0)), None)],
            BlobIndex(1),
            "Caller index 0 not found in blobs",
        );
    }

    #[test]
    fn test_caller_has_no_callees() {
        expect_error(
            vec![
                (BlobIndex(0), "caller", None, None),
                (BlobIndex(1), "callee", Some(BlobIndex(0)), None),
            ],
            BlobIndex(1),
            "Caller does not have any callees",
        );
    }

    #[test]
    fn test_caller_has_empty_callees() {
        expect_error(
            vec![
                (BlobIndex(0), "caller", None, Some(vec![])),
                (BlobIndex(1), "callee", Some(BlobIndex(0)), None),
            ],
            BlobIndex(1),
            "Incorrect Caller for this blob",
        );
    }

    #[test]
    fn test_no_caller_no_callees_returns_identity() {
        let (calldata, parameters) =
            make_test_case(vec![(BlobIndex(0), "caller", None, None)], BlobIndex(0));
        let result = check_caller_callees(&calldata, &parameters);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), calldata.identity);
    }

    #[test]
    fn test_both_caller_and_callees_valid() {
        // Blob 0 is caller, Blob 1 is callee, both reference each other, and Blob 1 also has a callee
        expect_ok(
            vec![
                (BlobIndex(0), "caller", None, Some(vec![BlobIndex(1)])),
                (
                    BlobIndex(1),
                    "callee",
                    Some(BlobIndex(0)),
                    Some(vec![BlobIndex(2)]),
                ),
                (BlobIndex(2), "next", Some(BlobIndex(1)), None),
            ],
            BlobIndex(1),
        );
    }

    #[test]
    fn test_self_reference_as_caller() {
        // Blob references itself as caller / callee (forbidden)
        expect_error(
            vec![(
                BlobIndex(0),
                "self",
                Some(BlobIndex(0)),
                Some(vec![BlobIndex(0)]),
            )],
            BlobIndex(0),
            "Self-reference as callee is forbidden",
        );
    }

    #[test]
    fn test_caller_has_callees_but_not_this_blob() {
        // Caller exists, has callees, but not the current blob (forbidden)
        expect_error(
            vec![
                (BlobIndex(0), "caller", None, Some(vec![BlobIndex(2)])),
                (BlobIndex(1), "callee", Some(BlobIndex(0)), None),
                (BlobIndex(2), "other", Some(BlobIndex(0)), None),
            ],
            BlobIndex(1),
            "Incorrect Caller for this blob",
        );
        expect_error(
            vec![
                (BlobIndex(0), "caller", None, Some(vec![BlobIndex(2)])),
                (BlobIndex(1), "callee", Some(BlobIndex(0)), None),
                (BlobIndex(2), "other", Some(BlobIndex(0)), None),
            ],
            BlobIndex(0),
            "Blob callees do not match actual callees",
        );
    }

    #[test]
    fn test_caller_has_callees_but_not_this_blob_2() {
        // Caller exists, has callees, but not the current blob (forbidden)
        expect_error(
            vec![
                (
                    BlobIndex(0),
                    "caller",
                    None,
                    Some(vec![BlobIndex(2), BlobIndex(3)]),
                ),
                (BlobIndex(1), "callee", None, None),
                (BlobIndex(2), "other", Some(BlobIndex(0)), None),
                (BlobIndex(3), "other3", None, None),
                (BlobIndex(4), "other4", Some(BlobIndex(0)), None),
            ],
            BlobIndex(0),
            "Blob callees do not match actual callees",
        );
    }

    #[test]
    fn test_incorrect_number_of_callees() {
        // Blob 1 and Blob 2 both reference Blob 0 as their caller,
        // but Blob 0 only lists one callee.
        expect_error(
            vec![
                (BlobIndex(0), "main", None, Some(vec![BlobIndex(1)])), // Only one callee listed
                (BlobIndex(1), "a", Some(BlobIndex(0)), None),
                (BlobIndex(2), "b", Some(BlobIndex(0)), None),
            ],
            BlobIndex(0),
            "Blob callees do not match actual callees",
        );
        // Inverse
        expect_error(
            vec![
                (
                    BlobIndex(0),
                    "main",
                    None,
                    Some(vec![BlobIndex(1), BlobIndex(2)]),
                ),
                (BlobIndex(1), "a", Some(BlobIndex(0)), None),
                (BlobIndex(2), "b", None, None),
            ],
            BlobIndex(0),
            "Blob callees do not match actual callees",
        );
    }
}