Skip to main content

rs_abieos_gf/
lib.rs

1#![allow(non_upper_case_globals)]
2#![allow(non_camel_case_types)]
3#![allow(non_snake_case)]
4
5//! # Rust Abieos
6//!
7//! Abieos is a Rust wrapper for the abieos C library
8
9use std::ffi::{CStr, CString};
10use std::os::raw::c_char;
11
12mod abieos_error;
13
14pub use abieos_error::AbieosError;
15
16pub mod bindings {
17    include!("bindings.rs");
18}
19
20pub use bindings::*;
21
22fn string_from_ptr(ptr: *const c_char) -> String {
23    unsafe {
24        CStr::from_ptr(ptr).to_str().expect("Failed to convert CStr to str").to_string()
25    }
26}
27
28/// Abieos is a Rust wrapper for the abieos C library
29pub struct Abieos {
30    pub context: Option<*mut abieos_context>,
31    pub is_destroyed: bool,
32}
33
34unsafe impl Send for Abieos {}
35
36/// Accepted name formats
37pub enum NameLike {
38    String(String),
39    StringRef(&'static str),
40    U64(u64),
41    I32(i32),
42}
43
44/// Accepted ABI formats
45pub enum AbiLike {
46    Json(String),
47    Hex(String),
48    Bin(Vec<u8>),
49}
50
51/// Abieos Contract reference
52pub struct AbieosContract {
53    pub context: *mut abieos_context,
54    pub name: u64,
55    pub abiLoaded: bool,
56}
57
58impl AbieosContract {
59    //! # Abieos Contract
60    //!
61    //!  AbieosContract is a contract reference that can be used to load ABIs and serialize/deserialize data
62    //!
63
64    /// Load an ABI from a JSON file
65    pub fn load_json_file(&mut self, path: &str) -> Result<&mut Self, AbieosError> {
66        let ref_abieos = Abieos::from_context(self.context);
67        match std::fs::read_to_string(path) {
68            Ok(file) => {
69                match ref_abieos.set_abi_json_native(self.name, file) {
70                    Ok(_) => {
71                        self.abiLoaded = true;
72                        Ok(self)
73                    }
74                    Err(e) => Err(e)
75                }
76            }
77            Err(_) => Err(AbieosError::FileRead),
78        }
79    }
80
81    /// Load an ABI
82    pub fn load_abi(&mut self, abi: AbiLike) -> Result<&mut Self, AbieosError> {
83        let ref_abieos = Abieos::from_context(self.context);
84        let result = match abi {
85            AbiLike::Json(abi_json) => {
86                ref_abieos.set_abi_json_native(self.name, abi_json)
87            }
88            AbiLike::Hex(abi_hex) => {
89                ref_abieos.set_abi_hex_native(self.name, abi_hex)
90            }
91            AbiLike::Bin(abi_bin) => {
92                ref_abieos.set_abi_bin_native(self.name, abi_bin)
93            }
94        };
95        match result {
96            Ok(_) => {
97                self.abiLoaded = true;
98                Ok(self)
99            }
100            Err(e) => Err(e)
101        }
102    }
103
104    /// Get data type for an action
105    pub fn get_type_for_action(&self, action: &str) -> Result<String, AbieosError> {
106        let ref_abieos = Abieos::from_context(self.context);
107        match ref_abieos.string_to_name(action) {
108            Ok(x) => ref_abieos.get_type_for_action_native(self.name, x),
109            Err(_) => Err(AbieosError::StringToName)
110        }
111    }
112
113    /// Get data type for a table
114    pub fn get_type_for_table(&self, table: &str) -> Result<String, AbieosError> {
115        let ref_abieos = Abieos::from_context(self.context);
116        match ref_abieos.string_to_name(table) {
117            Ok(x) => ref_abieos.get_type_for_table_native(self.name, x),
118            Err(_) => Err(AbieosError::StringToName)
119        }
120    }
121
122    /// Serialize JSON into binary (output as HEX)
123    pub fn json_to_hex(&self, datatype: &str, json: String) -> Result<String, AbieosError> {
124        let ref_abieos = Abieos::from_context(self.context);
125        ref_abieos.json_to_hex_native(self.name, datatype, json)
126    }
127
128    /// Deserialize HEX string into JSON
129    pub fn hex_to_json(&self, datatype: &str, hex: String) -> Result<String, AbieosError> {
130        let ref_abieos = Abieos::from_context(self.context);
131        ref_abieos.hex_to_json_native(self.name, datatype, hex)
132    }
133}
134
135impl AbieosContract {
136    pub fn new(context: *mut abieos_context, name: u64) -> AbieosContract {
137        AbieosContract { context, name, abiLoaded: false }
138    }
139}
140
141impl Abieos {
142    /// Reference a contract by name
143    pub fn contract(&self, account_name: NameLike) -> AbieosContract {
144        match account_name {
145            NameLike::StringRef(name) => {
146                let name_u64 = self.string_to_name(name)
147                    .expect("Failed to convert name to u64");
148                AbieosContract::new(self.ctx(), name_u64)
149            }
150            NameLike::String(name) => {
151                let name_u64 = self.string_to_name(name.as_str())
152                    .expect("Failed to convert name to u64");
153                AbieosContract::new(self.ctx(), name_u64)
154            }
155            NameLike::U64(name) => {
156                AbieosContract::new(self.ctx(), name)
157            }
158            NameLike::I32(name) => {
159                AbieosContract::new(self.ctx(), name as u64)
160            }
161        }
162    }
163}
164
165impl Default for Abieos {
166    fn default() -> Self {
167        Abieos::new()
168    }
169}
170unsafe impl Sync for Abieos {}
171impl Abieos {
172    /// Create a new Abieos instance
173    pub fn new() -> Abieos {
174        Abieos {
175            context: Some(abieos::create()),
176            is_destroyed: false,
177        }
178    }
179
180    /// Create a new Abieos instance from a context pointer
181    pub fn from_context(context: *mut abieos_context) -> Abieos {
182        Abieos {
183            context: Some(context),
184            is_destroyed: false,
185        }
186    }
187
188
189    /// Destroy the Abieos instance
190    pub fn destroy(&self) {
191        unsafe {
192            abieos_destroy(self.context.unwrap());
193        }
194    }
195
196    /// Get the last error message
197    fn get_error(&self) -> String {
198        let ctx = self.ctx();
199        unsafe {
200            let error = abieos_get_error(ctx);
201            CStr::from_ptr(error).to_str().unwrap().to_string()
202        }
203    }
204
205    /// Get the context pointer
206    fn ctx(&self) -> *mut abieos_context {
207        self.context.unwrap()
208    }
209
210    /// Convert a string slice into an u64 native name
211    pub fn string_to_name(&self, name: &str) -> Result<u64, AbieosError> {
212        let ctx = self.ctx();
213        if name.len() > 13 {
214            return Err(AbieosError::NameTooLong);
215        }
216        unsafe {
217            let c_buf = CString::new(name.as_bytes()).unwrap();
218            Ok(abieos_string_to_name(ctx, c_buf.as_ptr()))
219        }
220    }
221
222    /// Convert a C-string into an u64 native name
223    pub fn c_string_to_name(&self, name: &CStr) -> u64 {
224        let ctx = self.ctx();
225        if name.to_bytes().len() > 13 {
226            return 0;
227        }
228        unsafe {
229            abieos_string_to_name(ctx, name.as_ptr())
230        }
231    }
232
233    /// Convert an u64 native name into a string slice
234    pub fn name_to_string(&self, name: u64) -> Result<&str, AbieosError> {
235        let ctx = self.ctx();
236        unsafe {
237            let c_buf = abieos_name_to_string(ctx, name);
238            match CStr::from_ptr(c_buf).to_str() {
239                Ok(x) => Ok(x),
240                Err(_) => Err(AbieosError::NameToString),
241            }
242        }
243    }
244
245    /// Convert an u64 native name into a string slice
246    pub fn name_to_cstr(&self, name: u64) -> &CStr {
247        let ctx = self.ctx();
248        unsafe {
249            let c_buf = abieos_name_to_string(ctx, name);
250            CStr::from_ptr(c_buf)
251        }
252    }
253
254    /// Load a contract ABI to memory (JSON format)
255    pub fn set_abi_json(&self, contract: &str, abi_json: String) -> Result<bool, AbieosError> {
256        match self.string_to_name(contract) {
257            Ok(contract_u64) => unsafe {
258                let abi_content_cs = CString::new(abi_json).unwrap();
259                match abieos_set_abi(self.ctx(), contract_u64, abi_content_cs.as_ptr()) {
260                    1 => Ok(true),
261                    _ => Err(AbieosError::SetAbi(self.get_error()))
262                }
263            }
264            Err(_) => Err(AbieosError::StringToName)
265        }
266    }
267
268    /// Load a contract ABI to memory (JSON format as C-String)
269    pub fn set_abi_json_c(&self, contract: &str, abi_json: &CStr) -> Result<bool, AbieosError> {
270        match self.string_to_name(contract) {
271            Ok(contract_u64) => unsafe {
272                match abieos_set_abi(self.ctx(), contract_u64, abi_json.as_ptr()) {
273                    1 => Ok(true),
274                    _ => Err(AbieosError::SetAbi(self.get_error()))
275                }
276            }
277            Err(_) => Err(AbieosError::StringToName)
278        }
279    }
280
281    /// Load a contract ABI to memory (JSON format)
282    pub fn set_abi_json_native(&self, contract_u64: u64, abi_json: String) -> Result<bool, AbieosError> {
283        let abi_content_cs = CString::new(abi_json).unwrap();
284        unsafe {
285            match abieos_set_abi(self.ctx(), contract_u64, abi_content_cs.as_ptr()) {
286                1 => Ok(true),
287                _ => Err(AbieosError::SetAbi(self.get_error()))
288            }
289        }
290    }
291
292    /// Load a contract ABI to memory (HEX format)
293    pub fn set_abi_hex(&self, contract: &str, abi_hex: String) -> Result<bool, AbieosError> {
294        let abi_hex_cs = CString::new(abi_hex).unwrap();
295        match self.string_to_name(contract) {
296            Ok(contract_u64) => unsafe {
297                match abieos_set_abi_hex(self.ctx(), contract_u64, abi_hex_cs.as_ptr()) {
298                    1 => Ok(true),
299                    _ => Err(AbieosError::SetAbi(self.get_error()))
300                }
301            }
302            Err(_) => Err(AbieosError::StringToName)
303        }
304    }
305
306    /// Load a contract ABI to memory (HEX format, u64 contract name)
307    pub fn set_abi_hex_native(&self, contract: u64, abi_hex: String) -> Result<bool, AbieosError> {
308        let abi_hex_cs = CString::new(abi_hex).unwrap();
309        unsafe {
310            match abieos_set_abi_hex(self.ctx(), contract, abi_hex_cs.as_ptr()) {
311                1 => Ok(true),
312                _ => Err(AbieosError::SetAbi(self.get_error()))
313            }
314        }
315    }
316
317    /// Load a contract ABI to memory (binary format)
318    pub fn set_abi_bin(&self, contract: &str, abi_bin: Vec<u8>) -> Result<bool, AbieosError> {
319        match self.string_to_name(contract) {
320            Ok(contract_u64) => unsafe {
321                let abi_bin_data: *const c_char = abi_bin.as_ptr() as *const c_char;
322                let abi_bin_size: usize = abi_bin.len();
323                match abieos_set_abi_bin(self.ctx(), contract_u64, abi_bin_data, abi_bin_size) {
324                    1 => Ok(true),
325                    _ => Err(AbieosError::SetAbi(self.get_error()))
326                }
327            }
328            Err(_) => Err(AbieosError::StringToName)
329        }
330    }
331
332    /// Load a contract ABI to memory (binary format, u64 contract name)
333    pub fn set_abi_bin_native(&self, contract: u64, abi_bin: Vec<u8>) -> Result<bool, AbieosError> {
334        let abi_bin_data: *const c_char = abi_bin.as_ptr() as *const c_char;
335        let abi_bin_size: usize = abi_bin.len();
336        unsafe {
337            match abieos_set_abi_bin(self.ctx(), contract, abi_bin_data, abi_bin_size) {
338                1 => Ok(true),
339                _ => Err(AbieosError::SetAbi(self.get_error()))
340            }
341        }
342    }
343
344    /// Serialize JSON into binary (output as HEX)
345    pub fn json_to_hex(&self, account: &str, datatype: &str, json: String) -> Result<String, AbieosError> {
346        let ctx = self.ctx();
347        let account = self.string_to_name(account)?;
348
349        let datatype = CString::new(datatype).unwrap();
350        let json = CString::new(json).unwrap();
351        unsafe {
352            match abieos_json_to_bin_reorderable(ctx, account, datatype.as_ptr(), json.as_ptr()) {
353                1 => {
354                    let p = abieos_get_bin_hex(ctx);
355                    Ok(string_from_ptr(p))
356                }
357                _ => Err(AbieosError::JsonToHex(self.get_error()))
358            }
359        }
360    }
361
362    /// Serialize JSON into binary (output as HEX)
363    pub fn json_to_hex_c(&self, account: &CStr, datatype: &CStr, json: &CStr) -> &CStr {
364        let ctx = self.ctx();
365        let account = self.c_string_to_name(account);
366        unsafe {
367            match abieos_json_to_bin_reorderable(ctx, account, datatype.as_ptr(), json.as_ptr()) {
368                1 => {
369                    let p = abieos_get_bin_hex(ctx);
370                    CStr::from_ptr(p)
371                }
372                _ => c""
373            }
374        }
375    }
376
377    /// Serialize JSON into binary (output as HEX, u64 account name)
378    pub fn json_to_hex_native(&self, account: u64, datatype: &str, json: String) -> Result<String, AbieosError> {
379        let ctx = self.ctx();
380        let datatype = CString::new(datatype).unwrap();
381        let json = CString::new(json).unwrap();
382        unsafe {
383            match abieos_json_to_bin_reorderable(ctx, account, datatype.as_ptr(), json.as_ptr()) {
384                1 => {
385                    let p = abieos_get_bin_hex(ctx);
386                    Ok(string_from_ptr(p))
387                }
388                _ => Err(AbieosError::JsonToHex(self.get_error()))
389            }
390        }
391    }
392
393    /// Serialize JSON into binary (output as binary)
394    pub fn json_to_bin(&self, account: &str, datatype: &str, json: String) -> Result<Vec<u8>, AbieosError> {
395        let ctx = self.ctx();
396        let account = self.string_to_name(account)?;
397        let datatype = CString::new(datatype).unwrap();
398        let json = CString::new(json).unwrap();
399        unsafe {
400            match abieos_json_to_bin_reorderable(ctx, account, datatype.as_ptr(), json.as_ptr()) {
401                1 => {
402                    let p = abieos_get_bin_data(ctx);
403                    let len = abieos_get_bin_size(ctx);
404                    let mut result: Vec<c_char> = Vec::with_capacity(len as usize);
405                    std::ptr::copy_nonoverlapping(p, result.as_mut_ptr(), len as usize);
406                    result.set_len(len as usize);
407                    Ok(result.iter().map(|&c| c as u8).collect())
408                }
409                _ => Err(AbieosError::JsonToHex(self.get_error()))
410            }
411        }
412    }
413
414    /// Deserialize HEX string into JSON
415    pub fn hex_to_json(&self, account: &str, datatype: &str, hex: String) -> Result<String, AbieosError> {
416        let ctx = self.ctx();
417        let account = self.string_to_name(account).unwrap();
418
419        let datatype = CString::new(datatype).unwrap();
420        let hex = CString::new(hex).unwrap();
421        unsafe {
422            let p = abieos_hex_to_json(ctx, account, datatype.as_ptr(), hex.as_ptr());
423            if p.is_null() {
424                Err(AbieosError::HexToJson(self.get_error()))
425            } else {
426                Ok(string_from_ptr(p))
427            }
428        }
429    }
430
431
432    /// Deserialize HEX string into JSON
433    pub fn hex_to_json_c(&self, account: &CStr, datatype: &CStr, hex: &CStr) -> &CStr {
434        let ctx = self.ctx();
435        let account = self.c_string_to_name(account);
436        unsafe {
437            let p = abieos_hex_to_json(ctx, account, datatype.as_ptr(), hex.as_ptr());
438            CStr::from_ptr(p)
439        }
440    }
441
442    /// Deserialize Binary into JSON
443    pub fn bin_to_json(&self, account: &str, datatype: &str, bin: Vec<u8>) -> Result<String, AbieosError> {
444        let ctx = self.ctx();
445        let account = self.string_to_name(account).unwrap();
446        let datatype = CString::new(datatype).unwrap();
447        let bin_data: *const c_char = bin.as_ptr() as *const c_char;
448        let bin_size: usize = bin.len();
449        unsafe {
450            let p = abieos_bin_to_json(ctx, account, datatype.as_ptr(), bin_data, bin_size);
451            if p.is_null() {
452                Err(AbieosError::BinToJson(self.get_error()))
453            } else {
454                Ok(string_from_ptr(p))
455            }
456        }
457    }
458
459    /// Deserialize HEX string into JSON (u64 account name)
460    pub fn hex_to_json_native(&self, account: u64, datatype: &str, hex: String) -> Result<String, AbieosError> {
461        let ctx = self.ctx();
462        let datatype = CString::new(datatype).unwrap();
463        let hex = CString::new(hex).unwrap();
464        unsafe {
465            let p = abieos_hex_to_json(ctx, account, datatype.as_ptr(), hex.as_ptr());
466            if p.is_null() {
467                Err(AbieosError::HexToJson(self.get_error()))
468            } else {
469                Ok(string_from_ptr(p))
470            }
471        }
472    }
473
474
475    /// Get the type for an action (string names as input)
476    pub fn get_type_for_action(&self, contract: &str, action: &str) -> Result<String, AbieosError> {
477        let ctx = self.ctx();
478        let contract = self.string_to_name(contract).unwrap();
479        let action = self.string_to_name(action).unwrap();
480        unsafe {
481            let p = abieos_get_type_for_action(ctx, contract, action);
482            if p.is_null() {
483                Err(AbieosError::GetTypeForAction(self.get_error()))
484            } else {
485                Ok(string_from_ptr(p))
486            }
487        }
488    }
489
490    /// Get the type for an action (u64 names as input)
491    pub fn get_type_for_action_native(&self, contract: u64, action: u64) -> Result<String, AbieosError> {
492        let ctx = self.ctx();
493        let p = unsafe { abieos_get_type_for_action(ctx, contract, action) };
494        if p.is_null() {
495            Err(AbieosError::GetTypeForAction(self.get_error()))
496        } else {
497            Ok(string_from_ptr(p))
498        }
499    }
500
501    /// Get the type for a table
502    pub fn get_type_for_table(&self, contract: &str, table: &str) -> Result<String, AbieosError> {
503        let ctx = self.ctx();
504        let contract = self.string_to_name(contract).unwrap();
505        let table = self.string_to_name(table).unwrap();
506        unsafe {
507            let p = abieos_get_type_for_table(ctx, contract, table);
508            if p.is_null() {
509                Err(AbieosError::GetTypeForTable(self.get_error()))
510            } else {
511                Ok(string_from_ptr(p))
512            }
513        }
514    }
515
516    /// Get the type for a table (u64 names as input)
517    pub fn get_type_for_table_native(&self, contract: u64, table: u64) -> Result<String, AbieosError> {
518        let ctx = self.ctx();
519        let p = unsafe { abieos_get_type_for_table(ctx, contract, table) };
520        if p.is_null() {
521            Err(AbieosError::GetTypeForAction(self.get_error()))
522        } else {
523            Ok(string_from_ptr(p))
524        }
525    }
526
527    /// Get the type for an action result
528    pub fn get_type_for_action_result(&self, contract: &str, action: &str) -> Result<String, AbieosError> {
529        let ctx = self.ctx();
530        let contract = self.string_to_name(contract).unwrap();
531        let action_res = self.string_to_name(action).unwrap();
532        unsafe {
533            let p = abieos_get_type_for_action_result(ctx, contract, action_res);
534            if p.is_null() {
535                Err(AbieosError::GetTypeForActionResult(self.get_error()))
536            } else {
537                Ok(string_from_ptr(p))
538            }
539        }
540    }
541
542    /// Convert ABI binary to JSON
543    pub fn abi_bin_to_json(&self, abi: Vec<u8>) -> Result<String, AbieosError> {
544        let ctx = self.ctx();
545        let abi_bin_data: *const c_char = abi.as_ptr() as *const c_char;
546        let abi_bin_size: usize = abi.len();
547        unsafe {
548            let p = abieos_abi_bin_to_json(
549                ctx,
550                abi_bin_data,
551                abi_bin_size,
552            );
553            if p.is_null() {
554                Err(AbieosError::AbiBinToJson(self.get_error()))
555            } else {
556                Ok(string_from_ptr(p))
557            }
558        }
559    }
560
561    /// Convert ABI JSON to binary
562    pub fn abi_json_to_bin(&self, json: String) -> Result<Vec<u8>, AbieosError> {
563        let ctx = self.ctx();
564        let abi_json: CString = CString::new(json).unwrap();
565        unsafe {
566            match abieos_abi_json_to_bin(ctx, abi_json.as_ptr()) {
567                1 => {
568                    let p = abieos_get_bin_data(ctx);
569                    let len = abieos_get_bin_size(ctx);
570                    let mut result: Vec<c_char> = Vec::with_capacity(len as usize);
571                    std::ptr::copy_nonoverlapping(p, result.as_mut_ptr(), len as usize);
572                    result.set_len(len as usize);
573                    Ok(result.iter().map(|&c| c as u8).collect())
574                }
575                _ => Err(AbieosError::AbiJsonToBin(self.get_error()))
576            }
577        }
578    }
579}
580
581pub mod abieos {
582    //! # Abieos
583    //!
584    //!  Abieos is a Rust wrapper for the abieos C library
585
586    use crate::{abieos_context, abieos_create};
587
588    pub fn create() -> *mut abieos_context {
589        unsafe {
590            abieos_create()
591        }
592    }
593}