Skip to main content

rialo_two_step_authority/
lib.rs

1// Copyright (c) Subzero Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A reusable **two-step authority-transfer** primitive for governance domains.
5//!
6//! Governance NORTHSTAR §2.3 requires that transfer of a sole signing
7//! authority be two-step — the holder proposes a successor and the successor
8//! explicitly accepts — so that a transfer to an unusable key cannot strand
9//! the domain. Several programs need exactly this handshake (feature
10//! management, consensus-committee governance, …); this crate factors the
11//! state machine out so each program embeds one field and delegates rather
12//! than re-implementing the guards.
13//!
14//! The type is **pure and SVM-independent**: it holds no accounts and does no
15//! signature checking against a runtime. A consumer extracts the transaction
16//! signer, passes it in as `caller`, and maps [`AuthorityTransferError`] onto
17//! its own program error. The `caller` is checked against the authority (or
18//! pending) key inside each method, so a consumer may rely on that check as
19//! its authorization, or verify the signer upstream and pass the verified key
20//! through.
21
22// This crate is a dependency of `#![no_std]` on-chain program interfaces, so it
23// must compile for the SVM target; `std` is available only under `test`.
24#![cfg_attr(not(test), no_std)]
25
26// The `svm` module uses `ic_msg!`, which formats via `format!` and therefore
27// needs `alloc`. On-chain programs run with a global allocator, so pulling in
28// `alloc` under the `svm` feature is safe and does not compromise the
29// zero-alloc pure state machine consumers get without the feature.
30#[cfg(feature = "svm")]
31extern crate alloc;
32
33#[cfg(feature = "svm")]
34pub mod svm;
35
36use rialo_s_pubkey::Pubkey;
37
38/// Why a two-step transfer operation was rejected.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum AuthorityTransferError {
41    /// The caller is not the party allowed to perform this step — the current
42    /// authority for `propose`/`cancel`, the pending successor for `accept`.
43    Unauthorized,
44    /// `propose` named a target that cannot be a valid successor — either
45    /// the current authority (a no-op transfer) or the default pubkey (which
46    /// has no signer, so a subsequent accept would be impossible).
47    InvalidTransferTarget,
48    /// `propose` was called while a transfer was already pending; cancel it
49    /// first.
50    PendingTransferExists,
51    /// `accept` or `cancel` was called with no transfer pending.
52    NoPendingTransfer,
53}
54
55/// A current authority plus an optional pending successor, implementing the
56/// two-step transfer handshake.
57///
58/// Serializes as the `authority` pubkey followed by the optional `pending`
59/// pubkey. The transition methods (`propose`/`accept`/`cancel`) are the only
60/// way to mutate it once constructed.
61#[derive(Clone, Debug, PartialEq, Eq)]
62#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
63pub struct TwoStepAuthority {
64    /// The principal currently in control.
65    authority: Pubkey,
66    /// The proposed successor while a transfer is in flight; `None` otherwise.
67    pending: Option<Pubkey>,
68}
69
70impl TwoStepAuthority {
71    /// A fresh authority with no transfer pending.
72    pub fn new(authority: Pubkey) -> Self {
73        Self {
74            authority,
75            pending: None,
76        }
77    }
78
79    /// Build directly from an authority and an optional pending successor —
80    /// e.g. to reconstruct from a flat persisted layout that stores the two as
81    /// separate fields. Unlike the transition methods, this performs **no
82    /// validation**: states the handshake never produces (such as
83    /// `pending == Some(authority)`) are accepted as given, so callers are
84    /// trusted to supply a coherent pair.
85    pub fn from_parts(authority: Pubkey, pending: Option<Pubkey>) -> Self {
86        Self { authority, pending }
87    }
88
89    /// The principal currently in control.
90    pub fn authority(&self) -> Pubkey {
91        self.authority
92    }
93
94    /// The proposed successor, if a transfer is in flight.
95    pub fn pending(&self) -> Option<Pubkey> {
96        self.pending
97    }
98
99    /// Step 1 — the current authority (`caller`) proposes `new_authority` as
100    /// its successor. The successor must later [`accept`](Self::accept).
101    ///
102    /// Rejects a caller that is not the current authority; a `new_authority`
103    /// that cannot be a valid successor (equal to the current authority, or
104    /// the default pubkey — nobody can sign for it, so an accept would be
105    /// impossible and the pending slot could only be cleared by cancel — a
106    /// needless griefing window); or a proposal made while another is
107    /// already pending.
108    pub fn propose(
109        &mut self,
110        caller: &Pubkey,
111        new_authority: Pubkey,
112    ) -> Result<(), AuthorityTransferError> {
113        if caller != &self.authority {
114            return Err(AuthorityTransferError::Unauthorized);
115        }
116        if new_authority == self.authority || new_authority == Pubkey::default() {
117            return Err(AuthorityTransferError::InvalidTransferTarget);
118        }
119        if self.pending.is_some() {
120            return Err(AuthorityTransferError::PendingTransferExists);
121        }
122        self.pending = Some(new_authority);
123        Ok(())
124    }
125
126    /// Step 2 — the pending successor (`caller`) accepts, becoming the
127    /// authority and clearing the pending slot.
128    ///
129    /// Rejects when no transfer is pending or when `caller` is not the pending
130    /// successor.
131    pub fn accept(&mut self, caller: &Pubkey) -> Result<(), AuthorityTransferError> {
132        let pending = self
133            .pending
134            .ok_or(AuthorityTransferError::NoPendingTransfer)?;
135        if caller != &pending {
136            return Err(AuthorityTransferError::Unauthorized);
137        }
138        self.authority = pending;
139        self.pending = None;
140        Ok(())
141    }
142
143    /// The current authority (`caller`) cancels a pending transfer.
144    ///
145    /// Rejects a caller that is not the current authority, or a cancel with
146    /// nothing pending.
147    pub fn cancel(&mut self, caller: &Pubkey) -> Result<(), AuthorityTransferError> {
148        if caller != &self.authority {
149            return Err(AuthorityTransferError::Unauthorized);
150        }
151        if self.pending.is_none() {
152            return Err(AuthorityTransferError::NoPendingTransfer);
153        }
154        self.pending = None;
155        Ok(())
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    fn keys() -> (Pubkey, Pubkey, Pubkey) {
164        (
165            Pubkey::new_unique(),
166            Pubkey::new_unique(),
167            Pubkey::new_unique(),
168        )
169    }
170
171    #[test]
172    fn new_has_no_pending() {
173        let (a, _, _) = keys();
174        let auth = TwoStepAuthority::new(a);
175        assert_eq!(auth.authority(), a);
176        assert_eq!(auth.pending(), None);
177    }
178
179    #[test]
180    fn propose_sets_pending() {
181        let (a, b, _) = keys();
182        let mut auth = TwoStepAuthority::new(a);
183        assert_eq!(auth.propose(&a, b), Ok(()));
184        assert_eq!(auth.authority(), a, "authority unchanged until accept");
185        assert_eq!(auth.pending(), Some(b));
186    }
187
188    #[test]
189    fn propose_rejects_non_authority() {
190        let (a, b, c) = keys();
191        let mut auth = TwoStepAuthority::new(a);
192        assert_eq!(
193            auth.propose(&c, b),
194            Err(AuthorityTransferError::Unauthorized)
195        );
196        assert_eq!(auth.pending(), None);
197    }
198
199    #[test]
200    fn propose_rejects_self_target() {
201        let (a, _, _) = keys();
202        let mut auth = TwoStepAuthority::new(a);
203        assert_eq!(
204            auth.propose(&a, a),
205            Err(AuthorityTransferError::InvalidTransferTarget)
206        );
207    }
208
209    #[test]
210    fn propose_rejects_default_pubkey_target() {
211        // Nobody can sign for the default pubkey, so a subsequent accept
212        // would be impossible and the pending slot would be reachable only
213        // via cancel — a griefing footgun. The pure state machine rejects
214        // this at the same edge as the self-target case, so every consumer
215        // (including callers using the pure API directly) inherits the
216        // guard uniformly.
217        let (a, _, _) = keys();
218        let mut auth = TwoStepAuthority::new(a);
219        assert_eq!(
220            auth.propose(&a, Pubkey::default()),
221            Err(AuthorityTransferError::InvalidTransferTarget)
222        );
223        assert_eq!(auth.pending(), None);
224    }
225
226    #[test]
227    fn propose_rejects_when_already_pending() {
228        let (a, b, c) = keys();
229        let mut auth = TwoStepAuthority::new(a);
230        auth.propose(&a, b).unwrap();
231        assert_eq!(
232            auth.propose(&a, c),
233            Err(AuthorityTransferError::PendingTransferExists)
234        );
235        assert_eq!(auth.pending(), Some(b), "first proposal is preserved");
236    }
237
238    #[test]
239    fn accept_promotes_pending_and_clears() {
240        let (a, b, _) = keys();
241        let mut auth = TwoStepAuthority::new(a);
242        auth.propose(&a, b).unwrap();
243        assert_eq!(auth.accept(&b), Ok(()));
244        assert_eq!(auth.authority(), b);
245        assert_eq!(auth.pending(), None);
246    }
247
248    #[test]
249    fn accept_rejects_non_pending_caller() {
250        let (a, b, c) = keys();
251        let mut auth = TwoStepAuthority::new(a);
252        auth.propose(&a, b).unwrap();
253        // Even the current authority cannot accept on the successor's behalf.
254        assert_eq!(auth.accept(&a), Err(AuthorityTransferError::Unauthorized));
255        assert_eq!(auth.accept(&c), Err(AuthorityTransferError::Unauthorized));
256        assert_eq!(auth.authority(), a, "unchanged after failed accepts");
257    }
258
259    #[test]
260    fn accept_rejects_when_none_pending() {
261        let (a, _, _) = keys();
262        let mut auth = TwoStepAuthority::new(a);
263        assert_eq!(
264            auth.accept(&a),
265            Err(AuthorityTransferError::NoPendingTransfer)
266        );
267    }
268
269    #[test]
270    fn cancel_clears_pending() {
271        let (a, b, _) = keys();
272        let mut auth = TwoStepAuthority::new(a);
273        auth.propose(&a, b).unwrap();
274        assert_eq!(auth.cancel(&a), Ok(()));
275        assert_eq!(auth.authority(), a);
276        assert_eq!(auth.pending(), None);
277    }
278
279    #[test]
280    fn cancel_rejects_non_authority() {
281        let (a, b, c) = keys();
282        let mut auth = TwoStepAuthority::new(a);
283        auth.propose(&a, b).unwrap();
284        assert_eq!(auth.cancel(&c), Err(AuthorityTransferError::Unauthorized));
285        assert_eq!(auth.pending(), Some(b));
286    }
287
288    #[test]
289    fn cancel_rejects_when_none_pending() {
290        let (a, _, _) = keys();
291        let mut auth = TwoStepAuthority::new(a);
292        assert_eq!(
293            auth.cancel(&a),
294            Err(AuthorityTransferError::NoPendingTransfer)
295        );
296    }
297
298    #[test]
299    fn full_round_trip_rotates_control() {
300        let (a, b, _) = keys();
301        let mut auth = TwoStepAuthority::new(a);
302        auth.propose(&a, b).unwrap();
303        auth.accept(&b).unwrap();
304        // `a` is no longer the authority — its next propose is unauthorized,
305        // and `b` may now propose.
306        assert_eq!(
307            auth.propose(&a, Pubkey::new_unique()),
308            Err(AuthorityTransferError::Unauthorized)
309        );
310        assert_eq!(auth.propose(&b, Pubkey::new_unique()), Ok(()));
311    }
312}