Skip to main content

thru_base/
multisig.rs

1//! Client-side support for the on-chain multisig program
2//! (`programs/c/examples/tn_multisig_program.{c,h}`).
3//!
4//! Encoders and decoders mirror the packed structs in
5//! `tn_multisig_program.h` byte for byte. `MultisigLayout` builds the sorted
6//! transaction account list that both `CREATE_REQUEST` and `EXECUTE_REQUEST`
7//! must share: the program stores the account indices of an `INVOKE` request
8//! when it is proposed and requires the same pubkeys at the same indices when
9//! it is executed.
10
11use crate::txn_lib::{TnPubkey, Transaction};
12use crate::txn_tools::account_state_units;
13use anyhow::{Result, anyhow, bail, ensure};
14use sha2::{Digest, Sha256};
15
16/// Account discriminators: byte 0 of every account the multisig program owns
17/// (`TN_MULTISIG_ACCOUNT_TYPE_*_V1`). Values are never reused.
18pub const ACCOUNT_TYPE_MULTISIG_V1: u8 = 1;
19pub const ACCOUNT_TYPE_REQUEST_V1: u8 = 2;
20pub const MAX_MEMBERS: usize = 32;
21pub const MIN_MEMBERS: usize = 2;
22pub const MAX_REQUEST_DATA_SZ: usize = 4096;
23pub const MAX_LIVE_REQUESTS: u16 = 65535;
24
25pub const INSTR_CREATE_MULTISIG: u32 = 0;
26pub const INSTR_CREATE_REQUEST: u32 = 1;
27pub const INSTR_APPROVE_REQUEST: u32 = 2;
28pub const INSTR_EXECUTE_REQUEST: u32 = 3;
29pub const INSTR_DELETE_REQUEST: u32 = 4;
30
31pub const KIND_INVOKE: u8 = 0;
32pub const KIND_UPDATE_THRESHOLD: u8 = 1;
33pub const KIND_UPDATE_MEMBERSHIP: u8 = 2;
34pub const KIND_DELETE_MULTISIG: u8 = 3;
35
36pub const REQUEST_STATUS_OPEN: u8 = 0;
37
38/// Size of the packed `tn_multisig_account_t`.
39pub const MULTISIG_ACCOUNT_SZ: usize = 24 + 32 * MAX_MEMBERS;
40/// Size of the packed `tn_multisig_request_header_t`.
41pub const REQUEST_HEADER_SZ: usize = 40 + 32 + 32;
42/// Size of the packed `tn_multisig_invoke_request_t` (without trailing data).
43const INVOKE_HEADER_SZ: usize = 2 + 2 + 8 + 32;
44
45/// Program error codes (`TN_MULTISIG_ERR_*`), as (code, name, message).
46pub const ERRORS: &[(u64, &str, &str)] = &[
47    (
48        0x01,
49        "INVALID_INSTRUCTION",
50        "malformed multisig instruction",
51    ),
52    (
53        0x02,
54        "INVALID_ACCOUNT",
55        "account is not a multisig/request of this program",
56    ),
57    (
58        0x03,
59        "INVALID_STATE",
60        "multisig or request account is in an invalid state",
61    ),
62    (
63        0x04,
64        "UNAUTHORIZED",
65        "signer is not authorized for this action",
66    ),
67    (
68        0x05,
69        "ACCOUNT_CREATE_FAILED",
70        "could not create the account (already exists or bad proof)",
71    ),
72    (
73        0x06,
74        "ACCOUNT_RESIZE_FAILED",
75        "could not resize the account",
76    ),
77    (0x07, "ACCOUNT_WRITE_FAILED", "could not write the account"),
78    (
79        0x08,
80        "INVALID_MEMBER_COUNT",
81        "member count must be between 2 and 32",
82    ),
83    (
84        0x09,
85        "INVALID_THRESHOLD",
86        "threshold must be between 1 and the member count",
87    ),
88    (0x0A, "DUPLICATE_MEMBER", "member list contains a duplicate"),
89    (
90        0x0B,
91        "NOT_A_MEMBER",
92        "signer is not a member of this multisig",
93    ),
94    (
95        0x0C,
96        "DUPLICATE_APPROVAL",
97        "this member already approved the request",
98    ),
99    (
100        0x0D,
101        "REQUEST_STALE",
102        "the multisig changed after this request was proposed",
103    ),
104    (0x0E, "REQUEST_NOT_OPEN", "the request is not open"),
105    (
106        0x0F,
107        "REQUEST_NOT_APPROVED",
108        "the request does not have enough approvals yet",
109    ),
110    (0x10, "INVALID_REQUEST_KIND", "unknown request kind"),
111    (
112        0x11,
113        "INVALID_REQUEST_DATA",
114        "request data is malformed or accounts do not match",
115    ),
116    (0x12, "REQUEST_TOO_LARGE", "request data exceeds 4096 bytes"),
117    (0x13, "CPI_FAILED", "the invoked program failed"),
118    (
119        0x14,
120        "REQUEST_NOT_DELETABLE",
121        "only the proposer can cancel before approvals; anyone once stale",
122    ),
123    (
124        0x15,
125        "OUTSTANDING_REQUESTS",
126        "other requests are still live; cancel or execute them first",
127    ),
128    (0x16, "TOO_MANY_REQUESTS", "too many live requests"),
129];
130
131/// Looks up a multisig program error code.
132pub fn error_info(code: u64) -> Option<(&'static str, &'static str)> {
133    ERRORS
134        .iter()
135        .find(|(c, _, _)| *c == code)
136        .map(|(_, name, msg)| (*name, *msg))
137}
138
139pub fn kind_name(kind: u8) -> &'static str {
140    match kind {
141        KIND_INVOKE => "invoke",
142        KIND_UPDATE_THRESHOLD => "set-threshold",
143        KIND_UPDATE_MEMBERSHIP => "set-members",
144        KIND_DELETE_MULTISIG => "delete-multisig",
145        _ => "unknown",
146    }
147}
148
149/// Approvals a request of `kind` needs: config changes need a strict
150/// majority of all members, invokes need the threshold.
151pub fn required_approvals(kind: u8, member_cnt: u16, threshold: u16) -> u16 {
152    if kind == KIND_INVOKE {
153        threshold
154    } else {
155        member_cnt / 2 + 1
156    }
157}
158
159/* ---------- address derivation ---------- */
160
161/// Address of a non-ephemeral account created by `program` with `seed`
162/// (matches `tsys_account_create`).
163pub fn derive_account(program: &TnPubkey, seed: &[u8; 32]) -> TnPubkey {
164    let mut h = Sha256::new();
165    h.update(program);
166    h.update([0u8]);
167    h.update(seed);
168    let out = h.finalize();
169    let mut addr = [0u8; 32];
170    addr.copy_from_slice(&out[..32]);
171    addr
172}
173
174/// Turns a user-supplied seed string into 32 seed bytes. A 64-char hex
175/// string is used as is; anything else is hashed so any label works.
176pub fn seed_from_str(seed: &str) -> [u8; 32] {
177    if seed.len() == 64 {
178        if let Ok(bytes) = hex::decode(seed) {
179            let mut out = [0u8; 32];
180            out.copy_from_slice(&bytes);
181            return out;
182        }
183    }
184    let mut h = Sha256::new();
185    h.update(b"tn_multisig_seed");
186    h.update(seed.as_bytes());
187    let out = h.finalize();
188    let mut s = [0u8; 32];
189    s.copy_from_slice(&out[..32]);
190    s
191}
192
193/// Deterministic seed for the request with id `request_id` of `multisig`.
194pub fn request_seed(multisig: &TnPubkey, request_id: u64, attempt: u32) -> [u8; 32] {
195    let mut h = Sha256::new();
196    h.update(b"tn_multisig_request");
197    h.update(multisig);
198    h.update(request_id.to_le_bytes());
199    if attempt != 0 {
200        h.update(attempt.to_le_bytes());
201    }
202    let out = h.finalize();
203    let mut s = [0u8; 32];
204    s.copy_from_slice(&out[..32]);
205    s
206}
207
208/* ---------- instruction encoders ---------- */
209
210pub fn encode_create_multisig(
211    multisig_idx: u16,
212    creator_idx: u16,
213    members: &[TnPubkey],
214    threshold: u16,
215    seed: &[u8; 32],
216    proof: &[u8],
217) -> Vec<u8> {
218    let mut d = Vec::with_capacity(52 + members.len() * 32 + proof.len());
219    d.extend_from_slice(&INSTR_CREATE_MULTISIG.to_le_bytes());
220    d.extend_from_slice(&multisig_idx.to_le_bytes());
221    d.extend_from_slice(&creator_idx.to_le_bytes());
222    d.extend_from_slice(&(members.len() as u16).to_le_bytes());
223    d.extend_from_slice(&threshold.to_le_bytes());
224    d.extend_from_slice(seed);
225    d.extend_from_slice(&(proof.len() as u64).to_le_bytes());
226    for m in members {
227        d.extend_from_slice(m);
228    }
229    d.extend_from_slice(proof);
230    d
231}
232
233pub fn encode_create_request(
234    multisig_idx: u16,
235    request_idx: u16,
236    proposer_idx: u16,
237    kind: u8,
238    seed: &[u8; 32],
239    request_data: &[u8],
240    proof: &[u8],
241) -> Vec<u8> {
242    let mut d = Vec::with_capacity(60 + request_data.len() + proof.len());
243    d.extend_from_slice(&INSTR_CREATE_REQUEST.to_le_bytes());
244    d.extend_from_slice(&multisig_idx.to_le_bytes());
245    d.extend_from_slice(&request_idx.to_le_bytes());
246    d.extend_from_slice(&proposer_idx.to_le_bytes());
247    d.push(kind);
248    d.push(0);
249    d.extend_from_slice(seed);
250    d.extend_from_slice(&(request_data.len() as u64).to_le_bytes());
251    d.extend_from_slice(&(proof.len() as u64).to_le_bytes());
252    d.extend_from_slice(request_data);
253    d.extend_from_slice(proof);
254    d
255}
256
257/// `APPROVE_REQUEST`. The program only counts the approval for the request
258/// whose `request_id` and `sha256(request data)` match, so an approval can't
259/// land on a request recreated at the same address after it was reviewed.
260pub fn encode_approve_request(
261    multisig_idx: u16,
262    request_idx: u16,
263    approver_idx: u16,
264    expected_request_id: u64,
265    expected_request_hash: &[u8; 32],
266) -> Vec<u8> {
267    let mut d = Vec::with_capacity(50);
268    d.extend_from_slice(&INSTR_APPROVE_REQUEST.to_le_bytes());
269    d.extend_from_slice(&multisig_idx.to_le_bytes());
270    d.extend_from_slice(&request_idx.to_le_bytes());
271    d.extend_from_slice(&approver_idx.to_le_bytes());
272    d.extend_from_slice(&expected_request_id.to_le_bytes());
273    d.extend_from_slice(expected_request_hash);
274    d
275}
276
277/// The hash an approval names: `sha256(request data)` as stored on chain.
278pub fn request_data_hash(request_data: &[u8]) -> [u8; 32] {
279    let out = Sha256::digest(request_data);
280    let mut h = [0u8; 32];
281    h.copy_from_slice(&out[..32]);
282    h
283}
284
285pub fn encode_execute_request(multisig_idx: u16, request_idx: u16) -> Vec<u8> {
286    let mut d = Vec::with_capacity(8);
287    d.extend_from_slice(&INSTR_EXECUTE_REQUEST.to_le_bytes());
288    d.extend_from_slice(&multisig_idx.to_le_bytes());
289    d.extend_from_slice(&request_idx.to_le_bytes());
290    d
291}
292
293pub fn encode_delete_request(multisig_idx: u16, request_idx: u16, requester_idx: u16) -> Vec<u8> {
294    let mut d = Vec::with_capacity(10);
295    d.extend_from_slice(&INSTR_DELETE_REQUEST.to_le_bytes());
296    d.extend_from_slice(&multisig_idx.to_le_bytes());
297    d.extend_from_slice(&request_idx.to_le_bytes());
298    d.extend_from_slice(&requester_idx.to_le_bytes());
299    d
300}
301
302/* ---------- request payloads ---------- */
303
304#[derive(Debug, Clone, PartialEq, Eq)]
305pub struct InvokePayload {
306    pub target_program_idx: u16,
307    pub target_program: TnPubkey,
308    /// (account index, pubkey) for every account the child instruction uses.
309    pub refs: Vec<(u16, TnPubkey)>,
310    pub instr_data: Vec<u8>,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq)]
314pub enum RequestPayload {
315    Invoke(InvokePayload),
316    UpdateThreshold { new_threshold: u16 },
317    UpdateMembership { members: Vec<TnPubkey> },
318    DeleteMultisig,
319}
320
321impl RequestPayload {
322    pub fn kind(&self) -> u8 {
323        match self {
324            RequestPayload::Invoke(_) => KIND_INVOKE,
325            RequestPayload::UpdateThreshold { .. } => KIND_UPDATE_THRESHOLD,
326            RequestPayload::UpdateMembership { .. } => KIND_UPDATE_MEMBERSHIP,
327            RequestPayload::DeleteMultisig => KIND_DELETE_MULTISIG,
328        }
329    }
330
331    pub fn encode(&self) -> Vec<u8> {
332        match self {
333            RequestPayload::Invoke(p) => {
334                let mut d = Vec::new();
335                d.extend_from_slice(&p.target_program_idx.to_le_bytes());
336                d.extend_from_slice(&(p.refs.len() as u16).to_le_bytes());
337                d.extend_from_slice(&(p.instr_data.len() as u64).to_le_bytes());
338                d.extend_from_slice(&p.target_program);
339                for (idx, _) in &p.refs {
340                    d.extend_from_slice(&idx.to_le_bytes());
341                }
342                for (_, key) in &p.refs {
343                    d.extend_from_slice(key);
344                }
345                d.extend_from_slice(&p.instr_data);
346                d
347            }
348            RequestPayload::UpdateThreshold { new_threshold } => {
349                let mut d = new_threshold.to_le_bytes().to_vec();
350                d.extend_from_slice(&0u16.to_le_bytes());
351                d
352            }
353            RequestPayload::UpdateMembership { members } => {
354                let mut d = (members.len() as u16).to_le_bytes().to_vec();
355                d.extend_from_slice(&0u16.to_le_bytes());
356                for m in members {
357                    d.extend_from_slice(m);
358                }
359                d
360            }
361            RequestPayload::DeleteMultisig => Vec::new(),
362        }
363    }
364
365    pub fn decode(kind: u8, data: &[u8]) -> Result<Self> {
366        match kind {
367            KIND_INVOKE => {
368                ensure!(data.len() >= INVOKE_HEADER_SZ, "invoke payload too short");
369                let target_program_idx = u16_at(data, 0);
370                let ref_cnt = u16_at(data, 2) as usize;
371                let instr_sz = u64_at(data, 4) as usize;
372                let target_program = key_at(data, 12);
373                let idxs_off = INVOKE_HEADER_SZ;
374                let keys_off = idxs_off + ref_cnt * 2;
375                let data_off = keys_off + ref_cnt * 32;
376                ensure!(
377                    data.len() == data_off + instr_sz,
378                    "invoke payload size mismatch ({} != {})",
379                    data.len(),
380                    data_off + instr_sz
381                );
382                let refs = (0..ref_cnt)
383                    .map(|i| {
384                        (
385                            u16_at(data, idxs_off + i * 2),
386                            key_at(data, keys_off + i * 32),
387                        )
388                    })
389                    .collect();
390                Ok(RequestPayload::Invoke(InvokePayload {
391                    target_program_idx,
392                    target_program,
393                    refs,
394                    instr_data: data[data_off..].to_vec(),
395                }))
396            }
397            KIND_UPDATE_THRESHOLD => {
398                ensure!(data.len() == 4, "set-threshold payload must be 4 bytes");
399                Ok(RequestPayload::UpdateThreshold {
400                    new_threshold: u16_at(data, 0),
401                })
402            }
403            KIND_UPDATE_MEMBERSHIP => {
404                ensure!(data.len() >= 4, "set-members payload too short");
405                let cnt = u16_at(data, 0) as usize;
406                ensure!(
407                    data.len() == 4 + cnt * 32,
408                    "set-members payload size mismatch"
409                );
410                Ok(RequestPayload::UpdateMembership {
411                    members: (0..cnt).map(|i| key_at(data, 4 + i * 32)).collect(),
412                })
413            }
414            KIND_DELETE_MULTISIG => Ok(RequestPayload::DeleteMultisig),
415            other => bail!("unknown request kind {}", other),
416        }
417    }
418}
419
420/* ---------- account decoders ---------- */
421
422#[derive(Debug, Clone, PartialEq, Eq)]
423pub struct MultisigAccount {
424    pub account_type: u8,
425    pub flags: u8,
426    pub threshold: u16,
427    pub live_request_cnt: u16,
428    pub config_epoch: u64,
429    pub next_request_id: u64,
430    /// Sorted, as stored on chain. Bit `i` of a request's approval bitmap is
431    /// `members[i]`.
432    pub members: Vec<TnPubkey>,
433}
434
435impl MultisigAccount {
436    pub fn decode(data: &[u8]) -> Result<Self> {
437        ensure!(
438            data.len() >= 24,
439            "multisig account data too short ({} bytes)",
440            data.len()
441        );
442        let account_type = data[0];
443        ensure!(
444            account_type == ACCOUNT_TYPE_MULTISIG_V1,
445            "account type {} is not a multisig account (expected {})",
446            account_type,
447            ACCOUNT_TYPE_MULTISIG_V1
448        );
449        let member_cnt = u16_at(data, 2) as usize;
450        ensure!(
451            member_cnt <= MAX_MEMBERS,
452            "invalid member count {}",
453            member_cnt
454        );
455        ensure!(
456            data.len() >= 24 + member_cnt * 32,
457            "multisig account data truncated"
458        );
459        Ok(MultisigAccount {
460            account_type,
461            flags: data[1],
462            threshold: u16_at(data, 4),
463            live_request_cnt: u16_at(data, 6),
464            config_epoch: u64_at(data, 8),
465            next_request_id: u64_at(data, 16),
466            members: (0..member_cnt).map(|i| key_at(data, 24 + i * 32)).collect(),
467        })
468    }
469
470    pub fn member_index(&self, key: &TnPubkey) -> Option<usize> {
471        self.members.iter().position(|m| m == key)
472    }
473}
474
475#[derive(Debug, Clone, PartialEq, Eq)]
476pub struct RequestAccount {
477    pub account_type: u8,
478    pub kind: u8,
479    pub status: u8,
480    pub member_cnt_snapshot: u16,
481    pub required_approvals: u16,
482    pub request_id: u64,
483    pub config_epoch_snapshot: u64,
484    pub approval_bitmap: u64,
485    pub multisig: TnPubkey,
486    pub proposer: TnPubkey,
487    pub payload: RequestPayload,
488    /// The request data exactly as stored (what approvals hash).
489    pub raw_payload: Vec<u8>,
490}
491
492impl RequestAccount {
493    pub fn decode(data: &[u8]) -> Result<Self> {
494        ensure!(
495            data.len() >= REQUEST_HEADER_SZ,
496            "request account data too short ({} bytes)",
497            data.len()
498        );
499        let account_type = data[0];
500        ensure!(
501            account_type == ACCOUNT_TYPE_REQUEST_V1,
502            "account type {} is not a multisig request account (expected {})",
503            account_type,
504            ACCOUNT_TYPE_REQUEST_V1
505        );
506        let kind = data[1];
507        let data_sz = u64_at(data, 32) as usize;
508        ensure!(
509            data.len() >= REQUEST_HEADER_SZ + data_sz,
510            "request account data truncated"
511        );
512        let raw_payload = data[REQUEST_HEADER_SZ..REQUEST_HEADER_SZ + data_sz].to_vec();
513        let payload = RequestPayload::decode(kind, &raw_payload)?;
514        Ok(RequestAccount {
515            account_type,
516            kind,
517            status: data[2],
518            member_cnt_snapshot: u16_at(data, 4),
519            required_approvals: u16_at(data, 6),
520            request_id: u64_at(data, 8),
521            config_epoch_snapshot: u64_at(data, 16),
522            approval_bitmap: u64_at(data, 24),
523            multisig: key_at(data, 40),
524            proposer: key_at(data, 72),
525            payload,
526            raw_payload,
527        })
528    }
529
530    /// `sha256` of the stored request data, as an approval must name it.
531    pub fn data_hash(&self) -> [u8; 32] {
532        request_data_hash(&self.raw_payload)
533    }
534
535    pub fn approval_count(&self) -> u32 {
536        self.approval_bitmap.count_ones()
537    }
538
539    pub fn has_approved(&self, member_idx: usize) -> bool {
540        member_idx < 64 && (self.approval_bitmap >> member_idx) & 1 == 1
541    }
542
543    pub fn is_stale(&self, multisig: &MultisigAccount) -> bool {
544        self.config_epoch_snapshot != multisig.config_epoch
545    }
546
547    /// Members (from the current multisig state) who approved.
548    pub fn approvers(&self, multisig: &MultisigAccount) -> Vec<TnPubkey> {
549        multisig
550            .members
551            .iter()
552            .enumerate()
553            .filter(|(i, _)| self.has_approved(*i))
554            .map(|(_, k)| *k)
555            .collect()
556    }
557}
558
559/* ---------- transaction layout ---------- */
560
561/// The account list of a multisig program transaction: fee payer at 0, the
562/// multisig program at 1, then read-write accounts sorted, then read-only
563/// accounts sorted.
564#[derive(Debug, Clone, PartialEq, Eq)]
565pub struct MultisigLayout {
566    pub fee_payer: TnPubkey,
567    pub program: TnPubkey,
568    pub rw: Vec<TnPubkey>,
569    pub ro: Vec<TnPubkey>,
570}
571
572impl MultisigLayout {
573    /// Builds a layout. Duplicates are merged (read-write wins), and the fee
574    /// payer and program are dropped from the lists since they have fixed
575    /// slots.
576    pub fn new(fee_payer: TnPubkey, program: TnPubkey, rw: &[TnPubkey], ro: &[TnPubkey]) -> Self {
577        let keep = |k: &TnPubkey| *k != fee_payer && *k != program;
578        let mut rw_v: Vec<TnPubkey> = rw.iter().copied().filter(keep).collect();
579        rw_v.sort();
580        rw_v.dedup();
581        let mut ro_v: Vec<TnPubkey> = ro
582            .iter()
583            .copied()
584            .filter(keep)
585            .filter(|k| rw_v.binary_search(k).is_err())
586            .collect();
587        ro_v.sort();
588        ro_v.dedup();
589        MultisigLayout {
590            fee_payer,
591            program,
592            rw: rw_v,
593            ro: ro_v,
594        }
595    }
596
597    pub fn index_of(&self, key: &TnPubkey) -> Option<u16> {
598        if *key == self.fee_payer {
599            return Some(0);
600        }
601        if *key == self.program {
602            return Some(1);
603        }
604        if let Ok(i) = self.rw.binary_search(key) {
605            return Some(2 + i as u16);
606        }
607        if let Ok(i) = self.ro.binary_search(key) {
608            return Some(2 + self.rw.len() as u16 + i as u16);
609        }
610        None
611    }
612
613    pub fn idx(&self, key: &TnPubkey) -> Result<u16> {
614        self.index_of(key)
615            .ok_or_else(|| anyhow!("account {} is not in the transaction", short_hex(key)))
616    }
617
618    pub fn is_writable(&self, key: &TnPubkey) -> bool {
619        *key == self.fee_payer || self.rw.binary_search(key).is_ok()
620    }
621
622    /// Adds the layout's accounts to a transaction built with
623    /// `Transaction::new(fee_payer, program, ..)`.
624    pub fn apply(&self, mut tx: Transaction) -> Transaction {
625        for k in &self.rw {
626            tx = tx.add_rw_account(*k);
627        }
628        for k in &self.ro {
629            tx = tx.add_r_account(*k);
630        }
631        tx
632    }
633
634    /// The layout `CREATE_REQUEST` and `EXECUTE_REQUEST` share: the multisig
635    /// and request accounts are read-write, plus the child call's accounts.
636    pub fn for_request(
637        fee_payer: TnPubkey,
638        program: TnPubkey,
639        multisig: TnPubkey,
640        request: TnPubkey,
641        child_rw: &[TnPubkey],
642        child_ro: &[TnPubkey],
643    ) -> Self {
644        let mut rw = vec![multisig, request];
645        rw.extend_from_slice(child_rw);
646        Self::new(fee_payer, program, &rw, child_ro)
647    }
648
649    /// Rebuilds the execute-time layout from a stored request. Stored
650    /// (index, pubkey) pairs pin each referenced account's position. The
651    /// request does not record which accounts were writable, so the
652    /// read-write/read-only split must be the only one that satisfies every
653    /// stored index; an ambiguous request is refused rather than guessed.
654    /// `propose` only submits requests that `reproduces` accepts.
655    pub fn from_request(
656        executor: TnPubkey,
657        program: TnPubkey,
658        multisig: TnPubkey,
659        request: TnPubkey,
660        req: &RequestAccount,
661    ) -> Result<Self> {
662        Self::from_payload(executor, program, multisig, request, &req.payload)
663    }
664
665    pub fn from_payload(
666        executor: TnPubkey,
667        program: TnPubkey,
668        multisig: TnPubkey,
669        request: TnPubkey,
670        payload: &RequestPayload,
671    ) -> Result<Self> {
672        let invoke = match payload {
673            RequestPayload::Invoke(p) => p,
674            _ => {
675                return Ok(Self::for_request(
676                    executor,
677                    program,
678                    multisig,
679                    request,
680                    &[],
681                    &[],
682                ));
683            }
684        };
685
686        let mut pinned: Vec<(u16, TnPubkey)> = invoke.refs.clone();
687        pinned.push((invoke.target_program_idx, invoke.target_program));
688        pinned.sort();
689        pinned.dedup();
690
691        for (idx, key) in &pinned {
692            if *idx == 0 && *key != executor {
693                bail!(
694                    "this request references {} as the fee payer (index 0); execute it with that key as --fee-payer",
695                    short_hex(key)
696                );
697            }
698            if *idx == 1 && *key != program {
699                bail!(
700                    "request pins index 1 to {}, which is not the multisig program",
701                    short_hex(key)
702                );
703            }
704            if *key == executor && *idx != 0 {
705                bail!(
706                    "the executing key {} is referenced by this request; execute with a different --fee-payer",
707                    short_hex(key)
708                );
709            }
710        }
711
712        let movable: Vec<(u16, TnPubkey)> =
713            pinned.iter().copied().filter(|(i, _)| *i >= 2).collect();
714        let mut all: Vec<TnPubkey> = movable.iter().map(|(_, k)| *k).collect();
715        for k in [multisig, request] {
716            if !all.contains(&k) {
717                all.push(k);
718            }
719        }
720        all.sort();
721        all.dedup();
722        let total = all.len();
723
724        let mut found: Vec<Self> = Vec::new();
725        for rw_cnt in 2..=total {
726            let boundary = 2 + rw_cnt as u16;
727            let mut rw: Vec<TnPubkey> = vec![multisig, request];
728            let mut ro: Vec<TnPubkey> = Vec::new();
729            for (idx, key) in &movable {
730                if *key == multisig || *key == request {
731                    continue;
732                }
733                if *idx < boundary {
734                    rw.push(*key);
735                } else {
736                    ro.push(*key);
737                }
738            }
739            if rw.iter().any(|k| *k == invoke.target_program) {
740                continue;
741            }
742            let layout = Self::new(executor, program, &rw, &ro);
743            if layout.rw.len() != rw_cnt || layout.rw.len() + layout.ro.len() != total {
744                continue;
745            }
746            if pinned
747                .iter()
748                .all(|(idx, key)| layout.index_of(key) == Some(*idx))
749            {
750                found.push(layout);
751            }
752        }
753        match found.len() {
754            1 => Ok(found.remove(0)),
755            0 => bail!("could not rebuild the account layout this request was proposed with"),
756            _ => bail!(
757                "this request's writable/read-only accounts are ambiguous; it can't be executed safely"
758            ),
759        }
760    }
761
762    /// True if executing `payload` (from any other fee payer) rebuilds
763    /// exactly this layout's writable and read-only accounts.
764    pub fn reproduces(
765        &self,
766        multisig: TnPubkey,
767        request: TnPubkey,
768        payload: &RequestPayload,
769    ) -> bool {
770        let probe_executor = [0xEEu8; 32];
771        match Self::from_payload(probe_executor, self.program, multisig, request, payload) {
772            Ok(l) => l.rw == self.rw && l.ro == self.ro,
773            Err(_) => false,
774        }
775    }
776}
777
778/* ---------- transactions ---------- */
779
780pub const CREATE_COMPUTE_UNITS: u32 = 500_000;
781pub const SIMPLE_COMPUTE_UNITS: u32 = 300_000;
782pub const EXECUTE_COMPUTE_UNITS: u32 = 1_000_000;
783pub const MEMORY_UNITS: u16 = 10_000;
784pub const EXPIRY_AFTER: u32 = 100;
785
786pub struct TxParams {
787    pub fee: u64,
788    pub nonce: u64,
789    pub start_slot: u64,
790    pub chain_id: u16,
791}
792
793fn base_tx(fee_payer: TnPubkey, program: TnPubkey, p: &TxParams, cu: u32, su: u16) -> Transaction {
794    Transaction::new(fee_payer, program, p.fee, p.nonce)
795        .with_start_slot(p.start_slot)
796        .with_chain_id(p.chain_id)
797        .with_expiry_after(EXPIRY_AFTER)
798        .with_compute_units(cu)
799        .with_state_units(su)
800        .with_memory_units(MEMORY_UNITS)
801}
802
803pub fn build_create_multisig_tx(
804    creator: TnPubkey,
805    program: TnPubkey,
806    seed: &[u8; 32],
807    members: &[TnPubkey],
808    threshold: u16,
809    proof: &[u8],
810    p: &TxParams,
811) -> Result<(Transaction, TnPubkey)> {
812    let multisig = derive_account(&program, seed);
813    let layout = MultisigLayout::new(creator, program, &[multisig], &[]);
814    let data = encode_create_multisig(layout.idx(&multisig)?, 0, members, threshold, seed, proof);
815    let state_units = account_state_units(MULTISIG_ACCOUNT_SZ as u64)?;
816    let tx = layout.apply(base_tx(
817        creator,
818        program,
819        p,
820        CREATE_COMPUTE_UNITS,
821        state_units,
822    ));
823    Ok((tx.with_instructions(data), multisig))
824}
825
826/// Builds `CREATE_REQUEST`. For an invoke, `payload` must have been encoded
827/// against `layout` (see `MultisigLayout::for_request`).
828pub fn build_create_request_tx(
829    layout: &MultisigLayout,
830    multisig: TnPubkey,
831    request: TnPubkey,
832    seed: &[u8; 32],
833    payload: &RequestPayload,
834    proof: &[u8],
835    p: &TxParams,
836) -> Result<Transaction> {
837    let req_data = payload.encode();
838    ensure!(
839        req_data.len() <= MAX_REQUEST_DATA_SZ,
840        "request data is {} bytes; max is {}",
841        req_data.len(),
842        MAX_REQUEST_DATA_SZ
843    );
844    let data = encode_create_request(
845        layout.idx(&multisig)?,
846        layout.idx(&request)?,
847        0,
848        payload.kind(),
849        seed,
850        &req_data,
851        proof,
852    );
853    let state_units = account_state_units((REQUEST_HEADER_SZ + req_data.len()) as u64)?;
854    let tx = layout.apply(base_tx(
855        layout.fee_payer,
856        layout.program,
857        p,
858        CREATE_COMPUTE_UNITS,
859        state_units,
860    ));
861    Ok(tx.with_instructions(data))
862}
863
864pub fn build_approve_tx(
865    approver: TnPubkey,
866    program: TnPubkey,
867    multisig: TnPubkey,
868    request: TnPubkey,
869    request_id: u64,
870    request_hash: &[u8; 32],
871    p: &TxParams,
872) -> Result<Transaction> {
873    let layout = MultisigLayout::new(approver, program, &[request], &[multisig]);
874    let data = encode_approve_request(
875        layout.idx(&multisig)?,
876        layout.idx(&request)?,
877        0,
878        request_id,
879        request_hash,
880    );
881    let tx = layout.apply(base_tx(approver, program, p, SIMPLE_COMPUTE_UNITS, 0));
882    Ok(tx.with_instructions(data))
883}
884
885pub fn build_execute_tx(
886    layout: &MultisigLayout,
887    multisig: TnPubkey,
888    request: TnPubkey,
889    compute_units: u32,
890    state_units: u16,
891    p: &TxParams,
892) -> Result<Transaction> {
893    let data = encode_execute_request(layout.idx(&multisig)?, layout.idx(&request)?);
894    let tx = layout.apply(base_tx(
895        layout.fee_payer,
896        layout.program,
897        p,
898        compute_units,
899        state_units,
900    ));
901    Ok(tx.with_instructions(data))
902}
903
904pub fn build_delete_tx(
905    requester: TnPubkey,
906    program: TnPubkey,
907    multisig: TnPubkey,
908    request: TnPubkey,
909    p: &TxParams,
910) -> Result<Transaction> {
911    let layout = MultisigLayout::new(requester, program, &[multisig, request], &[]);
912    let data = encode_delete_request(layout.idx(&multisig)?, layout.idx(&request)?, 0);
913    let tx = layout.apply(base_tx(requester, program, p, SIMPLE_COMPUTE_UNITS, 0));
914    Ok(tx.with_instructions(data))
915}
916
917/* ---------- helpers ---------- */
918
919fn u16_at(d: &[u8], o: usize) -> u16 {
920    u16::from_le_bytes([d[o], d[o + 1]])
921}
922
923fn u64_at(d: &[u8], o: usize) -> u64 {
924    let mut b = [0u8; 8];
925    b.copy_from_slice(&d[o..o + 8]);
926    u64::from_le_bytes(b)
927}
928
929fn key_at(d: &[u8], o: usize) -> TnPubkey {
930    let mut k = [0u8; 32];
931    k.copy_from_slice(&d[o..o + 32]);
932    k
933}
934
935fn short_hex(k: &TnPubkey) -> String {
936    hex::encode(&k[..6])
937}
938
939#[cfg(test)]
940mod tests {
941    use super::*;
942
943    fn k(b: u8) -> TnPubkey {
944        [b; 32]
945    }
946
947    #[test]
948    fn approve_execute_delete_golden() {
949        // Same bytes as the Python builders in multisig_fullnode.py.
950        let approve = hex::encode(encode_approve_request(3, 2, 0, 7, &[0xAB; 32]));
951        assert_eq!(approve.len(), 2 * 50);
952        assert_eq!(&approve[..36], "020000000300020000000700000000000000");
953        assert_eq!(&approve[36..], "ab".repeat(32));
954        assert_eq!(
955            hex::encode(encode_execute_request(2, 4)),
956            "0300000002000400"
957        );
958        assert_eq!(
959            hex::encode(encode_delete_request(2, 3, 0)),
960            "04000000020003000000"
961        );
962    }
963
964    #[test]
965    fn create_multisig_layout_matches_header() {
966        let d = encode_create_multisig(2, 0, &[k(1), k(2)], 2, &k(9), &[0xAA, 0xBB]);
967        // u32 + 4*u16 + seed + u64 = 52 bytes of fixed args.
968        assert_eq!(&d[0..4], &[0, 0, 0, 0]);
969        assert_eq!(u16_at(&d, 8), 2);
970        assert_eq!(u16_at(&d, 10), 2);
971        assert_eq!(&d[12..44], &k(9));
972        assert_eq!(u64_at(&d, 44), 2);
973        assert_eq!(&d[52..84], &k(1));
974        assert_eq!(&d[116..], &[0xAA, 0xBB]);
975    }
976
977    #[test]
978    fn create_request_layout_matches_header() {
979        let payload = RequestPayload::UpdateThreshold { new_threshold: 3 };
980        let d = encode_create_request(
981            2,
982            3,
983            0,
984            payload.kind(),
985            &k(7),
986            &payload.encode(),
987            &[1, 2, 3],
988        );
989        assert_eq!(
990            u32::from_le_bytes([d[0], d[1], d[2], d[3]]),
991            INSTR_CREATE_REQUEST
992        );
993        assert_eq!(d[10], KIND_UPDATE_THRESHOLD);
994        assert_eq!(&d[12..44], &k(7));
995        assert_eq!(u64_at(&d, 44), 4);
996        assert_eq!(u64_at(&d, 52), 3);
997        assert_eq!(&d[60..64], &[3, 0, 0, 0]);
998        assert_eq!(&d[64..], &[1, 2, 3]);
999    }
1000
1001    #[test]
1002    fn payload_round_trip() {
1003        let payloads = vec![
1004            RequestPayload::Invoke(InvokePayload {
1005                target_program_idx: 6,
1006                target_program: k(0xEE),
1007                refs: vec![(2, k(3)), (5, k(4))],
1008                instr_data: vec![9, 8, 7],
1009            }),
1010            RequestPayload::UpdateThreshold { new_threshold: 2 },
1011            RequestPayload::UpdateMembership {
1012                members: vec![k(1), k(2), k(3)],
1013            },
1014            RequestPayload::DeleteMultisig,
1015        ];
1016        for p in payloads {
1017            assert_eq!(RequestPayload::decode(p.kind(), &p.encode()).unwrap(), p);
1018        }
1019    }
1020
1021    fn request_account(payload: RequestPayload, bitmap: u64) -> Vec<u8> {
1022        let body = payload.encode();
1023        let mut d = vec![ACCOUNT_TYPE_REQUEST_V1, payload.kind(), 0, 0];
1024        d.extend_from_slice(&3u16.to_le_bytes());
1025        d.extend_from_slice(&2u16.to_le_bytes());
1026        d.extend_from_slice(&7u64.to_le_bytes());
1027        d.extend_from_slice(&1u64.to_le_bytes());
1028        d.extend_from_slice(&bitmap.to_le_bytes());
1029        d.extend_from_slice(&(body.len() as u64).to_le_bytes());
1030        d.extend_from_slice(&k(0x11));
1031        d.extend_from_slice(&k(0x22));
1032        d.extend_from_slice(&body);
1033        d
1034    }
1035
1036    #[test]
1037    fn decode_accounts() {
1038        let mut ms = vec![ACCOUNT_TYPE_MULTISIG_V1, 0];
1039        ms.extend_from_slice(&3u16.to_le_bytes());
1040        ms.extend_from_slice(&2u16.to_le_bytes());
1041        ms.extend_from_slice(&1u16.to_le_bytes());
1042        ms.extend_from_slice(&1u64.to_le_bytes());
1043        ms.extend_from_slice(&8u64.to_le_bytes());
1044        for b in [1u8, 2, 3] {
1045            ms.extend_from_slice(&k(b));
1046        }
1047        ms.resize(MULTISIG_ACCOUNT_SZ, 0);
1048        let m = MultisigAccount::decode(&ms).unwrap();
1049        assert_eq!(m.members, vec![k(1), k(2), k(3)]);
1050        assert_eq!(
1051            (
1052                m.threshold,
1053                m.live_request_cnt,
1054                m.config_epoch,
1055                m.next_request_id
1056            ),
1057            (2, 1, 1, 8)
1058        );
1059
1060        let r = RequestAccount::decode(&request_account(RequestPayload::DeleteMultisig, 0b101))
1061            .unwrap();
1062        assert_eq!(r.request_id, 7);
1063        assert_eq!(r.multisig, k(0x11));
1064        assert_eq!(r.proposer, k(0x22));
1065        assert_eq!(r.approval_count(), 2);
1066        assert_eq!(r.approvers(&m), vec![k(1), k(3)]);
1067        assert_eq!(
1068            r.data_hash(),
1069            request_data_hash(&RequestPayload::DeleteMultisig.encode())
1070        );
1071        assert!(!r.is_stale(&m));
1072
1073        /* Each decoder accepts only its own account type. */
1074        assert!(RequestAccount::decode(&ms).is_err());
1075        let mut request = request_account(RequestPayload::DeleteMultisig, 0b101);
1076        assert!(MultisigAccount::decode(&request).is_err());
1077        request[0] = 0;
1078        assert!(RequestAccount::decode(&request).is_err());
1079    }
1080
1081    /// Propose with one fee payer, execute with another: the rebuilt layout
1082    /// must put every referenced account at its stored index.
1083    fn invoke_for(
1084        create: &MultisigLayout,
1085        ms: TnPubkey,
1086        child: &[TnPubkey],
1087        target: TnPubkey,
1088    ) -> RequestPayload {
1089        let mut refs: Vec<(u16, TnPubkey)> = child
1090            .iter()
1091            .chain([ms].iter())
1092            .map(|key| (create.index_of(key).unwrap(), *key))
1093            .collect();
1094        refs.sort();
1095        refs.dedup();
1096        RequestPayload::Invoke(InvokePayload {
1097            target_program_idx: create.index_of(&target).unwrap(),
1098            target_program: target,
1099            refs,
1100            instr_data: vec![1],
1101        })
1102    }
1103
1104    /// Propose with one fee payer, execute with another: picks a request
1105    /// address the proposal reproduces with (as `propose` does), then checks
1106    /// the rebuilt layout has the same indices and the same access modes.
1107    fn round_trip(child_rw: &[TnPubkey], child_ro: &[TnPubkey], target: TnPubkey) {
1108        let program = k(0x01);
1109        let ms = k(0x50);
1110        let (proposer, executor) = (k(0xA0), k(0xB0));
1111        let mut ro = child_ro.to_vec();
1112        ro.push(target);
1113        let child: Vec<TnPubkey> = child_rw.iter().chain(child_ro).copied().collect();
1114        let (req, create, payload) = (0x02u8..=0xFE)
1115            .map(|b| {
1116                let mut req = [b; 32];
1117                req[31] = 0x77;
1118                let create = MultisigLayout::for_request(proposer, program, ms, req, child_rw, &ro);
1119                let payload = invoke_for(&create, ms, &child, target);
1120                (req, create, payload)
1121            })
1122            .find(|(req, create, payload)| create.reproduces(ms, *req, payload))
1123            .expect("some request address reproduces");
1124        let stored = RequestAccount::decode(&request_account(payload, 0)).unwrap();
1125        let exec = MultisigLayout::from_request(executor, program, ms, req, &stored).unwrap();
1126        assert_eq!(
1127            (exec.rw.clone(), exec.ro.clone()),
1128            (create.rw.clone(), create.ro.clone())
1129        );
1130        for key in child.iter().chain([target, ms].iter()) {
1131            assert_eq!(exec.index_of(key), create.index_of(key));
1132        }
1133        assert!(!exec.is_writable(&target));
1134    }
1135
1136    #[test]
1137    fn ambiguous_access_modes_are_refused() {
1138        // rw {ms 0x50, req 0x60} all sort before ro {0x70, target 0x90}: 0x70
1139        // could be read-only or writable with the same indices.
1140        let (program, ms, target, ro_acct) = (k(1), k(0x50), k(0x90), k(0x70));
1141        let create =
1142            MultisigLayout::for_request(k(0xA0), program, ms, k(0x60), &[], &[ro_acct, target]);
1143        let payload = invoke_for(&create, ms, &[ro_acct], target);
1144        assert!(!create.reproduces(ms, k(0x60), &payload));
1145        assert!(MultisigLayout::from_payload(k(0xB0), program, ms, k(0x60), &payload).is_err());
1146        // A request address sorting after 0x70 removes the ambiguity.
1147        let create =
1148            MultisigLayout::for_request(k(0xA0), program, ms, k(0x80), &[], &[ro_acct, target]);
1149        let payload = invoke_for(&create, ms, &[ro_acct], target);
1150        assert!(create.reproduces(ms, k(0x80), &payload));
1151    }
1152
1153    #[test]
1154    fn layout_round_trips() {
1155        round_trip(&[k(0x30), k(0x70)], &[], k(0x90)); // token mint-to style
1156        round_trip(&[], &[k(0x20)], k(0x10)); // read-only child accounts
1157        round_trip(&[k(0x05)], &[k(0x99)], k(0x02)); // interleaved order
1158        round_trip(&[], &[], k(0x40)); // only the multisig
1159        round_trip(&[k(0x55), k(0x56), k(0x57)], &[k(0x58)], k(0xFF));
1160    }
1161
1162    #[test]
1163    fn executor_referenced_is_rejected() {
1164        let program = k(1);
1165        let (ms, req) = (k(0x50), k(0x60));
1166        let payload = RequestPayload::Invoke(InvokePayload {
1167            target_program_idx: 4,
1168            target_program: k(0x90),
1169            refs: vec![(2, ms), (3, k(0xB0))],
1170            instr_data: vec![],
1171        });
1172        let stored = RequestAccount::decode(&request_account(payload, 0)).unwrap();
1173        assert!(MultisigLayout::from_request(k(0xB0), program, ms, req, &stored).is_err());
1174    }
1175
1176    #[test]
1177    fn create_request_reserves_state_for_full_account() {
1178        let layout = MultisigLayout::for_request(k(0xA0), k(1), k(0x50), k(0x60), &[], &[k(0x90)]);
1179        let p = TxParams {
1180            fee: 1,
1181            nonce: 0,
1182            start_slot: 0,
1183            chain_id: 1,
1184        };
1185        let build = |data_len: usize| {
1186            let payload = RequestPayload::Invoke(InvokePayload {
1187                target_program_idx: layout.idx(&k(0x90)).unwrap(),
1188                target_program: k(0x90),
1189                refs: vec![(layout.idx(&k(0x50)).unwrap(), k(0x50))],
1190                instr_data: vec![0; data_len],
1191            });
1192            build_create_request_tx(&layout, k(0x50), k(0x60), &k(7), &payload, &[], &p)
1193                .unwrap()
1194                .req_state_units
1195        };
1196        // Header (104) + invoke overhead (78) + data + 64 bytes of account metadata.
1197        assert_eq!(build(16), 1);
1198        assert_eq!(build(4096 - 78), 2);
1199    }
1200
1201    #[test]
1202    fn derive_matches_wthru_style() {
1203        // sha256(program || 0 || seed)
1204        let a = derive_account(&k(1), &k(2));
1205        let mut h = Sha256::new();
1206        h.update(k(1));
1207        h.update([0u8]);
1208        h.update(k(2));
1209        assert_eq!(&a[..], &h.finalize()[..32]);
1210    }
1211}