pub struct Pubkey(/* private fields */);
Expand description

The address of a Solana account.

Some account addresses are ed25519 public keys, with corresponding secret keys that are managed off-chain. Often, though, account addresses do not have corresponding secret keys — as with program derived addresses — or the secret key is not relevant to the operation of a program, and may have even been disposed of. As running Solana programs can not safely create or manage secret keys, the full Keypair is not defined in solana-program but in solana-sdk.

Implementations§

§

impl Pubkey

pub fn new(pubkey_vec: &[u8]) -> Pubkey

👎Deprecated since 1.14.14: Please use ‘Pubkey::from’ or ‘Pubkey::try_from’ instead

pub const fn new_from_array(pubkey_array: [u8; 32]) -> Pubkey

pub fn new_rand() -> Pubkey

👎Deprecated since 1.3.9: Please use ‘Pubkey::new_unique’ instead

pub fn new_unique() -> Pubkey

unique Pubkey for tests and benchmarks.

pub fn create_with_seed( base: &Pubkey, seed: &str, owner: &Pubkey ) -> Result<Pubkey, PubkeyError>

pub fn find_program_address( seeds: &[&[u8]], program_id: &Pubkey ) -> (Pubkey, u8)

Find a valid program derived address and its corresponding bump seed.

Program derived addresses (PDAs) are account keys that only the program, program_id, has the authority to sign. The address is of the same form as a Solana Pubkey, except they are ensured to not be on the ed25519 curve and thus have no associated private key. When performing cross-program invocations the program can “sign” for the key by calling invoke_signed and passing the same seeds used to generate the address, along with the calculated bump seed, which this function returns as the second tuple element. The runtime will verify that the program associated with this address is the caller and thus authorized to be the signer.

The seeds are application-specific, and must be carefully selected to uniquely derive accounts per application requirements. It is common to use static strings and other pubkeys as seeds.

Because the program address must not lie on the ed25519 curve, there may be seed and program id combinations that are invalid. For this reason, an extra seed (the bump seed) is calculated that results in a point off the curve. The bump seed must be passed as an additional seed when calling invoke_signed.

The processes of finding a valid program address is by trial and error, and even though it is deterministic given a set of inputs it can take a variable amount of time to succeed across different inputs. This means that when called from an on-chain program it may incur a variable amount of the program’s compute budget. Programs that are meant to be very performant may not want to use this function because it could take a considerable amount of time. Programs that are already at risk of exceeding their compute budget should call this with care since there is a chance that the program’s budget may be occasionally and unpredictably exceeded.

As all account addresses accessed by an on-chain Solana program must be explicitly passed to the program, it is typical for the PDAs to be derived in off-chain client programs, avoiding the compute cost of generating the address on-chain. The address may or may not then be verified by re-deriving it on-chain, depending on the requirements of the program. This verification may be performed without the overhead of re-searching for the bump key by using the create_program_address function.

Warning: Because of the way the seeds are hashed there is a potential for program address collisions for the same program id. The seeds are hashed sequentially which means that seeds {“abcdef”}, {“abc”, “def”}, and {“ab”, “cd”, “ef”} will all result in the same program address given the same program id. Since the chance of collision is local to a given program id, the developer of that program must take care to choose seeds that do not collide with each other. For seed schemes that are susceptible to this type of hash collision, a common remedy is to insert separators between seeds, e.g. transforming {“abc”, “def”} into {“abc”, “-”, “def”}.

§Panics

Panics in the statistically improbable event that a bump seed could not be found. Use try_find_program_address to handle this case.

Panics if any of the following are true:

  • the number of provided seeds is greater than, or equal to, MAX_SEEDS,
  • any individual seed’s length is greater than MAX_SEED_LEN.
§Examples

This example illustrates a simple case of creating a “vault” account which is derived from the payer account, but owned by an on-chain program. The program derived address is derived in an off-chain client program, which invokes an on-chain Solana program that uses the address to create a new account owned and controlled by the program itself.

