neo-syscalls 0.14.0

Neo N3 Syscall Definitions
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
// Copyright (c) 2025-2026 R3E Network
// Licensed under the MIT License

//! Storage state management for Neo N3 syscall simulation.

#[cfg(not(target_arch = "wasm32"))]
use once_cell::sync::Lazy;

#[cfg(not(target_arch = "wasm32"))]
use neo_types::{NeoError, NeoResult, NeoStorageContext};
#[cfg(not(target_arch = "wasm32"))]
use std::collections::{HashMap, HashSet};
#[cfg(not(target_arch = "wasm32"))]
use std::sync::atomic::{AtomicU32, Ordering};
#[cfg(not(target_arch = "wasm32"))]
use std::sync::{Arc, RwLock};

#[cfg(not(target_arch = "wasm32"))]
pub(crate) const DEFAULT_CONTRACT_HASH: [u8; 20] = [0u8; 20];
#[cfg(not(target_arch = "wasm32"))]
pub(crate) const MAX_SCRIPT_HASH_STACK_DEPTH: usize = 1024;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) const DEFAULT_CALL_FLAGS: i32 = 0x0F;

#[cfg(not(target_arch = "wasm32"))]
pub(crate) type ContractStore = Arc<RwLock<HashMap<Vec<u8>, Vec<u8>>>>;

