1
//! The worlds a program is observed in: the input batch a script runs against
2
//! and what the stubbed host fns answer. The ledger batch drives
3
//! `entity-count`, entity iteration and the tag natives, and makes the
4
//! shipped transit and tag-sync scripts write tags. The entity and money
5
//! sources answer the same value in every world: a fixed entity of each
6
//! kind whose wasm struct shape another kind shares, and three units of one
7
//! commodity, allocated through the module's own exports.
8

            
9
use std::sync::atomic::{AtomicU64, Ordering};
10
use std::sync::{Arc, Mutex};
11

            
12
use scripting::checked_ref::CheckedAnyRef;
13
use scripting::host::{ExecutionState, define_host_functions};
14
use scripting::runtime::{alloc_ratio_ref, alloc_string_ref, logged_values};
15
use scripting::{
16
    ContextType, EntityHeaderArgs, EntityType, MemorySerializer, SplitArgs, TransactionArgs,
17
};
18
use uuid::Uuid;
19
use wasmtime::{
20
    AnyRef, AsContextMut, Caller, Engine, Extern, Linker, Module, Rooted, StructRef, Val,
21
};
22

            
23
const TIMESTAMP: i64 = 1_700_000_000_000;
24
const COMMODITY: [u8; 16] = [0xC0; 16];
25

            
26
/// A host fn answering a fixed entity, allocated through the module's
27
/// `alloc_<kind>` export from string fields.
28
struct EntitySource {
29
    import: &'static str,
30
    export: &'static str,
31
    fields: &'static [&'static [u8]],
32
}
33

            
34
/// The four kinds whose wasm struct shape another kind shares (ISS-058).
35
const ENTITY_SOURCES: [EntitySource; 4] = [
36
    EntitySource {
37
        import: "account_source",
38
        export: "alloc_account",
39
        fields: &[b"a-1", b"Checking", b"", b"ASSET"],
40
    },
41
    EntitySource {
42
        import: "transaction_source",
43
        export: "alloc_transaction",
44
        fields: &[b"t-1", b"note", b"12.00", b"2024-01-01"],
45
    },
46
    EntitySource {
47
        import: "commodity_entity_source",
48
        export: "alloc_commodity_entity",
49
        fields: &[b"c-1", b"USD", b"US Dollar"],
50
    },
51
    EntitySource {
52
        import: "tag_source",
53
        export: "alloc_tag_entity",
54
        fields: &[b"g-1", b"category", b"groceries", b"food"],
55
    },
56
];
57

            
58
pub(crate) struct World {
59
    pub(crate) name: &'static str,
60
    batch: Batch,
61
    protocol_version: i32,
62
    ratio_source: (i64, i64),
63
}
64

            
65
enum Batch {
66
    Empty,
67
    Ledger,
68
}
69

            
70
pub(crate) const WORLDS: [World; 2] = [
71
    World {
72
        name: "empty batch",
73
        batch: Batch::Empty,
74
        protocol_version: 1,
75
        ratio_source: (3, 4),
76
    },
77
    World {
78
        name: "ledger batch",
79
        batch: Batch::Ledger,
80
        protocol_version: 0,
81
        ratio_source: (-5, 2),
82
    },
83
];
84

            
85
/// One `log` call's message. Production drops a message that is not UTF-8 or
86
/// lies outside memory; the oracle keeps both so the gate still sees them.
87
#[derive(Clone, Debug, PartialEq, Eq)]
88
pub(crate) enum Logged {
89
    Text(String),
90
    InvalidUtf8(Vec<u8>),
91
    Unreadable,
92
}
93

            
94
impl World {
95
    /// The serialized input batch, sized for an output buffer of `output_size`.
96
4308
    pub(super) fn input(&self, output_size: u32) -> Vec<u8> {
97
4308
        let mut batch = MemorySerializer::new();
98
4308
        match self.batch {
99
            Batch::Empty => {
100
2154
                batch.set_context(ContextType::BatchProcess, EntityType::Transaction);
101
            }
102
2154
            Batch::Ledger => ledger(&mut batch),
103
        }
104
4308
        batch.finalize(output_size)
105
4308
    }
106

            
107
    /// The script host, with `log` captured into `output`, deterministic
108
    /// uuids and time, and the differential's host fns answered by this
109
    /// world; any other import traps when called.
110
8599
    pub(super) fn linker(
111
8599
        &self,
112
8599
        engine: &Engine,
113
8599
        module: &Module,
114
8599
        output: &Arc<Mutex<Vec<(u32, Logged)>>>,
115
8599
    ) -> wasmtime::Result<Linker<ExecutionState>> {
116
8599
        let mut linker = Linker::new(engine);
117
8599
        define_host_functions(&mut linker)?;
118
8599
        linker.allow_shadowing(true);
119
8599
        let sink = Arc::clone(output);
120
8599
        linker.func_wrap(
121
8599
            "env",
122
8599
            "log",
123
1148
            move |mut caller: Caller<'_, ExecutionState>, level: u32, ptr: u32, len: u32| {
124
1148
                let logged = logged(&mut caller, ptr, len);
125
1148
                if let Ok(mut lines) = sink.lock() {
126
1148
                    lines.push((level, logged));
127
                }
128
1148
            },
129
        )?;
130
8599
        let sink = Arc::clone(output);
131
8599
        linker.func_wrap(
132
8599
            "env",
133
8599
            "log_value",
134
            move |mut caller: Caller<'_, ExecutionState>,
135
                  args: Option<Rooted<AnyRef>>|
136
252
                  -> wasmtime::Result<i32> {
137
252
                let Some(text) = logged_values(&mut caller, args)? else {
138
8
                    return Ok(1);
139
                };
140
244
                if let Ok(mut lines) = sink.lock() {
141
244
                    lines.push((0, Logged::Text(text)));
142
                }
143
244
                Ok(0)
144
252
            },
145
        )?;
146
8599
        linker.func_wrap("env", "get_timestamp", || TIMESTAMP)?;
147
8599
        let issued = Arc::new(AtomicU64::new(0));
148
8599
        linker.func_wrap(
149
8599
            "env",
150
8599
            "generate_uuid",
151
2
            move |mut caller: Caller<'_, ExecutionState>, ptr: u32| {
152
2
                let uuid = u128::from(issued.fetch_add(1, Ordering::Relaxed) + 1);
153
2
                write_memory(&mut caller, ptr, &uuid.to_be_bytes());
154
2
            },
155
        )?;