By convention, the on-chain program will be compiled for use in two different contexts: both on-chain, to interpret a custom program instruction as a Solana transaction; and off-chain, as a library, so that clients can share the instruction data structure, constructors, and other common code.

First the on-chain Solana program:

// The custom instruction processed by our program. It includes the
// PDA's bump seed, which is derived by the client program. This
// definition is also imported into the off-chain client program.
// The computed address of the PDA will be passed to this program via
// the `accounts` vector of the `Instruction` type.
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct InstructionData {
    pub vault_bump_seed: u8,
    pub lamports: u64,
}

// The size in bytes of a vault account. The client program needs
// this information to calculate the quantity of lamports necessary
// to pay for the account's rent.
pub static VAULT_ACCOUNT_SIZE: u64 = 1024;

// The entrypoint of the on-chain program, as provided to the
// `entrypoint!` macro.
fn process_instruction(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    instruction_data: &[u8],
) -> ProgramResult {
    let account_info_iter = &mut accounts.iter();
    let payer = next_account_info(account_info_iter)?;
    // The vault PDA, derived from the payer's address
    let vault = next_account_info(account_info_iter)?;

    let mut instruction_data = instruction_data;
    let instr = InstructionData::deserialize(&mut instruction_data)?;
    let vault_bump_seed = instr.vault_bump_seed;
    let lamports = instr.lamports;
    let vault_size = VAULT_ACCOUNT_SIZE;

    // Invoke the system program to create an account while virtually
    // signing with the vault PDA, which is owned by this caller program.
    invoke_signed(
        &system_instruction::create_account(
            &payer.key,
            &vault.key,
            lamports,
            vault_size,
            &program_id,
        ),
        &[
            payer.clone(),
            vault.clone(),
        ],
        // A slice of seed slices, each seed slice being the set
        // of seeds used to generate one of the PDAs required by the
        // callee program, the final seed being a single-element slice
        // containing the `u8` bump seed.
        &[
            &[
                b"vault",
                payer.key.as_ref(),
                &[vault_bump_seed],
            ],
        ]
    )?;

    Ok(())
}

The client program:

fn create_vault_account(
    client: &RpcClient,
    program_id: Pubkey,
    payer: &Keypair,
) -> Result<()> {
    // Derive the PDA from the payer account, a string representing the unique
    // purpose of the account ("vault"), and the address of our on-chain program.
    let (vault_pubkey, vault_bump_seed) = Pubkey::find_program_address(
        &[b"vault", payer.pubkey().as_ref()],
        &program_id
    );

    // Get the amount of lamports needed to pay for the vault's rent
    let vault_account_size = usize::try_from(VAULT_ACCOUNT_SIZE)?;
    let lamports = client.get_minimum_balance_for_rent_exemption(vault_account_size)?;

    // The on-chain program's instruction data, imported from that program's crate.
    let instr_data = InstructionData {
        vault_bump_seed,
        lamports,
    };

    // The accounts required by both our on-chain program and the system program's
    // `create_account` instruction, including the vault's address.
    let accounts = vec![
        AccountMeta::new(payer.pubkey(), true),
        AccountMeta::new(vault_pubkey, false),
        AccountMeta::new(system_program::ID, false),
    ];

    // Create the instruction by serializing our instruction data via borsh
    let instruction = Instruction::new_with_borsh(
        program_id,
        &instr_data,
        accounts,
    );

    let blockhash = client.get_latest_blockhash()?;

    let transaction = Transaction::new_signed_with_payer(
        &[instruction],
        Some(&payer.pubkey()),
        &[payer],
        blockhash,
    );

    client.send_and_confirm_transaction(&transaction)?;

    Ok(())
}

pub fn try_find_program_address( seeds: &[&[u8]], program_id: &Pubkey ) -> Option<(Pubkey, u8)>

Find a valid program derived address and its corresponding bump seed.

The only difference between this method and find_program_address is that this one returns None in the statistically improbable event that a bump seed cannot be found; or if any of find_program_address’s preconditions are violated.

See the documentation for find_program_address for a full description.

