rave_engine 0.8.0

A secure and efficient JSON Schema validation and Rhai script execution engine
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
566
567
568
569
570
571
572
573
574
use super::utils::*;
use crate::{
    helper_fn::inner_get_agent_app_entries_activity,
    rhai_engine::RhaiEngine,
    types::{
        entries::{
            parked_link::{ParkedLink, ParkedLinkType},
            DataBlob,
        },
        Ledger, UnitMap,
    },
};
use hdi::prelude::{debug, trace, wasm_error, Action, ActionHash, ExternResult, Timestamp};
use rhai::{Array, Dynamic, EvalAltResult, Map, Position};
use serde_json::Value;
use std::str::FromStr;
use std::time::Duration;
use zfuel::fuel::ZFuel;

/// get spend links author
pub fn get_spend_links_author(spend_link_hash: String) -> Result<Dynamic, Box<EvalAltResult>> {
    let spend_link_hash = ActionHash::try_from(spend_link_hash).map_err(|e| {
        Box::new(EvalAltResult::ErrorRuntime(
            format!("Failed to parse ActionHash: {e}").into(),
            Position::NONE,
        ))
    })?;
    let a = ParkedLink::must_get(&spend_link_hash).map_err(|e| {
        Box::new(EvalAltResult::ErrorRuntime(
            format!("Failed to get ParkedLink: {e}").into(),
            Position::NONE,
        ))
    })?;
    Ok(Dynamic::from(a.creator.to_string()))
}

// todo: we can break this down to move most of the logic into the rhai script
pub fn check_cool_down_period(
    most_recent_spend_link_hash: String,
    agreement_id: String,
    executed_timestamp: String,
    cool_down_period: String,
    withdrawing_unit_index: String,
) -> Result<Dynamic, Box<EvalAltResult>> {
    let most_recent_spend_link_hash =
        ActionHash::try_from(most_recent_spend_link_hash).map_err(|e| {
            Box::new(EvalAltResult::ErrorRuntime(
                format!("Failed to parse ActionHash: {e}").into(),
                Position::NONE,
            ))
        })?;
    let agreement_id = ActionHash::try_from(agreement_id).map_err(|e| {
        Box::new(EvalAltResult::ErrorRuntime(
            format!("Failed to parse ActionHash: {e}").into(),
            Position::NONE,
        ))
    })?;
    let current_link = ParkedLink::must_get(&most_recent_spend_link_hash).map_err(|e| {
        Box::new(EvalAltResult::ErrorRuntime(
            format!("Failed to get ParkedLink: {e}").into(),
            Position::NONE,
        ))
    })?;
    let executed_timestamp = Timestamp::try_from(executed_timestamp).map_err(|e| {
        Box::new(EvalAltResult::ErrorRuntime(
            format!("Failed to parse Timestamp: {e}").into(),
            Position::NONE,
        ))
    })?;
    let until_time = (executed_timestamp
        - Duration::from_secs(cool_down_period.parse::<u64>().map_err(|e| {
            Box::new(EvalAltResult::ErrorRuntime(
                format!("Failed to parse cool_down_period: {e}").into(),
                Position::NONE,
            ))
        })?))
    .expect("Failed to subtract seconds from timestamp");

    let author = current_link.creator;

    let (agents_chain_entry_records, _agent_activity) = inner_get_agent_app_entries_activity(
        author.to_owned(),
        most_recent_spend_link_hash.to_owned(),
    )
    .map_err(|e| {
        Box::new(EvalAltResult::ErrorRuntime(
            e.to_string().into(),
            Position::NONE,
        ))
    })?;
    // get the ledger state would be at a specific time
    // use the highest timestamp and filter out the ones that are older than the minutes
    let filtered_agents_chain_entry_record_before_timestamp = agents_chain_entry_records
        .clone()
        .into_iter()
        .filter(|r| r.action().timestamp() < until_time)
        .collect::<Vec<_>>();
    let ledger_at_time =
        Ledger::calculate_from(&filtered_agents_chain_entry_record_before_timestamp);

    // get the spend links since the last 6 hours
    let all_links: Vec<ParkedLink> = agents_chain_entry_records
        .iter()
        .filter(|s| s.action().timestamp() > until_time)
        .filter_map(|r| r.try_into().ok())
        .filter(|s: &ParkedLink| s.ea_id == agreement_id)
        .collect();
    // calculate the total spend for the last 6 hours
    let total_spend_amounts = all_links.iter().filter_map(|s| s.amount()).collect();
    let total_spends = UnitMap::sum_vec(total_spend_amounts).unwrap_or_default();

    let ledger_balance_for_unit_6_hours_ago =
        ledger_at_time.balance.get_safe(&withdrawing_unit_index);
    let total_spend_amounts_for_unit_6_hours_ago = total_spends.get_safe(&withdrawing_unit_index);
    let difference = (ledger_balance_for_unit_6_hours_ago
        - total_spend_amounts_for_unit_6_hours_ago)
        .map_err(|e| {
            Box::new(EvalAltResult::ErrorRuntime(
                e.to_string().into(),
                Position::NONE,
            ))
        })?;
    if difference < ZFuel::zero() {
        return Ok(Dynamic::from(false));
    }
    Ok(Dynamic::from(true))
}

