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
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! Wrapped native functions for tests to use
//!
//! Native functions give tests the ability to execute shell commands,
//! read files, create block chains, push transactions to those chains,
//! and control block production on those chains.
//!
//! These functions and types wrap the [Raw Native Functions](crate::tester_raw).

#![cfg_attr(not(target_family = "wasm"), allow(unused_imports, dead_code))]

use crate::{
    actions::login_action, check, create_boot_transactions, get_optional_result_bytes,
    get_result_bytes, services, status_key, tester_raw, AccountNumber, Action, BlockTime, Caller,
    Checksum256, CodeByHashRow, CodeRow, DbId, DirectoryRegistry, Error, HostConfigRow, HttpBody,
    HttpHeader, HttpReply, HttpRequest, InnerTraceEnum, PackageRegistry, RunMode, Seconds,
    SignedTransaction, StatusRow, Tapos, TimePointSec, TimePointUSec, ToKey, Transaction,
    TransactionTrace,
};
#[cfg(target_family = "wasm")]
use crate::{MicroSeconds, PackageList, PackageOp};
use anyhow::anyhow;
use chrono::Utc;
use fracpack::{Pack, Unpack, UnpackOwned};
use futures::executor::block_on;
use psibase_macros::account_raw;
use serde::{de::DeserializeOwned, Deserialize};
use sha2::{Digest, Sha256};
use std::cell::{Cell, RefCell};
use std::path::{Path, PathBuf};
use std::{marker::PhantomData, ptr::null_mut};

/// Execute a shell command
///
/// Returns the process exit code
pub fn execute(command: &str) -> i32 {
    unsafe { tester_raw::testerExecute(command.as_ptr(), command.len()) }
}

/// Block chain under test
#[derive(Debug)]
pub struct Chain {
    chain_handle: u32,
    status: RefCell<Option<StatusRow>>,
    producing: Cell<bool>,
    is_auto_block_start: bool,
}

pub const PRODUCER_ACCOUNT: AccountNumber = AccountNumber::new(account_raw!("prod"));

impl Default for Chain {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for Chain {
    fn drop(&mut self) {
        unsafe { tester_raw::destroyChain(self.chain_handle) }
        tester_raw::tester_clear_chain_for_db(self.chain_handle)
    }
}

// Following are stub functions for the linter (running in a non-wasm environment)
// can see that these functions exist; otherwise, tests show linter errors for valid calls.
#[cfg(not(target_family = "wasm"))]
impl Chain {
    pub fn new() -> Chain {
        unimplemented!();
    }
    pub fn push(&self, _transaction: &SignedTransaction) -> TransactionTrace {
        unimplemented!();
    }
    pub fn start_block(&self) {
        unimplemented!();
    }
}

#[cfg(target_family = "wasm")]
impl Chain {
    /// Create a new chain and make it active for database native functions.
    ///
    /// Shortcut for `Tester::create(1 << 27, 1 << 27, 1 << 27, 1 << 27)`
    pub fn new() -> Chain {
        Self::create(1 << 27, 1 << 27, 1 << 27, 1 << 27)
    }

    /// Boot the tester chain with default services being deployed
    pub fn boot(&self) -> Result<(), Error> {
        let default_services: Vec<String> = vec!["TestDefault".to_string()];
        self.boot_with(&Self::default_registry(), &default_services[..])
    }

    pub fn default_registry() -> DirectoryRegistry {
        let psibase_data_dir = std::env::var("PSIBASE_DATADIR")
            .expect("Cannot find package directory: PSIBASE_DATADIR not defined");
        let packages_dir = Path::new(&psibase_data_dir).join("packages");
        DirectoryRegistry::new(packages_dir)
    }

    pub fn boot_with<R: PackageRegistry>(&self, reg: &R, services: &[String]) -> Result<(), Error> {
        let mut services = block_on(reg.resolve(services))?;

        const COMPRESSION_LEVEL: u32 = 4;
        let (boot_tx, subsequent_tx) = create_boot_transactions(
            &None,
            &None,
            PRODUCER_ACCOUNT,
            false,
            TimePointSec { seconds: 10 },
            &mut services[..],
            COMPRESSION_LEVEL,
        )
        .unwrap();

        for trx in boot_tx {
            self.push(&trx).ok()?;
        }

        self.start_block();

        for (_, group, _) in subsequent_tx {
            for trx in group {
                self.push(&trx).ok()?;
            }
        }

        self.start_block();

        Ok(())
    }

    /// Create a new chain and make it active for database native functions.
    ///
    /// The arguments are the file sizes in bytes for the database's
    /// various files.
    pub fn create(hot_bytes: u64, warm_bytes: u64, cool_bytes: u64, cold_bytes: u64) -> Chain {
        println!("TESTER CREATE");
        let chain_handle =
            unsafe { tester_raw::createChain(hot_bytes, warm_bytes, cool_bytes, cold_bytes) };
        if chain_handle == 0 {
            tester_raw::tester_select_chain_for_db(chain_handle)
        }
        let mut result = Chain {
            chain_handle,
            status: None.into(),
            producing: false.into(),
            is_auto_block_start: true,
        };
        result.load_local_services();
        result.start_session();
        result
    }

    fn load_local_services(&mut self) {
        use crate::{CODE_TABLE, NATIVE_TABLE_PRIMARY_INDEX};
        let prefix = (CODE_TABLE, NATIVE_TABLE_PRIMARY_INDEX).to_key();
        if unsafe {
            tester_raw::kvGreaterEqual(
                self.chain_handle,
                DbId::NativeSubjective,
                prefix.as_ptr(),
                prefix.len() as u32,
                prefix.len() as u32,
            )
        } != u32::MAX
        {
            return;
        }

        let packages_root: PathBuf = std::env::var_os("PSIBASE_DATADIR")
            .expect("Cannot find local service directory")
            .into();
        let packages_dir = packages_root.join("packages");
        let registry = DirectoryRegistry::new(packages_dir);
        let package_names = vec!["XDefault".to_string()];
        let packages =
            block_on(PackageList::new().resolve_changes(&registry, &package_names, false, true))
                .unwrap();
        let mut requests = Vec::new();
        unsafe {
            tester_raw::checkoutSubjective(self.chain_handle);
        }
        for op in packages {
            let PackageOp::Install(info) = op else {
                panic!("Only install is expected when there are no existing packages")
            };
            let mut package = block_on(registry.get_by_info(&info)).unwrap();
            for (account, info, code) in package.services() {
                let hash: [u8; 32] = Sha256::digest(&code).into();
                let code_hash: Checksum256 = hash.into();

                let code_row = CodeRow {
                    codeNum: *account,
                    flags: info.parse_flags(),
                    codeHash: code_hash.clone(),
                    vmType: 0,
                    vmVersion: 0,
                };
                let key = code_row.key();
                self.kv_put(DbId::NativeSubjective, &key, &code_row);
                let code_by_hash_row = CodeByHashRow {
                    codeHash: code_hash,
                    vmType: 0,
                    vmVersion: 0,
                    code: code.into(),
                };
                let key = code_by_hash_row.key();
                self.kv_put(DbId::NativeSubjective, &key, &code_by_hash_row);
            }

            let root_host = "\0";

            for (account, path, file) in package.data() {
                let Some(mime_type) = mime_guess::from_path(&path).first() else {
                    panic!("Cannot determine Mime-Type for {}", path)
                };
                requests.push(HttpRequest {
                    host: account.to_string() + "." + root_host,
                    method: "PUT".to_string(),
                    target: path,
                    contentType: mime_type.to_string(),
                    headers: Vec::new(),
                    body: file.into(),
                });
            }
            requests.push(HttpRequest {
                host: services::x_packages::SERVICE.to_string() + "." + root_host,
                method: "PUT".to_string(),
                target: format!("/manifest/{}", info.sha256),
                contentType: "application/json".to_string(),
                headers: vec![],
                body: serde_json::to_string(&package.manifest())
                    .unwrap()
                    .into_bytes()
                    .into(),
            });
            requests.push(HttpRequest {
                host: services::x_packages::SERVICE.to_string() + "." + root_host,
                method: "POST".to_string(),
                target: "/postinstall".to_string(),
                contentType: "application/json".to_string(),
                headers: vec![],
                body: serde_json::to_string(&info).unwrap().into_bytes().into(),
            });
        }
        check(
            unsafe { tester_raw::commitSubjective(self.chain_handle) },
            "Failed to commit changes",
        );
        for request in requests {
            let reply = self.http(&request).unwrap();
            if reply.status != 200 {
                panic!("PUT failed: {}", reply.text().unwrap());
            }
        }
    }

