And short descriptions to all solana-program modules and macros. (#24128)

* And short descriptions to all solana-program modules and macros.

Also fill out some of the docs within these modules.

* Update sdk/program/src/lib.rs

Co-authored-by: Tyera Eulberg <teulberg@gmail.com>

* Update sdk/program/src/sanitize.rs

Co-authored-by: Tyera Eulberg <teulberg@gmail.com>

* Update sdk/program/src/pubkey.rs

Co-authored-by: Tyera Eulberg <teulberg@gmail.com>

* Update sdk/program/src/program_memory.rs

Co-authored-by: Tyera Eulberg <teulberg@gmail.com>

* Update sdk/program/src/program_memory.rs

Co-authored-by: Tyera Eulberg <teulberg@gmail.com>

* Update sdk/program/src/program_memory.rs

Co-authored-by: Tyera Eulberg <teulberg@gmail.com>

* Update sdk/program/src/program_memory.rs

Co-authored-by: Tyera Eulberg <teulberg@gmail.com>

* Update sdk/program/src/program_memory.rs

Co-authored-by: Tyera Eulberg <teulberg@gmail.com>

* Update hash module docs

* Make solana-program crate docs match Pubkey docs

* Update sdk/program/src/program_memory.rs

Co-authored-by: Tyera Eulberg <teulberg@gmail.com>
This commit is contained in:
Brian Anderson 2022-04-20 20:20:17 -05:00 committed by GitHub
parent b42f34a7b8
commit 658752cda7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
44 changed files with 399 additions and 130 deletions

View File

@ -1,3 +1,5 @@
//! Account information.
use { use {
crate::{ crate::{
clock::Epoch, debug_account_data::*, program_error::ProgramError, clock::Epoch, debug_account_data::*, program_error::ProgramError,

View File

@ -1,3 +1,9 @@
//! The definition of address lookup table accounts.
//!
//! As used by the [`v0` message format][v0].
//!
//! [v0]: crate::message::v0
use solana_program::pubkey::Pubkey; use solana_program::pubkey::Pubkey;
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Clone)]

View File

@ -1,4 +1,7 @@
//! The `blake3` module provides functions for creating hashes. //! Hashing with the [blake3] hash function.
//!
//! [blake3]: https://github.com/BLAKE3-team/BLAKE3
use { use {
crate::sanitize::Sanitize, crate::sanitize::Sanitize,
borsh::{BorshDeserialize, BorshSchema, BorshSerialize}, borsh::{BorshDeserialize, BorshSchema, BorshSerialize},
@ -6,10 +9,12 @@ use {
thiserror::Error, thiserror::Error,
}; };
/// Size of hash /// Size of a hash in bytes.
pub const HASH_BYTES: usize = 32; pub const HASH_BYTES: usize = 32;
/// Maximum string length of a base58 encoded hash /// Maximum string length of a base58 encoded hash.
const MAX_BASE58_LEN: usize = 44; const MAX_BASE58_LEN: usize = 44;
/// A blake3 hash.
#[derive( #[derive(
Serialize, Serialize,
Deserialize, Deserialize,

View File

@ -1,5 +1,7 @@
#![allow(clippy::integer_arithmetic)] #![allow(clippy::integer_arithmetic)]
//! Borsh utils //! Utilities for the [borsh] serialization format.
//!
//! [borsh]: https://borsh.io/
use { use {
borsh::{ borsh::{
maybestd::io::{Error, Write}, maybestd::io::{Error, Write},

View File

@ -1,4 +1,4 @@
//! The latest Solana BPF loader. //! The latest BPF loader native program.
//! //!
//! The BPF loader is responsible for loading, finalizing, and executing BPF //! The BPF loader is responsible for loading, finalizing, and executing BPF
//! programs. Not all networks may support the latest loader. You can use the //! programs. Not all networks may support the latest loader. You can use the
@ -11,7 +11,14 @@
//! located in `entrypoint.rs`. //! located in `entrypoint.rs`.
//! //!
//! Note: Programs built for older loaders must use a matching entrypoint //! Note: Programs built for older loaders must use a matching entrypoint
//! version. An example is `bpf_loader_deprecated.rs` which requires //! version. An example is [`bpf_loader_deprecated`] which requires
//! `entrypoint_deprecated.rs`. //! [`entrypoint_deprecated`].
//!
//! The `solana deploy` and `solana program deploy` CLI commands use the
//! [upgradeable BPF loader][ubpfl].
//!
//! [`bpf_loader_deprecated`]: crate::bpf_loader_deprecated
//! [`entrypoint_deprecated`]: mod@crate::entrypoint_deprecated
//! [ubpfl]: crate::bpf_loader_upgradeable
crate::declare_id!("BPFLoader2111111111111111111111111111111111"); crate::declare_id!("BPFLoader2111111111111111111111111111111111");

View File

@ -1,4 +1,4 @@
//! An Upgradeable Solana BPF loader. //! An upgradeable BPF loader native program.
//! //!
//! The upgradeable BPF loader is responsible for deploying, upgrading, and //! The upgradeable BPF loader is responsible for deploying, upgrading, and
//! executing BPF programs. The upgradeable loader allows a program's authority //! executing BPF programs. The upgradeable loader allows a program's authority
@ -6,7 +6,14 @@
//! contract the usually enforces the policy that once a program is on-chain it //! contract the usually enforces the policy that once a program is on-chain it
//! becomes immutable. Because of this, care should be taken before executing //! becomes immutable. Because of this, care should be taken before executing
//! upgradeable programs which still have a functioning authority. For more //! upgradeable programs which still have a functioning authority. For more
//! information refer to `loader_upgradeable_instruction.rs` //! information refer to the [`loader_upgradeable_instruction`] module.
//!
//! The `solana deploy` and `solana program deploy` CLI commands use the
//! upgradeable BPF loader. Calling `solana program deploy --final` deploys a
//! program that cannot be upgraded, but it does so by revoking the authority to
//! upgrade, not by using the non-upgradeable loader.
//!
//! [`loader_upgradeable_instruction`]: crate::loader_upgradeable_instruction
use { use {
crate::{ crate::{

View File

@ -1,4 +1,4 @@
//! Provides information about the network's clock which is made up of ticks, slots, etc... //! Information about the network's clock, ticks, slots, etc.
// The default tick rate that the cluster attempts to achieve. Note that the actual tick // The default tick rate that the cluster attempts to achieve. Note that the actual tick
// rate at any given time should be expected to drift // rate at any given time should be expected to drift

View File

@ -1,7 +1,13 @@
//! Debug-formatting of account data.
use std::{cmp, fmt}; use std::{cmp, fmt};
pub(crate) const MAX_DEBUG_ACCOUNT_DATA: usize = 64; pub(crate) const MAX_DEBUG_ACCOUNT_DATA: usize = 64;
/// Format data as hex.
///
/// If `data`'s length is greater than 0, add a field called "data" to `f`. The
/// first 64 bytes of `data` is displayed; bytes after that are ignored.
pub fn debug_account_data(data: &[u8], f: &mut fmt::DebugStruct<'_, '_>) { pub fn debug_account_data(data: &[u8], f: &mut fmt::DebugStruct<'_, '_>) {
let data_len = cmp::min(MAX_DEBUG_ACCOUNT_DATA, data.len()); let data_len = cmp::min(MAX_DEBUG_ACCOUNT_DATA, data.len());
if data_len > 0 { if data_len > 0 {

View File

@ -1,6 +1,26 @@
//! Converting custom error codes to enums.
use num_traits::FromPrimitive; use num_traits::FromPrimitive;
/// Allows custom errors to be decoded back to their original enum /// Allows custom errors to be decoded back to their original enum.
///
/// Some Solana error enums, like [`ProgramError`], include a `Custom` variant,
/// like [`ProgramError::Custom`], that contains a `u32` error code. This code
/// may represent any error that is not covered by the error enum's named
/// variants. It is common for programs to convert their own error enums to an
/// error code and store it in the `Custom` variant, possibly with the help of
/// the [`ToPrimitive`] trait.
///
/// This trait builds on the [`FromPrimitive`] trait to help convert those error
/// codes to the original error enum they represent.
///
/// As this allows freely converting `u32` to any type that implements
/// `FromPrimitive`, it is only used correctly when the caller is certain of the
/// original error type.
///
/// [`ProgramError`]: crate::program_error::ProgramError
/// [`ProgramError::Custom`]: crate::program_error::ProgramError::Custom
/// [`ToPrimitive`]: num_traits::ToPrimitive
pub trait DecodeError<E> { pub trait DecodeError<E> {
fn decode_custom_error_to_enum(custom: u32) -> Option<E> fn decode_custom_error_to_enum(custom: u32) -> Option<E>
where where

View File

@ -1 +1,5 @@
//! The [ed25519 native program][np].
//!
//! [np]: https://docs.solana.com/developing/runtime-facilities/programs#ed25519-program
crate::declare_id!("Ed25519SigVerify111111111111111111111111111"); crate::declare_id!("Ed25519SigVerify111111111111111111111111111");

View File

@ -1,5 +1,8 @@
//! Solana Rust-based BPF program entry point supported by the latest //! The Rust-based BPF program entry point supported by the latest BPF loader.
//! BPFLoader. For more information see './bpf_loader.rs' //!
//! For more information see the [`bpf_loader`] module.
//!
//! [`bpf_loader`]: crate::bpf_loader
extern crate alloc; extern crate alloc;
use { use {

View File

@ -1,7 +1,13 @@
//! The Rust-based BPF program entry point supported by the original BPF loader.
//!
//! The original BPF loader is deprecated and exists for backwards-compatibility
//! reasons. This module should not be used by new programs.
//!
//! For more information see the [`bpf_loader_deprecated`] module.
//!
//! [`bpf_loader_deprecated`]: crate::bpf_loader_deprecated
#![allow(clippy::integer_arithmetic)] #![allow(clippy::integer_arithmetic)]
//! Solana Rust-based BPF program entry point supported by the original
//! and now deprecated BPFLoader. For more information see
//! './bpf_loader_deprecated.rs'
extern crate alloc; extern crate alloc;
use { use {
@ -29,7 +35,7 @@ pub type ProcessInstruction =
/// Programs indicate success with a return value of 0 /// Programs indicate success with a return value of 0
pub const SUCCESS: u64 = 0; pub const SUCCESS: u64 = 0;
/// Declare the entry point of the program. /// Declare the program entry point.
/// ///
/// Deserialize the program input arguments and call /// Deserialize the program input arguments and call
/// the user defined `process_instruction` function. /// the user defined `process_instruction` function.

View File

@ -1,4 +1,4 @@
//! configuration for epochs, slots //! Configuration for epochs and slots.
/// 1 Epoch = 400 * 8192 ms ~= 55 minutes /// 1 Epoch = 400 * 8192 ms ~= 55 minutes
pub use crate::clock::{Epoch, Slot, DEFAULT_SLOTS_PER_EPOCH}; pub use crate::clock::{Epoch, Slot, DEFAULT_SLOTS_PER_EPOCH};

View File

@ -1,3 +1,5 @@
//! Calculation of transaction fees.
#![allow(clippy::integer_arithmetic)] #![allow(clippy::integer_arithmetic)]
use { use {
crate::{clock::DEFAULT_MS_PER_SLOT, ed25519_program, message::Message, secp256k1_program}, crate::{clock::DEFAULT_MS_PER_SLOT, ed25519_program, message::Message, secp256k1_program},
@ -7,8 +9,10 @@ use {
#[derive(Serialize, Deserialize, Default, PartialEq, Eq, Clone, Debug, AbiExample)] #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Clone, Debug, AbiExample)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct FeeCalculator { pub struct FeeCalculator {
// The current cost of a signature This amount may increase/decrease over time based on /// The current cost of a signature.
// cluster processing load. ///
/// This amount may increase/decrease over time based on cluster processing
/// load.
pub lamports_per_signature: u64, pub lamports_per_signature: u64,
} }

View File

@ -1,4 +1,7 @@
//! The `hash` module provides functions for creating SHA-256 hashes. //! Hashing with the [SHA-256] hash function, and a general [`Hash`] type.
//!
//! [SHA-256]: https://en.wikipedia.org/wiki/SHA-2
//! [`Hash`]: struct@Hash
use { use {
crate::{sanitize::Sanitize, wasm_bindgen}, crate::{sanitize::Sanitize, wasm_bindgen},
@ -8,10 +11,21 @@ use {
thiserror::Error, thiserror::Error,
}; };
/// Size of a hash in bytes.
pub const HASH_BYTES: usize = 32; pub const HASH_BYTES: usize = 32;
/// Maximum string length of a base58 encoded hash /// Maximum string length of a base58 encoded hash.
const MAX_BASE58_LEN: usize = 44; const MAX_BASE58_LEN: usize = 44;
/// A hash; the 32-byte output of a hashing algorithm.
///
/// This struct is used most often in `solana-sdk` and related crates to contain
/// a [SHA-256] hash, but may instead contain a [blake3] hash, as created by the
/// [`blake3`] module (and used in [`Message::hash`]).
///
/// [SHA-256]: https://en.wikipedia.org/wiki/SHA-2
/// [blake3]: https://github.com/BLAKE3-team/BLAKE3
/// [`blake3`]: crate::blake3
/// [`Message::hash`]: crate::message::Message::hash
#[wasm_bindgen] #[wasm_bindgen]
#[derive( #[derive(
Serialize, Serialize,

View File

@ -1,4 +1,6 @@
//! Lamports credited to this address will be removed from the total supply (burned) at the end of //! A designated address for burning lamports.
//! the current block. //!
//! Lamports credited to this address will be removed from the total supply
//! (burned) at the end of the current block.
crate::declare_id!("1nc1nerator11111111111111111111111111111111"); crate::declare_id!("1nc1nerator11111111111111111111111111111111");

View File

@ -1,3 +1,7 @@
//! Hashing with the [keccak] (SHA-3) hash function.
//!
//! [keccak]: https://keccak.team/keccak.html
use { use {
crate::sanitize::Sanitize, crate::sanitize::Sanitize,
borsh::{BorshDeserialize, BorshSchema, BorshSerialize}, borsh::{BorshDeserialize, BorshSchema, BorshSerialize},

View File

@ -1,3 +1,5 @@
//! Defines the [`LamportsError`] type.
use {crate::instruction::InstructionError, thiserror::Error}; use {crate::instruction::InstructionError, thiserror::Error};
#[derive(Debug, Error)] #[derive(Debug, Error)]

View File

@ -154,14 +154,14 @@
//! //!
//! - [`Pubkey`] &mdash; The address of a [Solana account][acc]. Some account //! - [`Pubkey`] &mdash; The address of a [Solana account][acc]. Some account
//! addresses are [ed25519] public keys, with corresponding secret keys that //! addresses are [ed25519] public keys, with corresponding secret keys that
//! are managed off-chain. Often though account addresses do not have //! are managed off-chain. Often, though, account addresses do not have
//! corresponding secret keys, as with [_program derived addresses_][pdas], or //! corresponding secret keys &mdash; as with [_program derived
//! the secret key is not relevant to the operation of a program, and may have //! addresses_][pdas] &mdash; or the secret key is not relevant to the
//! even been disposed of. As running Solana programs can not safely create or //! operation of a program, and may have even been disposed of. As running
//! manage secret keys, the full [`Keypair`] is not defined in //! Solana programs can not safely create or manage secret keys, the full
//! `solana-program` but in `solana-sdk`. //! [`Keypair`] is not defined in `solana-program` but in `solana-sdk`.
//! - [`Hash`] &mdash; A [SHA-256] hash. Used to uniquely identify blocks, and //! - [`Hash`] &mdash; A cryptographic hash. Used to uniquely identify blocks,
//! also for general purpose hashing. //! and also for general purpose hashing.
//! - [`AccountInfo`] &mdash; A description of a single Solana account. All accounts //! - [`AccountInfo`] &mdash; A description of a single Solana account. All accounts
//! that might be accessed by a program invocation are provided to the program //! that might be accessed by a program invocation are provided to the program
//! entrypoint as `AccountInfo`. //! entrypoint as `AccountInfo`.
@ -612,26 +612,35 @@ pub mod wasm;
#[cfg(target_arch = "bpf")] #[cfg(target_arch = "bpf")]
pub use solana_sdk_macro::wasm_bindgen_stub as wasm_bindgen; pub use solana_sdk_macro::wasm_bindgen_stub as wasm_bindgen;
/// Re-export of [wasm-bindgen].
///
/// [wasm-bindgen]: https://rustwasm.github.io/docs/wasm-bindgen/
#[cfg(not(target_arch = "bpf"))] #[cfg(not(target_arch = "bpf"))]
pub use wasm_bindgen::prelude::wasm_bindgen; pub use wasm_bindgen::prelude::wasm_bindgen;
/// The [config native program][np].
///
/// [np]: https://docs.solana.com/developing/runtime-facilities/programs#config-program
pub mod config { pub mod config {
pub mod program { pub mod program {
crate::declare_id!("Config1111111111111111111111111111111111111"); crate::declare_id!("Config1111111111111111111111111111111111111");
} }
} }
/// The [vote native program][np].
///
/// [np]: https://docs.solana.com/developing/runtime-facilities/programs#vote-program
pub mod vote { pub mod vote {
pub mod program { pub mod program {
crate::declare_id!("Vote111111111111111111111111111111111111111"); crate::declare_id!("Vote111111111111111111111111111111111111111");
} }
} }
/// Same as `declare_id` except report that this id has been deprecated /// Same as [`declare_id`] except that it reports that this ID has been deprecated.
pub use solana_sdk_macro::program_declare_deprecated_id as declare_deprecated_id; pub use solana_sdk_macro::program_declare_deprecated_id as declare_deprecated_id;
/// Convenience macro to declare a static public key and functions to interact with it /// Convenience macro to declare a static public key and functions to interact with it.
/// ///
/// Input: a single literal base58 string representation of a program's id /// Input: a single literal base58 string representation of a program's ID.
/// ///
/// # Example /// # Example
/// ///
@ -651,9 +660,9 @@ pub use solana_sdk_macro::program_declare_deprecated_id as declare_deprecated_id
/// assert_eq!(id(), my_id); /// assert_eq!(id(), my_id);
/// ``` /// ```
pub use solana_sdk_macro::program_declare_id as declare_id; pub use solana_sdk_macro::program_declare_id as declare_id;
/// Convenience macro to define a static public key /// Convenience macro to define a static public key.
/// ///
/// Input: a single literal base58 string representation of a Pubkey /// Input: a single literal base58 string representation of a Pubkey.
/// ///
/// # Example /// # Example
/// ///
@ -674,95 +683,106 @@ extern crate serde_derive;
#[macro_use] #[macro_use]
extern crate solana_frozen_abi_macro; extern crate solana_frozen_abi_macro;
/// Convenience macro for doing integer division where the opersation's safety /// Convenience macro for doing integer division where the operation's safety
/// can be checked at compile-time /// can be checked at compile-time.
/// ///
/// Since `unchecked_div_by_const!()` is supposed to fail at compile-time, abuse /// Since `unchecked_div_by_const!()` is supposed to fail at compile-time, abuse
/// doctests to cover failure modes /// doctests to cover failure modes
/// Literal denominator div-by-zero fails ///
/// # Examples
///
/// Literal denominator div-by-zero fails:
///
/// ```compile_fail /// ```compile_fail
/// # use solana_program::unchecked_div_by_const; /// # use solana_program::unchecked_div_by_const;
/// # fn main() { /// # fn main() {
/// # let _ = unchecked_div_by_const!(10, 0); /// let _ = unchecked_div_by_const!(10, 0);
/// # } /// # }
/// ``` /// ```
/// # ///
/// # Const denominator div-by-zero fails /// Const denominator div-by-zero fails:
///
/// ```compile_fail /// ```compile_fail
/// # use solana_program::unchecked_div_by_const; /// # use solana_program::unchecked_div_by_const;
/// # fn main() { /// # fn main() {
/// # const D: u64 = 0; /// const D: u64 = 0;
/// # let _ = unchecked_div_by_const!(10, D); /// let _ = unchecked_div_by_const!(10, D);
/// # } /// # }
/// ``` /// ```
/// # ///
/// # Non-const denominator fails /// Non-const denominator fails:
///
/// ```compile_fail /// ```compile_fail
/// # use solana_program::unchecked_div_by_const; /// # use solana_program::unchecked_div_by_const;
/// # fn main() { /// # fn main() {
/// # let d = 0; /// let d = 0;
/// # let _ = unchecked_div_by_const!(10, d); /// let _ = unchecked_div_by_const!(10, d);
/// # } /// # }
/// ``` /// ```
/// # ///
/// Literal denominator div-by-zero fails /// Literal denominator div-by-zero fails:
///
/// ```compile_fail
/// # use solana_program::unchecked_div_by_const;
/// # fn main() {
/// const N: u64 = 10;
/// let _ = unchecked_div_by_const!(N, 0);
/// # }
/// ```
///
/// Const denominator div-by-zero fails:
///
/// ```compile_fail
/// # use solana_program::unchecked_div_by_const;
/// # fn main() {
/// const N: u64 = 10;
/// const D: u64 = 0;
/// let _ = unchecked_div_by_const!(N, D);
/// # }
/// ```
///
/// Non-const denominator fails:
///
/// ```compile_fail /// ```compile_fail
/// # use solana_program::unchecked_div_by_const; /// # use solana_program::unchecked_div_by_const;
/// # fn main() { /// # fn main() {
/// # const N: u64 = 10; /// # const N: u64 = 10;
/// # let _ = unchecked_div_by_const!(N, 0); /// let d = 0;
/// let _ = unchecked_div_by_const!(N, d);
/// # } /// # }
/// ``` /// ```
/// # ///
/// # Const denominator div-by-zero fails /// Literal denominator div-by-zero fails:
///
/// ```compile_fail /// ```compile_fail
/// # use solana_program::unchecked_div_by_const; /// # use solana_program::unchecked_div_by_const;
/// # fn main() { /// # fn main() {
/// # const N: u64 = 10; /// let n = 10;
/// # const D: u64 = 0; /// let _ = unchecked_div_by_const!(n, 0);
/// # let _ = unchecked_div_by_const!(N, D);
/// # } /// # }
/// ``` /// ```
/// # ///
/// # Non-const denominator fails /// Const denominator div-by-zero fails:
///
/// ```compile_fail /// ```compile_fail
/// # use solana_program::unchecked_div_by_const; /// # use solana_program::unchecked_div_by_const;
/// # fn main() { /// # fn main() {
/// # const N: u64 = 10; /// let n = 10;
/// # let d = 0; /// const D: u64 = 0;
/// # let _ = unchecked_div_by_const!(N, d); /// let _ = unchecked_div_by_const!(n, D);
/// # } /// # }
/// ``` /// ```
/// # ///
/// Literal denominator div-by-zero fails /// Non-const denominator fails:
///
/// ```compile_fail /// ```compile_fail
/// # use solana_program::unchecked_div_by_const; /// # use solana_program::unchecked_div_by_const;
/// # fn main() { /// # fn main() {
/// # let n = 10; /// let n = 10;
/// # let _ = unchecked_div_by_const!(n, 0); /// let d = 0;
/// let _ = unchecked_div_by_const!(n, d);
/// # } /// # }
/// ``` /// ```
/// #
/// # Const denominator div-by-zero fails
/// ```compile_fail
/// # use solana_program::unchecked_div_by_const;
/// # fn main() {
/// # let n = 10;
/// # const D: u64 = 0;
/// # let _ = unchecked_div_by_const!(n, D);
/// # }
/// ```
/// #
/// # Non-const denominator fails
/// ```compile_fail
/// # use solana_program::unchecked_div_by_const;
/// # fn main() {
/// # let n = 10;
/// # let d = 0;
/// # let _ = unchecked_div_by_const!(n, d);
/// # }
/// ```
/// #
#[macro_export] #[macro_export]
macro_rules! unchecked_div_by_const { macro_rules! unchecked_div_by_const {
($num:expr, $den:expr) => {{ ($num:expr, $den:expr) => {{

View File

@ -1,3 +1,7 @@
//! Instructions for the [non-upgradable BPF loader][nubpfl].
//!
//! [nubpfl]: crate::bpf_loader
use crate::{ use crate::{
instruction::{AccountMeta, Instruction}, instruction::{AccountMeta, Instruction},
pubkey::Pubkey, pubkey::Pubkey,

View File

@ -1,4 +1,6 @@
//! Upgradeable loader instruction definitions //! Instructions for the [upgradable BPF loader][ubpfl].
//!
//! [ubpfl]: crate::bpf_loader_upgradeable
#[repr(u8)] #[repr(u8)]
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]

View File

@ -35,6 +35,7 @@
use crate::account_info::AccountInfo; use crate::account_info::AccountInfo;
/// Print a message to the log.
#[macro_export] #[macro_export]
#[deprecated(since = "1.4.14", note = "Please use `msg` macro instead")] #[deprecated(since = "1.4.14", note = "Please use `msg` macro instead")]
macro_rules! info { macro_rules! info {

View File

@ -1,4 +1,7 @@
//! Definitions for the native SOL token and its fractional lamports.
#![allow(clippy::integer_arithmetic)] #![allow(clippy::integer_arithmetic)]
/// There are 10^9 lamports in one SOL /// There are 10^9 lamports in one SOL
pub const LAMPORTS_PER_SOL: u64 = 1_000_000_000; pub const LAMPORTS_PER_SOL: u64 = 1_000_000_000;

View File

@ -1,3 +1,5 @@
//! Cross-program invocation.
use crate::{ use crate::{
account_info::AccountInfo, entrypoint::ProgramResult, instruction::Instruction, pubkey::Pubkey, account_info::AccountInfo, entrypoint::ProgramResult, instruction::Instruction, pubkey::Pubkey,
}; };

View File

@ -1,3 +1,5 @@
//! The [`ProgramError`] type and related definitions.
#![allow(clippy::integer_arithmetic)] #![allow(clippy::integer_arithmetic)]
use { use {
crate::{decode_error::DecodeError, instruction::InstructionError, msg, pubkey::PubkeyError}, crate::{decode_error::DecodeError, instruction::InstructionError, msg, pubkey::PubkeyError},

View File

@ -1,10 +1,36 @@
//! Solana Rust-based BPF memory operations //! Basic low-level memory operations.
//!
//! Within the BPF environment, these are implemented as syscalls and executed by
//! the runtime in native code.
/// Memcpy /// Like C `memcpy`.
/// ///
/// @param dst - Destination /// # Arguments
/// @param src - Source ///
/// @param n - Number of bytes to copy /// - `dst` - Destination
/// - `src` - Source
/// - `n` - Number of bytes to copy
///
/// # Errors
///
/// When executed within a BPF program, the memory regions spanning `n` bytes
/// from from the start of `dst` and `src` must be mapped program memory. If not,
/// the program will abort.
///
/// The memory regions spanning `n` bytes from `dst` and `src` from the start
/// of `dst` and `src` must not overlap. If they do, then the program will abort
/// or, if run outside of the BPF VM, will panic.
///
/// # Safety
///
/// __This function is incorrectly missing an `unsafe` declaration.__
///
/// This function does not verify that `n` is less than or equal to the
/// lengths of the `dst` and `src` slices passed to it &mdash; it will copy
/// bytes to and from beyond the slices.
///
/// Specifying an `n` greater than either the length of `dst` or `src` will
/// likely introduce undefined behavior.
#[inline] #[inline]
pub fn sol_memcpy(dst: &mut [u8], src: &[u8], n: usize) { pub fn sol_memcpy(dst: &mut [u8], src: &[u8], n: usize) {
#[cfg(target_arch = "bpf")] #[cfg(target_arch = "bpf")]
@ -21,13 +47,25 @@ pub fn sol_memcpy(dst: &mut [u8], src: &[u8], n: usize) {
crate::program_stubs::sol_memcpy(dst.as_mut_ptr(), src.as_ptr(), n); crate::program_stubs::sol_memcpy(dst.as_mut_ptr(), src.as_ptr(), n);
} }
/// Memmove /// Like C `memmove`.
/// ///
/// @param dst - Destination /// # Arguments
/// @param src - Source ///
/// @param n - Number of bytes to copy /// - `dst` - Destination
/// - `src` - Source
/// - `n` - Number of bytes to copy
///
/// # Errors
///
/// When executed within a BPF program, the memory regions spanning `n` bytes
/// from from `dst` and `src` must be mapped program memory. If not, the program
/// will abort.
/// ///
/// # Safety /// # Safety
///
/// The same safety rules apply as in [`ptr::copy`].
///
/// [`ptr::copy`]: https://doc.rust-lang.org/std/ptr/fn.copy.html
#[inline] #[inline]
pub unsafe fn sol_memmove(dst: *mut u8, src: *mut u8, n: usize) { pub unsafe fn sol_memmove(dst: *mut u8, src: *mut u8, n: usize) {
#[cfg(target_arch = "bpf")] #[cfg(target_arch = "bpf")]
@ -42,11 +80,30 @@ pub unsafe fn sol_memmove(dst: *mut u8, src: *mut u8, n: usize) {
crate::program_stubs::sol_memmove(dst, src, n); crate::program_stubs::sol_memmove(dst, src, n);
} }
/// Memcmp /// Like C `memcmp`.
/// ///
/// @param s1 - Slice to be compared /// # Arguments
/// @param s2 - Slice to be compared ///
/// @param n - Number of bytes to compare /// - `s1` - Slice to be compared
/// - `s2` - Slice to be compared
/// - `n` - Number of bytes to compare
///
/// # Errors
///
/// When executed within a BPF program, the memory regions spanning `n` bytes
/// from from the start of `dst` and `src` must be mapped program memory. If not,
/// the program will abort.
///
/// # Safety
///
/// __This function is incorrectly missing an `unsafe` declaration.__
///
/// It does not verify that `n` is less than or equal to the lengths of the
/// `dst` and `src` slices passed to it &mdash; it will read bytes beyond the
/// slices.
///
/// Specifying an `n` greater than either the length of `dst` or `src` will
/// likely introduce undefined behavior.
#[inline] #[inline]
pub fn sol_memcmp(s1: &[u8], s2: &[u8], n: usize) -> i32 { pub fn sol_memcmp(s1: &[u8], s2: &[u8], n: usize) -> i32 {
let mut result = 0; let mut result = 0;
@ -67,11 +124,30 @@ pub fn sol_memcmp(s1: &[u8], s2: &[u8], n: usize) -> i32 {
result result
} }
/// Memset /// Like C `memset`.
/// ///
/// @param s - Slice to be set /// # Arguments
/// @param c - Repeated byte to set ///
/// @param n - Number of bytes to set /// - `s` - Slice to be set
/// - `c` - Repeated byte to set
/// - `n` - Number of bytes to set
///
/// # Errors
///
/// When executed within a BPF program, the memory region spanning `n` bytes
/// from from the start of `s` must be mapped program memory. If not, the program
/// will abort.
///
/// # Safety
///
/// __This function is incorrectly missing an `unsafe` declaration.__
///
/// This function does not verify that `n` is less than or equal to the length
/// of the `s` slice passed to it &mdash; it will write bytes beyond the
/// slice.
///
/// Specifying an `n` greater than the length of `s` will likely introduce
/// undefined behavior.
#[inline] #[inline]
pub fn sol_memset(s: &mut [u8], c: u8, n: usize) { pub fn sol_memset(s: &mut [u8], c: u8, n: usize) {
#[cfg(target_arch = "bpf")] #[cfg(target_arch = "bpf")]

View File

@ -1,5 +1,5 @@
//! A C representation of Rust's `std::option::Option` used across the FFI //! A C representation of Rust's `Option`, used across the FFI
//! boundary for Solana program interfaces //! boundary for Solana program interfaces.
//! //!
//! This implementation mostly matches `std::option` except iterators since the iteration //! This implementation mostly matches `std::option` except iterators since the iteration
//! trait requires returning `std::option::Option` //! trait requires returning `std::option::Option`

View File

@ -1,4 +1,4 @@
//! State transition types //! The [`Pack`] serialization trait.
use crate::program_error::ProgramError; use crate::program_error::ProgramError;

View File

@ -1,4 +1,4 @@
//! Syscall stubs when building for programs for non-BPF targets //! Implementations of syscalls used when `solana-program` is built for non-BPF targets.
#![cfg(not(target_arch = "bpf"))] #![cfg(not(target_arch = "bpf"))]

View File

@ -1,3 +1,7 @@
//! Contains a single utility function for deserializing from [bincode].
//!
//! [bincode]: https://docs.rs/bincode
use {crate::instruction::InstructionError, bincode::config::Options}; use {crate::instruction::InstructionError, bincode::config::Options};
/// Deserialize with a limit based the maximum amount of data a program can expect to get. /// Deserialize with a limit based the maximum amount of data a program can expect to get.

View File

@ -1,3 +1,5 @@
//! Solana account addresses.
#![allow(clippy::integer_arithmetic)] #![allow(clippy::integer_arithmetic)]
use { use {
crate::{decode_error::DecodeError, hash::hashv, wasm_bindgen}, crate::{decode_error::DecodeError, hash::hashv, wasm_bindgen},
@ -48,6 +50,20 @@ impl From<u64> for PubkeyError {
} }
} }
/// The address of a [Solana account][acc].
///
/// 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 &mdash; as with [_program derived
/// addresses_][pdas] &mdash; 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`.
///
/// [acc]: https://docs.solana.com/developing/programming-model/accounts
/// [ed25519]: https://ed25519.cr.yp.to/
/// [pdas]: https://docs.solana.com/developing/programming-model/calling-between-programs#program-derived-addresses
/// [`Keypair`]: https://docs.rs/solana-sdk/latest/solana_sdk/signer/keypair/struct.Keypair.html
#[wasm_bindgen] #[wasm_bindgen]
#[repr(transparent)] #[repr(transparent)]
#[derive( #[derive(

View File

@ -1,5 +1,8 @@
//! Configuration for network [rent].
//!
//! [rent]: https://docs.solana.com/implemented-proposals/rent
#![allow(clippy::integer_arithmetic)] #![allow(clippy::integer_arithmetic)]
//! configuration for network rent
use crate::clock::DEFAULT_SLOTS_PER_EPOCH; use crate::clock::DEFAULT_SLOTS_PER_EPOCH;
#[repr(C)] #[repr(C)]

View File

@ -1,3 +1,5 @@
//! A trait for sanitizing values and members of over the wire messages.
use thiserror::Error; use thiserror::Error;
#[derive(PartialEq, Debug, Error, Eq, Clone)] #[derive(PartialEq, Debug, Error, Eq, Clone)]
@ -10,13 +12,15 @@ pub enum SanitizeError {
InvalidValue, InvalidValue,
} }
/// Trait for sanitizing values and members of over the wire messages. /// A trait for sanitizing values and members of over-the-wire messages.
/// Implementation should recursively decent through the data structure ///
/// and sanitize all struct members and enum clauses. Sanitize excludes /// Implementation should recursively descend through the data structure and
/// signature verification checks, those are handled by another pass. /// sanitize all struct members and enum clauses. Sanitize excludes signature-
/// Sanitize checks should include but are not limited too: /// verification checks, those are handled by another pass. Sanitize checks
/// * All index values are in range /// should include but are not limited to:
/// * All values are within their static max/min bounds ///
/// - All index values are in range.
/// - All values are within their static max/min bounds.
pub trait Sanitize { pub trait Sanitize {
fn sanitize(&self) -> Result<(), SanitizeError> { fn sanitize(&self) -> Result<(), SanitizeError> {
Ok(()) Ok(())

View File

@ -1 +1,5 @@
//! The [secp256k1 native program][np].
//!
//! [np]: https://docs.solana.com/developing/runtime-facilities/programs#secp256k1-program
crate::declare_id!("KeccakSecp256k11111111111111111111111111111"); crate::declare_id!("KeccakSecp256k11111111111111111111111111111");

View File

@ -1,3 +1,5 @@
//! Key recovery from secp256k1 signatures.
use { use {
borsh::{BorshDeserialize, BorshSchema, BorshSerialize}, borsh::{BorshDeserialize, BorshSchema, BorshSerialize},
core::convert::TryFrom, core::convert::TryFrom,

View File

@ -1,3 +1,5 @@
//! Helpers for reading and writing bytes.
#![allow(clippy::integer_arithmetic)] #![allow(clippy::integer_arithmetic)]
use crate::{pubkey::Pubkey, sanitize::SanitizeError}; use crate::{pubkey::Pubkey, sanitize::SanitizeError};

View File

@ -1,3 +1,5 @@
//! Compact serde-encoding of vectors with small length.
#![allow(clippy::integer_arithmetic)] #![allow(clippy::integer_arithmetic)]
use { use {
serde::{ serde::{

View File

@ -1,7 +1,11 @@
//! named accounts for synthesized data accounts for bank state, etc. //! A type to hold data for the [`SlotHashes` sysvar][sv].
//! //!
//! this account carries the Bank's most recent bank hashes for some N parents //! [sv]: https://docs.solana.com/developing/runtime-facilities/sysvars#slothashes
//! //!
//! The sysvar ID is declared in [`sysvar::slot_hashes`].
//!
//! [`sysvar::slot_hashes`]: crate::slot_hashes
pub use crate::clock::Slot; pub use crate::clock::Slot;
use { use {
crate::hash::Hash, crate::hash::Hash,

View File

@ -1,7 +1,12 @@
//! A type to hold data for the [`SlotHistory` sysvar][sv].
//!
//! [sv]: https://docs.solana.com/developing/runtime-facilities/sysvars#slothistory
//!
//! The sysvar ID is declared in [`sysvar::slot_history`].
//!
//! [`sysvar::slot_history`]: crate::slot_history
#![allow(clippy::integer_arithmetic)] #![allow(clippy::integer_arithmetic)]
//!
//! slot history
//!
pub use crate::clock::Slot; pub use crate::clock::Slot;
use bv::{BitVec, BitsMut}; use bv::{BitVec, BitsMut};

View File

@ -1,3 +1,7 @@
//! The [stake native program][np].
//!
//! [np]: https://docs.solana.com/developing/runtime-facilities/sysvars#stakehistory
pub mod config; pub mod config;
pub mod instruction; pub mod instruction;
pub mod state; pub mod state;

View File

@ -1,7 +1,11 @@
//! named accounts for synthesized data accounts for bank state, etc. //! A type to hold data for the [`StakeHistory` sysvar][sv].
//! //!
//! this account carries history about stake activations and de-activations //! [sv]: https://docs.solana.com/developing/runtime-facilities/sysvars#stakehistory
//! //!
//! The sysvar ID is declared in [`sysvar::stake_history`].
//!
//! [`sysvar::stake_history`]: crate::sysvar::stake_history
pub use crate::clock::Epoch; pub use crate::clock::Epoch;
use std::ops::Deref; use std::ops::Deref;

View File

@ -1,3 +1,7 @@
//! Instructions and constructors for the system program.
//!
//! The system program ID is defined in [`system_program`].
#[allow(deprecated)] #[allow(deprecated)]
use { use {
crate::{ crate::{

View File

@ -1 +1,5 @@
//! The [system native program][np].
//!
//! [np]: https://docs.solana.com/developing/runtime-facilities/sysvars#stakehistory
crate::declare_id!("11111111111111111111111111111111"); crate::declare_id!("11111111111111111111111111111111");

View File

@ -37,6 +37,7 @@ pub fn is_sysvar_id(id: &Pubkey) -> bool {
ALL_IDS.iter().any(|key| key == id) ALL_IDS.iter().any(|key| key == id)
} }
/// Declares an ID that implements [`SysvarId`].
#[macro_export] #[macro_export]
macro_rules! declare_sysvar_id( macro_rules! declare_sysvar_id(
($name:expr, $type:ty) => ( ($name:expr, $type:ty) => (
@ -60,6 +61,7 @@ macro_rules! declare_sysvar_id(
) )
); );
/// Same as [`declare_sysvar_id`] except that it reports that this ID has been deprecated.
#[macro_export] #[macro_export]
macro_rules! declare_deprecated_sysvar_id( macro_rules! declare_deprecated_sysvar_id(
($name:expr, $type:ty) => ( ($name:expr, $type:ty) => (
@ -122,6 +124,7 @@ pub trait Sysvar:
} }
} }
/// Implements the [`Sysvar::get`] method for both BPF and host targets.
#[macro_export] #[macro_export]
macro_rules! impl_sysvar_get { macro_rules! impl_sysvar_get {
($syscall_name:ident) => { ($syscall_name:ident) => {