action的結構html
要說清楚這個方法的含義和用法,我們須要從action
的結構提及。詳見eoslib.hpp
中的action類,這裏把它的結構簡化表示成下面這樣:數組
* struct action { * account_name account; // the contract defining the primary code to execute for code/type * action_name name; // the action to be taken * permission_level[] authorization; // the accounts and permission levels provided * bytes data; // opaque data processed by code * };
一個action的數據包含:ide
account: action的處理器(handler)所在的合約帳號 name: action的名字 authorization: 調用者提供的action的權限列表(能夠是一組keys,也能夠是一組別人的許可權限) data: action的數據參數,若是是transfer action,這裏的數據就是相似這樣的內容:
{ "from": "inita", "to": "initb", "amount": "100.0000 EOS", "memo": "1234"} ui
你可能說,「不對,data明明是個byte數組,怎麼能存儲一個結構呢?」,這實際上是數據序列化的結果,關於序列化和反序列化,若是你還不是很瞭解,能夠從網上搜索一下相關知識。spa
如今咱們再說require_auth
就比較容易了,先看簽名:code
/** * Verifies that @ref name exists in the set of provided auths on a action. Throws if not found. * * @brief Verify specified account exists in the set of provided auths * @param name - name of the account to be verified */ void require_auth( account_name name );
英文好的看下注釋,再結合action的結構就徹底明白了:它校驗經過name
形參傳進來的帳戶,看是否在本action已提供的權限列表
中。若是在,則校驗經過,不然,拋出異常。htm
好比若是執行下面的命令發起一個action:blog
cleos push action hello.code hi '["user"]' -p user@active
這裏發起的這個hi
action的結構就是相似這樣的:ci
{ "account": "hello.code", "name": "hi", "authorization": [ {"account": "user", "permission":"active"} ], "data": ["user"] }
因此若是在hi
action的處理器裏面調用require_auth(N(user))
是能夠經過檢查的,由於user
在authorization
數組中;而require_auth(N(hello.code))
就會檢測失敗,並拋出異常。string
有時候,你可能就想看看某個帳戶是否在action的已提供權限列表
裏,並不想拋出異常,那該怎麼辦?
這個時候能夠用has_auth方法:
/** * Verifies that @ref name has auth. * * @brief Verifies that @ref name has auth. * @param name - name of the account to be verified */ bool has_auth( account_name name );
還有一個相似的require_auth2
方法,它的簽名是這樣的:
/** * Verifies that @ref name exists in the set of provided auths on a action. Throws if not found. * * @brief Verify specified account exists in the set of provided auths * @param name - name of the account to be verified * @param permission - permission level to be verified */ void require_auth2( account_name name, permission_name permission );
這個檢查更爲嚴格一點,除了指定帳戶,還要指定許可。這個許但是嚴格檢查的,也就是說,假如你在代碼裏寫的是:
require_auth(N(user), N(active));
那麼下面的命令是通不過這個檢查的:
cleos push action hello.code hi '["user"]' -p user@owner
儘管這裏使用的是更高的權限user@owner
,也沒法經過檢查。