    fn start_session(&mut self) {
        let row = HostConfigRow {
            hostVersion: format!("psitest-{}", env!("CARGO_PKG_VERSION")),
            config: r#"{"host":{"hosts":["psibase.io"]}}"#.to_string(),
        };

        unsafe {
            tester_raw::checkoutSubjective(self.chain_handle);
        }
        self.kv_put(DbId::NativeSession, &row.key(), &row);
        check(
            unsafe { tester_raw::commitSubjective(self.chain_handle) },
            "Failed to commit changes",
        );
        let trace = self.run_action(
            RunMode::RPC,
            true,
            services::x_http::Wrapper::pack_from(AccountNumber::default()).startSession(),
        );
        ChainEmptyResult { trace }.get().unwrap()
    }

    /// Advance the blockchain time by the specified number of microseconds and start a new block.
    ///
    /// This method increments the current block time by `seconds` and starts a new block at that time.
    /// If no current block exists, it starts from a default time (e.g., 0 microseconds).
    pub fn start_block_after(&self, micro_seconds: MicroSeconds) {
        // Scope the immutable borrow to ensure it’s dropped before calling start_block_at
        let current_time = {
            let status = self.status.borrow();
            status
                .as_ref()
                .map(|s| s.current.time)
                .unwrap_or(TimePointUSec { microseconds: 0 })
        };
        self.start_block_at(current_time + micro_seconds);
    }

    /// Start a new block
    ///
    /// Starts a new block at `time`. If `time.seconds` is 0,
    /// then starts a new block 1 second after the most recent.
    pub fn start_block_at(&self, time: BlockTime) {
        let status = &mut *self.status.borrow_mut();

        let (producer, term, mut commit_num) = if let Some(status) = status {
            let producers = if let Some(next) = &status.consensus.next {
                if status.current.commitNum < next.blockNum {
                    status.consensus.current.data.producers()
                } else {
                    next.consensus.data.producers()
                }
            } else {
                status.consensus.current.data.producers()
            };
            (
                if producers.is_empty() {
                    AccountNumber::from("firstproducer")
                } else {
                    producers[0].name
                },
                status.current.term,
                status.head.as_ref().map_or(0, |head| head.header.blockNum),
            )
        } else {
            (AccountNumber::from("firstproducer"), 0, 0)
        };

        // Guarantee that there is a recent block for fillTapos to use.
        if let Some(status) = status {
            if status.current.time + Seconds::new(1) < time {
                unsafe {
                    tester_raw::startBlock(
                        self.chain_handle,
                        (time - Seconds::new(1)).microseconds,
                        producer.value,
                        term,
                        commit_num,
                    )
                }
                commit_num += 1;
            }
        }
        unsafe {
            tester_raw::startBlock(
                self.chain_handle,
                time.microseconds,
                producer.value,
                term,
                commit_num,
            )
        }
        *status = self
            .kv_get::<StatusRow, _>(StatusRow::DB, &status_key())
            .unwrap();
        self.producing.replace(true);
    }

    /// Start a new block
    ///
    /// Starts a new block 1 second after the most recent.
    pub fn start_block(&self) {
        self.start_block_after(Seconds::new(1).into())
    }

    /// Finish a block
    ///
    /// This does nothing if a block isn't currently being produced.
    pub fn finish_block(&self) {
        unsafe { tester_raw::finishBlock(self.chain_handle) }
        self.producing.replace(false);
    }

    /// By default, the TestChain will automatically advance blocks.
    /// When disabled, the the chain will only advance blocks manually.
    /// To manually advance a block, call start_block.
    pub fn set_auto_block_start(&mut self, enable: bool) {
        self.is_auto_block_start = enable;
    }

    /// Push a transaction
    ///
    /// The returned trace includes detailed information about the execution,
    /// including whether it succeeded, and the cause if it failed.
    pub fn push(&self, transaction: &SignedTransaction) -> TransactionTrace {
        if !self.producing.get() {
            self.start_block();
        }

        let transaction = transaction.packed();
        let size = unsafe {
            tester_raw::pushTransaction(self.chain_handle, transaction.as_ptr(), transaction.len())
        };
        TransactionTrace::unpacked(&get_result_bytes(size)).unwrap()
    }