#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Copy)]
pub(crate) struct ActiveScriptHashes {
    pub(crate) calling: [u8; 20],
    pub(crate) entry: [u8; 20],
    pub(crate) executing: [u8; 20],
    pub(crate) call_flags: i32,
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for ActiveScriptHashes {
    fn default() -> Self {
        Self {
            calling: DEFAULT_CONTRACT_HASH,
            entry: DEFAULT_CONTRACT_HASH,
            executing: DEFAULT_CONTRACT_HASH,
            call_flags: DEFAULT_CALL_FLAGS,
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) static ACTIVE_SCRIPT_HASHES: Lazy<RwLock<ActiveScriptHashes>> =
    Lazy::new(|| RwLock::new(ActiveScriptHashes::default()));
#[cfg(not(target_arch = "wasm32"))]
pub(crate) static ACTIVE_SCRIPT_HASH_STACK: Lazy<RwLock<Vec<ActiveScriptHashes>>> =
    Lazy::new(|| RwLock::new(Vec::new()));
#[cfg(not(target_arch = "wasm32"))]
pub(crate) static ACTIVE_WITNESSES: Lazy<RwLock<HashSet<Vec<u8>>>> =
    Lazy::new(|| RwLock::new(HashSet::new()));
#[cfg(not(target_arch = "wasm32"))]
pub(crate) static ACTIVE_CRYPTO_RESULTS: Lazy<RwLock<CryptoVerificationResults>> =
    Lazy::new(|| RwLock::new(CryptoVerificationResults::default()));

// B5-B9: host-mode state for runtime syscalls.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) static ACTIVE_TIME: Lazy<RwLock<i64>> = Lazy::new(|| RwLock::new(0));
#[cfg(not(target_arch = "wasm32"))]
pub(crate) static ACTIVE_RANDOM: Lazy<RwLock<i64>> = Lazy::new(|| RwLock::new(0));
#[cfg(not(target_arch = "wasm32"))]
pub(crate) static ACTIVE_GAS_LEFT: Lazy<RwLock<i64>> = Lazy::new(|| RwLock::new(0));
#[cfg(not(target_arch = "wasm32"))]
pub(crate) static ACTIVE_INVOCATION_COUNTER: Lazy<RwLock<i32>> = Lazy::new(|| RwLock::new(0));

#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Copy, Default)]
pub(crate) struct CryptoVerificationResults {
    pub(crate) check_sig: bool,
    pub(crate) check_multisig: bool,
    pub(crate) verify_with_ecdsa: bool,
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone)]
pub(crate) struct ContextHandle {
    pub(crate) read_only: bool,
    pub(crate) contract: [u8; 20],
    pub(crate) store: ContractStore,
}

#[cfg(not(target_arch = "wasm32"))]
#[allow(clippy::type_complexity)]
pub(crate) struct StorageState {
    next_context: AtomicU32,
    contexts: RwLock<HashMap<u32, ContextHandle>>,
    contract_stores: RwLock<HashMap<[u8; 20], ContractStore>>,
}

#[cfg(not(target_arch = "wasm32"))]
impl StorageState {
    pub(crate) fn new() -> Self {
        Self {
            next_context: AtomicU32::new(1),
            contexts: RwLock::new(HashMap::new()),
            contract_stores: RwLock::new(HashMap::new()),
        }
    }

    pub(crate) fn create_context(
        &self,
        contract: [u8; 20],
        read_only: bool,
    ) -> NeoResult<NeoStorageContext> {
        let store = self.get_or_create_store(contract);
        let id = self.next_context.fetch_add(1, Ordering::SeqCst);
        let handle = ContextHandle {
            read_only,
            contract,
            store,
        };
        self.contexts
            .write()
            .map_err(|_| NeoError::InvalidState)?
            .insert(id, handle);
        Ok(if read_only {
            NeoStorageContext::read_only(id)
        } else {
            NeoStorageContext::new(id)
        })
    }

    pub(crate) fn clone_as_read_only(
        &self,
        context: &NeoStorageContext,
    ) -> NeoResult<NeoStorageContext> {
        let handle = self
            .contexts
            .read()
            .map_err(|_| NeoError::InvalidState)?
            .get(&context.id())
            .cloned()
            .ok_or(NeoError::InvalidState)?;
        let id = self.next_context.fetch_add(1, Ordering::SeqCst);
        let ro_handle = ContextHandle {
            read_only: true,
            contract: handle.contract,
            store: handle.store,
        };
        self.contexts
            .write()
            .map_err(|_| NeoError::InvalidState)?
            .insert(id, ro_handle);
        Ok(NeoStorageContext::read_only(id))
    }

    pub(crate) fn get_handle(&self, context: &NeoStorageContext) -> NeoResult<ContextHandle> {
        self.contexts
            .read()
            .map_err(|_| NeoError::InvalidState)?
            .get(&context.id())
            .cloned()
            .ok_or(NeoError::InvalidState)
    }

    pub(crate) fn reset(&self) -> NeoResult<()> {
        self.contexts
            .write()
            .map_err(|_| NeoError::InvalidState)?
            .clear();
        self.contract_stores
            .write()
            .map_err(|_| NeoError::InvalidState)?
            .clear();
        self.next_context.store(1, Ordering::SeqCst);
        Ok(())
    }

    /// Put a single key/value pair into the default (current contract) store.
    /// This is the host-mode equivalent of a `System.Storage.Put` issued by a
    /// contract — used by the neo-test harness to seed state that contract
    /// code then reads via `NeoStorage` / `RawStorage` (D6: harness was
    /// disconnected from this global).
    ///
    /// NOTE (D6 partial): writes under the executing contract hash at the
    /// time of the write (default: all-zeros sentinel). Reads via
    /// `NeoVMSyscall::storage_get` resolve the same hash at read time, so
    /// round-trips work when no explicit contract hash has been set. The full
    /// fix (exposing context creation + explicit hash routing for neo-test)
    /// is deferred to the macro/import redesign.
    pub(crate) fn put(&self, key: Vec<u8>, value: Vec<u8>) {
        if let Ok(mut map) = self
            .get_or_create_store(crate::storage::current_executing_script_hash())
            .write()
        {
            map.insert(key, value);
        }
    }

    fn get_or_create_store(&self, contract: [u8; 20]) -> ContractStore {
        let mut stores = match self.contract_stores.write() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        stores
            .entry(contract)
            .or_insert_with(|| Arc::new(RwLock::new(HashMap::new())))
            .clone()
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) static STORAGE_STATE: Lazy<StorageState> = Lazy::new(StorageState::new);

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn current_calling_script_hash() -> [u8; 20] {
    match ACTIVE_SCRIPT_HASHES.read() {
        Ok(active) => active.calling,
        Err(poisoned) => poisoned.into_inner().calling,
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn current_entry_script_hash() -> [u8; 20] {
    match ACTIVE_SCRIPT_HASHES.read() {
        Ok(active) => active.entry,
        Err(poisoned) => poisoned.into_inner().entry,
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn current_executing_script_hash() -> [u8; 20] {
    match ACTIVE_SCRIPT_HASHES.read() {
        Ok(active) => active.executing,
        Err(poisoned) => poisoned.into_inner().executing,
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn set_current_contract_hash(hash: [u8; 20]) {
    set_current_script_hashes(hash, hash, hash);
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn set_current_script_hashes(calling: [u8; 20], entry: [u8; 20], executing: [u8; 20]) {
    match ACTIVE_SCRIPT_HASHES.write() {
        Ok(mut active) => {
            active.calling = calling;
            active.entry = entry;
            active.executing = executing;
        }
        Err(poisoned) => {
            let mut active = poisoned.into_inner();
            active.calling = calling;
            active.entry = entry;
            active.executing = executing;
        }
    }
    clear_script_hash_stack();
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn set_current_calling_script_hash(hash: [u8; 20]) {
    match ACTIVE_SCRIPT_HASHES.write() {
        Ok(mut active) => active.calling = hash,
        Err(poisoned) => poisoned.into_inner().calling = hash,
    }
    clear_script_hash_stack();
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn set_current_entry_script_hash(hash: [u8; 20]) {
    match ACTIVE_SCRIPT_HASHES.write() {
        Ok(mut active) => active.entry = hash,
        Err(poisoned) => poisoned.into_inner().entry = hash,
    }
    clear_script_hash_stack();
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn set_current_executing_script_hash(hash: [u8; 20]) {
    match ACTIVE_SCRIPT_HASHES.write() {
        Ok(mut active) => active.executing = hash,
        Err(poisoned) => poisoned.into_inner().executing = hash,
    }
    clear_script_hash_stack();
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn current_call_flags() -> i32 {
    match ACTIVE_SCRIPT_HASHES.read() {
        Ok(active) => active.call_flags,
        Err(poisoned) => poisoned.into_inner().call_flags,
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn set_current_call_flags(flags: i32) {
    match ACTIVE_SCRIPT_HASHES.write() {
        Ok(mut active) => active.call_flags = flags,
        Err(poisoned) => poisoned.into_inner().call_flags = flags,
    }
    clear_script_hash_stack();
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn push_current_executing_script_hash(hash: [u8; 20], call_flags: i32) -> NeoResult<()> {
    let mut active = match ACTIVE_SCRIPT_HASHES.write() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    };
    let mut stack = match ACTIVE_SCRIPT_HASH_STACK.write() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    };

    if stack.len() >= MAX_SCRIPT_HASH_STACK_DEPTH {
        return Err(NeoError::InvalidOperation);
    }

    stack.push(*active);
    active.calling = active.executing;
    active.executing = hash;
    active.call_flags = call_flags;
    Ok(())
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn pop_current_script_hash_frame() -> NeoResult<()> {
    let mut active = match ACTIVE_SCRIPT_HASHES.write() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    };
    let mut stack = match ACTIVE_SCRIPT_HASH_STACK.write() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    };

    if let Some(previous) = stack.pop() {
        *active = previous;
        Ok(())
    } else {
        Err(NeoError::InvalidState)
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn clear_script_hash_stack() {
    match ACTIVE_SCRIPT_HASH_STACK.write() {
        Ok(mut stack) => stack.clear(),
        Err(poisoned) => poisoned.into_inner().clear(),
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn reset_current_contract_hash() {
    set_current_script_hashes(
        DEFAULT_CONTRACT_HASH,
        DEFAULT_CONTRACT_HASH,
        DEFAULT_CONTRACT_HASH,
    );
    set_current_call_flags(DEFAULT_CALL_FLAGS);
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn set_active_witnesses<I>(witnesses: I)
where
    I: IntoIterator<Item = Vec<u8>>,
{
    let updated: HashSet<Vec<u8>> = witnesses.into_iter().collect();
    match ACTIVE_WITNESSES.write() {
        Ok(mut active) => *active = updated,
        Err(poisoned) => *poisoned.into_inner() = updated,
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn has_active_witness(account: &[u8]) -> bool {
    match ACTIVE_WITNESSES.read() {
        Ok(active) => active.contains(account),
        Err(poisoned) => poisoned.into_inner().contains(account),
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn clear_active_witnesses() {
    match ACTIVE_WITNESSES.write() {
        Ok(mut active) => active.clear(),
        Err(poisoned) => poisoned.into_inner().clear(),
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn set_crypto_verification_results(results: CryptoVerificationResults) {
    match ACTIVE_CRYPTO_RESULTS.write() {
        Ok(mut active) => *active = results,
        Err(poisoned) => *poisoned.into_inner() = results,
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn active_crypto_verification_results() -> CryptoVerificationResults {
    match ACTIVE_CRYPTO_RESULTS.read() {
        Ok(active) => *active,
        Err(poisoned) => *poisoned.into_inner(),
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn reset_crypto_verification_results() {
    set_crypto_verification_results(CryptoVerificationResults::default());
}

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

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn create_context_recovers_when_store_lock_is_poisoned() {
        let state = StorageState::new();
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = state.contract_stores.write().unwrap();
            panic!("poison contract stores lock");
        }));

        let result = state.create_context(DEFAULT_CONTRACT_HASH, false);
        assert!(result.is_ok());
    }
}