Skip to main content

quai_consensus/
lib.rs

1//! Quai-native transaction encoding and signing; never Ethereum transaction envelopes.
2mod conversion;
3mod qi_operation;
4mod wrapping;
5pub use qi_operation::SignedQiOperation;
6pub use wrapping::{QiWrappingIntent, QiWrappingTransaction, SignedQiWrappingTransaction};
7pub mod document;
8pub mod proto;
9mod qi;
10mod quai;
11pub use conversion::{
12    ConversionSlippage, KAWPOW_FORK_BLOCK, KQUAI_CHANGE_HOLD_INTERVAL, MIN_QUAI_CONVERSION_VALUE,
13    QiConversionIntent, QiConversionTransaction, QuaiToQiTransaction,
14    SHA_EQUIVALENT_DIFFICULTY_FORK_BLOCK, SignedQiConversionTransaction,
15    conversion_batch_discount_bps, conversion_held,
16};
17use prost::Message;
18pub use qi::{Denomination, OutPoint, QiInput, QiOutput, QiTransaction, SignedQiTransaction};
19pub use quai::{AccessTuple, QuaiTransaction, SignedQuaiTransaction};
20pub use ruint::aliases::U256;
21use thiserror::Error;
22
23/// Encoded input/output byte ceiling, not a promise that a node accepts this size.
24///
25/// This bounds decoding and encoding. For what the pinned node's pool actually
26/// takes, see [`MAX_POOL_TRANSACTION_BYTES`].
27pub const MAX_TRANSACTION_BYTES: usize = 1024 * 1024;
28
29/// Largest signed **Quai** transaction the pinned node's pool accepts, its
30/// `txMaxSize` of four 32 KiB slots.
31///
32/// A transaction above this is rejected with `ErrOversizedData` before any other
33/// validation, which for a deployment means the nonce was already reserved and
34/// the transaction already signed. The realistic way to reach it is contract
35/// init code, so deployment planning bounds against this rather than against
36/// [`MAX_TRANSACTION_BYTES`].
37///
38/// Qi transactions take a different pool path that applies no size check, so
39/// this bound is Quai-ledger only; a Qi transaction is bounded by its input and
40/// output counts instead.
41pub const MAX_POOL_TRANSACTION_BYTES: usize = 4 * 32 * 1024;
42/// Total nested-message ceiling, checked before protobuf decoder allocation.
43pub const MAX_TRANSACTION_MESSAGES: usize = 16384;
44
45/// Transaction validation errors do not echo transaction data or secret material.
46#[derive(Debug, Error)]
47#[non_exhaustive]
48pub enum TransactionError {
49    /// Input exceeds this SDK's allocation policy.
50    #[error("transaction exceeds size limit")]
51    TooLarge,
52    /// Wire encoding is malformed, ambiguous, noncanonical, or includes unknown fields.
53    #[error("invalid or noncanonical transaction encoding")]
54    InvalidEncoding,
55    /// A required field is absent or malformed.
56    #[error("invalid transaction field: {0}")]
57    InvalidField(&'static str),
58    /// Unsupported transaction kind for this typed decoder.
59    #[error("unexpected transaction type")]
60    WrongType,
61    /// The signer/recipient has an unsupported ledger or location combination.
62    #[error("invalid transaction address scope")]
63    InvalidScope,
64    /// A signature failed validation or recovery.
65    #[error("transaction signature validation failed")]
66    InvalidSignature,
67    /// A single-input signing method was given multiple inputs. Use the explicit
68    /// ordered local-key aggregation signing path for such transactions.
69    #[error("multi-input transaction requires explicit ordered-key signing")]
70    MultiInputSigningUnavailable,
71}
72
73fn integer_bytes(n: U256) -> Vec<u8> {
74    let bytes = n.to_be_bytes::<32>();
75    let first = bytes.iter().position(|b| *b != 0).unwrap_or(bytes.len());
76    bytes[first..].to_vec()
77}
78fn integer(bytes: Option<&[u8]>, name: &'static str) -> Result<U256, TransactionError> {
79    let b = bytes.ok_or(TransactionError::InvalidField(name))?;
80    if b.len() > 32 || b.first() == Some(&0) {
81        return Err(TransactionError::InvalidField(name));
82    }
83    Ok(U256::from_be_slice(b))
84}
85fn encode(p: &proto::Transaction) -> Result<Vec<u8>, TransactionError> {
86    if p.encoded_len() > MAX_TRANSACTION_BYTES {
87        return Err(TransactionError::TooLarge);
88    }
89    Ok(p.encode_to_vec())
90}
91fn decode(bytes: &[u8]) -> Result<proto::Transaction, TransactionError> {
92    if bytes.len() > MAX_TRANSACTION_BYTES {
93        return Err(TransactionError::TooLarge);
94    }
95    let mut budget = MAX_TRANSACTION_MESSAGES;
96    preflight(bytes, WireKind::Transaction, &mut budget)?;
97    let p = proto::Transaction::decode(bytes).map_err(|_| TransactionError::InvalidEncoding)?;
98    // Prost otherwise drops unknown fields and accepts duplicates/overlong varints.
99    if p.encode_to_vec() != bytes {
100        return Err(TransactionError::InvalidEncoding);
101    }
102    Ok(p)
103}
104
105#[derive(Clone, Copy)]
106enum WireKind {
107    Transaction,
108    AccessList,
109    AccessTuple,
110    Hash,
111    Inputs,
112    Input,
113    OutPoint,
114    Outputs,
115    Output,
116}
117fn preflight(mut bytes: &[u8], kind: WireKind, budget: &mut usize) -> Result<(), TransactionError> {
118    *budget = budget.checked_sub(1).ok_or(TransactionError::TooLarge)?;
119    fn varint(bytes: &mut &[u8]) -> Result<u64, TransactionError> {
120        let mut n = 0u64;
121        for shift in (0..70).step_by(7) {
122            let (&b, rest) = bytes
123                .split_first()
124                .ok_or(TransactionError::InvalidEncoding)?;
125            *bytes = rest;
126            if shift == 63 && b > 1 {
127                return Err(TransactionError::InvalidEncoding);
128            }
129            n |= u64::from(b & 127) << shift;
130            if b < 128 {
131                return Ok(n);
132            }
133        }
134        Err(TransactionError::InvalidEncoding)
135    }
136    while !bytes.is_empty() {
137        let key = varint(&mut bytes)?;
138        let tag = key >> 3;
139        if tag == 0 {
140            return Err(TransactionError::InvalidEncoding);
141        }
142        match key & 7 {
143            0 => {
144                varint(&mut bytes)?;
145            }
146            1 => {
147                bytes = bytes.get(8..).ok_or(TransactionError::InvalidEncoding)?;
148            }
149            5 => {
150                bytes = bytes.get(4..).ok_or(TransactionError::InvalidEncoding)?;
151            }
152            2 => {
153                let len =
154                    usize::try_from(varint(&mut bytes)?).map_err(|_| TransactionError::TooLarge)?;
155                let part = bytes.get(..len).ok_or(TransactionError::InvalidEncoding)?;
156                bytes = &bytes[len..];
157                use WireKind::*;
158                let child = match (kind, tag) {
159                    (Transaction, 9) => Some(AccessList),
160                    (Transaction, 13 | 19 | 20) => Some(Hash),
161                    (Transaction, 15) => Some(Inputs),
162                    (Transaction, 16) => Some(Outputs),
163                    (AccessList, 1) => Some(AccessTuple),
164                    (AccessTuple, 2) => Some(Hash),
165                    (Inputs, 1) => Some(Input),
166                    (Input, 1) => Some(OutPoint),
167                    (OutPoint, 1) => Some(Hash),
168                    (Outputs, 1) => Some(Output),
169                    _ => None,
170                };
171                if let Some(child) = child {
172                    preflight(part, child, budget)?;
173                }
174            }
175            _ => return Err(TransactionError::InvalidEncoding),
176        }
177    }
178    Ok(())
179}
180
181/// Decode a bounded canonical protobuf object, preserving explicit field presence.
182/// This checks the wire format, not transaction semantics, signatures or spendability.
183/// Use document::TransactionDocument::from_proto or a concrete signed type to validate.
184pub fn decode_proto_transaction(bytes: &[u8]) -> Result<proto::Transaction, TransactionError> {
185    decode(bytes)
186}
187/// Whether `bytes` could be read as a transaction with inputs.
188///
189/// Deliberately lenient, so a signer can refuse such bytes as a message: no
190/// size bound, canonical-form check or unknown-field rejection, and a field
191/// with an unexpected wire type is skipped as unknown, as protobuf-go does. Any
192/// top-level length-delimited field 15 (`tx_ins`) counts, whatever it holds,
193/// which can only refuse more. The walk allocates nothing, so hostile input
194/// costs time linear in its length and no memory. Bytes that are not a
195/// well-formed protobuf message at all are not a transaction. It is not a
196/// validity check.
197pub fn has_transaction_inputs(bytes: &[u8]) -> bool {
198    fn varint(bytes: &[u8]) -> Option<(u64, usize)> {
199        let mut value = 0u64;
200        for (i, byte) in bytes.iter().take(10).enumerate() {
201            value |= u64::from(byte & 0x7f) << (7 * i);
202            if byte & 0x80 == 0 {
203                return Some((value, i + 1));
204            }
205        }
206        None
207    }
208    let mut rest = bytes;
209    // Open groups; only fields outside every group are top level. A depth
210    // count rather than a stack, so nesting allocates nothing; not matching
211    // group-end field numbers can only refuse more.
212    let mut depth = 0u64;
213    let mut inputs = false;
214    while !rest.is_empty() {
215        let Some((key, used)) = varint(rest) else {
216            return false;
217        };
218        rest = &rest[used..];
219        let field = key >> 3;
220        if field == 0 {
221            return false;
222        }
223        let skip = match key & 7 {
224            0 => match varint(rest) {
225                Some((_, used)) => used,
226                None => return false,
227            },
228            1 => 8,
229            2 => {
230                let Some((length, used)) = varint(rest) else {
231                    return false;
232                };
233                let Some(total) = usize::try_from(length)
234                    .ok()
235                    .and_then(|length| length.checked_add(used))
236                else {
237                    return false;
238                };
239                if field == 15 && depth == 0 {
240                    inputs = true;
241                }
242                total
243            }
244            3 => {
245                depth += 1;
246                0
247            }
248            4 => {
249                let Some(outer) = depth.checked_sub(1) else {
250                    return false;
251                };
252                depth = outer;
253                0
254            }
255            5 => 4,
256            _ => return false,
257        };
258        if rest.len() < skip {
259            return false;
260        }
261        rest = &rest[skip..];
262    }
263    inputs && depth == 0
264}
265/// Encode a raw protobuf object within the byte/message policy. This does not
266/// establish a valid transaction or authorize submission.
267pub fn encode_proto_transaction(value: &proto::Transaction) -> Result<Vec<u8>, TransactionError> {
268    let bytes = encode(value)?;
269    let mut budget = MAX_TRANSACTION_MESSAGES;
270    preflight(&bytes, WireKind::Transaction, &mut budget)?;
271    Ok(bytes)
272}