// /// verify if the record is a Spend or a ParkedSpend
// pub fn verify_valid_spend_records(spend: Map) -> Result<Dynamic, Box<EvalAltResult>> {
//     let spend_record = try_into_record(spend.clone()).map_err(|e| {
//         Box::new(EvalAltResult::ErrorRuntime(
//             format!("Failed to parse Spend: {spend:?} Error: {e} End").into(),
//             Position::NONE,
//         ))
//     })?;
//     if let Ok(spend) = Spend::try_from(&spend_record) {
//         if spend.amount.is_zero() {
//             return Ok(Dynamic::from(false));
//         }
//         Ok(Dynamic::from(true))
//     } else if let Ok(parked_spend) = ParkedLink::try_from(&spend_record) {
//         if let ParkedLinkType::ParkedSpendData(parked_spend_tag) = parked_spend.tag {
//             if parked_spend_tag.amount.is_zero() {
//                 return Ok(Dynamic::from(false));
//             }
//             return Ok(Dynamic::from(true));
//         } else {
//             return Ok(Dynamic::from(false));
//         }
//     } else {
//         return Ok(Dynamic::from(false));
//     }
// }

fn get_parked_link_from_source(allocation: Map) -> ExternResult<(ParkedLink, ActionHash)> {
    // todo: better error handling
    let source = allocation["source"].to_string();

    let source_action = ActionHash::try_from(source)
        .map_err(|e| wasm_error!("Failed to parse ActionHash: {}", e))?;

    let parked_link = ParkedLink::must_get(&source_action)?;

    Ok((parked_link, source_action))
}
/// sort allocation based on timestamp of the sources
pub fn acceding_sort_allocation(allocation: Array) -> Result<Array, Box<EvalAltResult>> {
    let parked_links: Vec<(ParkedLink, ActionHash)> = allocation
        .into_iter()
        .filter_map(|a| {
            a.try_cast::<Map>()
                .and_then(|map| get_parked_link_from_source(map).ok())
        })
        .collect();

    let mut sorted_parked_links = parked_links;
    sorted_parked_links.sort_by_key(|(a, _)| a.timestamp);

    // convert Vec<ParkedLink> to A Vec<Map>
    let sorted_parked_links_map: Vec<Map> = sorted_parked_links
        .into_iter()
        .map(|(a, id)| {
            let mut map = Map::new();
            let amount: Map = if let Some(amount) = a.amount() {
                amount.to_map()
            } else {
                UnitMap::new().to_map()
            };
            map.insert("amount".into(), Dynamic::from(amount));
            map.insert("source".into(), Dynamic::from(id.to_string()));
            map.insert("spender".into(), Dynamic::from(a.creator.to_string()));
            map
        })
        .collect();

    Ok(sorted_parked_links_map
        .into_iter()
        .map(Dynamic::from)
        .collect())
}

/// get data blob
pub fn get_data_blob(hash: String) -> Result<Dynamic, Box<EvalAltResult>> {
    let blob_hash_id = ActionHash::try_from(hash).map_err(|e| {
        Box::new(EvalAltResult::ErrorRuntime(
            format!("Failed to parse ActionHash: {e}").into(),
            Position::NONE,
        ))
    })?;

    let blob = DataBlob::must_get(&blob_hash_id).map_err(|e| {
        Box::new(EvalAltResult::ErrorRuntime(
            format!("Failed to get DataBlob: {e}").into(),
            Position::NONE,
        ))
    })?;

    let blob_bytes = (blob.0).data;
    let value: Value = rmp_serde::from_slice(&blob_bytes).map_err(|e| {
        Box::new(EvalAltResult::ErrorRuntime(
            format!("Failed to parse DataBlob: {blob_bytes:?} Error: {e} End").into(),
            Position::NONE,
        ))
    })?;

    // convert value to dynamic
    let dynamic = RhaiEngine::json_to_rhai_dynamic(&value);
    debug!("value: {:?}", dynamic);
    Ok(dynamic)
}

