前言
參考工程,以下工程均可在 GitHub找到
cosmwasm: branch 0.13wasmd: branch v0.15.1cosmwasm-template: branch 0.13wasmvm: branch 0.13
Rust編譯
注意點
-
win系統洗掉所有不需要的代碼進行編譯,需要修改
.cargo組態檔[build] rustflags = "-C link-arg=-s" -
優化程式,提高運行速度:
如果用
cargo編譯,使用--release標志;如果用rustc編譯,使用-O標志,但是優化會降低編譯速度,而且在開發程序中通常是不可取的,
wasm虛擬機
編譯原理
wasmvm是基于wasmer.io引擎作業的,依賴這個庫:cosmwasm,這庫是用rust寫的,為了便于go呼叫,最終編譯成了libwasmvm.so動態庫,并生成了讓cgo呼叫的bindings.h頭檔案,
Contract就是一些上傳到區塊鏈系統的wasm位元組碼,在創建Contract時初始化,除了包含在wasm代碼中的狀態,沒有其他狀態,對于一個Contract,要經過三步:
- 創建:用
rust把邏輯代碼編譯成wasm位元組碼,然后把位元組碼上傳到區塊鏈系統 - 實體化一個instance:把上傳到系統的
wasm位元組碼拿出來放到虛擬機中 - 呼叫實體:根據
json scheme中的欄位,在虛擬機中執行對應的函式,涉及到了cosmwasm-vm、cosmwasm-storage、cosmwasm-std
Contract是不可變的,因為邏輯代碼固定了;instance是可變的,因為狀態可變,
運行機制
-
所有查詢都是作為交易的一部分執行的,每個合約都定義了一個公開的
query函式,該函式只能以只讀模式訪問合約的資料存盤,并且可以對加載的資料進行計算,查詢的資料格式定義在公開的State中,見cosmwasm-template/src/state.rs#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct State { pub count: i32, pub owner: Addr, } -
cosmos-sdk中公開的查詢設計了執行時間限制,用來限制濫用,但是無法避免DoS攻擊,比如無限回圈的wasm合約,為了避免此類問題,設計了query_custom用來為交易定義固定的gas限制,query_custom可以在特定app的組態檔中定義所有呼叫的 gas 限制,該檔案可由每個節點操作員自定義,并具有合理的默認值,配置見wasmd/x/wasm/README.md -> Configuration

