Persistent WebAssembly instances in Linera
In the Linera protocol, every message, operation or event stream processed by a contract used to instantiate the contract, run it and finalize it. This pull request keeps the contract instances alive for the whole block, and uses snapshots of the running Wasm machine to roll back a failed transaction.
Linera is a blockchain built on microchains: every user or application can own a chain, and the chains talk to each other through asynchronous messages. Smart contracts are compiled to WebAssembly and run in a virtual machine (wasmer or wasmtime) inside the validators and the clients. A block typically contains many incoming messages and operations, and several of them often target the same application.
In the original execution model, each of these was handled in isolation: the contract was instantiated, its state was loaded from storage, the entry point was run, and the contract was finalized and its state stored back. For a busy application, such as an order book receiving a burst of bids and asks, the same contract was thus loaded and saved dozens of times in one block. Interactions between contracts made it worse: when contract A handles a message that makes it call contract B, which in turn calls A, every step paid the full set-up cost.
The pull request changes this model: a contract instance is created the first time it is needed in a block and stays alive until the block ends. The SDK functions load and store are then called once per application and per block. This also gives a natural place for checks that only make sense at the level of the block. In a flash loan, contract A borrows tokens from a bank and contract B pays them back; if the bank's terminate function sees that the loan has not been repaid, the block cannot be created.
The difficulty is checkpointing. An incoming bundle of messages may fail, and its effects must then be undone. Saving the chain state is no longer enough, since the Wasm machine itself now holds state across transactions. The solution is to take snapshots of the running Wasm instances, implemented for both wasmer and wasmtime. They are small (about 1.1 MB for the matching engine), fast, and cost no fuel, whereas a software load/store pair costs around 25,000 fuel units even for a trivial counter contract. In the browser, where Wasm instances cannot share memory, the snapshots are serialized and the instances are wound down after every transaction.
On a benchmark where 50 bids and 50 asks are sent to the same matching-engine application, processing the inbox goes from 760 ms to 413 ms. Since the contract API and the cost structure both change, this is a protocol-level change, which could not be backported to the running testnet.