EOS require_auth函数
action的结构
要说清楚这个方法的含义和用法,咱们需要从action
的结构说起。详见eoslib.hpp
中的action类,这里把它的结构简化表示成下面这样:
1 2 3 4 5 6 | * 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的数据包含:
1 2 3 4 | account: action的处理器(handler)所在的合约账号 name: action的名字 authorization: 调用者提供的action的权限列表(可以是一组keys,也可以是一组别人的许可权限) data: action的数据参数,如果是transfer action,这里的数据就是类似这样的内容: |
{ "from": "inita", "to": "initb", "amount": "100.0000 EOS", "memo": "1234"}
你可能说,“不对,data明明是个byte数组,怎么能存储一个结构呢?”,这其实是数据序列化的结果,关于序列化和反序列化,如果你还不是很了解,可以从网上搜索一下相关知识。
require_auth
现在我们再说require_auth
就比较容易了,先看签名:
1 2 3 4 5 6 7 | /** * 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已提供的权限列表
中。如果在,则校验通过,否则,抛出异常。
比如如果执行下面的命令发起一个action:
1 | cleos push action hello.code hi '["user"]' -p user@active |
这里发起的这个hi
action的结构就是类似这样的:
1 | { "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))
就会检测失败,并抛出异常。
有时候,你可能就想看看某个账户是否在action的已提供权限列表
里,并不想抛出异常,那该怎么办?
这个时候可以用has_auth方法:
1 2 3 4 5 6 7 | /** * 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
还有一个类似的require_auth2
方法,它的签名是这样的:
1 2 3 4 5 6 7 8 | /** * 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 ); |
这个检查更为严格一点,除了指定账户,还要指定许可。这个许可是严格检查的,也就是说,假如你在代码里写的是:
1 | require_auth(N(user), N(active)); |
那么下面的命令是通不过这个检查的:
1 | cleos push action hello.code hi '["user"]' -p user@owner |
尽管这里使用的是更高的权限user@owner
,也无法通过检查。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2018-09-17 书单
2014-09-17 SDUT1157:小鼠迷宫问题(bfs+dfs)