I'm trying to write a simple Solana Program using Rust/Anchor which uses a PDA.
Here is the Program code:
use anchor_lang::prelude::*;
declare_id!("51v31qHaEQniLoYuvvtXByZcfiyvog3R2EKC39EPD52p");
#[program]
pub mod solana_sandbox {
use super::*;
pub fn initialize(ctx: Context<Initialize>, bump: u8) -> ProgramResult {
ctx.accounts.sandbox_account.bump = bump;
Ok(())
}
}
#[derive(Accounts)]
#[instruction(bump: u8)]
pub struct Initialize<'info> {
#[account(mut)]
pub signer: Signer<'info>,
#[account(
init,
seeds = [b"seed".as_ref()],
bump,
payer = signer,
)]
pub sandbox_account: Account<'info, SandboxAccount>,
pub system_program: Program<'info, System>,
}
#[account]
#[derive(Default)]
pub struct SandboxAccount {
pub bump: u8,
}
Here is the client code:
const [sandboxPda, sandboxBump] = await PublicKey.findProgramAddress([Buffer.from('seed')], this.program.programId);
await program.rpc.initialize(
sandboxBump,
{
accounts: {
signer: keypair.publicKey,
sandboxAccount: sandboxPda,
systemProgram: anchor.web3.SystemProgram.programId,
},
signers: [keypair],
instructions: []
});
It works correctly, but I have a doubt. I get sandboxBump from findProgramAddress and input this but it isn't used.
If I set bump when init like this :
#[account(
init,
seeds = [b"seed".as_ref()],
bump = bump,
payer = signer,
)]
Error occurred. So I delete the instruction macro from the program code but it still works correctly. So is bump value no need when PDA initialization or does anchor system use it automatically?
Appreciate any help!
For enhanced security Solana makes sure all the Program Address will not lie on the ed25519 curve
. As the address is not on the curve there will no be associated private key hence no risk.
For generating program address solana uses 256-bit pre-image resistant hash function using collection of seeds and a program id as input, as it's output can't be predicted in advance and can't be controlled in any manner there is 50% chance of newly generated address will lie on ed25519
curve. In such case where generated address is on curve, which is prohibited by solana. Solana will use a different set of seeds or a seed bump to find a valid address (address off the curve).
In short bump
will be used only in case where provided input doesn't generate a valid program address.
Program addresses are deterministically derived from a collection of seeds and a program id using a 256-bit pre-image resistant hash function. Program address must not lie on the ed25519 curve to ensure there is no associated private key. During generation, an error will be returned if the address is found to lie on the curve. There is about a 50/50 chance of this happening for a given collection of seeds and program id. If this occurs a different set of seeds or a seed bump (additional 8 bit seed) can be used to find a valid program address off the curve.
references: