Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
402 changes: 402 additions & 0 deletions Cargo.lock

Large diffs are not rendered by default.

21 changes: 14 additions & 7 deletions interface/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
[package]
name = "spl-nonce-interface"
version = "0.1.0"
description = "TBD"
authors = {workspace = true}
repository = {workspace = true}
homepage = {workspace = true}
license = {workspace = true}
edition = {workspace = true}
description = "Interface for the SPL Nonce program"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm thinking maybe we should just drop the "nonce" terminology altogether. any "programmatic signer/authority" can be used to decouple asset authority from signatures that must cover the recent blockhash

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting. Would spl-program-signer or spl-pda-authority or spl-authority-proxy be more accurate?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

spl-ed25519-signer?

@joncinque join the bikeshed session!

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've been summoned! I really like including ed25519. On the other hand, this is still meant to cover single-use durable signatures, so how about spl-ed25519-durable-signer?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated terms!

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there really isn't anything "durable" about this thing tho. that qualifier was added to the original feature as a call out to its extending the ttl of an otherwise short-lived nonce value. here we're simply never signing a nonce with a lifetime at all. this is so much more powerful and shouldn't be burdened by historical artifacts. the technology has advanced to the point as to make the old ways irrelevant. let them die


wherever we land, we should also rename the repo before it gets much content

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I understand -- "durable" means "long-lasting", and this program provides a long-lasting way to sign transactions. What are other powers that you want to highlight with the name?

Someone could make a different version of this program that requires signing the same blockhash as the outer transaction, which could be called ed25519-blockhash-signer. In this case, would ed25519-hash-signer be better? Or if you feel really strongly about spl-ed25519-signer, I can get behind it

authors = { workspace = true }
repository = { workspace = true }
homepage = { workspace = true }
license = { workspace = true }
edition = { workspace = true }

[lib]
crate-type = ["rlib"]

[package.metadata.solana]
program-id = "2iZvRhbVukqhBXdKTpjmY5w2omXQbziFq1r5WkxSJKFD"
program-id = "nonce34S3Viw97xQwWGpRWEGufiSpfVEAiFe7Lefv7y"

[lints]
workspace = true

[dependencies]
# TODO: Need to update `solana-zero-copy` to use latest wincode before
# we can use the latest `solana-address` & wincode versions
solana-address = { version = "=2.5.0", features = ["curve25519", "syscalls", "decode", "wincode"] }
solana-sha256-hasher = { version = "3.1.0", default-features = false, features = ["sha2"] }
solana-signature = { version = "3.4.0", default-features = false }
solana-zero-copy = { version = "1.0.0", features = ["wincode"] }
wincode = { version = "0.4.9", features = ["derive"] }
77 changes: 77 additions & 0 deletions interface/src/instruction.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/// Instructions supported by the SPL Nonce program.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NonceInstruction {
/// Creates a new nonce state account for the given authority policy. Anyone
/// may initialize the canonical pre-funded PDA for a given authority policy.
///
/// On success, the state account is initialized with:
/// - `nonce = 0`
/// - the authority policy that will govern future signed actions
///
/// The nonce state address is derived from [`NonceStatePda`](crate::pda::NonceStatePda)
/// and must already be pre-funded with enough lamports to be rent-exempt before
/// this instruction runs. During initialization, the program claims that PDA
/// as nonce state and writes the initial state into it.
///
/// Accounts required:
/// - `[writable]` Nonce state PDA to initialize (pre-funded)
/// - `[]` System program used to allocate and assign the pre-funded PDA
Initialize,

/// Verifies threshold Ed25519 signatures over a signed message, then
/// performs the action committed in that message.
///
/// The signed message specifies one of:
/// - `Execute`: run signed CPI instructions
/// - `AdvanceNonce`: increment the nonce, invalidating all previously signed messages
/// - `Close`: close the state account and refund lamports
///
/// On success, the program:
/// 1. Verifies that enough authority-policy members signed the message
/// 2. Checks the message nonce matches the state and the deadline has not passed
/// 3. Performs the committed action
///
/// The instruction data format is defined in [`message`](crate::message).
///
/// Accounts required:
/// - `[writable]` Nonce state PDA
/// - Remaining: accounts from the signed message's account table, in the
/// exact same order. `AdvanceNonce` requires no remaining accounts.
Submit,
}