    pub fn run_action(&mut self, mode: RunMode, head: bool, action: Action) -> TransactionTrace {
        let packed = action.packed();
        let size = unsafe {
            tester_raw::runAction(self.chain_handle, mode, head, packed.as_ptr(), packed.len())
        };
        TransactionTrace::unpacked(&get_result_bytes(size)).unwrap()
    }

    /// Copy database to `path`
    ///
    /// Runs the following shell command: `mkdir -p {path} && cp -a {src}/* {path}`,
    /// where `{path}` is the passed-in argument and `{src}` is the chain's database.
    ///
    /// Returns shell exit status; 0 if successful
    pub fn copy_database(&self, path: &str) -> i32 {
        let src = unsafe { self.get_path() };
        execute(&format! {"mkdir -p {path} && cp -a {src}/* {path}", src = src, path = path})
    }

    /// Get filesystem path of chain's database
    ///
    /// See [`copy_database`](Self::copy_database) for the most-common use case
    ///
    /// # Safety
    ///
    /// It is safe to copy the files to another location on the filesystem. However,
    /// modifying the original files or launching `psinode` on the original files
    /// will corrupt the database and likely crash the `psitest` process running this
    /// wasm.
    pub unsafe fn get_path(&self) -> String {
        let size = tester_raw::getChainPath(self.chain_handle, null_mut(), 0);
        let mut bytes = Vec::with_capacity(size);
        tester_raw::getChainPath(self.chain_handle, bytes.as_mut_ptr(), size);
        bytes.set_len(size);
        String::from_utf8_unchecked(bytes)
    }

    /// Select chain for database native functions
    ///
    /// After you call `select_chain`, the following functions will use
    /// this chain's database:
    ///
    /// * [`native_raw::kvGet`](crate::native_raw::kvGet)
    /// * [`native_raw::getSequential`](crate::native_raw::getSequential)
    /// * [`native_raw::kvGreaterEqual`](crate::native_raw::kvGreaterEqual)
    /// * [`native_raw::kvLessThan`](crate::native_raw::kvLessThan)
    /// * [`native_raw::kvMax`](crate::native_raw::kvMax)
    pub fn select_chain(&self) {
        tester_raw::tester_select_chain_for_db(self.chain_handle)
    }

    pub fn kv_get_bytes(&self, db: DbId, key: &[u8]) -> Option<Vec<u8>> {
        let size =
            unsafe { tester_raw::kvGet(self.chain_handle, db, key.as_ptr(), key.len() as u32) };
        get_optional_result_bytes(size)
    }

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

