链锁式 VRFs
简介
在处理计算机时,由于计算机的确定性,随机性是一个重要但难以处理的问题。在谈到区块链时更是如此,因为计算机不仅是确定性的,而且是透明的。因此,可信的随机数不能在 Solidity 中原生生成,因为随机性将在链上计算,这对所有矿工和用户来说是公共信息。
所以我们可以使用一些 web2 技术来生成随机性,然后在链上使用它们。
什么是 oracle?
- oracle 从外部世界向区块链的智能合约发送数据,反之亦然。
- 然后,智能合约可以使用这些数据来做出决定并改变其状态。
- 它们充当了区块链和外部世界之间的桥梁。
- 但需要注意的是,区块链 oracle 本身不是数据源,它的工作是查询、验证和认证外部数据,然后再将其传递给智能合约。
今天我们将学习其中一个名为 Chainlink VRF 的 oracle。
介绍
- Chainlink VRF 是用于生成随机值的 oracle。
- 这些值通过密码学证明进行验证。
- 这些证明证明了结果没有被 oracle 操作员、用户、矿工等篡改或操纵。
- 证明被公布在链上,以便它们可以被验证。
- 在验证成功后,它们会被要求随机性的智能合约所使用。
官方的 Chainlink 文档将 VRF 描述为
Chainlink VRF(可验证的随机函数)是为智能合约设计的一个可证明的公平和可验证的随机性来源。智能合约开发者可以使用 Chainlink VRF 作为防篡改的随机数发生器(RNG),为任何依赖不可预测结果的应用构建可靠的智能合约。
它是如何工作的?
-
Chainlink 有两个合约,我们主要关注的是 VRFConsumerBase.sol 和 VRFCoordinator。
-
VRFConsumerBase 是调用 VRF 协调员的合约,它最终负责发布随机性。
-
我们将继承 VRFConsumerBase,并将使用其中的两个函数。
- requestRandomness,它对随机性提出初始请求。
- fulfillRandomness,这是一个接收并对经过验证的随机性进行处理的函数。
-
如果你看一下这个图,你就可以理解这个流程,RandomGameWinner 合约将继承 VRFConsumerBase 合约,并将在 VRFConsumerBase 中调用 requestRandomness 函数。
-
在调用该函数时,对随机性的请求开始了,VRFConsumerBase 进一步调用 VRFCoordinator 合约,该合约负责从外部世界获取随机性的回报。
-
在 VRFCoordinator 获得随机性后,它调用 VRFConsumerBase 中的 fullFillRandomness 函数,然后进一步选择获胜者。
-
注意重要的部分是,尽管你调用了 requireRandomness 函数,但你在 fullFillRandomness 函数中获得了随机性。
前提条件
- 你已经完成了 Etherscan 的验证级别
- 你已经完成了第 2 层教程
要求
- 我们今天将建立一个抽奖游戏
- 每个游戏都会有一个最大的玩家人数和一个参赛费。
- 在最大数量的玩家进入游戏后,将随机选出一名获胜者
- 获胜者将获得 maxplayers*entryfee 数额的乙醚,以赢得游戏。