psibase 0.23.0

Library and command-line tool for interacting with psibase networks
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
//! Wrapped native functions for services to use
//!
//! Native functions give services the ability to print debugging messages,
//! abort transactions on errors, access databases and event logs, and
//! synchronously call other services. There aren't many native functions
//! since services implement most psibase functionality.
//!
//! These functions wrap the [Raw Native Functions](crate::native_raw).

use crate::{
    native_raw, AccountNumber, DbId, HttpRequest, MicroSeconds, SocketEndpoint, TLSInfo, ToKey,
};
use anyhow::anyhow;
use fracpack::{Pack, Unpack, UnpackOwned};

/// Write message to console
///
/// Message should be UTF8.
pub fn write_console_bytes(message: &[u8]) {
    unsafe {
        if let Some(first) = message.first() {
            native_raw::writeConsole(first, message.len() as u32);
        }
    }
}

/// Write message to console
pub fn write_console(message: &str) {
    write_console_bytes(message.as_bytes());
}

/// Abort with message
///
/// Message should be UTF8.
pub fn abort_message_bytes(message: &[u8]) -> ! {
    unsafe {
        if let Some(first) = message.first() {
            native_raw::abortMessage(first, message.len() as u32)
        } else {
            native_raw::abortMessage(std::ptr::null(), 0)
        }
    }
}

/// Abort with message
pub fn abort_message(message: &str) -> ! {
    abort_message_bytes(message.as_bytes());
}

/// Abort with message if condition is false
pub fn check(condition: bool, message: &str) {
    if !condition {
        abort_message_bytes(message.as_bytes());
    }
}

/// Abort with message if optional value is empty
pub fn check_some<T>(opt_value: Option<T>, message: &str) -> T {
    if opt_value.is_none() {
        abort_message_bytes(message.as_bytes());
    }
    opt_value.unwrap()
}

/// Abort with message if optional has value
pub fn check_none<T>(opt_value: Option<T>, message: &str) {
    if opt_value.is_some() {
        abort_message_bytes(message.as_bytes());
    }
}

/// Get the most-recent result when the size is known in advance
///
/// Other functions set the result.
pub fn get_result_bytes(size: u32) -> Vec<u8> {
    let mut result = Vec::with_capacity(size as usize);
    if size > 0 {
        unsafe {
            let actual_size = native_raw::getResult(result.as_mut_ptr(), size, 0);
            result.set_len(std::cmp::min(size, actual_size) as usize);
        }
    }
    result
}

/// Get the most-recent key
///
/// Other functions set the key.
pub fn get_key_bytes() -> Vec<u8> {
    unsafe {
        let size = native_raw::getKey(std::ptr::null_mut(), 0);
        let mut result = Vec::with_capacity(size as usize);
        if size > 0 {
            native_raw::getKey(result.as_mut_ptr(), size);
            result.set_len(size as usize);
        }
        result
    }
}

/// Get the currently-executing action.
///
/// If the contract, while handling action A, calls itself with action B:
///    * Before the call to B, [get_current_action] returns A.
///    * After the call to B, [get_current_action] returns B.
///    * After B returns, [get_current_action] returns A.
///
/// Note: The above only applies if the contract uses [crate::native_raw::call].
pub fn get_current_action_bytes() -> Vec<u8> {
    let size;
    unsafe {
        size = native_raw::getCurrentAction();
    };
    get_result_bytes(size)
}

/// Get the currently-executing action.
///
/// This version creates an extra copy of [crate::Action::rawData];
/// consider using [with_current_action] instead.
///
/// If the contract, while handling action A, calls itself with action B:
///    * Before the call to B, [get_current_action] returns A.
///    * After the call to B, [get_current_action] returns B.
///    * After B returns, [get_current_action] returns A.
///
/// Note: The above only applies if the contract uses [crate::native_raw::call].
pub fn get_current_action() -> crate::Action {
    let bytes = get_current_action_bytes();
    <crate::Action>::unpacked(&bytes[..]).unwrap() // unwrap won't panic
}

/// Get the currently-executing action and pass it to `f`.
///
/// This is more efficient than [get_current_action] since it avoids
/// creating an extra copy of [crate::Action::rawData].
///
/// If the contract, while handling action A, calls itself with action B:
///    * Before the call to B, [get_current_action] returns A.
///    * After the call to B, [get_current_action] returns B.
///    * After B returns, [get_current_action] returns A.
///
/// Note: The above only applies if the contract uses [crate::native_raw::call].
pub fn with_current_action<R, F: Fn(crate::SharedAction) -> R>(f: F) -> R {
    let bytes = get_current_action_bytes();
    let act = <crate::SharedAction>::unpacked(&bytes[..]).unwrap(); // unwrap won't panic
    f(act)
}

/// Set the currently-executing action's return value
pub fn set_retval<T: Pack>(val: &T) {
    let bytes = val.packed();
    unsafe { native_raw::setRetval(bytes.as_ptr(), bytes.len() as u32) };
}