    /// Set a key-value pair
    ///
    /// If key already exists, then replace the existing value.
    pub fn kv_put_bytes(&mut self, db: DbId, key: &[u8], value: &[u8]) {
        unsafe {
            tester_raw::kvPut(
                self.chain_handle,
                db,
                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>(&mut self, db: DbId, key: &K, value: &V) {
        self.kv_put_bytes(db, &key.to_key(), &value.packed())
    }

    /// Create a new account
    ///
    /// Create a new account which authenticates using `auth-any`.
    /// Doesn't fail if the account already exists.
    pub fn new_account(&self, account: AccountNumber) -> Result<(), anyhow::Error> {
        services::accounts::Wrapper::push(self)
            .newAccount(account, AccountNumber::new(account_raw!("auth-any")), false)
            .get()
    }

    /// Deploy a service
    ///
    /// Set code on an account. Also creates the account if needed.
    pub fn deploy_service(&self, account: AccountNumber, code: &[u8]) -> Result<(), anyhow::Error> {
        self.new_account(account)?;
        // TODO: update setcode::setCode to not need a vec. Needs changes to the service macro.
        services::setcode::Wrapper::push_from(self, account)
            .setCode(account, 0, 0, code.to_vec().into())
            .get()
    }

    pub fn http(&self, request: &HttpRequest) -> Result<HttpReply, anyhow::Error> {
        let packed_request = request.packed();
        let fd = unsafe {
            tester_raw::httpRequest(
                self.chain_handle,
                packed_request.as_ptr(),
                packed_request.len(),
            )
        };
        let mut size: u32 = 0;
        let err = unsafe { tester_raw::socketRecv(fd, &mut size) };
        if err != 0 {
            Err(anyhow!("Could not read response: {}", err))?;
        }

        Ok(HttpReply::unpacked(&get_result_bytes(size))?)
    }

    pub fn get(&self, account: AccountNumber, target: &str) -> Result<HttpReply, anyhow::Error> {
        self.get_auth(account, target, "")
    }

    pub fn post(
        &self,
        account: AccountNumber,
        target: &str,
        data: HttpBody,
    ) -> Result<HttpReply, anyhow::Error> {
        self.post_auth(account, target, data, "")
    }

    pub fn graphql<T: DeserializeOwned>(
        &self,
        account: AccountNumber,
        query: &str,
    ) -> Result<T, anyhow::Error> {
        self.graphql_auth(account, query, "")
    }

    pub fn get_auth(
        &self,
        account: AccountNumber,
        target: &str,
        token: &str,
    ) -> Result<HttpReply, anyhow::Error> {
        let mut headers = Vec::new();
        if !token.is_empty() {
            headers.push(HttpHeader::new(
                "Authorization",
                &format!("Bearer {}", token),
            ));
        }
        self.http(&HttpRequest {
            host: format!("{}.psibase.io", account),
            method: "GET".into(),
            target: target.into(),
            contentType: "".into(),
            body: <Vec<u8>>::new().into(),
            headers,
        })
    }

    pub fn post_auth(
        &self,
        account: AccountNumber,
        target: &str,
        data: HttpBody,
        token: &str,
    ) -> Result<HttpReply, anyhow::Error> {
        let mut headers = Vec::new();
        if !token.is_empty() {
            headers.push(HttpHeader::new(
                "Authorization",
                &format!("Bearer {}", token),
            ));
        }
        self.http(&HttpRequest {
            host: format!("{}.psibase.io", account),
            method: "POST".into(),
            target: target.into(),
            contentType: data.contentType,
            body: data.body,
            headers,
        })
    }

    pub fn graphql_auth<T: DeserializeOwned>(
        &self,
        account: AccountNumber,
        query: &str,
        token: &str,
    ) -> Result<T, anyhow::Error> {
        self.post_auth(account, "/graphql", HttpBody::graphql(query), token)?
            .json()
    }

    pub fn login(
        &self,
        user: AccountNumber,
        service: AccountNumber,
    ) -> Result<String, anyhow::Error> {
        let expiration = TimePointSec::from(Utc::now()) + Seconds::new(10);

        let tapos = Tapos {
            expiration,
            refBlockSuffix: 0,
            flags: Tapos::DO_NOT_BROADCAST_FLAG,
            refBlockIndex: 0,
        };

        let trx = Transaction {
            tapos,
            actions: vec![login_action(user, service, "psibase.io")],
            claims: vec![],
        };

        let strx = SignedTransaction {
            transaction: trx.packed().into(),
            proofs: vec![],
        };

        let reply = self.post(
            services::transact::SERVICE,
            "/login",
            HttpBody {
                contentType: "application/octet-stream".into(),
                body: strx.packed().into(),
            },
        )?;

        #[derive(Deserialize)]
        struct LoginReply {
            access_token: String,
        }

        let login_reply: LoginReply = reply.json()?;
        Ok(login_reply.access_token)
    }
}

impl Chain {
    /// Fill tapos fields
    ///
    /// `expire_seconds` is relative to the most-recent block.
    pub fn fill_tapos(&self, trx: &mut Transaction, expire_seconds: u32) {
        trx.tapos.expiration.seconds = expire_seconds as i64;
        trx.tapos.refBlockIndex = 0;
        trx.tapos.refBlockSuffix = 0;
        if let Some(status) = &*self.status.borrow() {
            trx.tapos.expiration =
                status.current.time.seconds() + Seconds::new(expire_seconds as i64);
            if let Some(head) = &status.head {
                let mut suffix = [0; 4];
                suffix.copy_from_slice(&head.blockId[head.blockId.len() - 4..]);
                trx.tapos.refBlockIndex = (head.header.blockNum & 0x7f) as u8;
                trx.tapos.refBlockSuffix = u32::from_le_bytes(suffix);
            }
        }
    }
}

pub struct ChainEmptyResult {
    pub trace: TransactionTrace,
}

impl ChainEmptyResult {
    pub fn get(&self) -> Result<(), anyhow::Error> {
        if let Some(e) = &self.trace.error {
            Err(anyhow!("{}", e))
        } else {
            Ok(())
        }
    }

    pub fn match_error(self, msg: &str) -> Result<TransactionTrace, anyhow::Error> {
        self.trace.match_error(msg)
    }
}

pub struct ChainResult<T: fracpack::UnpackOwned> {
    pub trace: TransactionTrace,
    _marker: PhantomData<T>,
}

impl<T: fracpack::UnpackOwned> ChainResult<T> {
    pub fn get(&self) -> Result<T, anyhow::Error> {
        self.get_with_debug(false)
    }

    fn is_user_action(act: &Action) -> bool {
        use crate::{
            self as psibase, method,
            services::{cpu_limit, db, events, transact, virtual_server},
        };
        !(act.service == db::SERVICE && act.method == method!("open")
            || act.service == cpu_limit::SERVICE
            || act.sender == transact::SERVICE && act.service == virtual_server::SERVICE
            || act.service == events::SERVICE && act.method == method!("sync"))
    }

    pub fn get_with_debug(&self, debug: bool) -> Result<T, anyhow::Error> {
        if let Some(e) = &self.trace.error {
            return Err(anyhow!("{}", e));
        }
        if let Some(transact) = self.trace.action_traces.last() {
            let ret = transact
                .inner_traces
                .iter()
                // TODO: improve this filter.. we need to return whatever is the name of the action somehow if possible...
                .filter_map(|inner| {
                    if let InnerTraceEnum::ActionTrace(at) = &inner.inner {
                        if !Self::is_user_action(&at.action) {
                            return None;
                        }
                        if debug {
                            println!(
                                ">>> ChainResult::get - Inner action trace: {} (raw_retval={})",
                                at.action.method, at.raw_retval
                            );
                        }
                        if at.raw_retval.is_empty() {
                            return None;
                        } else {
                            Some(&at.raw_retval)
                        }
                    } else {
                        None
                    }
                })
                .next();
            if let Some(ret) = ret {
                if debug {
                    println!(">>> ChainResult::get - Unpacking ret: `{}`", ret);
                }
                let unpacked_ret = T::unpacked(ret)?;
                return Ok(unpacked_ret);
            }
        }
        Err(anyhow!("Can't find action in trace"))
    }

    pub fn match_error(self, msg: &str) -> Result<TransactionTrace, anyhow::Error> {
        self.trace.match_error(msg)
    }
}

#[derive(Clone, Debug)]
pub struct ChainPusher<'a> {
    pub chain: &'a Chain,
    pub sender: AccountNumber,
    pub service: AccountNumber,
}

impl<'a> Caller for ChainPusher<'a> {
    type ReturnsNothing = ChainEmptyResult;
    type ReturnType<T: fracpack::UnpackOwned> = ChainResult<T>;

    fn call_returns_nothing<Args: fracpack::Pack>(
        &self,
        method: crate::MethodNumber,
        args: Args,
    ) -> Self::ReturnsNothing {
        let mut trx = Transaction {
            tapos: Default::default(),
            actions: vec![Action {
                sender: self.sender,
                service: self.service,
                method,
                rawData: args.packed().into(),
            }],
            claims: vec![],
        };
        self.chain.fill_tapos(&mut trx, 2);
        let trace = self.chain.push(&SignedTransaction {
            transaction: trx.packed().into(),
            proofs: Default::default(),
        });

        if self.chain.is_auto_block_start {
            self.chain.start_block();
        }

        ChainEmptyResult { trace }
    }

    fn call<Ret: fracpack::UnpackOwned, Args: fracpack::Pack>(
        &self,
        method: crate::MethodNumber,
        args: Args,
    ) -> Self::ReturnType<Ret> {
        let mut trx = Transaction {
            tapos: Default::default(),
            actions: vec![Action {
                sender: self.sender,
                service: self.service,
                method,
                rawData: args.packed().into(),
            }],
            claims: vec![],
        };
        self.chain.fill_tapos(&mut trx, 2);
        let trace = self.chain.push(&SignedTransaction {
            transaction: trx.packed().into(),
            proofs: Default::default(),
        });
        let ret = ChainResult::<Ret> {
            trace,
            _marker: Default::default(),
        };

        if self.chain.is_auto_block_start {
            self.chain.start_block();
        }

        ret
    }
}