Rust智能合約安全:3大關鍵策略防御DoS攻擊

Rust智能合約安全:防御拒絕服務攻擊

拒絕服務(DoS)攻擊會導致智能合約在一段時間內無法被正常使用,甚至永久癱瘓。主要原因包括:

  1. 合約邏輯存在計算復雜度過高的缺陷,導致Gas消耗超出限制。

  2. 跨合約調用時對外部合約執行狀態的依賴,可能被外部合約阻塞。

  3. 合約所有者丟失私鑰,無法執行關鍵的特權函數。

下面結合具體例子進行分析。

1. 避免遍歷可被外部操控的大型數據結構

以下是一個簡單的"分紅"合約,存在DoS風險:

rust #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { pub registered: Vec, pub accounts: UnorderedMap<accountid, balance="">, }

pub fn register_account(&mut self) { if self.accounts.insert(&env::predecessor_account_id(), &0).is_some() { env::panic("The account is already registered".to_string().as_bytes()); } else { self.registered.push(env::predecessor_account_id()); } log!("Registered account {}", env::predecessor_account_id()); }

pub fn distribute_token(&mut self, amount: u128) { assert_eq!(env::predecessor_account_id(), DISTRIBUTOR, "ERR_NOT_ALLOWED");

for cur_account in self.registered.iter() {
    let balance = self.accounts.get(&cur_account).expect("ERR_GET");
    self.accounts.insert(&cur_account, &balance.checked_add(amount).expect("ERR_ADD"));
    log!("Try distribute to account {}", &cur_account);
    
    ext_ft_token::ft_transfer(
        cur_account.clone(),
        amount,
        &FTTOKEN,
        0,
        GAS_FOR_SINGLE_CALL
    );
}

}

該合約的問題在於registered數組大小沒有限制,可被惡意用戶操控使其過大,導致distribute_token函數Gas消耗超限。

推薦的解決方案是採用"提現"模式:

rust pub fn distribute_token(&mut self, amount: u128) { assert_eq!(env::predecessor_account_id(), DISTRIBUTOR, "ERR_NOT_ALLOWED");

for account in self.registered.iter() {
    let balance = self.accounts.get(&account).unwrap();
    self.accounts.insert(&account, &(balance + amount));
}

}

pub fn withdraw(&mut self) { let account = env::predecessor_account_id(); let amount = self.accounts.get(&account).unwrap(); self.accounts.insert(&account, &0);

ext_ft_token::ft_transfer(account, amount, &FTTOKEN, 0, GAS_FOR_SINGLE_CALL);

}

2. 避免跨合約調用狀態依賴

下面是一個"競價"合約示例:

rust #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { pub registered: Vec, pub bid_price: UnorderedMap<accountid,balance>, pub current_leader: AccountId, pub highest_bid: u128, }

pub fn bid(&mut self, sender_id: AccountId, amount: u128) -> PromiseOrValue { assert!(amount > self.highest_bid);

if self.current_leader == DEFAULT_ACCOUNT {
    self.current_leader = sender_id;
    self.highest_bid = amount;
} else {
    ext_ft_token::account_exist(
        self.current_leader.clone(),
        &FTTOKEN,
        0,
        env::prepaid_gas() - GAS_FOR_SINGLE_CALL * 4,
    ).then(ext_self::account_resolve(
        sender_id,
        amount,
        &env::current_account_id(),
        0,
        GAS_FOR_SINGLE_CALL * 3,
    ));
}

PromiseOrValue::Value(0)

}

#[private] pub fn account_resolve(&mut self, sender_id: AccountId, amount: u128) { match env::promise_result(0) { PromiseResult::Successful(_) => { ext_ft_token::ft_transfer( self.current_leader.clone(), self.highest_bid, &FTTOKEN, 0, GAS_FOR_SINGLE_CALL * 2, ); self.current_leader = sender_id; self.highest_bid = amount; } PromiseResult::Failed => { ext_ft_token::ft_transfer( sender_id.clone(), amount, &FTTOKEN, 0, GAS_FOR_SINGLE_CALL * 2, ); log!("Return Back Now"); } PromiseResult::NotReady => unreachable!(), }; }

該合約存在的問題是,如果前一個出價最高者注銷了帳戶,新的競價者將無法成功更新狀態。

解決方法是實現合理的錯誤處理,例如將無法退回的代幣暫存,後續再由用戶自行提取:

rust pub struct Contract { // ... pub lost_found: UnorderedMap<accountid, balance="">, }

pub fn account_resolve(&mut self, sender_id: AccountId, amount: u128) { match env::promise_result(0) { PromiseResult::Successful(_) => { // 正常退款邏輯 } PromiseResult::Failed => { // 將無法退回的代幣暫存 let lost_amount = self.lost_found.get(&self.current_leader).unwrap_or(0); self.lost_found.insert(&self.current_leader, &(lost_amount + self.highest_bid));

        // 更新狀態
        self.current_leader = sender_id;
        self.highest_bid = amount;
    }
    PromiseResult::NotReady => unreachable!(),
}

}

pub fn withdraw_lost_found(&mut self) { let account = env::predecessor_account_id(); let amount = self.lost_found.get(&account).unwrap_or(0); if amount > 0 { self.lost_found.insert(&account, &0); ext_ft_token::ft_transfer(account, amount, &FTTOKEN, 0, GAS_FOR_SINGLE_CALL); } }

3. 避免單點故障

合約所有者私鑰丟失會導致關鍵特權功能無法使用。解決方法是採用多籤名機制:

rust pub struct Contract { pub owners: Vec, pub required_confirmations: u64, pub transactions: Vec, }

pub fn propose_transaction(&mut self, transaction: Transaction) { assert!(self.owners.contains(&env::predecessor_account_id()), "Not an owner"); self.transactions.push(transaction); }

pub fn confirm_transaction(&mut self, transaction_id: u64) { assert!(self.owners.contains(&env::predecessor_account_id()), "Not an owner");

let transaction = &mut self.transactions[transaction_id as usize];
transaction.confirmations += 1;

if transaction.confirmations >= self.required_confirmations {
    self.execute_transaction(transaction_id);
}

}

fn execute_transaction(&mut self, transaction_id: u64) { let transaction = self.transactions.remove(transaction_id as usize); // 執行交易邏輯 }

通過多籤名機制,可以避免單個所有者私鑰丟失導致的合約癱瘓,提高合約的去中心化程度和安全性。

</accountid,></accountid,balance></accountid,>

查看原文
此頁面可能包含第三方內容,僅供參考(非陳述或保證),不應被視為 Gate 認可其觀點表述,也不得被視為財務或專業建議。詳見聲明
  • 讚賞
  • 5
  • 分享
留言
0/400
GasFee_Nightmarevip
· 14小時前
不愧是Gas大户
回復0
假装在读白皮书vip
· 14小時前
DoS都避免不了 还有啥安全可谈
回復0
HashRatePhilosophervip
· 15小時前
rust大军来啦,对手颤抖吧
回復0
测试网薅毛狂人vip
· 15小時前
防dos你搁这套理论呢
回復0
MEV迷踪侠vip
· 15小時前
Gas费爆表我麻了
回復0
交易,隨時隨地
qrCode
掃碼下載 Gate APP
社群列表
繁體中文
  • 简体中文
  • English
  • Tiếng Việt
  • 繁體中文
  • Español
  • Русский
  • Français (Afrique)
  • Português (Portugal)
  • Bahasa Indonesia
  • 日本語
  • بالعربية
  • Українська
  • Português (Brasil)