### Solana Syscall `sol_poseidon` - C Example Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0129-alt-bn128-simplified-error-code.md This snippet illustrates the usage of the `sol_poseidon` syscall in C. It outlines the parameters required for computing the Poseidon hash and the expected input format. ```c #include #include // Forward declaration of the syscall (assuming it's provided by the Solana SDK) // extern int sol_poseidon(uint32_t parameters, uint32_t endianness, uint32_t vals_len, const uint8_t* vals, uint8_t* output); int compute_poseidon_hash(const uint8_t* input_data[], size_t input_lengths[], size_t num_inputs, uint8_t* output_buffer) { uint32_t parameters = 0; // Alt_BN128 curve uint32_t endianness = 0; // Big endian uint32_t vals_len = (uint32_t)num_inputs; // The 'vals' parameter is expected to be a pointer to an array of buffers. // The exact representation might require careful memory management and casting. // For this example, we assume input_data is already in a suitable format or can be adapted. // int result = sol_poseidon(parameters, endianness, vals_len, (const uint8_t*)input_data, output_buffer); // Simulate a successful call for demonstration int result = 0; // Assuming 0 indicates success or no specific error code returned directly if (result == 0) { // Process output_buffer } return result; } ``` -------------------------------- ### Solana Syscall `sol_poseidon` - Rust Example Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0129-alt-bn128-simplified-error-code.md This snippet demonstrates how to use the `sol_poseidon` syscall in Rust to compute a Poseidon hash. It shows the setup of input parameters and the call to the syscall. ```rust use solana_program::entrypoint::ProgramResult; // Assuming necessary imports and context setup pub fn hash_with_poseidon(data: &[&[u8]]) -> ProgramResult { let parameters: u32 = 0; // Alt_BN128 curve let endianness: u32 = 0; // Big endian let vals_len = data.len() as u32; // Convert &[&[u8]] to a format acceptable by the syscall, likely Vec> or similar. // This part is conceptual as the exact syscall interface might vary. let mut vals_buffers: Vec> = data.iter().map(|&slice| slice.to_vec()).collect(); // The actual syscall invocation would look something like this (conceptual): // unsafe { // sol_poseidon(parameters, endianness, vals_len, vals_buffers.as_ptr() as *const u8, /* output buffer */); // } // For demonstration, we'll simulate a successful call. // In a real scenario, you'd check the return value. Ok(()) } ``` -------------------------------- ### Rust: Initializing VoteStateV4 with Default Values Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0185-vote-account-v4.md Provides an example of how to initialize a VoteStateV4 account with default values for the new fields when migrating from older versions. This includes setting collector accounts and commission basis points. ```rust VoteStateV4 { // .. inflation_rewards_collector: vote_pubkey, block_revenue_collector: old_vote_state.node_pubkey, inflation_rewards_commission_bps: 100u16 * (old_vote_state.commission as u16), block_revenue_commission_bps: 10_000u16, pending_delegator_rewards: 0u64, bls_pubkey_compressed: None, // .. } ``` -------------------------------- ### Deploy Slashing Program - Solana Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0204-slashable-event-verification.md Details the steps for deploying a new slashing program on Solana, including creating program accounts, verifying build hashes, and updating the program cache. This process is initiated at the epoch boundary when a specific feature flag is activated. ```bash 1. Create a new program account at S1ashing11111111111111111111111111111111111 owned by the default upgradeable loader with an upgrade authority set to None, and create the associated program data account. 2. Verify that the buffer account S1asHs4je6wPb2kWiHqNNdpNRiDaBEDQyfyCThhsrgv has a verified build hash of 192ed727334abe822d5accba8b886e25f88b03c76973c2e7290cfb55b9e1115f 3. Serialize the contents of S1asHs4je6wPb2kWiHqNNdpNRiDaBEDQyfyCThhsrgv into the program data account for S1ashing11111111111111111111111111111111111 4. Invoke the loader to deploy the new program account and program data account. This step also updates the program cache. 4. Zero out the buffer account S1asHs4je6wPb2kWiHqNNdpNRiDaBEDQyfyCThhsrgv, and update the changes to capitalization and account data lengths accordingly. ``` -------------------------------- ### ZK Token SDK Instructions Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0153-elgamal-proof-program.md This snippet outlines the instructions within the ZK Token SDK that are relevant to the ZK ElGamal Proof program. It details which instructions will be renamed and which will be removed due to their specific ties to the SPL Token program. ```Rust pub enum ZkTokenProofInstruction { /// Verifies a proof that certifies that an ElGamal ciphertext encrypts the value zero. VerifyZeroBalance, /// Verifies a proof that certifies that a tuple of Pedersen commitments satisfy a percentage relation. VerifyFeeSigma, /// Verifies the zero-knowledge proofs that are necessary for the `Withdraw` instruction in SPL Token. VerifyWithdraw, /// Verifies the zero-knowledge proofs that are necessary for the `Transfer` instruction in SPL Token. VerifyTransfer, /// Verifies the zero-knowledge proofs that are necessary for the `Transfer` instruction in SPL Token. VerifyTransferWithFee, /// Verifies that a Pedersen commitment contains a positive 64-bit value. VerifyRangeProofU64, } ``` -------------------------------- ### Migrate Native Program to Core BPF - Solana Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0088-enable-core-bpf-programs.md Details the steps for migrating an existing native Solana program to a Core BPF program. This involves creating a buffer account with the BPF implementation and using a feature gate to replace the native program. ```bash 1. Verifiably build the ELF of the BPF implementation. 2. Generate a new keypair for the source buffer account. 3. Create the buffer account and write the ELF bytes to it. 4. Generate a new keypair for the feature gate. 5. Create a new feature gate to replace the target program with the source buffer. 6. Follow the existing process for activating features. ``` -------------------------------- ### MoveStake and MoveLamports Instructions for Solana Stake Program Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0148-stake-program-move-instructions.md This snippet outlines the proposed MoveStake and MoveLamports instructions for the Solana stake program. MoveStake facilitates the transfer of active stake between accounts, while MoveLamports handles the movement of excess lamports. These instructions are designed to simplify stake management and address specific operational challenges within the Solana ecosystem. ```English MoveStake: Move a given `amount` of active stake from one active account to another active account, or from an active account to an inactive one, turning it into an active account. If the entire source account delegation is moved, the source account becomes inactive. In all cases, rent-exempt balance is unaffected and minimum delegations are respected for accounts that end in an active state. MoveLamports: Move a given `amount` of excess lamports from one active or inactive account to another active or inactive account, where "excess lamports" refers to lamports that are neither delegated stake nor required for rent-exemption. ``` -------------------------------- ### Rust Syscall Error Handling Example Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0137-curve25519-error.md Illustrates how Solana's Rust SDK handles syscall errors, specifically the `SyscallError::InvalidAttribute`. This snippet demonstrates the expected error type that will be returned by the modified curve25519 syscalls. ```Rust use solana_program::program_error::ProgramError; #[derive(Debug)] pub enum SyscallError { InvalidAttribute, // ... other error variants } impl From for ProgramError { fn from(e: SyscallError) -> Self { match e { SyscallError::InvalidAttribute => ProgramError::InvalidInstructionData, // ... map other errors } } } // Example usage within a program: // let result: Result<(), SyscallError> = perform_curve_operation(...); // match result { // Ok(_) => { /* success */ }, // Err(SyscallError::InvalidAttribute) => { /* handle invalid attribute error */ }, // Err(_) => { /* handle other errors */ }, // } ``` -------------------------------- ### Address Lookup Table Program Reimplementation for Core BPF Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0128-migrate-address-lookup-table-to-core-bpf.md This snippet refers to the reimplementation of the Address Lookup Table program to be compiled and executed by the BPF loader. The reimplemented program maintains the original ABI and functionality, with dynamic compute usage based on the VM's compute unit meter. The source code is available at a specified GitHub repository. ```Rust https://github.com/solana-program/address-lookup-table. ``` -------------------------------- ### Syscall Signature for Last Restart Slot Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0047-syscall-and-sysvar-for-last-restart-slot.md Defines the Rust function signature for the Solana syscall that retrieves the last restart slot. This syscall is intended to be called from within a program to get the cluster's last restart slot value. ```rust fn sol_get_last_restart_slot() -> Slot ``` -------------------------------- ### Solana Transaction Receipt Tree: Five Leaf Nodes Hash Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0064-transaction-receipt.md Demonstrates the hashing process for a transaction receipt tree with five leaf nodes. This example highlights how the tree structure and hashing are applied for an odd number of leaves, including the use of a duplicated intermediate node. ```text L0 := sha256(concat(0x00, R0)) L1 := sha256(concat(0x00, R1)) L2 := sha256(concat(0x00, R2)) L3 := sha256(concat(0x00, R3)) L4 := sha256(concat(0x00, R4)) Nα := sha256(concat(0x01, L0, L1)) Nβ := sha256(concat(0x01, L2, L3)) Nγ := sha256(concat(0x01, L4, L4)) Nδ := sha256(concat(0x01, Nα, Nβ)) Iε := sha256(concat(0x01, Nγ, Nγ)) Nζ := sha256(concat(0x01, Nδ, Iε)) Nτ := sha256(concat(0x80, Nζ, u64_le_encode(5))) # leaf count ``` -------------------------------- ### Solana Proposal Lifecycle Flowchart Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0001-simd-process.md A Mermaid flowchart illustrating the lifecycle of a Solana proposal, from the initial 'Idea' stage through 'Draft', 'Review', 'Accepted', 'Implemented', and 'Activated'. It also shows potential 'fail' states like 'Stagnant' and 'Withdrawn', and highlights the 'Living' state. ```mermaid flowchart LR Idea Draft Review Accepted subgraph fail[ ]; Stagnant Withdrawn end style fail fill:#ffe8e7,stroke:none style Accepted fill:#f3f8dc,stroke:#c3db50; Idea ---> Draft; Draft ---> Review; Review ---> Accepted; Accepted ---> Implemented; Implemented ---> Activated; Review ---> Living; Accepted ---> Withdrawn; Draft ---> Stagnant; Review ---> Stagnant; Review ---> Withdrawn; ``` -------------------------------- ### Calculate Accounts Lattice Hash for a Block Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0215-accounts-lattice-hash.md This pseudocode illustrates how to compute the Accounts Lattice Hash for a given block, starting with the prior block's hash. It involves subtracting the hash of the account's state before modification and adding the hash of the account's state after modification for each modified account. ```pseudocode LTHASH' := LTHASH for each account modified in B: LTHASH'.sub( lthash( account ) ) LTHASH'.add( lthash( account' ) ) return LTHASH' ``` -------------------------------- ### Solana EpochRewards Sysvar Account Structure Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0118-partitioned-epoch-reward-distribution.md Defines the structure of the EpochRewards sysvar account in Solana, which stores information about the ongoing reward distribution. This includes fields for the starting block height, number of partitions, parent blockhash, total points, total rewards, distributed rewards, and an active status flag. ```rust #[repr(C, align(16))] // C representation, 16-byte alignment struct EpochRewards{ // little-endian unsigned 64-bit integer /* 0x00 */ distribution_starting_block_height: u64, // little-endian unsigned 64-bit integer /* 0x08 */ num_partitions: u64, // byte-array of length 32 /* 0x10 */ parent_blockhash: Hash, // total points calculated for the current epoch, where points equals the sum // of delegated stake * credits observed for all delegations // little-endian unsigned 128-bit integer /* 0x30 */ total_points: u128, // total rewards for the current epoch, in lamports // little-endian unsigned 64-bit integer /* 0x40 */ total_rewards: u64, // distributed rewards for the current epoch, in lamports // little-endian unsigned 64-bit integer /* 0x48 */ distributed_rewards: u64, // whether the rewards period (calculation and distribution) is active // byte. false: 0x00, true: 0x01 /* 0x50 */ active: bool, } ``` -------------------------------- ### Solana Rust: Get Data Slice Function Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0075-precompile-for-secp256r1-sigverify.md This Rust function, `get_data_slice`, is designed to extract a specific slice of data from transaction instructions. It handles cases where the instruction index is a wildcard (0xFFFF) or a specific index, ensuring the requested offset and length are within the bounds of the instruction data. This function is reusable across different precompiles. ```rust // This function is re-used across precompiles in accordance with SIMD-0152 fn get_data_slice(all_tx_data, instruction_index, offset, length) { // Get the right instruction_data if instruction_index == 0xFFFF { instruction_data = all_tx_data.data } else { if instruction_index >= num_instructions { return Error } instruction_data = all_tx_data.instruction_datas[instruction_index] } start = offset end = offset + length if end > instruction_data_length { return Error } return instruction_data[start..end] } ``` -------------------------------- ### Rust: Get Remaining Compute Units in Solana Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0049-syscall-get-remaining-compute-units.md This Rust code snippet demonstrates how to use the proposed `sol_remaining_compute_units()` syscall within a Solana program. It shows a loop that processes events, checking the remaining compute units before processing expensive or cheap events to avoid exceeding the transaction's budget. This helps in efficient resource management. ```Rust fn process_events() { while (true) { let event = peek_event(); match event.type { CheapEvent => { if sol_remaining_compute_units() < 10_000 { break; } process_cheap(event); }, ExpensiveEvent => { if sol_remaining_compute_units() < 40_000 { break; } process_expensive(event); } } pop_event(); } } ``` -------------------------------- ### Solana PQR Instructions: UHMUL64, UDIV32, UDIV64, UREM32, UREM64, LMUL32, LMUL64, SHMUL64, SDIV32, SDIV64, SREM32, SREM64 Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0174-sbpf-arithmetics-improvements.md This snippet lists the Product, Quotient, and Remainder (PQR) instructions introduced in Solana, along with their respective opcodes. These instructions cover unsigned and signed multiplication, division, and remainder operations for 32-bit and 64-bit integers. ```Assembly UHMUL64 (opcode 0x36, 0x3E) UDIV32 (opcode 0x46, 0x4E) UDIV64 (opcode 0x56, 0x5E) UREM32 (opcode 0x66, 0x6E) UREM64 (opcode 0x76, 0x7E) LMUL32 (opcode 0x86, 0x8E) LMUL64 (opcode 0x96, 0x9E) SHMUL64 (opcode 0xB6, 0xBE) SDIV32 (opcode 0xC6, 0xCE) SDIV64 (opcode 0xD6, 0xDE) SREM32 (opcode 0xE6, 0xEE) SREM64 (opcode 0xF6, 0xFE) ``` -------------------------------- ### Solana Precompile Verify Instruction Data Structures Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0152-precompiles.md Defines the data structures for the PrecompileVerifyInstruction and PrecompileOffsets used in Solana's precompile feature. These structures specify how signature, public key, and message data are laid out within transaction instructions for verification. ```Rust struct PrecompileVerifyInstruction { num_signatures: u8, // Number of signatures to verify padding: u8, // Single byte padding offsets: PrecompileOffsets[], // Array of `num_signatures` offsets additionalData?: Bytes, // Optional additional data, e.g. // signatures included in the same // instruction } struct PrecompileOffsets { signature_offset: u16 LE, // Offset to signature (offset within // the specified instruction data) signature_instruction_index: u16 LE, // Instruction index to signature public_key_offset: u16 LE, // Offset to public key public_key_instruction_index: u16 LE, // Instruction index to public key message_offset: u16 LE, // Offset to start of message data message_length: u16 LE, // Size of message data message_instruction_index: u16 LE, // Instruction index to message } ``` -------------------------------- ### Mozilla Access Policy - Technical vs. Social Controls Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0007-access-policy.md This snippet, borrowed from Mozilla's access policy, discusses the trade-offs between technical and social controls in managing repository access. It highlights the increased management overhead of granular technical permissions versus the risks of overly broad social permissions, advocating for a balanced approach. ```English There are two sorts of control which can be used to stop people checking in - technical and social. A "full technical" implementation would have per-directory permissions everywhere, but would lead to a greatly-increased management overhead for IT, vouchers and developers alike. A "full social" implementation would just have a single permission which gave you complete access to everything, but (depending on the height of the barrier to that permission) there is a risk of making developer's lives more difficult when they are excluded, or of giving the untrustworthy or incompetent power to mess things up. Therefore, a good policy balances the use of technical and social controls to minimize both management overhead and risk to the development process. ``` -------------------------------- ### Solana Restart Phase: Validator Actions Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0046-optimistic-cluster-restart-automation.md Outlines the initial actions a Solana validator takes when entering the 'wen restart phase' during a cluster restart. The validator refrains from creating new blocks or voting and propagates its local voted fork information to other restarting validators. ```text The operator restarts the validator into the `wen restart phase` at boot, where it will not make new blocks or vote. The validator propagates its local voted fork information to all other validators in restart. ``` -------------------------------- ### Solana Precompile Verify Function Logic Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0152-precompiles.md Provides a pseudocode implementation of the 'verify' function for Solana precompiles. It outlines the process of validating transaction signatures by iterating through provided offsets and invoking the sigverify function. ```Pseudocode fn verify() { if data_length == 0 { return Error } num_signatures = data[0] if num_signatures == 0 { return Error } if data_length < (2 + num_signatures * size_of_offsets) { return Error } all_tx_data = { data, instruction_datas } data_position = 2 for i in 0..num_signatures { offsets = (PrecompileOffsets) data[data_position..data_position+size_of_offsets] data_position += size_of_offsets signature = get_data_slice(all_tx_data, offsets.signature_instruction_index, offsets.signature_offset signature_length) if !signature { return Error } public_key = get_data_slice(all_tx_data, offsets.public_key_instruction_index, offsets.public_key_offset, public_key_length) if !public_key { return Error } message = get_data_slice(all_tx_data, offsets.message_instruction_index, offsets.message_offset offsets.message_length) if !message { return Error } // sigverify includes validating signature and public_key result = sigverify(signature, public_key, message) if result != Success { return Error } } return Success } fn get_data_slice(all_tx_data, instruction_index, offset, length) { // Get the right instruction_data if instruction_index == 0xFFFF { instruction_data = all_tx_data.data } else { if instruction_index >= num_instructions { return Error } instruction_data = all_tx_data.instruction_datas[instruction_index] } start = offset end = offset + length if end > instruction_data_length { return Error } return instruction_data[start..end] } ``` -------------------------------- ### Solana Restart Protocol: Fork Verification Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0046-optimistic-cluster-restart-automation.md Explains the verification process for Solana validators regarding a coordinator's chosen heaviest fork during a restart. Validators check if the coordinator's choice is reasonable; if not, they halt and await human intervention. ```text Each validator verifies that the coordinator's choice is reasonable: 1. If yes, proceed and restart 2. If no, print out what it thinks is wrong, halt and wait for human ``` -------------------------------- ### Secp256r1 Signature Verification Instruction Data Structure Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0075-precompile-for-secp256r1-sigverify.md Defines the structure of the instruction data for the Secp256r1 program's 'verify' instruction. It includes the number of signatures, padding, and an array of offsets for each signature. ```Pseudocode struct Secp256r1SigVerifyInstruction { num_signatures: uint8 LE, // Number of signatures to verify padding: uint8 LE, // Single byte padding offsets: Array, // Array of offset structs additionalData?: Bytes, // Optional additional data, e.g. // signatures included in the same // instruction } Note: Array does not contain any length prefixes or padding between elements. struct Secp256r1SignatureOffsets { signature_offset: uint16 LE, // Offset to signature signature_instruction_index: uint16 LE, // Instruction index to signature public_key_offset: uint16 LE, // Offset to public key public_key_instruction_index: uint16 LE, // Instruction index to public key message_offset: uint16 LE, // Offset to start of message data message_length: uint16 LE, // Size of message data message_instruction_index: uint16 LE, // Instruction index to message } ``` -------------------------------- ### Secp256r1 Program Verification Logic Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0075-precompile-for-secp256r1-sigverify.md Provides pseudocode for the Secp256r1 program's verification logic. It handles instruction data validation, signature count, offset parsing, and data retrieval for signature verification. ```Pseudocode /// `data` is the secp256r1 program's instruction data. `instruction_datas` is /// the full slice of instruction datas for all instructions in the transaction, /// including the secp256r1 program's instruction data. /// length_of_data is the length of `data` /// SERIALIZED_OFFSET_STRUCT_SIZE is the length of the serialized /// Secp256r1SignatureOffsets struct /// SERIALIZED_PUBLIC_KEY_LENGTH and SERIALIZED_SIGNATURE_LENGTH represent the /// length of the serialized public key and signature respectively function verify() { if length_of_data == 0 { return Error } num_signatures = data[0] if num_signatures == 0 && length_of_data > 1 { return Error } if length_of_data < (num_signatures * SERIALIZED_OFFSET_STRUCT_SIZE + 2) { return Error } all_tx_data = { data, instruction_datas } data_start_position = 2 for i in 0..num_signatures { offsets = (Secp256r1SignatureOffsets) all_tx_data.data[data_start_position..data_start_position + SERIALIZED_OFFSET_STRUCT_SIZE] data_position += SERIALIZED_OFFSET_STRUCT_SIZE signature = get_data_slice(all_tx_data, offsets.signature_instruction_index, offsets.signature_offset signature_length) if !signature { return Error } public_key = get_data_slice(all_tx_data, offsets.public_key_instruction_index, offsets.public_key_offset, SERIALIZED_PUBLIC_KEY_LENGTH) if !public_key { return Error } message = get_data_slice(all_tx_data, offsets.message_instruction_index, offsets.message_offset offsets.message_length) if !message { return Error } // sigverify includes validating signature and public_key ``` -------------------------------- ### KeccakSecp256k1 Precompile: Prevent zero signatures Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0152-precompiles.md This change modifies the KeccakSecp256k1 precompile to disallow an input of `[0]`, which represents verifying zero signatures. By implementing this, the precompile will return an error for such useless instructions, preventing anomalies. ```Rust if num_signatures == 0 { return Err(Error::InvalidSignatureCount); } ``` -------------------------------- ### Solana Restart Protocol: Non-Conforming Validators Source: https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0046-optimistic-cluster-restart-automation.md Defines the tolerance for 'non-conforming' validators within the Solana restart protocol. It assumes that at most 5% of validators in restart can be malicious or contain bugs, aligning with other consensus protocol algorithms. ```text We assume that as most 5% of the validators in restart can be malicious or contains bugs, this number is consistent with other algorithms in the consensus protocol. We call these `non-conforming` validators. ```