156
8599
        let version = self.protocol_version;
157
8599
        linker.func_wrap("nomi", "rpc_protocol_version", move || version)?;
158
8599
        let (numer, denom) = self.ratio_source;
159
8599
        linker.func_wrap(
160
8599
            "nomi",
161
8599
            "ratio_source",
162
109
            move |mut caller: Caller<'_, ExecutionState>| -> wasmtime::Result<Option<Rooted<StructRef>>> {
163
109
                alloc_ratio_ref(&mut caller, numer, denom).map(Some)
164
109
            },
165
        )?;
166
8599
        for source in &ENTITY_SOURCES {
167
34396
            linker.func_wrap(
168
34396
                "nomi",
169
34396
                source.import,
170
60
                move |mut caller: Caller<'_, ExecutionState>| -> wasmtime::Result<Option<Rooted<StructRef>>> {
171
60
                    entity_source(&mut caller, source).map(Some)
172
60
                },
173
            )?;
174
        }
175
8599
        linker.func_wrap(
176
8599
            "nomi",
177
8599
            "money_source",
178
88
            |mut caller: Caller<'_, ExecutionState>| -> wasmtime::Result<Option<Rooted<StructRef>>> {
179
88
                money_source(&mut caller).map(Some)
180
88
            },
181
        )?;
182
8599
        linker.define_unknown_imports_as_traps(module)?;
183
8599
        Ok(linker)
184
8599
    }