/// Functions for handling ParkedSpend data in the DNA context.
/// This module provides utilities for parsing and handling parked spends
/// within the Holochain DNA environment.
pub fn parse_record_to_parked_amount_and_source(
    record: Map,
) -> Result<Dynamic, Box<EvalAltResult>> {
    // Convert the input Map to a Record type
    let record = try_into_record(record)?;
    let record_id = record.action_address();
    let action = record.action();

    // Ensure the action is a CreateLink and extract it
    let create_link = match action {
        Action::CreateLink(create_link) => create_link,
        _ => {
            return Err(Box::new(EvalAltResult::ErrorRuntime(
                "Expected CreateLink action".into(),
                Position::NONE,
            )))
        }
    };

    // Parse the link tag into a ParkedL
    let tag = ParkedLinkType::from_create_link(create_link).map_err(|e| {
        Box::new(EvalAltResult::ErrorRuntime(
            format!("Failed to parse ParkedData: {e}").into(),
            Position::NONE,
        ))
    })?;

    // Convert allocations to Rhai format
    // Each allocation is converted into a map with amount, agent, and source fields
    if let ParkedLinkType::ParkedSpendBalance(parked_spend_tag) = tag {
        trace!("parked_spend_tag: {:?}", parked_spend_tag);
        let mut map = Map::new();
        // Convert amount to array of strings
        map.insert(
            "amount".into(),
            Dynamic::from(parked_spend_tag.amount.to_map()),
        );
        map.insert("source".into(), Dynamic::from(record_id.to_string()));

        trace!("parse_record_to_parked_amount_and_source: {:?}", map);
        Ok(Dynamic::from(map))
    } else if let ParkedLinkType::ParkedSpendCredit(parked_spend_tag) = tag {
        trace!("parked_spend_credit_tag: {:?}", parked_spend_tag);
        let mut map = Map::new();
        // Convert amount to array of strings
        map.insert(
            "amount".into(),
            Dynamic::from(parked_spend_tag.amount.to_map()),
        );
        map.insert("source".into(), Dynamic::from(record_id.to_string()));

        trace!("parse_record_to_parked_amount_and_source: {:?}", map);
        Ok(Dynamic::from(map))
    } else {
        Err(Box::new(EvalAltResult::ErrorRuntime(
            "Expected ParkedSpendData".into(),
            Position::NONE,
        )))
    }
}