-
正在執行的合約和被查詢的合約在執行當前
CosmWasm訊息之前,都具有對狀態快照的只讀訪問,見cosmwasm/vm/src/calls.rs -> call_query_raw,這也避免了重入攻擊,/// Calls Wasm export "query" and returns raw data from the contract. /// The result is length limited to prevent abuse but otherwise unchecked. pub fn call_query_raw<A, S, Q>( instance: &mut Instance<A, S, Q>, env: &[u8], msg: &[u8], ) -> VmResult<Vec<u8>> where A: Api + 'static, S: Storage + 'static, Q: Querier + 'static, { instance.set_storage_readonly(true); call_raw(instance, "query", &[env, msg], MAX_LENGTH_QUERY) }當前合約只寫入快取,成功后重繪,見
cosmwasm/vm/src/calls.rs -> call_raw,/// Calls a function with the given arguments. /// The exported function must return exactly one result (an offset to the result Region). fn call_raw<A, S, Q>( instance: &mut Instance<A, S, Q>, name: &str, args: &[&[u8]], result_max_length: usize, ) -> VmResult<Vec<u8>> where A: Api + 'static, S: Storage + 'static, Q: Querier + 'static, { let mut arg_region_ptrs = Vec::<Val>::with_capacity(args.len()); for arg in args { let region_ptr = instance.allocate(arg.len())?; instance.write_memory(region_ptr, arg)?; arg_region_ptrs.push(region_ptr.into()); } let result = instance.call_function1(name, &arg_region_ptrs)?; let res_region_ptr = ref_to_u32(&result)?; let data = instance.read_memory(res_region_ptr, result_max_length)?; // free return value in wasm (arguments were freed in wasm code) instance.deallocate(res_region_ptr)?; Ok(data) } -
為了避免重入攻擊,合約不能直接呼叫其他的合約,而是通過回傳一個訊息串列,這些訊息在合約執行后在同一事務中發送給其他合約和被驗證,如果,訊息執行和驗證失敗,合約也將回滾,見
wasmd/x/wasm/internal/keeper/handler_plugin.go -> handleSdkMessage,func (h MessageHandler) handleSdkMessage(ctx sdk.Context, contractAddr sdk.Address, msg sdk.Msg) error { if err := msg.ValidateBasic(); err != nil { return err } // make sure this account can send it for _, acct := range msg.GetSigners() { if !acct.Equals(contractAddr) { return sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "contract doesn't have permission") } } // find the handler and execute it handler := h.router.Route(ctx, msg.Route()) if handler == nil { return sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, msg.Route()) } res, err := handler(ctx, msg) if err != nil { return err } events := make(sdk.Events, len(res.Events)) for i := range res.Events { events[i] = sdk.Event(res.Events[i]) } // redispatch all events, (type sdk.EventTypeMessage will be filtered out in the handler) ctx.EventManager().EmitEvents(events) return nil }
資料互動機制
有兩種資料用來合約與區塊鏈之間的互動:Message Data 和 Context Data,
-
Message Data:是由交易發送者簽名的在事務中傳遞的任意位元組資料,標準的JSON編碼,cosmwasm/packages/std/src/results/cosmos_msg.rs -> CosmosMsg,#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] // See https://github.com/serde-rs/serde/issues/1296 why we cannot add De-Serialize trait bounds to T pub enum CosmosMsg<T = Empty> where T: Clone + fmt::Debug + PartialEq + JsonSchema, { Bank(BankMsg), // by default we use RawMsg, but a contract can override that // to call into more app-specific code (whatever they define) Custom(T), Staking(StakingMsg), Wasm(WasmMsg), } -
Context Data:是由cosmos SDK運行時傳入的,提供了一些有憑證的背景關系,背景關系資料可能包括簽名者的地址、合約的地址、發送的Token數量、塊的高度,以及合同可能需要控制內部邏輯的任何其他資訊,見cosmwasm/packages/std/src/types.rs -> Env,#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq, JsonSchema)] pub struct Env { pub block: BlockInfo, pub contract: ContractInfo, }
由于go/cgo不能處理c型別的資料,eg.strings,也不支持對堆分配資料的參考,所以不管是Message Data還是Context Data,都是用JSON編碼的,
資料存盤機制
Instance State(實體狀態)只能被合約的一個實體訪問,具有完全的讀寫訪問權限,實體狀態存盤有兩種方式:
-
singleton:只有一個鍵(合約或配置作為鍵)的資料訪問模式,見cosmwasm/packages/storage/src/singleton.rs -> Singleton/// Singleton effectively combines PrefixedStorage with TypedStorage to /// work on a single storage key. It performs the to_length_prefixed transformation /// on the given name to ensure no collisions, and then provides the standard /// TypedStorage accessors, without requiring a key (which is defined in the constructor) pub struct Singleton<'a, T> where T: Serialize + DeserializeOwned, { storage: &'a mut dyn Storage, key: Vec<u8>, // see https://doc.rust-lang.org/std/marker/struct.PhantomData.html#unused-type-parameters for why this is needed data: PhantomData<T>, } -
kvstore:多個鍵的資料訪問模式,可以在實體化時設定實體狀態,并且在呼叫時讀取和修改它,它是唯一的并帶前綴的"db",只能被這個實體訪問,見cosmwasm/packages/storage/src/prefixed_storage.rs -> PrefixedStoragepub struct PrefixedStorage<'a> { storage: &'a mut dyn Storage, prefix: Vec<u8>, }還設計了只讀合約狀態來實作所有實體之間的共享資料,見
cosmwasm/packages/storage/src/prefixed_storage.rs -> ReadonlyPrefixedStoragepub struct ReadonlyPrefixedStorage<'a> { storage: &'a dyn Storage, prefix: Vec<u8>, }
合約狀態可以用某一種或兩種方式來存盤,根據需要進行配置,見cosmwasm-template/src/state.rs
pub fn config(storage: &mut dyn Storage) -> Singleton<State> {
singleton(storage, CONFIG_KEY)
}
pub fn config_read(storage: &dyn Storage) -> ReadonlySingleton<State> {
singleton_read(storage, CONFIG_KEY)
}
來看看wasm合約的運行目錄