pub fn create_program_address( seeds: &[&[u8]], program_id: &Pubkey ) -> Result<Pubkey, PubkeyError>

Create a valid program derived address without searching for a bump seed.

Because this function does not create a bump seed, it may unpredictably return an error for any given set of seeds and is not generally suitable for creating program derived addresses.

However, it can be used for efficiently verifying that a set of seeds plus bump seed generated by find_program_address derives a particular address as expected. See the example for details.

See the documentation for find_program_address for a full description of program derived addresses and bump seeds.

§Examples

Creating a program derived address involves iteratively searching for a bump seed for which the derived Pubkey does not lie on the ed25519 curve. This search process is generally performed off-chain, with the find_program_address function, after which the client passes the bump seed to the program as instruction data.

Depending on the application requirements, a program may wish to verify that the set of seeds, plus the bump seed, do correctly generate an expected address.

The verification is performed by appending to the other seeds one additional seed slice that contains the single u8 bump seed, calling create_program_address, checking that the return value is Ok, and that the returned Pubkey has the expected value.

let (expected_pda, bump_seed) = Pubkey::find_program_address(&[b"vault"], &program_id);
let actual_pda = Pubkey::create_program_address(&[b"vault", &[bump_seed]], &program_id)?;
assert_eq!(expected_pda, actual_pda);

pub const fn to_bytes(self) -> [u8; 32]

pub fn is_on_curve(&self) -> bool

pub fn log(&self)

Log a Pubkey from a program

Trait Implementations§

§

impl BorshDeserialize for Pubkey

§

fn deserialize_reader<R>(reader: &mut R) -> Result<Pubkey, Error>
where R: Read,

§

fn deserialize(buf: &mut &[u8]) -> Result<Self, Error>

Deserializes this instance from a given slice of bytes. Updates the buffer to point at the remaining bytes.
§

fn try_from_slice(v: &[u8]) -> Result<Self, Error>

Deserialize this instance from a slice of bytes.
§

fn try_from_reader<R>(reader: &mut R) -> Result<Self, Error>
where R: Read,

§

impl BorshSerialize for Pubkey

§

fn serialize<W>(&self, writer: &mut W) -> Result<(), Error>
where W: Write,

§

fn try_to_vec(&self) -> Result<Vec<u8>, Error>

Serialize this instance into a vector of bytes.
§

impl AsMut<[u8]> for Pubkey

§

fn as_mut(&mut self) -> &mut [u8]

Converts this type into a mutable reference of the (usually inferred) input type.
§

impl AsRef<[u8]> for Pubkey

§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
§

impl BorshDeserialize for Pubkey

§

fn deserialize(buf: &mut &[u8]) -> Result<Pubkey, Error>

Deserializes this instance from a given slice of bytes. Updates the buffer to point at the remaining bytes.
§

fn try_from_slice(v: &[u8]) -> Result<Self, Error>

Deserialize this instance from a slice of bytes.
§

impl BorshDeserialize for Pubkey

§

fn deserialize_reader<__R>(reader: &mut __R) -> Result<Pubkey, Error>
where __R: Read,

§

fn deserialize(buf: &mut &[u8]) -> Result<Self, Error>

Deserializes this instance from a given slice of bytes. Updates the buffer to point at the remaining bytes.
§

fn try_from_slice(v: &[u8]) -> Result<Self, Error>

Deserialize this instance from a slice of bytes.
§

fn try_from_reader<R>(reader: &mut R) -> Result<Self, Error>
where R: Read,

§

impl BorshSchema for Pubkey

§

fn declaration() -> String

Get the name of the type without brackets.
§

fn add_definitions_recursively(definitions: &mut BTreeMap<String, Definition>)

Recursively, using DFS, add type definitions required for this type. Type definition partially explains how to serialize/deserialize a type.
§

impl BorshSchema for Pubkey
where [u8; 32]: BorshSchema,

§

fn declaration() -> String

Get the name of the type without brackets.
§

fn add_definitions_recursively(definitions: &mut HashMap<String, Definition>)

