A Detailed Explanation of Function Visibility and Access Control in Rust Smart Contracts

robot
Abstract generation in progress

Rust Smart Contracts Development Diary (7) Contract Security and Calculation Precision

This article will introduce permission control in Rust smart contracts from two perspectives:

  • Visibility of contract method access/call
  • Access control/division of responsibilities for privileged functions

1. Contract Function Visibility

The visibility control of contract functions is crucial for protecting key parts from being misoperated. Taking the security incident of Bancor Network exchange on June 18, 2020, as an example, the misconfiguration of a key transfer function as public exposed users' assets worth $590,000 to risk.

In Rust smart contracts, function visibility mainly includes:

  • pub fn: public function, callable from outside the contract
  • fn: default private, can only be called within the contract
  • pub(crate) fn: restrict calls to within crate

Another way to set the internal method is to define a separate impl Contract code block without the #[near_bindgen] modifier.

For the callback function, it must be set to public but restricted to be called only by the contract itself. This can be implemented using the #[private] macro.

By default, everything in Rust is private, except for items in pub trait and pub enum.

2. Access Control of Privileged Functions

In addition to function visibility, a complete access control whitelist mechanism needs to be established from a semantic level. Similar to Solidity's Ownable contract, certain privileged functions can only be called by the owner.

In Rust smart contracts, custom Traits can be implemented:

rust pub trait Ownable { fn assert_owner(\u0026self) { assert_eq!(env::predecessor_account_id(), self.get_owner()); } fn get_owner(\u0026self) -\u003e AccountId; fn set_owner(&mut self, owner: AccountId); }

This enables access control for privileged functions. Based on this, it is also possible to set up multi-user whitelists or multiple whitelist groups.

3. More Access Control Methods

Other access control methods include:

  • Timing control of contract calls
  • Multi-signature calling mechanism for contract functions
  • Implementation of DAO governance

These contents will be detailed in subsequent articles.

View Original
This page may contain third-party content, which is provided for information purposes only (not representations/warranties) and should not be considered as an endorsement of its views by Gate, nor as financial or professional advice. See Disclaimer for details.
  • Reward
  • Comment
  • Share
Comment
0/400
No comments
Trade Crypto Anywhere Anytime
qrCode
Scan to download Gate app
Community
English
  • 简体中文
  • English
  • Tiếng Việt
  • 繁體中文
  • Español
  • Русский
  • Français (Afrique)
  • Português (Portugal)
  • Bahasa Indonesia
  • 日本語
  • بالعربية
  • Українська
  • Português (Brasil)