psibase 0.1.6

Library and command-line tool for interacting with psibase blockchains
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
use crate::services::{
    account_sys, admin_sys, auth_ec_sys, common_sys, nft_sys, producer_sys, proxy_sys,
    psispace_sys, setcode_sys, transaction_sys,
};
use crate::{
    method_raw, AccountNumber, Action, Claim, MethodNumber, ProducerConfigRow, PublicKey,
    SharedGenesisActionData, SharedGenesisService, SignedTransaction, Tapos, TimePointSec,
    Transaction,
};
use fracpack::Pack;
use include_dir::{include_dir, Dir};
use psibase_macros::account_raw;

macro_rules! account {
    ($name:expr) => {
        AccountNumber::new(account_raw!($name))
    };
}

macro_rules! method {
    ($name:expr) => {
        MethodNumber::new(method_raw!($name))
    };
}

const ACCOUNTS: [AccountNumber; 23] = [
    account_sys::SERVICE,
    admin_sys::SERVICE,
    account!("alice"),
    auth_ec_sys::SERVICE,
    account!("auth-any-sys"),
    account!("bob"),
    common_sys::SERVICE,
    account!("doc-sys"),
    account!("explore-sys"),
    nft_sys::SERVICE,
    producer_sys::SERVICE,
    proxy_sys::SERVICE,
    psispace_sys::SERVICE,
    account!("r-account-sys"),
    account!("r-ath-ec-sys"),
    account!("r-prod-sys"),
    account!("r-proxy-sys"),
    account!("r-tok-sys"),
    setcode_sys::SERVICE,
    account!("symbol-sys"),
    account!("token-sys"),
    transaction_sys::SERVICE,
    account!("verifyec-sys"),
];

macro_rules! sgc {
    ($acc:literal, $flags:expr, $wasm:literal) => {
        SharedGenesisService {
            service: account!($acc),
            flags: $flags,
            vmType: 0,
            vmVersion: 0,
            code: include_bytes!(concat!("../boot-image/", $wasm)).into(),
        }
    };
}

macro_rules! store {
    ($acc:literal, $dest:expr, $ty:expr, $src:expr) => {
        store_sys(
            account!($acc),
            account!($acc),
            $dest,
            $ty,
            include_bytes!(concat!("../boot-image/", $src)),
        )
    };
}

macro_rules! store_common {
    ($name:literal, $ty:expr) => {
        store!(
            "common-sys",
            concat!("/common/", $name),
            $ty,
            concat!("CommonSys/common/", $name)
        )
    };
}

macro_rules! store_third_party {
    ($name:literal, $ty:expr) => {
        store!(
            "common-sys",
            concat!("/common/", $name),
            $ty,
            concat!("CommonSys/common/thirdParty/", $name)
        )
    };
}

fn set_producers_action(name: AccountNumber, key: Claim) -> Action {
    producer_sys::Wrapper::pack().setProducers(vec![ProducerConfigRow {
        producerName: name,
        producerAuth: key,
    }])
}

fn to_claim(key: &PublicKey) -> Claim {
    Claim {
        service: account!("verifyec-sys"),
        rawData: key.packed().into(),
    }
}

fn new_account_action(sender: AccountNumber, account: AccountNumber) -> Action {
    account_sys::Wrapper::pack_from(sender).newAccount(account, account!("auth-any-sys"), false)
}

fn set_key_action(account: AccountNumber, key: &PublicKey) -> Action {
    auth_ec_sys::Wrapper::pack_from(account).setKey(key.clone())
}

fn set_auth_service_action(account: AccountNumber, auth_service: AccountNumber) -> Action {
    account_sys::Wrapper::pack_from(account).setAuthCntr(auth_service)
}

fn reg_server(service: AccountNumber, server_service: AccountNumber) -> Action {
    proxy_sys::Wrapper::pack_from(service).registerServer(server_service)
}

fn store_sys(
    service: AccountNumber,
    sender: AccountNumber,
    path: &str,
    content_type: &str,
    content: &[u8],
) -> Action {
    psispace_sys::Wrapper::pack_from_to(sender, service).storeSys(
        path.to_string(),
        content_type.to_string(),
        content.to_vec().into(),
    )
}

