parallelchain-io / parallelchain-protocol

Specification for the ParallelChain (and ParallelChain Mainnet) blockchain protocols.
https://parallelchain.io
1 stars 1 forks source link

Wasm file generated by pchain_compile maybe invalid in pchain_runtime #11

Open TLiu2084 opened 11 months ago

TLiu2084 commented 11 months ago

Observation 1

If one of the project dependencies pulls in wasm-bindgen when compiling to the wasm32 architecture, wasmer runtime could fail to compile the wasmer module. (See issue on GitHub)

Observation 2

By default, WebAssembly is run in single thread. There is a threads proposal for WebAssembly adds a number of instructions for dealing with multithreaded programs. But on blockchain, all contract call should be deterministic, and multi-threads in smart contract shouldn't be allow. But I found that even we use std::thread::spawn in the contract, the output WASM file still won't contain any atomic opcodes. Even we add a non_determinism_filter middleware to wasmer compiler, it won't be able to filter out these invalid threads contract. As the result, contract with std::thread::spawn can deploy successfully on mainnet.

When you try to call the thread function, pchain_runtime would return RuntimeError. It is because Rust implemented std::sync::atomic module for the threads proposal is not direct equivalents to the functions in std::thread module. (See more on rust doc)

// Example
#[call]
     fn spwan_thread(num: u64){
        use std::thread;
        use std::sync::{Arc, Mutex};

        let data = Arc::new(Mutex::new(vec![]));

        let data1 = data.clone();
        // create a thread
        let handle = thread::spawn( move || {
            for i in 0..5 {
                data1.lock().unwrap().push(i);
            }
        });

        // main thread
        for i in 0..num {
            data.lock().unwrap().push(i);
        }

        handle.join().unwrap();

        pchain_sdk::log(
            "topic: spwan_thread".as_bytes(), 
            "done".as_bytes()
        );
    }