使用不同签名者修改账户:Solana 中的权限控制

  • 0xE
  • 发布于 2025-04-01 10:25
  • 阅读 505

本教程将展示如何在 Solana Anchor 中用不同签名者(Signer)初始化和更新账户,并探讨权限控制机制。

此前文章中,我们仅使用单一签名者初始化并修改账户,功能受限。现实场景中,如 Alice 向 Bob 转移积分,需允许 Alice 修改 Bob 创建的账户。本教程将展示如何在 Solana Anchor 中用不同签名者(Signer)初始化和更新账户,并探讨权限控制机制。


初始化账户

初始化账户的 Rust 代码保持不变,使用标准 Anchor 模式创建账户。

Rust 实现

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

declare_id!("26Kiu5LSV5xXDN3yGwE8L6aU59kKRKdyyKtSQv5Vu5VC");

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

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

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

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

    pub system_program: Program<'info, System>,
}

#[account]
pub struct MyStorage {
    x: u64,
}

客户端调整

测试代码引入新签名者,需显式指定:

  • 创建 newKeypair 模拟新用户。
  • 空投 1 SOL 支付交易费用。
  • 显式传递 signer 公钥并配置 .signers()。

测试代码

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

// this airdrops sol to an address
async function airdropSol(publicKey, amount) {
  let airdropTx = await anchor.getProvider().connection.requestAirdrop(publicKey, amount);
  await confirmTransaction(airdropTx);
}

async function confirmTransaction(tx) {
  const latestBlockHash = await anchor.getProvider().connection.getLatestBlockhash();
  await anchor.getProvider().connection.confirmTransaction({
    blockhash: latestBlockHash.blockhash,
    lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
    signature: tx,
  });
}

describe("other_write", () => {
  anchor.setProvider(anchor.AnchorProvider.env());

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

  it("Is initialized!", async () => {
    const newKeypair = anchor.web3.Keypair.generate();
    await airdropSol(newKeypair.publicKey, 1e9); // 1 SOL

    let seeds = [];
    const [myStorage, _bump] = anchor.web3.PublicKey.findProgramAddressSync(seeds, program.programId);

    await program.methods.initialize().accounts({
      myStorage: myStorage,
      signer: newKeypair.publicKey // ** THIS MUST BE EXPLICITLY SPECIFIED **
    }).signers([newKeypair]).rpc();
  });
});

为何两次指定签名者?

  • .accounts({ signer: ... }):指定账户结构中的 Signer 公钥,Anchor 验证其与交易签名匹配。
  • .signers([newKeypair]):提供私钥签名交易,默认签名者无需此步骤。

字段名可自定义(如 fren 替代 signer),只需 Rust 与客户端一致。


签名者验证机制

Anchor 的 Signer 类型

Signer<'info> 表示交易签名者,Anchor 自动验证其公钥与签名一致。若使用非默认签名者,需显式传递公钥,否则 Anchor 默认使用环境签名者(provider wallet)。

“未知签名者”错误

若签名与公钥不匹配,会触发错误:

  • 省略 .signers([newKeypair]):默认签名者与 newKeypair.publicKey 不符,导致 Missing signature。
  • 省略 signer: newKeypair.publicKey:Anchor 使用默认签名者,签名不匹配 newKeypair,报 unknown signer。

跨用户修改账户

以下程序展示 Alice 初始化账户,Bob 更新其值。

Rust 实现

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

declare_id!("26Kiu5LSV5xXDN3yGwE8L6aU59kKRKdyyKtSQv5Vu5VC");

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

    pub fn initialize(ctx: Context&lt;Initialize>) -> Result&lt;()> {
        Ok(())
    }

    pub fn update_value(ctx: Context&lt;UpdateValue>, new_value: u64) -> Result&lt;()> {
        ctx.accounts.my_storage.x = new_value;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize&lt;'info> {
    #[account(init,
              payer = fren,
              space=size_of::&lt;MyStorage>() + 8,
              seeds = [],
              bump)]
    pub my_storage: Account&lt;'info, MyStorage>,

    #[account(mut)]
    pub fren: Signer&lt;'info>, // A public key is passed here

    pub system_program: Program&lt;'info, System>,
}

#[derive(Accounts)]
pub struct UpdateValue&lt;'info> {
    #[account(mut, seeds = [], bump)]
    pub my_storage: Account&lt;'info, MyStorage>,

      // THIS FIELD MUST BE INCLUDED
    #[account(mut)]
    pub fren: Signer&lt;'info>,
}

#[account]
pub struct MyStorage {
    x: u64,
}

测试代码


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

// this airdrops sol to an address
async function airdropSol(publicKey, amount) {
  let airdropTx = await anchor.getProvider().connection.requestAirdrop(publicKey, amount);
  await confirmTransaction(airdropTx);
}

async function confirmTransaction(tx) {
  const latestBlockHash = await anchor.getProvider().connection.getLatestBlockhash();
  await anchor.getProvider().connection.confirmTransaction({
    blockhash: latestBlockHash.blockhash,
    lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
    signature: tx,
  });
}

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

  const program = anchor.workspace.OtherWrite as Program&lt;OtherWrite>;

  it("Is initialized!", async () => {
    const alice = anchor.web3.Keypair.generate();
    const bob = anchor.web3.Keypair.generate();

    const airdrop_alice_tx = await anchor.getProvider().connection.requestAirdrop(alice.publicKey, 1 * anchor.web3.LAMPORTS_PER_SOL);
    await confirmTransaction(airdrop_alice_tx);

    const airdrop_alice_bob = await anchor.getProvider().connection.requestAirdrop(bob.publicKey, 1 * anchor.web3.LAMPOINTS_PER_SOL);
    await confirmTransaction(airdrop_alice_bob);...

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

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

0 条评论

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