1mod 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
23pub const MAX_TRANSACTION_BYTES: usize = 1024 * 1024;
28
29pub const MAX_POOL_TRANSACTION_BYTES: usize = 4 * 32 * 1024;
42pub const MAX_TRANSACTION_MESSAGES: usize = 16384;
44
45#[derive(Debug, Error)]
47#[non_exhaustive]
48pub enum TransactionError {
49 #[error("transaction exceeds size limit")]
51 TooLarge,
52 #[error("invalid or noncanonical transaction encoding")]
54 InvalidEncoding,
55 #[error("invalid transaction field: {0}")]
57 InvalidField(&'static str),
58 #[error("unexpected transaction type")]
60 WrongType,
61 #[error("invalid transaction address scope")]
63 InvalidScope,
64 #[error("transaction signature validation failed")]
66 InvalidSignature,
67 #[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 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
181pub fn decode_proto_transaction(bytes: &[u8]) -> Result<proto::Transaction, TransactionError> {
185 decode(bytes)
186}
187pub 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 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}
265pub 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}