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
,也没法经过检查。