impl TryFrom<u8> for NonceInstruction {
type Error = ();

fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(Self::Initialize),
1 => Ok(Self::Submit),
_ => Err(()),
}
}
}

impl From<NonceInstruction> for u8 {
fn from(value: NonceInstruction) -> Self {
value as u8
}
}

#[cfg(test)]
mod tests {
use super::NonceInstruction;

#[test]
fn discriminants_match() {
assert_eq!(u8::from(NonceInstruction::Initialize), 0);
assert_eq!(u8::from(NonceInstruction::Submit), 1);
}

#[test]
fn try_from_rejects_unknown() {
assert!(NonceInstruction::try_from(2).is_err());
assert!(NonceInstruction::try_from(255).is_err());
}
}
9 changes: 9 additions & 0 deletions interface/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,11 @@
//! Interface for the Nonce program.
#![no_std]

extern crate alloc;

pub mod instruction;
pub mod message;
pub mod pda;
pub mod state;

solana_address::declare_id!("nonce34S3Viw97xQwWGpRWEGufiSpfVEAiFe7Lefv7y");
197 changes: 197 additions & 0 deletions interface/src/message.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
//! Wire-format types for offline-authorized signed messages submitted via `Submit`.
//!
//! Flow:
//! 1. Build a [`SignedMessage`].
//! 2. Serialize it with `wincode`.
//! 3. Have authority-policy members sign those exact serialized [`SignedMessage`]
//! bytes offline using Ed25519.
//! 4. Construct [`InstructionData`] from the signatures and message.
//! 5. Submit that payload via [`NonceInstruction::Submit`](crate::instruction::NonceInstruction::Submit).
//!
//! The signatures cover only the serialized [`SignedMessage`], not the outer
//! Solana transaction. The transaction is just the transport that carries the
//! signed message to the program.
//!
//! ## Wire layout
//!
//! ```text
//! InstructionData
//! ┌───────────────┬────────────────────────┬────────────────────────┐
//! │ discriminator │ signatures │ message │
//! │ u8 │ count:u8 + entries │ SignedMessage │
//! └───────────────┴────────────────────────┴────────────────────────┘
//!
//! SignedMessage
//! ┌─────────┬──────────────────┬────────────────────────────────────┐
//! │ version │ header │ action │
//! │ u8 │ MessageHeader │ SignedAction │
//! └─────────┴──────────────────┴────────────────────────────────────┘
//!
//! MessageHeader
//! ┌──────────────┬──────────────────────────────┐
//! │ nonce │ deadline │
//! │ u32 LE │ i64 LE (0 = no expiration) │
//! └──────────────┴──────────────────────────────┘
//! ```
//!
//! ### `SignedAction::Execute`
//!
//! ```text
//! ┌──────────────────────┬──────────────────────────────┐
//! │ account_table │ instructions │
//! │ count:u8 + addresses │ count:u8 + CpiInstructions │
Comment thread
grod220 marked this conversation as resolved.
Outdated
//! └──────────────────────┴──────────────────────────────┘
//! ```
//!
//! The `account_table` is the signed list of addresses that CPI instructions
//! reference by index. When the transaction is submitted, the caller must pass
//! those same addresses as remaining accounts on the `Submit` instruction, in
//! the same order:
//!
//! ```text
//! Submit accounts:
//! [0] NonceStatePda (always first)
//! [1] account_table[0]
//! [2] account_table[1]
//! [3] account_table[2]
//! ...
//! ```
//!
//! The program checks that the submitted accounts match the signed table
//! exactly, preventing account substitution by the submitter.
//!
//! ### `SignedAction::AdvanceNonce`
//!
//! No payload.
//!
//! This action consumes the current nonce and increments it, invalidating all
//! previously signed messages for the account.
//!
//! ### `SignedAction::Close`
//!
//! ```text
//! ┌─────────────────────┐
//! │ recipient: Address │
//! └─────────────────────┘
//! ```
//!
//! The signed message specifies which address receives the lamports when the
//! nonce state account is closed.