Recursively, using DFS, add type definitions required for this type. For primitive types this is an empty map. Type definition explains how to serialize/deserialize a type.
§

fn add_definition( declaration: String, definition: Definition, definitions: &mut HashMap<String, Definition> )

Helper method to add a single type definition to the map.
§

fn schema_container() -> BorshSchemaContainer

§

impl BorshSchema for Pubkey
where [u8; 32]: BorshSchema,

§

fn declaration() -> String

Get the name of the type without brackets.
§

fn add_definitions_recursively(definitions: &mut HashMap<String, Definition>)

Recursively, using DFS, add type definitions required for this type. For primitive types this is an empty map. Type definition explains how to serialize/deserialize a type.
§

fn add_definition( declaration: String, definition: Definition, definitions: &mut HashMap<String, Definition> )

Helper method to add a single type definition to the map.
§

fn schema_container() -> BorshSchemaContainer

§

impl BorshSerialize for Pubkey

§

fn serialize<__W>(&self, writer: &mut __W) -> Result<(), Error>
where __W: Write,

§

impl BorshSerialize for Pubkey

§

fn serialize<W>(&self, writer: &mut W) -> Result<(), Error>
where W: Write,

§

fn try_to_vec(&self) -> Result<Vec<u8>, Error>

Serialize this instance into a vector of bytes.
§

impl Clone for Pubkey

§

fn clone(&self) -> Pubkey

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for Pubkey

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for Pubkey

§

fn default() -> Pubkey

Returns the “default value” for a type. Read more
§

impl<'de> Deserialize<'de> for Pubkey

§

fn deserialize<__D>( __deserializer: __D ) -> Result<Pubkey, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
§

impl Display for Pubkey

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl From<[u8; 32]> for Pubkey

§

fn from(from: [u8; 32]) -> Pubkey

Converts to this type from the input type.
§

impl FromStr for Pubkey

§

type Err = ParsePubkeyError

The associated error which can be returned from parsing.
§

fn from_str(s: &str) -> Result<Pubkey, <Pubkey as FromStr>::Err>

Parses a string s to return a value of this type. Read more
§

impl FromWasmAbi for Pubkey

§

type Abi = u32

The wasm ABI type that this converts from when coming back out from the ABI boundary.
§

unsafe fn from_abi(js: u32) -> Pubkey

Recover a Self from Self::Abi. Read more
§

impl Hash for Pubkey

§

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
§

impl IntoWasmAbi for Pubkey

§

type Abi = u32

The wasm ABI type that this converts into when crossing the ABI boundary.
§

fn into_abi(self) -> u32

Convert self into Self::Abi so that it can be sent across the wasm ABI boundary.
§

impl Key for Pubkey

§

fn key(&self) -> Pubkey

§

impl LongRefFromWasmAbi for Pubkey

§

type Abi = u32

Same as RefFromWasmAbi::Abi
§

type Anchor = Ref<'static, Pubkey>

Same as RefFromWasmAbi::Anchor
§

unsafe fn long_ref_from_abi( js: <Pubkey as LongRefFromWasmAbi>::Abi ) -> <Pubkey as LongRefFromWasmAbi>::Anchor

Same as RefFromWasmAbi::ref_from_abi
§

impl OptionFromWasmAbi for Pubkey

§

fn is_none(abi: &<Pubkey as FromWasmAbi>::Abi) -> bool

Tests whether the argument is a “none” instance. If so it will be deserialized as None, and otherwise it will be passed to FromWasmAbi.
§

impl OptionIntoWasmAbi for Pubkey

§

fn none() -> <Pubkey as IntoWasmAbi>::Abi

Returns an ABI instance indicating “none”, which JS will interpret as the None branch of this option. Read more
§

impl Ord for Pubkey

§

fn cmp(&self, other: &Pubkey) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
§

impl PartialEq for Pubkey

§

fn eq(&self, other: &Pubkey) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl PartialOrd for Pubkey

§

fn partial_cmp(&self, other: &Pubkey) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
§