fn without_tapos(actions: Vec<Action>, expiration: TimePointSec) -> Transaction {
    Transaction {
        tapos: Tapos {
            expiration,
            refBlockSuffix: 0,
            flags: 0,
            refBlockIndex: 0,
        },
        actions,
        claims: vec![],
    }
}

fn genesis_transaction(expiration: TimePointSec) -> SignedTransaction {
    let services = vec![
        sgc!("account-sys", 0, "AccountSys.wasm"),
        sgc!("admin-sys", 0, "AdminSys.wasm"),
        sgc!("auth-ec-sys", 0, "AuthEcSys.wasm"),
        sgc!("auth-any-sys", 0, "AuthAnySys.wasm"),
        sgc!("common-sys", 0, "CommonSys.wasm"),
        sgc!("explore-sys", 0, "ExploreSys.wasm"),
        sgc!("nft-sys", 0, "NftSys.wasm"),
        sgc!("producer-sys", 2, "ProducerSys.wasm"),
        sgc!("proxy-sys", 0, "ProxySys.wasm"),
        sgc!("psispace-sys", 0, "PsiSpaceSys.wasm"),
        sgc!("r-account-sys", 0, "RAccountSys.wasm"),
        sgc!("r-ath-ec-sys", 0, "RAuthEcSys.wasm"),
        sgc!("r-prod-sys", 0, "RProducerSys.wasm"),
        sgc!("r-proxy-sys", 0, "RProxySys.wasm"),
        sgc!("r-tok-sys", 0, "RTokenSys.wasm"),
        sgc!("setcode-sys", 2, "SetCodeSys.wasm"), // TODO: flags
        sgc!("symbol-sys", 0, "SymbolSys.wasm"),
        sgc!("token-sys", 0, "TokenSys.wasm"),
        sgc!("transact-sys", 3, "TransactionSys.wasm"), // TODO: flags
        sgc!("verifyec-sys", 0, "VerifyEcSys.wasm"),
    ];

    let genesis_action_data = SharedGenesisActionData {
        memo: "".to_string(),
        services,
    };

    let actions = vec![Action {
        sender: AccountNumber { value: 0 },
        service: AccountNumber { value: 0 },
        method: method!("boot"),
        rawData: genesis_action_data.packed().into(),
    }];

    SignedTransaction {
        transaction: without_tapos(actions, expiration).packed().into(),
        proofs: vec![],
    }
}

fn fill_dir(dir: &Dir, actions: &mut Vec<Action>, sender: AccountNumber, service: AccountNumber) {
    for e in dir.entries() {
        match e {
            include_dir::DirEntry::Dir(d) => fill_dir(d, actions, sender, service),
            include_dir::DirEntry::File(e) => {
                let path = e.path().to_str().unwrap();
                if let Some(t) = mime_guess::from_path(path).first() {
                    // println!(
                    //     "{} {} {} {}",
                    //     sender,
                    //     service,
                    //     &("/".to_owned() + path),
                    //     t.essence_str()
                    // );
                    actions.push(store_sys(
                        service,
                        sender,
                        &("/".to_owned() + path),
                        t.essence_str(),
                        e.contents(),
                    ));
                }
            }
        }
    }
}

/// Create boot transactions
///
/// This returns a set of transactions which boot a blockchain.
/// The first transaction, the genesis transaction, installs
/// a set of service WASMs. The remainder initialize the services
/// and install apps and documentation. All of these transactions
/// should go into the first block.
///
/// If `initial_key` is set, then this initializes all accounts to use
/// that key and sets the key the initial producer signs blocks with.
/// If it is not set, then this initializes all accounts to use
/// `auth-any-sys` (no keys required) and sets it up so producers
/// don't need to sign blocks.
///
/// The first block should contain this entire set of transactions.
/// You may optionally add additional transactions after the ones this
/// function returns.
///
/// The interface to this function doesn't support customization.
/// If you want a custom boot, then use `boot.rs` as a guide to
/// create your own.
// TODO: switch to builder pattern
// TODO: sometimes tries to set keys on non-existing accounts
pub fn create_boot_transactions(
    initial_key: &Option<PublicKey>,
    initial_producer: AccountNumber,
    install_ui: bool,
    install_doc: bool,
    install_token_users: bool,
    expiration: TimePointSec,
) -> Vec<SignedTransaction> {
    let mut transactions = vec![genesis_transaction(expiration)];
    let mut init_actions = vec![
        account_sys::Wrapper::pack().init(),
        transaction_sys::Wrapper::pack().init(),
        nft_sys::Wrapper::pack().init(),
        Action {
            sender: account!("token-sys"),
            service: account!("token-sys"),
            method: method!("init"),
            rawData: ().packed().into(),
        },
        Action {
            sender: account!("symbol-sys"),
            service: account!("symbol-sys"),
            method: method!("init"),
            rawData: ().packed().into(),
        },
    ];
    let mut actions = Vec::new();
    actions.append(&mut init_actions);

    if install_ui {
        let html = "text/html";
        let js = "text/javascript";
        let css = "text/css";
        let ttf = "font/ttf";

        let mut reg_actions = vec![
            reg_server(account_sys::SERVICE, account!("r-account-sys")),
            reg_server(admin_sys::SERVICE, admin_sys::SERVICE),
            reg_server(auth_ec_sys::SERVICE, account!("r-ath-ec-sys")),
            reg_server(common_sys::SERVICE, common_sys::SERVICE),
            reg_server(account!("explore-sys"), account!("explore-sys")),
            reg_server(producer_sys::SERVICE, account!("r-prod-sys")),
            reg_server(proxy_sys::SERVICE, account!("r-proxy-sys")),
            reg_server(psispace_sys::SERVICE, psispace_sys::SERVICE),
        ];

        let mut common_sys_files = vec![
            store!(
                "common-sys",
                "/ui/common.index.html",
                html,
                "CommonSys/ui/vanilla/common.index.html"
            ),
            store_common!("keyConversions.mjs", js),
            store_common!("rpc.mjs", js),
            store_common!("SimpleUI.mjs", js),
            store_common!("useGraphQLQuery.mjs", js),
            store_common!("useLocalStorage.mjs", js),
            store_common!("widgets.mjs", js),
            store_common!("fonts/raleway.css", css),
            store_common!("fonts/raleway-variable-italic.ttf", ttf),
            store_common!("fonts/raleway-variable-normal.ttf", ttf),
            store_common!("fonts/red-hat-mono.css", css),
            store_common!("fonts/red-hat-mono-variable-normal.ttf", ttf),
        ];

        fill_dir(
            &include_dir!("$CARGO_MANIFEST_DIR/boot-image/CommonSys/ui/dist"),
            &mut common_sys_files,
            common_sys::SERVICE,
            common_sys::SERVICE,
        );

        let mut common_sys_3rd_party_files = vec![
            store_third_party!("htm.module.js", js),
            store_third_party!("iframeResizer.contentWindow.js", js),
            store_third_party!("iframeResizer.js", js),
            store_third_party!("react-dom.development.js", js),
            store_third_party!("react-dom.production.min.js", js),
            store_third_party!("react-router-dom.min.js", js),
            store_third_party!("react.development.js", js),
            store_third_party!("react.production.min.js", js),
            store_third_party!("semantic-ui-react.min.js", js),
            store_third_party!("useLocalStorageState.js", js),
        ];

        let mut account_sys_files = vec![
            // store!(
            //     "r-account-sys",
            //     "/index.html",
            //     html,
            //     "AccountSys/ui/vanilla/index.html"
            // ),
            // store!(
            //     "r-account-sys",
            //     "/ui/index.js",
            //     js,
            //     "AccountSys/ui/vanilla/index.js"
            // ),
        ];
        fill_dir(
            &include_dir!("$CARGO_MANIFEST_DIR/boot-image/AccountSys/ui/dist"),
            &mut account_sys_files,
            account!("r-account-sys"),
            account!("r-account-sys"),
        );

        let mut admin_sys_files = vec![];
        fill_dir(
            &include_dir!("$CARGO_MANIFEST_DIR/boot-image/AdminSys/ui/dist"),
            &mut admin_sys_files,
            admin_sys::SERVICE,
            admin_sys::SERVICE,
        );

        let mut auth_ec_sys_files = vec![
            // store!("r-ath-ec-sys", "/", html, "AuthEcSys/ui/index.html"),
            // store!("r-ath-ec-sys", "/ui/index.js", js, "AuthEcSys/ui/index.js"),
        ];

        let mut explore_sys_files = vec![
            // store!(
            //    "explore-sys",
            //    "/ui/index.js",
            //    js,
            //    "ExploreSys/ui/index.js"
            // ),
        ];
        fill_dir(
            &include_dir!("$CARGO_MANIFEST_DIR/boot-image/ExploreSys/ui/dist"),
            &mut explore_sys_files,
            account!("explore-sys"),
            account!("explore-sys"),
        );

        let mut token_sys_files = vec![
            // store!(
            //     "r-tok-sys",
            //     "/index.html",
            //     html,
            //     "CommonSys/ui/vanilla/common.index.html"
            // ),
            // store!(
            //     "r-tok-sys",
            //     "/ui/index.js",
            //     js,
            //     "TokenSys/ui/vanilla/index.js"
            // ),
        ];
        fill_dir(
            &include_dir!("$CARGO_MANIFEST_DIR/boot-image/TokenSys/ui/dist"),
            &mut token_sys_files,
            account!("r-tok-sys"),
            account!("r-tok-sys"),
        );

        let mut psispace_sys_files = vec![];
        fill_dir(
            &include_dir!("$CARGO_MANIFEST_DIR/boot-image/PsiSpaceSys/ui/dist"),
            &mut psispace_sys_files,
            psispace_sys::SERVICE,
            psispace_sys::SERVICE,
        );

        actions.append(&mut reg_actions);
        actions.append(&mut common_sys_files);
        actions.append(&mut common_sys_3rd_party_files);
        actions.append(&mut account_sys_files);
        actions.append(&mut admin_sys_files);
        actions.append(&mut auth_ec_sys_files);
        actions.append(&mut explore_sys_files);
        actions.append(&mut token_sys_files);
        actions.append(&mut psispace_sys_files);
    }

    if install_doc {
        let mut doc_actions = vec![
            new_account_action(account_sys::SERVICE, account!("doc-sys")), //
        ];
        fill_dir(
            &include_dir!("$CARGO_MANIFEST_DIR/boot-image/doc"),
            &mut doc_actions,
            account!("doc-sys"),
            psispace_sys::SERVICE,
        );
        actions.append(&mut doc_actions);
    }

    if install_token_users {
        #[allow(clippy::inconsistent_digit_grouping)]
        let mut create_and_fund_example_users = vec![
            new_account_action(account_sys::SERVICE, account!("alice")),
            new_account_action(account_sys::SERVICE, account!("bob")),
            Action {
                sender: account!("symbol-sys"),
                service: account!("token-sys"),
                method: method!("setTokenConf"),
                rawData: (1u32, method!("untradeable"), false).packed().into(),
            },
            Action {
                sender: account!("symbol-sys"),
                service: account!("token-sys"),
                method: method!("mint"),
                rawData: (1u32, (1_000_000_00000000_u64,), ("memo",)).packed().into(),
            },
            Action {
                sender: account!("symbol-sys"),
                service: account!("token-sys"),
                method: method!("credit"),
                rawData: (1u32, account!("alice"), (1_000_00000000_u64,), ("memo",))
                    .packed()
                    .into(),
            },
            Action {
                sender: account!("symbol-sys"),
                service: account!("token-sys"),
                method: method!("credit"),
                rawData: (1u32, account!("bob"), (1_000_00000000_u64,), ("memo",))
                    .packed()
                    .into(),
            },
        ];
        actions.append(&mut create_and_fund_example_users);
    }

    actions.push(set_producers_action(
        initial_producer,
        match initial_key {
            Some(k) => to_claim(k),
            None => Claim {
                service: AccountNumber::new(0),
                rawData: Default::default(),
            },
        },
    ));

    if let Some(k) = initial_key {
        for account in ACCOUNTS {
            actions.push(set_key_action(account, k));
            actions.push(set_auth_service_action(account, auth_ec_sys::SERVICE));
        }
    }

    while !actions.is_empty() {
        let mut n = 0;
        let mut size = 0;
        while n < actions.len() && size < 1024 * 1024 {
            size += actions[n].rawData.len();
            n += 1;
        }
        transactions.push(SignedTransaction {
            transaction: without_tapos(actions.drain(..n).collect(), expiration)
                .packed()
                .into(),
            proofs: vec![],
        });
    }
    transactions
}