use {
alloc::vec::Vec,
solana_address::Address,
solana_signature::SIGNATURE_BYTES,
solana_zero_copy::unaligned::{I64, U32},
wincode::{SchemaRead, SchemaWrite, containers},
};

/// Current signed-message format version.
pub const SIGNED_MESSAGE_VERSION: u8 = 1;

/// Serialized size of [`MessageHeader`] in bytes.
pub const HEADER_LEN: usize = 12;

/// Full instruction-data body passed to
/// [`NonceInstruction::Submit`](crate::instruction::NonceInstruction::Submit).
#[derive(Clone, Debug, PartialEq, SchemaRead, SchemaWrite)]
pub struct InstructionData {
/// Must be `NonceInstruction::Submit` (1).
pub discriminator: u8,
/// Ed25519 signatures over the serialized [`InstructionData::message`].
#[wincode(with = "containers::Vec<SignatureEntry, u8>")]
pub signatures: Vec<SignatureEntry>,
/// The exact value authority-policy members sign. Contains the nonce,
/// deadline, and action the program verifies and executes.
pub message: SignedMessage,
}

/// One authority-member approval attached to [`InstructionData`].
#[derive(Clone, Debug, PartialEq, Eq, SchemaRead, SchemaWrite)]
pub struct SignatureEntry {
/// Index into [`AuthorityPolicy::members`](crate::state::AuthorityPolicy::members).
pub signer_index: u8,
Comment thread
grod220 marked this conversation as resolved.
Outdated
/// Ed25519 signature over the serialized [`SignedMessage`].
pub signature: [u8; SIGNATURE_BYTES],
}

/// The message authority-policy members approve offline.
#[derive(Clone, Debug, PartialEq, SchemaRead, SchemaWrite)]
pub struct SignedMessage {
/// Format version. Must be [`SIGNED_MESSAGE_VERSION`].
pub version: u8,
/// Replay-protection header containing the expected nonce and optional
/// deadline.
pub header: MessageHeader,
/// The exact action the authority approved.
pub action: SignedAction,
}

/// Fixed-size replay-protection header for a [`SignedMessage`].
#[repr(C)]
#[derive(Clone, Debug, PartialEq, SchemaRead, SchemaWrite)]
#[wincode(assert_zero_copy)]
pub struct MessageHeader {
/// Expected nonce value. Must match the nonce stored in the state account.
pub nonce: U32,
/// Unix timestamp after which the message expires.
/// Zero means the message does not expire.
pub deadline: I64,
Comment thread
grod220 marked this conversation as resolved.
Outdated
}

const _: () = assert!(core::mem::size_of::<MessageHeader>() == HEADER_LEN);

/// Every post-initialization operation the authority can approve goes through
/// one of these variants.
#[derive(Clone, Debug, PartialEq, SchemaRead, SchemaWrite)]
#[wincode(tag_encoding = "u8")]
pub enum SignedAction {
/// Execute the signed CPI sequence.
Execute {
/// Account addresses referenced by CPI instructions. The program checks
/// that this table matches the `Submit` instruction's remaining
/// accounts in order, and CPI instructions reference this table by index.
#[wincode(with = "containers::Vec<Address, u8>")]
account_table: Vec<Address>,
/// CPI instructions to execute in order. Each instruction references
/// its program and accounts by index into
/// [`SignedAction::Execute`]'s `account_table`.
#[wincode(with = "containers::Vec<CpiInstruction, u8>")]
instructions: Vec<CpiInstruction>,
},
/// Increment the nonce without executing any CPI, invalidating all
/// previously signed messages for the account.
AdvanceNonce,
/// Close the nonce state account and refund its lamports.
Close {
/// Address that receives all lamports from the closed account.
recipient: Address,
},
}

/// A CPI instruction authorized by [`SignedAction::Execute`].
#[derive(Clone, Debug, PartialEq, SchemaRead, SchemaWrite)]
pub struct CpiInstruction {
/// Index into [`SignedAction::Execute`]'s `account_table` for the target
/// program to invoke.
pub program_id_index: u8,
/// Per-account metadata for the CPI.
#[wincode(with = "containers::Vec<AccountMeta, u8>")]
pub accounts: Vec<AccountMeta>,
/// Raw instruction data passed to the target program.
#[wincode(with = "containers::Vec<u8, u16>")]
pub data: Vec<u8>,
}

/// An account passed to a CPI, identified by its position in the signed
/// account table along with the signer and writable privileges the authority
/// approved for it.
#[derive(Clone, Debug, PartialEq, Eq, SchemaRead, SchemaWrite)]
pub struct AccountMeta {
Comment thread
grod220 marked this conversation as resolved.
Outdated
/// Position of this account in [`SignedAction::Execute`]'s `account_table`.
pub account_index: u8,
/// Whether the authority approved this account as a signer for the CPI.
pub is_signer: bool,
/// Whether the authority approved this account as writable for the CPI.
pub is_writable: bool,
Comment thread
grod220 marked this conversation as resolved.
Outdated
}
57 changes: 57 additions & 0 deletions interface/src/pda.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//! PDA derivation helpers for the SPL Nonce program.
//!
//! One [`AuthorityPolicy`] determines two canonical PDAs:
//! [`NonceStatePda`] and [`NonceAuthorityPda`].

use {crate::state::AuthorityPolicy, solana_address::Address};

/// Nonce state account PDA. Stores the nonce counter and authority policy.
///
/// Seeds: `["nonce-state", authority_policy_hash, bump]`
pub struct NonceStatePda;

impl NonceStatePda {
pub const SEED_PREFIX: &[u8] = b"nonce-state";

#[inline(always)]
pub fn derive_address_and_bump(
program_id: &Address,
authority_policy: &AuthorityPolicy,
) -> (Address, u8) {
let authority_policy_hash = authority_policy.hash();
Address::derive_program_address(&[Self::SEED_PREFIX, &authority_policy_hash], program_id)
.expect("failed to derive NonceStatePda from authority policy")
}

#[inline(always)]
pub fn derive_address(program_id: &Address, authority_policy: &AuthorityPolicy) -> Address {
Self::derive_address_and_bump(program_id, authority_policy).0
Comment thread
grod220 marked this conversation as resolved.
Outdated
}
}

/// Nonce authority PDA.
///
/// The PDA the program signs as when executing committed CPI instructions.
/// Downstream programs can recognize this address as an owner or authority.
///
/// Seeds: `["nonce-authority", authority_policy_hash, bump]`
pub struct NonceAuthorityPda;

impl NonceAuthorityPda {
pub const SEED_PREFIX: &[u8] = b"nonce-authority";

#[inline(always)]
pub fn derive_address_and_bump(
program_id: &Address,
authority_policy: &AuthorityPolicy,
Comment thread
grod220 marked this conversation as resolved.
Outdated
) -> (Address, u8) {
let authority_policy_hash = authority_policy.hash();
Address::derive_program_address(&[Self::SEED_PREFIX, &authority_policy_hash], program_id)
.expect("failed to derive NonceAuthorityPda from authority policy")
}

#[inline(always)]
pub fn derive_address(program_id: &Address, authority_policy: &AuthorityPolicy) -> Address {
Self::derive_address_and_bump(program_id, authority_policy).0
Comment thread
grod220 marked this conversation as resolved.
Outdated
}
}
Loading
Loading