Anchor 中的 init_if_needed 与重新初始化攻击防范

  • 0xE
  • 发布于 2025-04-01 10:34
  • 阅读 491

本文介绍了 Anchor 中 init_if_needed 宏的用法,分析了其简化账户初始化的优势,同时探讨了重新初始化攻击的风险,并提出了通过单一初始化和限制操作等防护措施来确保程序安全性的建议。

在之前的 Solana 教程中,账户需先通过单独事务初始化才能写入数据。为简化操作,Anchor 提供了 init_if_needed 宏,允许在单次事务中初始化并操作账户。本文将探讨其用法、潜在的重新初始化攻击风险及防护措施。


init_if_needed 示例

以下计数器程序无需独立初始化,直接递增计数。

Rust 实现

use anchor_lang::prelude::*;
use std::mem::size_of;

declare_id!("BryuGUGr6sYHmG7w6BmLmTCM7kmZjNKRXXEDWkiahUAP");

#[program]
pub mod init_if_needed {
    use super::*;

    pub fn increment(ctx: Context<Initialize>) -> Result<()> {
        let current_counter = ctx.accounts.my_pda.counter;
        ctx.accounts.my_pda.counter = current_counter + 1;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(
        init_if_needed,
        payer = signer,
        space = size_of::<MyPDA>() + 8,
        seeds = [],
        bump
    )]
    pub my_pda: Account<'info, MyPDA>,

    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
pub struct MyPDA {
    pub counter: u64,
}

Typescript 测试

import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { InitIfNeeded } from "../target/types/init_if_needed";

describe("init_if_needed", () => {
  // Configure the client to use the local cluster.
  anchor.setProvider(anchor.AnchorProvider.env());

  const program = anchor.workspace.InitIfNeeded as Program<InitIfNeeded>;

  it("Is initialized!", async () => {
    const [myPda, _bump] = anchor.web3.PublicKey.findProgramAddressSync([], program.programId);
    await program.methods.increment().accounts({myPda: myPda}).rpc();
    await program.methods.increment().accounts({myPda: myPda}).rpc();
    await program.methods.increment().accounts({myPda: myPda}).rpc();

    let result = await program.account.myPda.fetch(myPda);
    console.log(`counter is ${result.counter}`);
  });
});

构建错误

运行 anchor build 时,报错:

error: init_if_needed requires that anchor-lang be imported with the init-if-needed cargo feature enabled. Carefully read the init_if_needed docs before using this feature to make sure you know how to protect yourself against re-initialization attacks.
  --> programs/init_if_needed/src/lib.rs:20:9
   |
20 |         init_if_needed,
   |

解决方法:在 Cargo.toml 中启用特性:

[dependencies]
anchor-lang = { version = "0.29.0", features = ["init-if-needed"] }

但在使用前,需理解重新初始化攻击的风险。


默认初始化限制

Anchor 默认禁止账户重复初始化,若尝试初始化已存在账户,事务失败。

Anchor 的初始化判定

  • 未初始化:账户 lamports 余额为 0 或所有者为系统程序(111...111)。
  • 已初始化:账户由程序拥有且 lamports 非零。

验证示例

以下程序展示初始化限制及潜在漏洞:

Rust 实现


use anchor_lang::prelude::*;
use anchor_lang::system_program;
use std::mem::size_of;

declare_id!("43CvSmeND3dwybVMNsi3TVrrnAFvfxaXq1bXMuVsszGh");

#[program]
pub mod reinit_attack {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        Ok(())
    }

    pub fn drain_lamports(ctx: Context<DrainLamports>) -> Result<()> {
        let lamports = ctx.accounts.my_pda.to_account_info().lamports();
        ctx.accounts.my_pda.sub_lamports(lamports)?;
        ctx.accounts.signer.add_lamports(lamports)?;
        Ok(())
    }

    pub fn give_to_system_program(ctx: Context<GiveToSystemProgram>) -> Result<()> {
        let account_info = &mut ctx.accounts.my_pda.to_account_info();...

剩余50%的内容订阅专栏后可查看

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
0xE
0xE
0x59f6...a17e
17年进入币圈,Web3 开发者。刨根问底探链上真相,品味坎坷悟 Web3 人生。