impl RefFromWasmAbi for Pubkey

§

type Abi = u32

The wasm ABI type references to Self are recovered from.
§

type Anchor = Ref<'static, Pubkey>

The type that holds the reference to Self for the duration of the invocation of the function that has an &Self parameter. This is required to ensure that the lifetimes don’t persist beyond one function call, and so that they remain anonymous.
§

unsafe fn ref_from_abi( js: <Pubkey as RefFromWasmAbi>::Abi ) -> <Pubkey as RefFromWasmAbi>::Anchor

Recover a Self::Anchor from Self::Abi. Read more
§

impl RefMutFromWasmAbi for Pubkey

§

type Abi = u32

Same as RefFromWasmAbi::Abi
§

type Anchor = RefMut<'static, Pubkey>

Same as RefFromWasmAbi::Anchor
§

unsafe fn ref_mut_from_abi( js: <Pubkey as RefMutFromWasmAbi>::Abi ) -> <Pubkey as RefMutFromWasmAbi>::Anchor

Same as RefFromWasmAbi::ref_from_abi
§

impl Sanitize for Pubkey

§

impl Serialize for Pubkey

§

fn serialize<__S>( &self, __serializer: __S ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
§

impl TryFrom<&[u8]> for Pubkey

§

type Error = TryFromSliceError

The type returned in the event of a conversion error.
§

fn try_from(pubkey: &[u8]) -> Result<Pubkey, <Pubkey as TryFrom<&[u8]>>::Error>

Performs the conversion.
§

impl TryFrom<&str> for Pubkey

§

type Error = ParsePubkeyError

The type returned in the event of a conversion error.
§

fn try_from(s: &str) -> Result<Pubkey, <Pubkey as TryFrom<&str>>::Error>

Performs the conversion.
§

impl TryFrom<Vec<u8>> for Pubkey

§

type Error = Vec<u8>

The type returned in the event of a conversion error.
§

fn try_from( pubkey: Vec<u8> ) -> Result<Pubkey, <Pubkey as TryFrom<Vec<u8>>>::Error>

Performs the conversion.
§

impl TryFromJsValue for Pubkey

§

type Error = JsValue

The type returned in the event of a conversion error.
§

fn try_from_js_value( value: JsValue ) -> Result<Pubkey, <Pubkey as TryFromJsValue>::Error>

Performs the conversion.
§

impl VectorFromWasmAbi for Pubkey

§

type Abi = <Box<[JsValue]> as FromWasmAbi>::Abi

§

unsafe fn vector_from_abi( js: <Pubkey as VectorFromWasmAbi>::Abi ) -> Box<[Pubkey]>

§

impl VectorIntoWasmAbi for Pubkey

§

impl Zeroable for Pubkey

§

fn zeroed() -> Self

§

impl Copy for Pubkey

§

impl Eq for Pubkey

§

impl Pod for Pubkey

§

impl StructuralPartialEq for Pubkey

Auto Trait Implementations§

§

impl Freeze for Pubkey

§

impl RefUnwindSafe for Pubkey

§

impl Send for Pubkey

§

impl Sync for Pubkey

§

impl Unpin for Pubkey

§

impl UnwindSafe for Pubkey

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> CheckedBitPattern for T
where T: AnyBitPattern,

§

type Bits = T

Self must have the same layout as the specified Bits except for the possible invalid bit patterns being checked during is_valid_bit_pattern.
§

fn is_valid_bit_pattern(_bits: &T) -> bool

If this function returns true, then it must be valid to reinterpret bits as &Self.
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> ReturnWasmAbi for T
where T: IntoWasmAbi,

§

type Abi = <T as IntoWasmAbi>::Abi

Same as IntoWasmAbi::Abi
source§

fn return_abi(self) -> <T as ReturnWasmAbi>::Abi

Same as IntoWasmAbi::into_abi, except that it may throw and never return in the case of Err.
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> AnyBitPattern for T
where T: Pod,

source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

§

impl<T> NoUninit for T
where T: Pod,