/// Greedy multi-source spend over a `consumed_inputs`-shaped allocation array
/// (`[#{ data: #{ amount: #{ unit: "amt" }, source: s } }, …]`): draw each
/// allocation's `unit_index` amount in array order until `needed` is covered,
/// subtracting what is drawn in place — exact ZFuel integer arithmetic, so no
/// float accumulation and no epsilon-tolerant compare anywhere.
///
/// Returns `#{ covered: bool, sources: [source, …] }`, one source per
/// allocation actually drawn from. When the array's total cannot cover
/// `needed`, NOTHING is consumed and `covered` is false — the caller refuses
/// the run, and a partially-drained array would only distort its remainder
/// accounting. A `needed` of zero is covered by drawing nothing.
pub fn consume_allocations(
    allocations: &mut Array,
    unit_index: String,
    needed: String,
) -> Result<Map, Box<EvalAltResult>> {
    fn err(msg: String) -> Box<EvalAltResult> {
        Box::new(EvalAltResult::ErrorRuntime(msg.into(), Position::NONE))
    }
    // The ZFuel at `unit_index` within an allocation's amount map; absent => 0.
    fn amount_at(amount: &Map, unit_index: &str, i: usize) -> Result<ZFuel, Box<EvalAltResult>> {
        match amount.get(unit_index) {
            None => Ok(ZFuel::zero()),
            Some(v) => {
                let s = v.to_string();
                ZFuel::from_str(&s).map_err(|e| {
                    err(format!(
                        "consume_allocations: allocation {i} amount \"{s}\" is not a valid fuel amount: {e:?}"
                    ))
                })
            }
        }
    }
    // Pass 1's read: walk to the unit amount WITHOUT cloning the nested maps —
    // the cover check only sums amounts. Pass 2's `parts` clones the owned maps
    // it needs because it rewrites each drawn allocation's remainder in place.
    fn amount_of(alloc: &Dynamic, unit_index: &str, i: usize) -> Result<ZFuel, Box<EvalAltResult>> {
        let alloc_map = alloc
            .read_lock::<Map>()
            .ok_or_else(|| err(format!("consume_allocations: allocation {i} is not a map")))?;
        let data = alloc_map
            .get("data")
            .and_then(|d| d.read_lock::<Map>())
            .ok_or_else(|| {
                err(format!(
                    "consume_allocations: allocation {i} has no data map"
                ))
            })?;
        let amount = data
            .get("amount")
            .and_then(|a| a.read_lock::<Map>())
            .ok_or_else(|| {
                err(format!(
                    "consume_allocations: allocation {i} has no data.amount map"
                ))
            })?;
        amount_at(&amount, unit_index, i)
    }
    // One allocation's owned (map, data, amount-map, unit amount); absent unit => 0.
    fn parts(
        alloc: &Dynamic,
        unit_index: &str,
        i: usize,
    ) -> Result<(Map, Map, Map, ZFuel), Box<EvalAltResult>> {
        let alloc_map = alloc
            .clone()
            .try_cast::<Map>()
            .ok_or_else(|| err(format!("consume_allocations: allocation {i} is not a map")))?;
        let data = alloc_map
            .get("data")
            .and_then(|d| d.clone().try_cast::<Map>())
            .ok_or_else(|| {
                err(format!(
                    "consume_allocations: allocation {i} has no data map"
                ))
            })?;
        let amount = data
            .get("amount")
            .and_then(|a| a.clone().try_cast::<Map>())
            .ok_or_else(|| {
                err(format!(
                    "consume_allocations: allocation {i} has no data.amount map"
                ))
            })?;
        let amt = amount_at(&amount, unit_index, i)?;
        Ok((alloc_map, data, amount, amt))
    }

    let needed_fuel = ZFuel::from_str(&needed).map_err(|e| {
        err(format!(
            "consume_allocations: needed amount \"{needed}\" is not a valid fuel amount: {e:?}"
        ))
    })?;
    let zero = ZFuel::zero();
    // A negative need would trivially satisfy pass 1 (any total ≥ a negative)
    // and draw nothing — reported as covered, the caller would then emit a
    // NEGATIVE payment. Refuse loudly; the caller's amount computation is
    // broken or hostile.
    if needed_fuel < zero {
        return Err(err(format!(
            "consume_allocations: needed amount \"{needed}\" must not be negative"
        )));
    }

    // Pass 1 — cover check without mutation.
    let mut total = ZFuel::zero();
    for (i, alloc) in allocations.iter().enumerate() {
        let amt = amount_of(alloc, &unit_index, i)?;
        if amt > zero {
            total = (total + amt).map_err(|e| err(format!("consume_allocations: {e:?}")))?;
        }
    }
    let mut result = Map::new();
    if total < needed_fuel {
        result.insert("covered".into(), Dynamic::from(false));
        result.insert("sources".into(), Dynamic::from(Array::new()));
        return Ok(result);
    }

    // Pass 2 — draw in array order until covered.
    let mut remaining = needed_fuel;
    let mut sources = Array::new();
    for (i, slot) in allocations.iter_mut().enumerate() {
        if remaining <= zero {
            break;
        }
        let (mut alloc_map, mut data, mut amount, amt) = parts(slot, &unit_index, i)?;
        if amt <= zero {
            continue;
        }
        let source = data.get("source").cloned().ok_or_else(|| {
            err(format!(
                "consume_allocations: allocation {i} has no data.source"
            ))
        })?;
        let drawn = if amt >= remaining { remaining } else { amt };
        let left = (amt - drawn).map_err(|e| err(format!("consume_allocations: {e:?}")))?;
        remaining = (remaining - drawn).map_err(|e| err(format!("consume_allocations: {e:?}")))?;
        amount.insert(unit_index.clone().into(), left.to_string().into());
        data.insert("amount".into(), Dynamic::from(amount));
        alloc_map.insert("data".into(), Dynamic::from(data));
        *slot = Dynamic::from(alloc_map);
        sources.push(source);
    }
    result.insert("covered".into(), Dynamic::from(true));
    result.insert("sources".into(), Dynamic::from(sources));
    Ok(result)
}

#[cfg(test)]
mod consume_allocations_tests {
    use super::*;

    fn alloc(amount: &str, source: &str) -> Dynamic {
        let mut amt = Map::new();
        amt.insert("0".into(), Dynamic::from(amount.to_string()));
        let mut data = Map::new();
        data.insert("amount".into(), Dynamic::from(amt));
        data.insert("source".into(), Dynamic::from(source.to_string()));
        let mut m = Map::new();
        m.insert("data".into(), Dynamic::from(data));
        Dynamic::from(m)
    }

    fn amount_left(arr: &Array, i: usize) -> String {
        arr[i]
            .clone()
            .try_cast::<Map>()
            .unwrap()
            .get("data")
            .unwrap()
            .clone()
            .try_cast::<Map>()
            .unwrap()
            .get("amount")
            .unwrap()
            .clone()
            .try_cast::<Map>()
            .unwrap()
            .get("0")
            .unwrap()
            .to_string()
    }

    fn sources_of(result: &Map) -> Vec<String> {
        result
            .get("sources")
            .unwrap()
            .clone()
            .try_cast::<Array>()
            .unwrap()
            .into_iter()
            .map(|s| s.to_string())
            .collect()
    }

    fn covered(result: &Map) -> bool {
        result
            .get("covered")
            .unwrap()
            .clone()
            .try_cast::<bool>()
            .unwrap()
    }

    #[test]
    fn splits_across_sources_when_no_single_one_covers() {
        // The B58 case: 5 + 5 parked, a 7 invoice — single-source matching
        // refused this even though the total suffices.
        let mut arr: Array = vec![alloc("5", "s1"), alloc("5", "s2")];
        let result = consume_allocations(&mut arr, "0".into(), "7".into()).unwrap();
        assert!(covered(&result));
        assert_eq!(sources_of(&result), vec!["s1", "s2"]);
        assert_eq!(amount_left(&arr, 0), "0");
        assert_eq!(amount_left(&arr, 1), "3");
    }

    #[test]
    fn insufficient_total_consumes_nothing() {
        let mut arr: Array = vec![alloc("5", "s1"), alloc("5", "s2")];
        let result = consume_allocations(&mut arr, "0".into(), "11".into()).unwrap();
        assert!(!covered(&result));
        assert!(sources_of(&result).is_empty());
        assert_eq!(amount_left(&arr, 0), "5");
        assert_eq!(amount_left(&arr, 1), "5");
    }

    #[test]
    fn exact_total_drains_every_source() {
        let mut arr: Array = vec![alloc("5", "s1"), alloc("5", "s2")];
        let result = consume_allocations(&mut arr, "0".into(), "10".into()).unwrap();
        assert!(covered(&result));
        assert_eq!(sources_of(&result), vec!["s1", "s2"]);
        assert_eq!(amount_left(&arr, 0), "0");
        assert_eq!(amount_left(&arr, 1), "0");
    }

    #[test]
    fn zero_needed_is_covered_drawing_nothing() {
        let mut arr: Array = vec![alloc("5", "s1")];
        let result = consume_allocations(&mut arr, "0".into(), "0".into()).unwrap();
        assert!(covered(&result));
        assert!(sources_of(&result).is_empty());
        assert_eq!(amount_left(&arr, 0), "5");
    }

    #[test]
    fn skips_drained_sources_and_handles_mixed_precision() {
        // "20" (precision 0) minus "19.5" (precision 1) must leave exactly "0.5".
        let mut arr: Array = vec![alloc("0", "s1"), alloc("20", "s2")];
        let result = consume_allocations(&mut arr, "0".into(), "19.5".into()).unwrap();
        assert!(covered(&result));
        assert_eq!(sources_of(&result), vec!["s2"]);
        assert_eq!(amount_left(&arr, 1), "0.5");
    }

    #[test]
    fn garbage_amount_errors_naming_the_allocation() {
        let mut arr: Array = vec![alloc("not-a-number", "s1")];
        let e = consume_allocations(&mut arr, "0".into(), "1".into())
            .unwrap_err()
            .to_string();
        assert!(e.contains("not-a-number"), "must name the value: {e}");
    }

    #[test]
    fn negative_needed_errors_instead_of_trivially_covering() {
        // A negative need satisfies "total >= needed" for ANY pool and draws
        // nothing — reporting it covered would let the caller emit a negative
        // payment with no sources. It must refuse loudly, untouched pool.
        let mut arr: Array = vec![alloc("5", "s1")];
        let e = consume_allocations(&mut arr, "0".into(), "-7".into())
            .unwrap_err()
            .to_string();
        assert!(e.contains("must not be negative"), "got: {e}");
        assert_eq!(amount_left(&arr, 0), "5");
    }
}