185
}
186

            
187
60
fn entity_source(
188
60
    caller: &mut Caller<'_, ExecutionState>,
189
60
    source: &EntitySource,
190
60
) -> wasmtime::Result<Rooted<StructRef>> {
191
60
    let args = source
192
60
        .fields
193
60
        .iter()
194
228
        .map(|field| {
195
228
            alloc_string_ref(caller, field).map(|array| Val::AnyRef(Some(array.to_anyref())))
196
228
        })
197
        .collect::<wasmtime::Result<Vec<_>>>()?;
198
60
    call_export(caller, source.export, &args)
199
60
}
200

            
201
/// Three units of the ledger's commodity, atomic (the module's
202
/// `commodity_new` leaves the unit term null).
203
88
fn money_source(caller: &mut Caller<'_, ExecutionState>) -> wasmtime::Result<Rooted<StructRef>> {
204
88
    let (hi, lo) = Uuid::from_bytes(COMMODITY).as_u64_pair();
205
88
    call_export(
206
88
        caller,
207
88
        "commodity_new",
208
88
        &[
209
88
            Val::I64(3),
210
88
            Val::I64(1),
211
88
            Val::I64(hi as i64),
212
88
            Val::I64(lo as i64),
213
88
        ],
214
88
    )
215
88
}
216

            
217
/// Re-enters the module's exported allocator `name` for the struct it
218
/// returns, so the host never has to spell a guest struct type itself.
219
148
fn call_export(
220
148
    caller: &mut Caller<'_, ExecutionState>,
221
148
    name: &str,
222
148
    args: &[Val],
223
148
) -> wasmtime::Result<Rooted<StructRef>> {
224
148
    let func = caller
225
148
        .get_export(name)
226
148
        .and_then(Extern::into_func)
227
        .ok_or_else(|| wasmtime::Error::msg(format!("the module does not export `{name}`")))?;
228
148
    let mut results = [Val::AnyRef(None)];
229
148
    func.call(caller.as_context_mut(), args, &mut results)?;
230
148
    match results {
231
148
        [Val::AnyRef(Some(any))] => any.checked_struct(caller.as_context_mut()),
232
        _ => Err(wasmtime::Error::msg(format!("`{name}` returned no struct"))),
233
    }
234
148
}
235

            
236
/// An entity-create batch whose primary transaction moves money Suica →
237
/// Metro with no `category` tag and one tagged split, beside a second,
238
/// tagged transaction.
239
2154
fn ledger(batch: &mut MemorySerializer) {
240
2154
    batch.set_context(ContextType::EntityCreate, EntityType::Transaction);
241
2154
    let commute = transaction(batch, 1, true, 0);
242
2154
    batch.set_primary(commute);
243
2154
    let suica = split(batch, 2, commute, "Suica", -5000);
244
2154
    split(batch, 3, commute, "Metro", 5000);
245
2154
    batch.add_tag([4; 16], parent(suica), false, false, "project", "commute");
246
2154
    let groceries = transaction(batch, 5, false, 2);
247
2154
    split(batch, 6, groceries, "Cash", -1234);
248
2154
    split(batch, 7, groceries, "Groceries", 1234);
249
2154
    batch.add_tag([8; 16], parent(groceries), false, false, "payee", "Grocer");
250
2154
    batch.add_tag([9; 16], parent(groceries), false, false, "note", "weekly");
251
2154
}
252

            
253
4308
fn transaction(batch: &mut MemorySerializer, id: u8, is_primary: bool, tag_count: u32) -> u32 {
254
4308
    batch.add_transaction(
255
4308
        EntityHeaderArgs {
256
4308
            is_primary,
257
4308
            ..header(id, -1)
258
4308
        },
259
4308
        TransactionArgs {
260
4308
            post_date: TIMESTAMP,
261
4308
            enter_date: TIMESTAMP,
262
4308
            split_count: 2,
263
4308
            tag_count,
264
4308
            is_multi_currency: false,
265
4308
        },
266
4308
    )
267
4308
}
268

            
269
8616
fn split(batch: &mut MemorySerializer, id: u8, tx: u32, account: &str, value: i64) -> u32 {
270
8616
    batch.add_split(
271
8616
        header(id, parent(tx)),
272
8616
        SplitArgs {
273
8616
            account_id: [id.wrapping_add(0x80); 16],
274
8616
            commodity_id: COMMODITY,
275
8616
            value_num: value,
276
8616
            value_denom: 100,
277
8616
            reconcile_state: 0,
278
8616
            reconcile_date: 0,
279
8616
            account_name: account,
280
8616
        },
281
8616
    )
282
8616
}
283

            
284
12924
fn header(id: u8, parent_idx: i32) -> EntityHeaderArgs {
285
12924
    EntityHeaderArgs {
286
12924
        id: [id; 16],
287
12924
        parent_idx,
288
12924
        is_primary: false,
289
12924
        is_context: false,
290
12924
    }
291
12924
}
292

            
293
15078
fn parent(idx: u32) -> i32 {
294
15078
    i32::try_from(idx).unwrap_or(i32::MAX)
295
15078
}
296

            
297
1148
fn logged(caller: &mut Caller<'_, ExecutionState>, ptr: u32, len: u32) -> Logged {
298
1148
    let Some(Extern::Memory(memory)) = caller.get_export("memory") else {
299
        return Logged::Unreadable;
300
    };
301
1148
    let range = usize::try_from(ptr)
302
1148
        .ok()
303
1148
        .zip(usize::try_from(len).ok())
304
1148
        .and_then(|(start, len)| Some(start..start.checked_add(len)?));
305
1148
    match range.and_then(|range| memory.data(&caller).get(range)) {
306
1
        None => Logged::Unreadable,
307
1147
        Some(bytes) => std::str::from_utf8(bytes).map_or_else(
308
1
            |_| Logged::InvalidUtf8(bytes.to_vec()),
309
1146
            |text| Logged::Text(text.to_string()),
310
        ),
311
    }
312
1148
}
313

            
314
2
fn write_memory(caller: &mut Caller<'_, ExecutionState>, ptr: u32, bytes: &[u8]) {
315
2
    let Some(Extern::Memory(memory)) = caller.get_export("memory") else {
316
        return;
317
    };
318
2
    let target = usize::try_from(ptr)
319
2
        .ok()
320
2
        .and_then(|start| Some(start..start.checked_add(bytes.len())?))
321
2
        .and_then(|range| memory.data_mut(&mut *caller).get_mut(range));
322
2
    if let Some(target) = target {
323
2
        target.copy_from_slice(bytes);
324
    }
325
2
}