0Pricing
Blockchain Smart Contracts with Solidity · 课时

访问控制模式

使用 `Ownable`、`Pausable` 和基于角色的访问控制(RBAC)模式,实施稳健的访问控制机制。

访问控制模式 是 CoddyKit 上的免费 Blockchain Smart Contracts with Solidity 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Blockchain Smart Contracts with Solidity 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What is Access Control?

In smart contracts, access control defines who can perform specific actions. It's like setting permissions on a file or folder.

Without proper access control, anyone could call sensitive functions, leading to vulnerabilities or unintended behavior.

Why It's Crucial

Imagine a contract that manages funds or critical system settings. You wouldn't want just anyone to be able to:

  • Withdraw all funds.
  • Change the contract's owner.
  • Pause essential operations.

Access control is a fundamental security measure.

The `onlyOwner` Modifier

A common pattern is to restrict certain functions to the contract's owner (the address that deployed it).

This is often achieved using a modifier, a special keyword in Solidity that can alter the behavior of a function.

Custom `onlyOwner` Example

Here's how you might manually implement an onlyOwner modifier and use it:

pragma solidity ^0.8.0;

contract MyBasicOwnable {
  address public owner;

  constructor() {
    owner = msg.sender;
  }

  modifier onlyOwner() {
    require(msg.sender == owner, "Not owner");
    _;
  }

  function setGreeting(string memory _text) public onlyOwner {
    // Only the owner can call this
    // ... (e.g., update a greeting message)
  }
}

OpenZeppelin's `Ownable`

While you can write your own, it's best practice to use battle-tested libraries. OpenZeppelin provides a secure and standardized Ownable contract.

By inheriting from Ownable, your contract gets the owner state variable and the onlyOwner modifier automatically.

Using OpenZeppelin `Ownable`

Simply import and inherit Ownable. The contract deployer automatically becomes the owner.

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/access/Ownable.sol";

contract MyOzOwnable is Ownable {
  uint256 public value;

  function setValue(uint256 _newValue) public onlyOwner {
    value = _newValue;
  }

  function getValue() public view returns (uint256) {
    return value;
  }
}

The `Pausable` Pattern

The Pausable pattern allows a contract to be put into a 'paused' state, preventing certain functions from being called.

This is crucial for emergency situations, like discovering a critical bug or reacting to a hack, giving developers time to mitigate issues.

Using OpenZeppelin `Pausable`

OpenZeppelin's Pausable provides paused state, whenNotPaused and whenPaused modifiers, and _pause()/_unpause() functions.

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MyPausableContract is Pausable, Ownable {
  uint256 public counter;

  function increment() public whenNotPaused {
    counter++;
  }

  function pauseContract() public onlyOwner {
    _pause(); // Only owner can pause
  }

  function unpauseContract() public onlyOwner {
    _unpause(); // Only owner can unpause
  }
}

Role-Based Access Control (RBAC)

For more complex contracts, a single 'owner' might not be enough. Role-Based Access Control (RBAC) allows defining multiple roles (e.g., 'minter', 'admin', 'pauser').

OpenZeppelin's AccessControl contract helps manage these roles efficiently.

Using OpenZeppelin `AccessControl`

Define roles as bytes32 constants. The deployer automatically gets DEFAULT_ADMIN_ROLE, which can grant/revoke other roles.

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/access/AccessControl.sol";

contract MyRBACContract is AccessControl {
  bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
  bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");

  constructor() {
    _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    _grantRole(MINTER_ROLE, msg.sender); // Deployer is also a minter
  }

  function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
    // Logic to mint tokens
  }

  function systemPause() public onlyRole(PAUSER_ROLE) {
    // Logic to pause critical system functions
  }
}

Access Control Check

Which of the following are benefits of implementing access control patterns like Ownable, Pausable, or AccessControl in smart contracts?

Recap: Access Control Patterns

You've learned about essential access control patterns in Solidity:

  • Ownable: Restricts functions to a single owner, often the contract deployer.
  • Pausable: Allows for emergency pausing/unpausing of contract functionality.
  • AccessControl (RBAC): Provides flexible, role-based permissions for more complex scenarios.

These patterns are critical for building robust and secure smart contracts, often leveraged from OpenZeppelin's battle-tested libraries.

常见问题解答

「访问控制模式」课时是免费的吗?

是的 — 「访问控制模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Blockchain Smart Contracts with Solidity 课程的其余内容,请升级到 CoddyKit PRO。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。

「访问控制模式」这节课中我会学到什么?

使用 `Ownable`、`Pausable` 和基于角色的访问控制(RBAC)模式,实施稳健的访问控制机制。 你通过在浏览器中直接运行的动手代码来练习 Blockchain Smart Contracts with Solidity,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Blockchain Smart Contracts with Solidity 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Blockchain Smart Contracts with Solidity 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「访问控制模式」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Blockchain Smart Contracts with Solidity 课中编写并运行代码吗?

能。每节 Blockchain Smart Contracts with Solidity 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 常见漏洞(重入等)
  2. 访问控制模式
  3. 使用 SafeMath 进行安全编码
  4. 审计、测试与漏洞赏金
← 返回 Blockchain Smart Contracts with Solidity