pub fn get_optional_result_bytes(size: u32) -> Option<Vec<u8>> {
    if size < u32::MAX {
        Some(get_result_bytes(size))
    } else {
        None
    }
}

#[derive(Debug)]
pub struct KvHandle(native_raw::KvHandle);

pub use native_raw::KvMode;

impl KvHandle {
    pub fn new(db: DbId, prefix: &[u8], mode: KvMode) -> KvHandle {
        match db {
            DbId::Service | DbId::WriteOnly | DbId::BlockLog | DbId::Native => Self::import(
                crate::services::db::Wrapper::call().open(db, prefix.to_vec().into(), mode as u8),
            ),
            DbId::Subjective | DbId::Session | DbId::Temporary => Self::import(
                crate::services::x_db::Wrapper::call().open(db, prefix.to_vec().into(), mode as u8),
            ),
            _ => KvHandle(unsafe {
                native_raw::kvOpen(db, prefix.as_ptr(), prefix.len() as u32, mode)
            }),
        }
    }
    pub fn subtree(&self, prefix: &[u8], mode: KvMode) -> KvHandle {
        KvHandle(unsafe {
            native_raw::kvOpenAt(self.0, prefix.as_ptr(), prefix.len() as u32, mode)
        })
    }
    pub fn import(index: u32) -> KvHandle {
        let handles =
            Vec::<u32>::unpacked(&get_result_bytes(unsafe { native_raw::importHandles() }))
                .unwrap();
        KvHandle(native_raw::KvHandle(handles[index as usize]))
    }
}

impl Drop for KvHandle {
    fn drop(&mut self) {
        unsafe { native_raw::kvClose(self.0) }
    }
}

/// Set a key-value pair
///
/// If key already exists, then replace the existing value.
pub fn kv_put_bytes(db: &KvHandle, key: &[u8], value: &[u8]) {
    unsafe {
        native_raw::kvPut(
            db.0,
            key.as_ptr(),
            key.len() as u32,
            value.as_ptr(),
            value.len() as u32,
        )
    }
}

/// Set a key-value pair
///
/// If key already exists, then replace the existing value.
pub fn kv_put<K: ToKey, V: Pack>(db: &KvHandle, key: &K, value: &V) {
    kv_put_bytes(db, &key.to_key(), &value.packed())
}

/// Add a sequentially-numbered record
///
/// Returns the id.
pub fn put_sequential_bytes(db: DbId, value: &[u8]) -> u64 {
    unsafe { native_raw::putSequential(db, value.as_ptr(), value.len() as u32) }
}

/// Add a sequentially-numbered record
///
/// Returns the id.
pub fn put_sequential<Type: Pack, V: Pack>(
    db: DbId,
    service: AccountNumber,
    ty: &Type,
    value: &V,
) -> u64 {
    put_sequential_bytes(db, &(service, Some(ty), Some(value)).packed())
}

/// Remove a key-value pair if it exists
pub fn kv_remove_bytes(db: &KvHandle, key: &[u8]) {
    unsafe { native_raw::kvRemove(db.0, key.as_ptr(), key.len() as u32) }
}

/// Remove a key-value pair if it exists
pub fn kv_remove<K: ToKey>(db: &KvHandle, key: &K) {
    kv_remove_bytes(db, &key.to_key())
}

/// Get a key-value pair, if any
pub fn kv_get_bytes(db: &KvHandle, key: &[u8]) -> Option<Vec<u8>> {
    let size = unsafe { native_raw::kvGet(db.0, key.as_ptr(), key.len() as u32) };
    get_optional_result_bytes(size)
}

/// Get a key-value pair, if any
pub fn kv_get<V: UnpackOwned, K: ToKey>(
    db: &KvHandle,
    key: &K,
) -> Result<Option<V>, fracpack::Error> {
    if let Some(v) = kv_get_bytes(db, &key.to_key()) {
        Ok(Some(V::unpacked(&v)?))
    } else {
        Ok(None)
    }
}

/// Get the first key-value pair which is greater than or equal to the provided
/// key
///
/// If one is found, and the first `match_key_size` bytes of the found key
/// matches the provided key, then returns the value. Use [get_key_bytes] to get
/// the found key.
pub fn kv_greater_equal_bytes(db: &KvHandle, key: &[u8], match_key_size: u32) -> Option<Vec<u8>> {
    let size =
        unsafe { native_raw::kvGreaterEqual(db.0, key.as_ptr(), key.len() as u32, match_key_size) };
    get_optional_result_bytes(size)
}

/// Get the first key-value pair which is greater than or equal to the provided
/// key
///
/// If one is found, and the first `match_key_size` bytes of the found key
/// matches the provided key, then returns the value. Use [get_key_bytes] to get
/// the found key.
pub fn kv_greater_equal<K: ToKey, V: UnpackOwned>(
    db: &KvHandle,
    key: &K,
    match_key_size: u32,
) -> Option<V> {
    let bytes = kv_greater_equal_bytes(db, &key.to_key(), match_key_size);
    bytes.map(|v| V::unpacked(&v[..]).unwrap())
}

