zcash_primitives/transaction/components/
transparent.rs1use corez::io::{self, Read, Write};
5
6use ::transparent::{
7 address::Script,
8 bundle::{Authorization, Authorized, Bundle, OutPoint, TxIn, TxOut},
9};
10use zcash_encoding::Vector;
11use zcash_protocol::value::{BalanceError, ZatBalance, Zatoshis};
12use zcash_script::script;
13
14const TXID_SIZE: usize = 32;
16
17pub fn read_outpoint<R: Read>(mut reader: R) -> io::Result<OutPoint> {
22 let mut hash = [0u8; TXID_SIZE];
23 reader.read_exact(&mut hash)?;
24 let mut n = [0u8; size_of::<u32>()];
25 reader.read_exact(&mut n)?;
26 Ok(OutPoint::new(hash, u32::from_le_bytes(n)))
27}
28
29pub fn write_outpoint<W: Write>(mut writer: W, outpoint: &OutPoint) -> io::Result<()> {
34 writer.write_all(outpoint.hash())?;
35 writer.write_all(&outpoint.n().to_le_bytes())
36}
37
38pub fn read_script<R: Read>(reader: R) -> io::Result<Script> {
43 let script = Vector::read_bytes(reader)?;
44 Ok(Script(script::Code(script)))
45}
46
47pub fn write_script<W: Write>(writer: W, script: &Script) -> io::Result<()> {
51 Vector::write_bytes(writer, &script.0.0)
52}
53
54pub fn script_serialized_size(script: &Script) -> usize {
56 Vector::serialized_size_of_u8_vec(&script.0.0)
57}
58
59pub fn read_txin<R: Read>(mut reader: R) -> io::Result<TxIn<Authorized>> {
65 let prevout = read_outpoint(&mut reader)?;
66 let script_sig = read_script(&mut reader)?;
67 let mut sequence = [0u8; size_of::<u32>()];
68 reader.read_exact(&mut sequence)?;
69 Ok(TxIn::from_parts(
70 prevout,
71 script_sig,
72 u32::from_le_bytes(sequence),
73 ))
74}
75
76pub fn write_txin<W: Write>(mut writer: W, txin: &TxIn<Authorized>) -> io::Result<()> {
81 write_outpoint(&mut writer, txin.prevout())?;
82 write_script(&mut writer, txin.script_sig())?;
83 writer.write_all(&txin.sequence().to_le_bytes())
84}
85
86pub fn read_txout<R: Read>(mut reader: R) -> io::Result<TxOut<Zatoshis>> {
93 let mut value = [0u8; size_of::<i64>()];
94 reader.read_exact(&mut value)?;
95 let value = Zatoshis::from_nonnegative_i64_le_bytes(value)
96 .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "value out of range"))?;
97 let script_pubkey = read_script(&mut reader)?;
98 Ok(TxOut::new(value, script_pubkey))
99}
100
101pub fn write_txout<W: Write>(mut writer: W, txout: &TxOut<Zatoshis>) -> io::Result<()> {
106 writer.write_all(&txout.value().to_i64_le_bytes())?;
107 write_script(&mut writer, txout.script_pubkey())
108}
109
110pub fn value_balance<A, E, F>(
123 bundle: &Bundle<A, Zatoshis>,
124 mut get_prevout_value: F,
125) -> Result<Option<ZatBalance>, E>
126where
127 A: Authorization,
128 E: From<BalanceError>,
129 F: FnMut(&OutPoint) -> Result<Option<Zatoshis>, E>,
130{
131 let mut input_sum = Zatoshis::ZERO;
132 for txin in &bundle.vin {
133 if let Some(v) = get_prevout_value(txin.prevout())? {
134 input_sum = (input_sum + v).ok_or(BalanceError::Overflow)?;
135 } else {
136 return Ok(None);
137 }
138 }
139
140 let output_sum = bundle
141 .vout
142 .iter()
143 .map(|p| ZatBalance::from(p.value()))
144 .sum::<Option<ZatBalance>>()
145 .ok_or(BalanceError::Overflow)?;
146
147 let balance = (ZatBalance::from(input_sum) - output_sum).ok_or(BalanceError::Underflow)?;
148 Ok(Some(balance))
149}
150
151#[cfg(test)]
152mod tests {
153 use corez::io;
154 use proptest::prelude::*;
155
156 use ::transparent::{
157 address::Script,
158 bundle::{
159 Authorized, Bundle, OutPoint, TxIn, TxOut,
160 testing::{arb_outpoint, arb_script_pubkey, arb_txin, arb_txout},
161 },
162 };
163 use zcash_protocol::value::{
164 BalanceError, MAX_MONEY, ZatBalance, Zatoshis, testing::arb_zatoshis,
165 };
166 use zcash_script::script;
167
168 use super::{
169 read_outpoint, read_script, read_txin, read_txout, script_serialized_size, value_balance,
170 write_outpoint, write_script, write_txin, write_txout,
171 };
172
173 const OUTPOINT_LEN: usize = 32 + 4;
175
176 const EMPTY_SCRIPT: u8 = 0x00;
178
179 const TXID: [u8; 32] = [0xaa; 32];
181
182 const OUTPUT_INDEX: u32 = 0x0403_0201;
184
185 const SEQUENCE: u32 = 0x0807_0605;
187
188 const OP_1: u8 = 0x51;
190
191 const LARGER_ZATS: u64 = 50_000;
193
194 const SMALLER_ZATS: u64 = 20_000;
196
197 const LARGER: Zatoshis = Zatoshis::const_from_u64(LARGER_ZATS);
199
200 const SMALLER: Zatoshis = Zatoshis::const_from_u64(SMALLER_ZATS);
202
203 const DIFFERENCE: ZatBalance = ZatBalance::const_from_u64(LARGER_ZATS - SMALLER_ZATS);
205
206 fn fake_input() -> TxIn<Authorized> {
207 TxIn::from_parts(OutPoint::fake(), Script::default(), u32::MAX)
208 }
209
210 fn spend_one_create(created: Zatoshis) -> Bundle<Authorized, Zatoshis> {
212 Bundle {
213 vin: vec![fake_input()],
214 vout: vec![TxOut::new(created, Script::default())],
215 authorization: Authorized,
216 }
217 }
218
219 #[test]
220 fn value_balance_is_inputs_minus_outputs() {
221 let balance =
222 value_balance::<_, BalanceError, _>(&spend_one_create(SMALLER), |_| Ok(Some(LARGER)));
223 assert_eq!(balance, Ok(Some(DIFFERENCE)));
224 }
225
226 #[test]
227 fn value_balance_is_negative_when_outputs_exceed_inputs() {
228 let balance =
229 value_balance::<_, BalanceError, _>(&spend_one_create(LARGER), |_| Ok(Some(SMALLER)));
230 assert_eq!(balance, Ok(Some(-DIFFERENCE)));
231 }
232
233 #[test]
234 fn value_balance_is_unknown_when_a_prevout_is_unknown() {
235 let balance = value_balance::<_, BalanceError, _>(&spend_one_create(SMALLER), |_| Ok(None));
236 assert_eq!(balance, Ok(None));
237 }
238
239 #[test]
240 fn value_balance_reports_overflow_of_the_input_sum() {
241 let two_inputs = Bundle {
242 vin: vec![fake_input(), fake_input()],
243 vout: vec![],
244 authorization: Authorized,
245 };
246 let balance = value_balance::<_, BalanceError, _>(&two_inputs, |_| {
247 Ok(Some(Zatoshis::const_from_u64(MAX_MONEY)))
248 });
249 assert_eq!(balance, Err(BalanceError::Overflow));
250 }
251
252 #[test]
253 fn outpoint_layout() {
254 let outpoint = OutPoint::new(TXID, OUTPUT_INDEX);
255 let mut expected = TXID.to_vec();
256 expected.extend_from_slice(&[0x01, 0x02, 0x03, 0x04]);
257
258 let mut bytes = vec![];
259 write_outpoint(&mut bytes, &outpoint).unwrap();
260 assert_eq!(bytes, expected);
261 assert_eq!(read_outpoint(&expected[..]).unwrap(), outpoint);
262 }
263
264 #[test]
265 fn script_layout() {
266 let script = Script(script::Code(vec![OP_1]));
267 let expected = [0x01, OP_1];
269
270 let mut bytes = vec![];
271 write_script(&mut bytes, &script).unwrap();
272 assert_eq!(bytes, expected);
273 assert_eq!(read_script(&expected[..]).unwrap(), script);
274 }
275
276 #[test]
277 fn empty_script_layout() {
278 let script = Script::default();
279
280 let mut bytes = vec![];
281 write_script(&mut bytes, &script).unwrap();
282 assert_eq!(bytes, [EMPTY_SCRIPT]);
283 assert_eq!(read_script(&bytes[..]).unwrap(), script);
284 assert_eq!(script_serialized_size(&script), bytes.len());
285 }
286
287 #[test]
288 fn txin_layout() {
289 let txin = TxIn::from_parts(
290 OutPoint::new(TXID, OUTPUT_INDEX),
291 Script(script::Code(vec![OP_1])),
292 SEQUENCE,
293 );
294 let mut expected = TXID.to_vec();
296 expected.extend_from_slice(&[0x01, 0x02, 0x03, 0x04]);
297 expected.extend_from_slice(&[0x01, OP_1]);
298 expected.extend_from_slice(&[0x05, 0x06, 0x07, 0x08]);
299
300 let mut bytes = vec![];
301 write_txin(&mut bytes, &txin).unwrap();
302 assert_eq!(bytes, expected);
303 assert_eq!(read_txin(&expected[..]).unwrap(), txin);
304 }
305
306 #[test]
307 fn txout_layout() {
308 let txout = TxOut::new(Zatoshis::const_from_u64(1), Script::default());
309 let expected = [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, EMPTY_SCRIPT];
311
312 let mut bytes = vec![];
313 write_txout(&mut bytes, &txout).unwrap();
314 assert_eq!(bytes, expected);
315 assert_eq!(read_txout(&expected[..]).unwrap(), txout);
316 }
317
318 proptest! {
319 #[test]
320 fn outpoint_round_trips(outpoint in arb_outpoint()) {
321 let mut bytes = vec![];
322 write_outpoint(&mut bytes, &outpoint).unwrap();
323 prop_assert_eq!(bytes.len(), OUTPOINT_LEN);
324 prop_assert_eq!(read_outpoint(&bytes[..]).unwrap(), outpoint);
325 }
326
327 #[test]
328 fn script_round_trips(script in arb_script_pubkey()) {
329 let mut bytes = vec![];
330 write_script(&mut bytes, &script).unwrap();
331 prop_assert_eq!(bytes.len(), script_serialized_size(&script));
332 prop_assert_eq!(read_script(&bytes[..]).unwrap(), script);
333 }
334
335 #[test]
336 fn txin_round_trips(txin in arb_txin()) {
337 let mut bytes = vec![];
338 write_txin(&mut bytes, &txin).unwrap();
339 prop_assert_eq!(read_txin(&bytes[..]).unwrap(), txin);
340 }
341
342 #[test]
343 fn txout_round_trips(txout in arb_txout(arb_zatoshis())) {
344 let mut bytes = vec![];
345 write_txout(&mut bytes, &txout).unwrap();
346 prop_assert_eq!(read_txout(&bytes[..]).unwrap(), txout);
347 }
348 }
349
350 #[test]
351 fn read_script_rejects_truncated_script() {
352 let err = read_script(&[0x05, 0x51][..]).unwrap_err();
354 assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
355 }
356
357 #[test]
358 fn read_txout_rejects_out_of_range_value() {
359 let mut too_large = (MAX_MONEY + 1).to_le_bytes().to_vec();
360 too_large.push(EMPTY_SCRIPT);
361 assert_eq!(
362 read_txout(&too_large[..]).unwrap_err().kind(),
363 io::ErrorKind::InvalidData
364 );
365
366 let mut negative = (-1i64).to_le_bytes().to_vec();
367 negative.push(EMPTY_SCRIPT);
368 assert_eq!(
369 read_txout(&negative[..]).unwrap_err().kind(),
370 io::ErrorKind::InvalidData
371 );
372 }
373}