wasm:存放部署到區塊鏈的合約二進制位元組碼
modules:存放實體化的合約以及合約狀態資料,合約狀態資料先從記憶體存盤中加載,若沒有則從檔案中加載,然后放入記憶體,檔案加載合約資料見:cosmwasm/packages/vm/src/file_system_cache.rs -> load
/// Loads an artifact from the file system and returns a module (i.e. artifact + store).
pub fn load(&self, checksum: &Checksum, store: &Store) -> VmResult<Option<Module>> {
let filename = checksum.to_hex();
let file_path = self.latest_modules_path().join(filename);
let result = unsafe { Module::deserialize_from_file(store, &file_path) };
match result {
Ok(module) => Ok(Some(module)),
Err(DeserializeError::Io(err)) => match err.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(VmError::cache_err(format!(
"Error opening module file: {}",
err
))),
},
Err(err) => Err(VmError::cache_err(format!(
"Error deserializing module: {}",
err
))),
}
}
合約資料與世界狀態互動
合約初始化時,wasm的資料存盤被實體化為db傳遞給合約,見wasmvm/lib.go -> Instantiate
func (vm *VM) Instantiate(
code CodeID,
env types.Env, // 區塊資料和合約賬號
info types.MessageInfo,
initMsg []byte,
store KVStore, // 資料存盤
goapi GoAPI,
querier Querier,
gasMeter GasMeter,
gasLimit uint64,
) (*types.InitResponse, uint64, error) {
envBin, err := json.Marshal(env)
if err != nil {
return nil, 0, err
}
infoBin, err := json.Marshal(info)
if err != nil {
return nil, 0, err
}
// 傳遞給合約
data, gasUsed, err := api.Instantiate(vm.cache, code, envBin, infoBin, initMsg, &gasMeter, store, &goapi, &querier, gasLimit, vm.memoryLimit, vm.printDebug)
if err != nil {
return nil, gasUsed, err
}
var resp types.InitResult
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, gasUsed, err
}
if resp.Err != "" {
return nil, gasUsed, fmt.Errorf("%s", resp.Err)
}
return resp.Ok, gasUsed, nil
}
合約呼叫初始化函式將資料存放至db中,見cosmwasm-template/src/contract.rs -> init
pub fn init(
deps: DepsMut,
_env: Env,
info: MessageInfo,
msg: InitMsg,
) -> Result<InitResponse, ContractError> {
let state = State {
count: msg.count,
owner: deps.api.canonical_address(&info.sender)?,
};
config(deps.storage).save(&state)?;
Ok(InitResponse::default())
}
來看deps.storage,它實作了兩種存盤:ExternalStorage(將vm中提供的資料包裝成state,是空結構體)和MemoryStorage(結構體的屬性是基于b樹的散串列),兩種存盤都是為了方便對db的操作,具體的操作方法見:cosmwasm/packages/std/imports.rs,具體的實作見:cosmwasm/packages/vm/imports.rs
extern "C" {
fn db_read(key: u32) -> u32;
fn db_write(key: u32, value: u32);
fn db_remove(key: u32);
// scan creates an iterator, which can be read by consecutive next() calls
#[cfg(feature = "iterator")]
fn db_scan(start_ptr: u32, end_ptr: u32, order: i32) -> u32;
#[cfg(feature = "iterator")]
fn db_next(iterator_id: u32) -> u32;
fn canonicalize_address(source_ptr: u32, destination_ptr: u32) -> u32;
fn humanize_address(source_ptr: u32, destination_ptr: u32) -> u32;
fn debug(source_ptr: u32);
/// Executes a query on the chain (import). Not to be confused with the
/// query export, which queries the state of the contract.
fn query_chain(request: u32) -> u32;
}
合約正確執行,操作完資料后,回傳結果給區塊鏈,區塊鏈根據錯誤資訊更新世界狀態,大致流程圖如下,根據資料流向畫的:

與cosmos集成
見wasmd/INTEGRATION.md
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318087.html
標籤:區塊鏈
上一篇:區塊鏈與基因測序上場景上的思路有何隱私保護問題與保護方法?
下一篇:如何在一個檔案中撰寫多個函式?
