Reads transaction data from a reader.
(r: &mut &[u8])
| 98 | |
| 99 | /// Reads transaction data from a reader. |
| 100 | pub fn read_tx_data(r: &mut &[u8]) -> Result<(Vec<u8>, OpTxType), SpanBatchError> { |
| 101 | let mut tx_data = Vec::new(); |
| 102 | let first_byte = |
| 103 | *r.first().ok_or(SpanBatchError::Decoding(SpanDecodingError::InvalidTransactionData))?; |
| 104 | let mut tx_type = 0; |
| 105 | if first_byte <= 0x7F { |
| 106 | // EIP-2718: Non-legacy tx, so write tx type |
| 107 | tx_type = first_byte; |
| 108 | tx_data.push(tx_type); |
| 109 | r.advance(1); |
| 110 | } |
| 111 | |
| 112 | // Read the RLP header with a different reader pointer. This prevents the initial pointer from |
| 113 | // being advanced in the case that what we read is invalid. |
| 114 | let rlp_header = Header::decode(&mut (**r).as_ref()) |
| 115 | .map_err(|_| SpanBatchError::Decoding(SpanDecodingError::InvalidTransactionData))?; |
| 116 | |
| 117 | let tx_payload = if rlp_header.list { |
| 118 | // Grab the raw RLP for the transaction data from `r`. It was unaffected since we copied it. |
| 119 | let payload_length_with_header = rlp_header.payload_length + rlp_header.length(); |
| 120 | if payload_length_with_header > SpanBatchElement::MAX_SPAN_BATCH_ELEMENTS as usize { |
| 121 | return Err(SpanBatchError::TooBigSpanBatchSize); |
| 122 | } |
| 123 | if payload_length_with_header > r.len() { |
| 124 | return Err(SpanBatchError::Decoding(SpanDecodingError::InvalidTransactionData)); |
| 125 | } |
| 126 | let payload = r[0..payload_length_with_header].to_vec(); |
| 127 | r.advance(payload_length_with_header); |
| 128 | Ok(payload) |
| 129 | } else { |
| 130 | Err(SpanBatchError::Decoding(SpanDecodingError::InvalidTransactionData)) |
| 131 | }?; |
| 132 | tx_data.extend_from_slice(&tx_payload); |
| 133 | |
| 134 | Ok(( |
| 135 | tx_data, |
| 136 | tx_type |
| 137 | .try_into() |
| 138 | .map_err(|_| SpanBatchError::Decoding(SpanDecodingError::InvalidTransactionType))?, |
| 139 | )) |
| 140 | } |
| 141 | |
| 142 | #[cfg(test)] |
| 143 | mod tests { |