/// Get the key-value pair immediately-before provided key
///
/// If one is found, and the first `match_key_size` bytes of the found key
/// matches the provided key, then returns the value. Use [get_key_bytes] to get
/// the found key.
pub fn kv_less_than_bytes(db: &KvHandle, key: &[u8], match_key_size: u32) -> Option<Vec<u8>> {
    let size =
        unsafe { native_raw::kvLessThan(db.0, key.as_ptr(), key.len() as u32, match_key_size) };
    get_optional_result_bytes(size)
}

/// Get the key-value pair immediately-before provided key
///
/// If one is found, and the first `match_key_size` bytes of the found key
/// matches the provided key, then returns the value. Use [get_key_bytes] to get
/// the found key.
pub fn kv_less_than<K: ToKey, V: UnpackOwned>(
    db: &KvHandle,
    key: &K,
    match_key_size: u32,
) -> Option<V> {
    let bytes = kv_less_than_bytes(db, &key.to_key(), match_key_size);
    bytes.map(|v| V::unpacked(&v[..]).unwrap())
}

/// Get the maximum key-value pair which has key as a prefix
///
/// If one is found, then returns the value. Use [get_key_bytes] to get the found key.
pub fn kv_max_bytes(db: &KvHandle, key: &[u8]) -> Option<Vec<u8>> {
    let size = unsafe { native_raw::kvMax(db.0, key.as_ptr(), key.len() as u32) };
    get_optional_result_bytes(size)
}

/// Get the maximum key-value pair which has key as a prefix
///
/// If one is found, then returns the value. Use [get_key_bytes] to get the found key.
pub fn kv_max<K: ToKey, V: UnpackOwned>(db: &KvHandle, key: &K) -> Option<V> {
    let bytes = kv_max_bytes(db, &key.to_key());
    bytes.map(|v| V::unpacked(&v[..]).unwrap())
}

pub fn get_sequential_bytes(db_id: DbId, id: u64) -> Option<Vec<u8>> {
    let size = unsafe { native_raw::getSequential(db_id, id) };
    get_optional_result_bytes(size)
}

/// Sets the CPU timer to expire after the current transaction/query/callback
/// context has run for a given time. When the timer
/// expires, the current context will be terminated. Setting the timeout
/// replaces any previous timeout.
pub fn set_max_cpu_time<T: Into<MicroSeconds>>(time: T) {
    let time: MicroSeconds = time.into();
    let time = (time.value * 1000) as u64;
    unsafe { native_raw::setMaxCpuTime(time) }
}

pub use scopeguard;

pub fn checkout_subjective() {
    unsafe { native_raw::checkoutSubjective() }
}

pub fn commit_subjective() -> bool {
    unsafe { native_raw::commitSubjective() }
}

pub fn abort_subjective() {
    unsafe { native_raw::abortSubjective() }
}

/// The `subjective_tx` macro creates a scope in which
/// the subjective database is accessible. It is necessary to use
/// this scope for any reads or writes to the subjective database.
///
/// The statement will be executed one or more times until
/// it is successfully committed.
///
/// Unstructured control flow that exits the statement, (e.g. break,
/// return, panic), will discard any changes made to the
/// subjective database.
#[macro_export]
macro_rules! subjective_tx {
    {$($stmt:tt)*} => {
        $crate::native::checkout_subjective();
        #[allow(unreachable_code)]
        let r = loop {
            let mut guard = $crate::native::scopeguard::guard((), |_|{
                $crate::native::abort_subjective();
            });
            let result = { $($stmt)* };
            $crate::native::scopeguard::ScopeGuard::into_inner(guard);
            if $crate::native::commit_subjective() {
                break result;
            }
        };
        r
    }
}

/// Starts a new HTTP request and returns the socket
pub fn socket_open(
    req: HttpRequest,
    tls: Option<TLSInfo>,
    endpoint: Option<SocketEndpoint>,
) -> Result<i32, anyhow::Error> {
    let packed = (req, tls, endpoint).packed();
    let sock = unsafe { native_raw::socketOpen(packed.as_ptr(), packed.len()) };
    if sock >= 0 {
        Ok(sock)
    } else {
        Err(anyhow!("socket_open: {}", -sock))
    }
}

/// Send a message to a socket
pub fn socket_send(fd: i32, data: &[u8]) -> Result<(), anyhow::Error> {
    let err = unsafe { native_raw::socketSend(fd, data.as_ptr(), data.len()) };
    if err == 0 {
        Ok(())
    } else {
        Err(anyhow!("socket_send: {}", err))
    }
}

/// Change flags on a socket. The mask determines which flags are set.
///
/// If this function is called within a subjectiveCheckout, it will only take
/// effect if the top-level commit succeeds. If another context changes the
/// flags, subjectiveCommit may fail.
pub fn socket_set_flags(fd: i32, mask: u32, value: u32) -> Result<(), anyhow::Error> {
    let err = unsafe { native_raw::socketSetFlags(fd, mask, value) };
    if err == 0 {
        Ok(())
    } else {
        Err(anyhow!("socket_set_flags: {}", err))
    }
}