1use std::{fmt, ops::Deref};
19
20use integer_encoding::VarInt;
21use serde::{Deserialize, Serialize};
22use tari_crypto::{compressed_key::CompressedKey, ristretto::RistrettoPublicKey, tari_utilities::ByteArray};
23use tari_max_size::MaxSizeVecError;
24use tari_utilities::{ByteArrayError, hex::Hex};
25
26use super::ScriptError;
27
28pub type HashValue = [u8; 32];
29pub type ScalarValue = [u8; 32];
30pub type Message = [u8; MESSAGE_LENGTH];
31
32const PUBLIC_KEY_LENGTH: usize = 32;
33const MESSAGE_LENGTH: usize = 32;
34type MultiSigArgs = (u8, u8, Vec<CompressedKey<RistrettoPublicKey>>, Box<Message>, usize);
35
36pub fn slice_to_hash(slice: &[u8]) -> Result<HashValue, ScriptError> {
40 HashValue::try_from(slice).map_err(|_| ScriptError::InvalidData)
41}
42
43pub fn slice_to_boxed_hash(slice: &[u8]) -> Result<Box<HashValue>, ScriptError> {
47 Ok(Box::new(slice_to_hash(slice)?))
48}
49
50pub fn slice_to_message(slice: &[u8]) -> Result<Message, ScriptError> {
54 Message::try_from(slice).map_err(|_| ScriptError::InvalidData)
55}
56
57pub fn slice_to_boxed_message(slice: &[u8]) -> Result<Box<Message>, ScriptError> {
61 Ok(Box::new(slice_to_message(slice)?))
62}
63
64fn bytes_after_varint(bytes: &[u8], size: usize) -> Result<&[u8], ScriptError> {
66 bytes
67 .get(size.checked_add(1).ok_or(ScriptError::InvalidData)?..)
68 .ok_or(ScriptError::InvalidData)
69}
70
71pub fn slice_to_vec_pubkeys(slice: &[u8], num: usize) -> Result<Vec<CompressedKey<RistrettoPublicKey>>, ScriptError> {
73 let required_len = num.checked_mul(PUBLIC_KEY_LENGTH).ok_or(ScriptError::InvalidData)?;
74 if slice.len() < required_len {
75 return Err(ScriptError::InvalidData);
76 }
77
78 let public_keys = slice
79 .as_chunks::<PUBLIC_KEY_LENGTH>()
80 .0
81 .iter()
82 .take(num)
83 .map(|chunk| CompressedKey::from_canonical_bytes(chunk))
84 .collect::<Result<Vec<CompressedKey<RistrettoPublicKey>>, ByteArrayError>>()?;
85
86 Ok(public_keys)
87}
88
89const OP_CHECK_HEIGHT_VERIFY: u8 = 0x66;
91const OP_CHECK_HEIGHT: u8 = 0x67;
92const OP_COMPARE_HEIGHT_VERIFY: u8 = 0x68;
93const OP_COMPARE_HEIGHT: u8 = 0x69;
94
95const OP_DROP: u8 = 0x70;
97const OP_DUP: u8 = 0x71;
98const OP_REV_ROT: u8 = 0x72;
99const OP_PUSH_HASH: u8 = 0x7a;
100const OP_PUSH_ZERO: u8 = 0x7b;
101const OP_NOP: u8 = 0x73;
102const OP_PUSH_ONE: u8 = 0x7c;
103const OP_PUSH_INT: u8 = 0x7d;
104const OP_PUSH_PUBKEY: u8 = 0x7e;
105
106const OP_EQUAL: u8 = 0x80;
108const OP_EQUAL_VERIFY: u8 = 0x81;
109const OP_ADD: u8 = 0x93;
110const OP_SUB: u8 = 0x94;
111const OP_GE_ZERO: u8 = 0x82;
112const OP_GT_ZERO: u8 = 0x83;
113const OP_LE_ZERO: u8 = 0x84;
114const OP_LT_ZERO: u8 = 0x85;
115
116pub const OP_OR_VERIFY: u8 = 0x64;
118pub const OP_OR: u8 = 0x65;
119
120const OP_CHECK_SIG: u8 = 0xac;
122const OP_CHECK_SIG_VERIFY: u8 = 0xad;
123const OP_CHECK_MULTI_SIG: u8 = 0xae;
124const OP_CHECK_MULTI_SIG_VERIFY: u8 = 0xaf;
125const OP_HASH_BLAKE256: u8 = 0xb0;
126const OP_HASH_SHA256: u8 = 0xb1;
127const OP_HASH_SHA3: u8 = 0xb2;
128const OP_TO_RISTRETTO_POINT: u8 = 0xb3;
129const OP_CHECK_MULTI_SIG_VERIFY_AGGREGATE_PUB_KEY: u8 = 0xb4;
130
131const OP_RETURN: u8 = 0x60;
133const OP_IF_THEN: u8 = 0x61;
134const OP_ELSE: u8 = 0x62;
135const OP_END_IF: u8 = 0x63;
136
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub enum Opcode {
139 CheckHeightVerify(u64),
144 CheckHeight(u64),
150 CompareHeightVerify,
157 CompareHeight,
163
164 Nop,
167 PushZero,
170 PushOne,
173 PushHash(Box<HashValue>),
176 PushInt(i64),
179 PushPubKey(Box<CompressedKey<RistrettoPublicKey>>),
183 Drop,
185 Dup,
188 RevRot,
191
192 GeZero,
197 GtZero,
201 LeZero,
205 LtZero,
209 Add,
213 Sub,
217 Equal,
223 EqualVerify,
227
228 Or(u8),
233 OrVerify(u8),
238
239 HashBlake256,
248 HashSha256,
252 HashSha3,
256 CheckSig(Box<Message>),
269 CheckSigVerify(Box<Message>),
272 CheckMultiSig(u8, u8, Vec<CompressedKey<RistrettoPublicKey>>, Box<Message>),
294 CheckMultiSigVerify(u8, u8, Vec<CompressedKey<RistrettoPublicKey>>, Box<Message>),
297 CheckMultiSigVerifyAggregatePubKey(u8, u8, Vec<CompressedKey<RistrettoPublicKey>>, Box<Message>),
300 ToRistrettoPoint,
306
307 Return,
310 IfThen,
317 Else,
319 EndIf,
321}
322
323impl Opcode {
324 pub fn get_version(&self) -> OpcodeVersion {
325 match self {
326 Opcode::CheckHeightVerify(..) |
327 Opcode::CheckHeight(..) |
328 Opcode::CompareHeightVerify |
329 Opcode::CompareHeight |
330 Opcode::Nop |
331 Opcode::PushZero |
332 Opcode::PushOne |
333 Opcode::PushHash(..) |
334 Opcode::PushInt(..) |
335 Opcode::PushPubKey(..) |
336 Opcode::Drop |
337 Opcode::Dup |
338 Opcode::RevRot |
339 Opcode::GeZero |
340 Opcode::GtZero |
341 Opcode::LeZero |
342 Opcode::LtZero |
343 Opcode::Add |
344 Opcode::Sub |
345 Opcode::Equal |
346 Opcode::EqualVerify |
347 Opcode::Or(..) |
348 Opcode::OrVerify(..) |
349 Opcode::HashBlake256 |
350 Opcode::HashSha256 |
351 Opcode::HashSha3 |
352 Opcode::CheckSig(..) |
353 Opcode::CheckSigVerify(..) |
354 Opcode::CheckMultiSig(..) |
355 Opcode::CheckMultiSigVerify(..) |
356 Opcode::CheckMultiSigVerifyAggregatePubKey(..) |
357 Opcode::ToRistrettoPoint |
358 Opcode::Return |
359 Opcode::IfThen |
360 Opcode::Else |
361 Opcode::EndIf => OpcodeVersion::V0,
362 }
363 }
364
365 pub fn parse(bytes: &[u8], max_opcodes: usize) -> Result<Vec<Opcode>, ScriptError> {
368 let mut script = Vec::new();
369 let mut bytes_copy = bytes;
370
371 while !bytes_copy.is_empty() {
372 if script.len() >= max_opcodes {
373 return Err(MaxSizeVecError::MaxSizeVecLengthError {
374 expected: max_opcodes,
375 actual: script.len().saturating_add(1),
376 }
377 .into());
378 }
379 let (opcode, bytes_left) = Opcode::read_next(bytes_copy)?;
380 script.push(opcode);
381 bytes_copy = bytes_left;
382 }
383
384 Ok(script)
385 }
386
387 fn read_next(bytes: &[u8]) -> Result<(Opcode, &[u8]), ScriptError> {
390 let code = bytes.first().ok_or(ScriptError::InvalidOpcode)?;
391 #[allow(clippy::enum_glob_use)]
392 use Opcode::*;
393 let scrubbed_bytes = bytes.get(1..).ok_or(ScriptError::InvalidData)?;
394 match *code {
395 OP_CHECK_HEIGHT_VERIFY => {
396 let (height, size) = u64::decode_var(scrubbed_bytes).ok_or(ScriptError::InvalidData)?;
397 Ok((CheckHeightVerify(height), bytes_after_varint(bytes, size)?))
398 },
399 OP_CHECK_HEIGHT => {
400 let (height, size) = u64::decode_var(scrubbed_bytes).ok_or(ScriptError::InvalidData)?;
401 Ok((CheckHeight(height), bytes_after_varint(bytes, size)?))
402 },
403 OP_COMPARE_HEIGHT_VERIFY => Ok((CompareHeightVerify, scrubbed_bytes)),
404 OP_COMPARE_HEIGHT => Ok((CompareHeight, scrubbed_bytes)),
405 OP_NOP => Ok((Nop, scrubbed_bytes)),
406 OP_PUSH_ZERO => Ok((PushZero, scrubbed_bytes)),
407 OP_PUSH_ONE => Ok((PushOne, scrubbed_bytes)),
408 OP_PUSH_HASH => {
409 let hash = slice_to_boxed_hash(bytes.get(1..33).ok_or(ScriptError::InvalidData)?)?;
410 Ok((PushHash(hash), bytes.get(33..).ok_or(ScriptError::InvalidData)?))
411 },
412 OP_PUSH_INT => {
413 let (n, size) = i64::decode_var(scrubbed_bytes).ok_or(ScriptError::InvalidData)?;
414 Ok((PushInt(n), bytes_after_varint(bytes, size)?))
415 },
416 OP_PUSH_PUBKEY => {
417 let p = CompressedKey::from_canonical_bytes(bytes.get(1..33).ok_or(ScriptError::InvalidData)?)?;
418 Ok((
419 PushPubKey(Box::new(p)),
420 bytes.get(33..).ok_or(ScriptError::InvalidData)?,
421 ))
422 },
423 OP_DROP => Ok((Drop, scrubbed_bytes)),
424 OP_DUP => Ok((Dup, scrubbed_bytes)),
425 OP_REV_ROT => Ok((RevRot, scrubbed_bytes)),
426 OP_GE_ZERO => Ok((GeZero, scrubbed_bytes)),
427 OP_GT_ZERO => Ok((GtZero, scrubbed_bytes)),
428 OP_LE_ZERO => Ok((LeZero, scrubbed_bytes)),
429 OP_LT_ZERO => Ok((LtZero, scrubbed_bytes)),
430 OP_ADD => Ok((Add, scrubbed_bytes)),
431 OP_SUB => Ok((Sub, scrubbed_bytes)),
432 OP_EQUAL => Ok((Equal, scrubbed_bytes)),
433 OP_EQUAL_VERIFY => Ok((EqualVerify, scrubbed_bytes)),
434 OP_OR => {
435 let n = bytes.get(1).ok_or(ScriptError::InvalidData)?;
436 Ok((Or(*n), bytes.get(2..).ok_or(ScriptError::InvalidData)?))
437 },
438 OP_OR_VERIFY => {
439 let n = bytes.get(1).ok_or(ScriptError::InvalidData)?;
440 Ok((OrVerify(*n), bytes.get(2..).ok_or(ScriptError::InvalidData)?))
441 },
442 OP_HASH_BLAKE256 => Ok((HashBlake256, scrubbed_bytes)),
443 OP_HASH_SHA256 => Ok((HashSha256, scrubbed_bytes)),
444 OP_HASH_SHA3 => Ok((HashSha3, scrubbed_bytes)),
445 OP_CHECK_SIG => {
446 let msg = slice_to_boxed_message(bytes.get(1..33).ok_or(ScriptError::InvalidData)?)?;
447 Ok((CheckSig(msg), bytes.get(33..).ok_or(ScriptError::InvalidData)?))
448 },
449 OP_CHECK_SIG_VERIFY => {
450 let msg = slice_to_boxed_message(bytes.get(1..33).ok_or(ScriptError::InvalidData)?)?;
451 Ok((CheckSigVerify(msg), bytes.get(33..).ok_or(ScriptError::InvalidData)?))
452 },
453 OP_CHECK_MULTI_SIG => {
454 let (m, n, keys, msg, end) = Opcode::read_multisig_args(bytes)?;
455 Ok((
456 CheckMultiSig(m, n, keys, msg),
457 bytes.get(end..).ok_or(ScriptError::InvalidData)?,
458 ))
459 },
460 OP_CHECK_MULTI_SIG_VERIFY => {
461 let (m, n, keys, msg, end) = Opcode::read_multisig_args(bytes)?;
462 Ok((
463 CheckMultiSigVerify(m, n, keys, msg),
464 bytes.get(end..).ok_or(ScriptError::InvalidData)?,
465 ))
466 },
467 OP_CHECK_MULTI_SIG_VERIFY_AGGREGATE_PUB_KEY => {
468 let (m, n, keys, msg, end) = Opcode::read_multisig_args(bytes)?;
469 Ok((
470 CheckMultiSigVerifyAggregatePubKey(m, n, keys, msg),
471 bytes.get(end..).ok_or(ScriptError::InvalidData)?,
472 ))
473 },
474 OP_TO_RISTRETTO_POINT => Ok((ToRistrettoPoint, scrubbed_bytes)),
475 OP_RETURN => Ok((Return, scrubbed_bytes)),
476 OP_IF_THEN => Ok((IfThen, scrubbed_bytes)),
477 OP_ELSE => Ok((Else, scrubbed_bytes)),
478 OP_END_IF => Ok((EndIf, scrubbed_bytes)),
479 _ => Err(ScriptError::InvalidOpcode),
480 }
481 }
482
483 fn read_multisig_args(bytes: &[u8]) -> Result<MultiSigArgs, ScriptError> {
484 if bytes.len() < 3 {
485 return Err(ScriptError::InvalidData);
486 }
487 let m = bytes.get(1).ok_or(ScriptError::InvalidData)?;
488 let n = bytes.get(2).ok_or(ScriptError::InvalidData)?;
489 let num = *n as usize;
490 let len = num
491 .checked_mul(PUBLIC_KEY_LENGTH)
492 .and_then(|v| v.checked_add(3))
493 .ok_or(ScriptError::InvalidData)?;
494 let end = len.checked_add(MESSAGE_LENGTH).ok_or(ScriptError::InvalidData)?;
495 let keys = slice_to_vec_pubkeys(bytes.get(3..len).ok_or(ScriptError::InvalidData)?, num)?;
496 let msg = slice_to_boxed_message(bytes.get(len..end).ok_or(ScriptError::InvalidData)?)?;
497
498 Ok((*m, *n, keys, msg, end))
499 }
500
501 pub fn to_bytes<'a>(&self, array: &'a mut Vec<u8>) -> &'a [u8] {
504 let n = array.len();
505 #[allow(clippy::enum_glob_use)]
506 use Opcode::*;
507 match self {
508 CheckHeightVerify(height) => {
509 array.push(OP_CHECK_HEIGHT_VERIFY);
510 let mut buf = [0u8; 10];
511 let used = height.encode_var(&mut buf[..]);
512 array.extend_from_slice(buf.get(0..used).expect("Length is always valid"));
513 },
514 CheckHeight(height) => {
515 array.push(OP_CHECK_HEIGHT);
516 let mut buf = [0u8; 10];
517 let used = height.encode_var(&mut buf[..]);
518 array.extend_from_slice(buf.get(0..used).expect("Length is always valid"));
519 },
520 CompareHeightVerify => array.push(OP_COMPARE_HEIGHT_VERIFY),
521 CompareHeight => array.push(OP_COMPARE_HEIGHT),
522 Nop => array.push(OP_NOP),
523 PushZero => array.push(OP_PUSH_ZERO),
524 PushOne => array.push(OP_PUSH_ONE),
525 PushHash(h) => {
526 array.push(OP_PUSH_HASH);
527 array.extend_from_slice(h.deref());
528 },
529 PushInt(n) => {
530 array.push(OP_PUSH_INT);
531 let mut buf = [0u8; 10];
532 let used = n.encode_var(&mut buf[..]);
533 array.extend_from_slice(buf.get(0..used).expect("Length is always valid"));
534 },
535 PushPubKey(p) => {
536 array.push(OP_PUSH_PUBKEY);
537 array.extend_from_slice(p.deref().as_bytes());
538 },
539 Drop => array.push(OP_DROP),
540 Dup => array.push(OP_DUP),
541 RevRot => array.push(OP_REV_ROT),
542 GeZero => array.push(OP_GE_ZERO),
543 GtZero => array.push(OP_GT_ZERO),
544 LeZero => array.push(OP_LE_ZERO),
545 LtZero => array.push(OP_LT_ZERO),
546 Add => array.push(OP_ADD),
547 Sub => array.push(OP_SUB),
548 Equal => array.push(OP_EQUAL),
549 EqualVerify => array.push(OP_EQUAL_VERIFY),
550 Or(n) => {
551 array.push(OP_OR);
552 array.push(*n);
553 },
554 OrVerify(n) => {
555 array.push(OP_OR_VERIFY);
556 array.push(*n);
557 },
558 HashBlake256 => array.push(OP_HASH_BLAKE256),
559 HashSha256 => array.push(OP_HASH_SHA256),
560 HashSha3 => array.push(OP_HASH_SHA3),
561 CheckSig(msg) => {
562 array.push(OP_CHECK_SIG);
563 array.extend_from_slice(msg.deref());
564 },
565 CheckSigVerify(msg) => {
566 array.push(OP_CHECK_SIG_VERIFY);
567 array.extend_from_slice(msg.deref());
568 },
569 CheckMultiSig(m, n, public_keys, msg) => {
570 array.extend_from_slice(&[OP_CHECK_MULTI_SIG, *m, *n]);
571 for public_key in public_keys {
572 array.extend(public_key.as_bytes());
573 }
574 array.extend_from_slice(msg.deref());
575 },
576 CheckMultiSigVerify(m, n, public_keys, msg) => {
577 array.extend_from_slice(&[OP_CHECK_MULTI_SIG_VERIFY, *m, *n]);
578 for public_key in public_keys {
579 array.extend(public_key.as_bytes());
580 }
581 array.extend_from_slice(msg.deref());
582 },
583 CheckMultiSigVerifyAggregatePubKey(m, n, public_keys, msg) => {
584 array.extend_from_slice(&[OP_CHECK_MULTI_SIG_VERIFY_AGGREGATE_PUB_KEY, *m, *n]);
585 for public_key in public_keys {
586 array.extend(public_key.as_bytes());
587 }
588 array.extend_from_slice(msg.deref());
589 },
590 ToRistrettoPoint => array.push(OP_TO_RISTRETTO_POINT),
591 Return => array.push(OP_RETURN),
592 IfThen => array.push(OP_IF_THEN),
593 Else => array.push(OP_ELSE),
594 EndIf => array.push(OP_END_IF),
595 };
596
597 array.get(n..).expect("Length is always valid")
598 }
599}
600
601impl fmt::Display for Opcode {
602 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
603 #[allow(clippy::enum_glob_use)]
604 use Opcode::*;
605 match self {
606 CheckHeightVerify(height) => write!(fmt, "CheckHeightVerify({})", *height),
607 CheckHeight(height) => write!(fmt, "CheckHeight({})", *height),
608 CompareHeightVerify => write!(fmt, "CompareHeightVerify"),
609 CompareHeight => write!(fmt, "CompareHeight"),
610 Nop => write!(fmt, "Nop"),
611 PushZero => write!(fmt, "PushZero"),
612 PushOne => write!(fmt, "PushOne"),
613 PushHash(h) => write!(fmt, "PushHash({})", (*h).to_hex()),
614 PushInt(n) => write!(fmt, "PushInt({})", *n),
615 PushPubKey(h) => write!(fmt, "PushPubKey({})", (*h).to_hex()),
616 Drop => write!(fmt, "Drop"),
617 Dup => write!(fmt, "Dup"),
618 RevRot => write!(fmt, "RevRot"),
619 GeZero => write!(fmt, "GeZero"),
620 GtZero => write!(fmt, "GtZero"),
621 LeZero => write!(fmt, "LeZero"),
622 LtZero => write!(fmt, "LtZero"),
623 Add => write!(fmt, "Add"),
624 Sub => write!(fmt, "Sub"),
625 Equal => write!(fmt, "Equal"),
626 EqualVerify => write!(fmt, "EqualVerify"),
627 Or(n) => write!(fmt, "Or({})", *n),
628 OrVerify(n) => write!(fmt, "OrVerify({})", *n),
629 HashBlake256 => write!(fmt, "HashBlake256"),
630 HashSha256 => write!(fmt, "HashSha256"),
631 HashSha3 => write!(fmt, "HashSha3"),
632 CheckSig(msg) => write!(fmt, "CheckSig({})", (*msg).to_hex()),
633 CheckSigVerify(msg) => write!(fmt, "CheckSigVerify({})", (*msg).to_hex()),
634 CheckMultiSig(m, n, public_keys, msg) => {
635 let keys: Vec<String> = public_keys.iter().map(|p| p.to_hex()).collect();
636 write!(
637 fmt,
638 "CheckMultiSig({}, {}, [{}], {})",
639 *m,
640 *n,
641 keys.join(", "),
642 (*msg).to_hex()
643 )
644 },
645 CheckMultiSigVerify(m, n, public_keys, msg) => {
646 let keys: Vec<String> = public_keys.iter().map(|p| p.to_hex()).collect();
647 write!(
648 fmt,
649 "CheckMultiSigVerify({}, {}, [{}], {})",
650 *m,
651 *n,
652 keys.join(", "),
653 (*msg).to_hex()
654 )
655 },
656 CheckMultiSigVerifyAggregatePubKey(m, n, public_keys, msg) => {
657 let keys: Vec<String> = public_keys.iter().map(|p| p.to_hex()).collect();
658 write!(
659 fmt,
660 "CheckMultiSigVerifyAggregatePubKey({}, {}, [{}], {})",
661 *m,
662 *n,
663 keys.join(", "),
664 (*msg).to_hex()
665 )
666 },
667 ToRistrettoPoint => write!(fmt, "ToRistrettoPoint"),
668 Return => write!(fmt, "Return"),
669 IfThen => write!(fmt, "IfThen"),
670 Else => write!(fmt, "Else"),
671 EndIf => write!(fmt, "EndIf"),
672 }
673 }
674}
675
676#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
687#[repr(u8)]
688pub enum OpcodeVersion {
689 V0 = 0,
690}
691
692#[cfg(test)]
693mod test {
694 #![allow(clippy::indexing_slicing)]
695 use crate::{op_codes::*, script::MAX_SCRIPT_OPCODES};
696
697 #[test]
698 fn empty_script() {
699 assert_eq!(Opcode::parse(&[], MAX_SCRIPT_OPCODES).unwrap(), Vec::new())
700 }
701
702 #[test]
703 fn parse() {
704 let script = [0xFF, 0x71, 0x00];
705 let err = Opcode::parse(&script, MAX_SCRIPT_OPCODES).unwrap_err();
706 assert!(matches!(err, ScriptError::InvalidOpcode));
707
708 let script = [0x60u8, 0x71];
709 let opcodes = Opcode::parse(&script, MAX_SCRIPT_OPCODES).unwrap();
710 let code = opcodes.first().unwrap();
711 assert_eq!(code, &Opcode::Return);
712 let code = opcodes.get(1).unwrap();
713 assert_eq!(code, &Opcode::Dup);
714
715 let err = Opcode::parse(&[0x7a], MAX_SCRIPT_OPCODES).unwrap_err();
716 assert!(matches!(err, ScriptError::InvalidData));
717 }
718
719 #[test]
720 fn parse_stops_at_max_opcodes() {
721 let script = vec![OP_NOP; MAX_SCRIPT_OPCODES];
723 assert_eq!(
724 Opcode::parse(&script, MAX_SCRIPT_OPCODES).unwrap().len(),
725 MAX_SCRIPT_OPCODES
726 );
727
728 let mut script = vec![OP_NOP; MAX_SCRIPT_OPCODES + 1];
731 script.push(0xFF);
732 let err = Opcode::parse(&script, MAX_SCRIPT_OPCODES).unwrap_err();
733 assert_eq!(
734 err,
735 ScriptError::MaxSizeVecError(MaxSizeVecError::MaxSizeVecLengthError {
736 expected: MAX_SCRIPT_OPCODES,
737 actual: MAX_SCRIPT_OPCODES + 1,
738 })
739 );
740 }
741
742 #[test]
743 fn push_hash() {
744 let (code, b) = Opcode::read_next(b"\x7a/thirty-two~character~hash~val./").unwrap();
745 assert!(matches!(code, Opcode::PushHash(v) if &*v == b"/thirty-two~character~hash~val./"));
746 assert!(b.is_empty());
747 }
748
749 #[test]
750 fn check_height() {
751 fn test_check_height(op: &Opcode, val: u8, display: &str) {
752 assert!(matches!(Opcode::read_next(&[val, 255]), Err(ScriptError::InvalidData)));
754 let s = &[val, 63, 1, 2, 3];
755 let (opcode, rem) = Opcode::read_next(s).unwrap();
756 assert_eq!(opcode, *op);
757 assert_eq!(rem, &[1, 2, 3]);
758 let mut arr = vec![1, 2, 3];
760 op.to_bytes(&mut arr);
761 assert_eq!(&arr, &[1, 2, 3, val, 63]);
762 assert_eq!(format!("{op}").as_str(), display);
764 }
765 test_check_height(&Opcode::CheckHeight(63), 0x67, "CheckHeight(63)");
766 test_check_height(&Opcode::CheckHeightVerify(63), 0x66, "CheckHeightVerify(63)");
767 }
768
769 #[test]
770 fn push_int() {
771 assert!(matches!(Opcode::read_next(&[0x7d, 255]), Err(ScriptError::InvalidData)));
773 let s = &[OP_PUSH_INT, 130, 4];
774 let (opcode, rem) = Opcode::read_next(s).unwrap();
775 let mut arr = vec![];
776 Opcode::PushInt(257).to_bytes(&mut arr);
777 assert!(matches!(opcode, Opcode::PushInt(257)));
778 assert!(rem.is_empty());
779 let op = Opcode::PushInt(257);
781 let mut arr = vec![];
782 op.to_bytes(&mut arr);
783 assert_eq!(&arr, &[OP_PUSH_INT, 130, 4]);
784 assert_eq!(format!("{op}").as_str(), "PushInt(257)");
786 }
787
788 #[test]
789 fn push_pubkey() {
790 assert!(matches!(
792 Opcode::read_next(b"\x7eshort_needs_33_bytes"),
793 Err(ScriptError::InvalidData)
794 ));
795 let key = CompressedKey::<RistrettoPublicKey>::from_hex(
796 "6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401",
797 )
798 .unwrap();
799 let s = &[
800 OP_PUSH_PUBKEY,
801 108,
802 156,
803 180,
804 211,
805 229,
806 115,
807 81,
808 70,
809 33,
810 34,
811 49,
812 15,
813 162,
814 44,
815 144,
816 177,
817 230,
818 223,
819 181,
820 40,
821 214,
822 70,
823 21,
824 54,
825 61,
826 18,
827 97,
828 167,
829 93,
830 163,
831 228,
832 1,
833 ];
834 let op = Opcode::PushPubKey(Box::new(key));
835 let (opcode, rem) = Opcode::read_next(s).unwrap();
836 assert_eq!(opcode, op);
837 assert!(rem.is_empty());
838 let mut arr = vec![];
840 op.to_bytes(&mut arr);
841 assert_eq!(&arr, s);
842 assert_eq!(
844 format!("{op}").as_str(),
845 "PushPubKey(6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)"
846 );
847 }
848
849 #[test]
850 fn or() {
851 fn test_or(op: &Opcode, val: u8, display: &str) {
852 assert!(matches!(Opcode::read_next(&[val]), Err(ScriptError::InvalidData)));
854 let s = &[val, 5, 83];
855 let (opcode, rem) = Opcode::read_next(s).unwrap();
856 assert_eq!(opcode, *op);
857 assert_eq!(rem, &[83]);
858 let mut arr = vec![];
860 op.to_bytes(&mut arr);
861 assert_eq!(&arr, &[val, 5]);
862 assert_eq!(format!("{op}").as_str(), display);
864 }
865 test_or(&Opcode::Or(5), OP_OR, "Or(5)");
866 test_or(&Opcode::OrVerify(5), OP_OR_VERIFY, "OrVerify(5)");
867 }
868
869 #[test]
870 fn check_sig() {
871 fn test_checksig(op: &Opcode, val: u8, display: &str) {
872 assert!(matches!(Opcode::read_next(&[val]), Err(ScriptError::InvalidData)));
874 let msg = &[
875 val, 108, 156, 180, 211, 229, 115, 81, 70, 33, 34, 49, 15, 162, 44, 144, 177, 230, 223, 181, 40, 214,
876 70, 21, 54, 61, 18, 97, 167, 93, 163, 228, 1,
877 ];
878 let (opcode, rem) = Opcode::read_next(msg).unwrap();
879 assert_eq!(opcode, *op);
880 assert!(rem.is_empty());
881 let mut arr = vec![];
883 op.to_bytes(&mut arr);
884 assert_eq!(arr, msg);
885 assert_eq!(format!("{op}").as_str(), display);
887 }
888 let msg = &[
889 108, 156, 180, 211, 229, 115, 81, 70, 33, 34, 49, 15, 162, 44, 144, 177, 230, 223, 181, 40, 214, 70, 21,
890 54, 61, 18, 97, 167, 93, 163, 228, 1,
891 ];
892 test_checksig(
893 &Opcode::CheckSig(Box::new(*msg)),
894 OP_CHECK_SIG,
895 "CheckSig(6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)",
896 );
897 test_checksig(
898 &Opcode::CheckSigVerify(Box::new(*msg)),
899 OP_CHECK_SIG_VERIFY,
900 "CheckSigVerify(6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)",
901 );
902 }
903
904 #[test]
905 fn check_multisig() {
906 fn test_checkmultisig(op: &Opcode, val: u8, display: &str) {
907 assert!(matches!(Opcode::read_next(&[val]), Err(ScriptError::InvalidData)));
909 let bytes = &[
910 val, 1, 2, 156, 139, 197, 249, 13, 34, 17, 145, 116, 142, 141, 215, 104, 111, 9, 225, 17, 75, 75, 173,
911 164, 195, 103, 237, 88, 174, 25, 156, 81, 235, 16, 11, 86, 233, 240, 24, 177, 56, 186, 132, 53, 33,
912 179, 36, 58, 41, 216, 23, 48, 195, 164, 194, 81, 8, 177, 8, 177, 202, 71, 194, 19, 45, 181, 105, 108,
913 156, 180, 211, 229, 115, 81, 70, 33, 34, 49, 15, 162, 44, 144, 177, 230, 223, 181, 40, 214, 70, 21, 54,
914 61, 18, 97, 167, 93, 163, 228, 1,
915 ];
916 let (opcode, rem) = Opcode::read_next(bytes).unwrap();
917 assert_eq!(opcode, *op);
918 assert!(rem.is_empty());
919 let mut arr = vec![];
921 op.to_bytes(&mut arr);
922 assert_eq!(arr, bytes);
923 assert_eq!(format!("{op}").as_str(), display);
925 }
926 let msg = &[
927 108, 156, 180, 211, 229, 115, 81, 70, 33, 34, 49, 15, 162, 44, 144, 177, 230, 223, 181, 40, 214, 70, 21,
928 54, 61, 18, 97, 167, 93, 163, 228, 1,
929 ];
930 let p1 = "9c8bc5f90d221191748e8dd7686f09e1114b4bada4c367ed58ae199c51eb100b";
931 let p2 = "56e9f018b138ba843521b3243a29d81730c3a4c25108b108b1ca47c2132db569";
932 let keys = vec![
933 CompressedKey::<RistrettoPublicKey>::from_hex(p1).unwrap(),
934 CompressedKey::<RistrettoPublicKey>::from_hex(p2).unwrap(),
935 ];
936
937 test_checkmultisig(
938 &Opcode::CheckMultiSig(1, 2, keys.clone(), Box::new(*msg)),
939 OP_CHECK_MULTI_SIG,
940 "CheckMultiSig(1, 2, [9c8bc5f90d221191748e8dd7686f09e1114b4bada4c367ed58ae199c51eb100b, \
941 56e9f018b138ba843521b3243a29d81730c3a4c25108b108b1ca47c2132db569], \
942 6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)",
943 );
944 test_checkmultisig(
945 &Opcode::CheckMultiSigVerify(1, 2, keys.clone(), Box::new(*msg)),
946 OP_CHECK_MULTI_SIG_VERIFY,
947 "CheckMultiSigVerify(1, 2, [9c8bc5f90d221191748e8dd7686f09e1114b4bada4c367ed58ae199c51eb100b, \
948 56e9f018b138ba843521b3243a29d81730c3a4c25108b108b1ca47c2132db569], \
949 6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)",
950 );
951 test_checkmultisig(
952 &Opcode::CheckMultiSigVerifyAggregatePubKey(1, 2, keys, Box::new(*msg)),
953 OP_CHECK_MULTI_SIG_VERIFY_AGGREGATE_PUB_KEY,
954 "CheckMultiSigVerifyAggregatePubKey(1, 2, \
955 [9c8bc5f90d221191748e8dd7686f09e1114b4bada4c367ed58ae199c51eb100b, \
956 56e9f018b138ba843521b3243a29d81730c3a4c25108b108b1ca47c2132db569], \
957 6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401)",
958 );
959 }
960
961 #[test]
962 fn deserialise_no_param_opcodes() {
963 fn test_opcode(code: u8, expected: &Opcode) {
964 let s = &[code, 1, 2, 3];
965 let (opcode, rem) = Opcode::read_next(s).unwrap();
966 assert_eq!(opcode, *expected);
967 assert_eq!(rem, &[1, 2, 3]);
968 }
969 test_opcode(OP_COMPARE_HEIGHT_VERIFY, &Opcode::CompareHeightVerify);
970 test_opcode(OP_COMPARE_HEIGHT, &Opcode::CompareHeight);
971 test_opcode(OP_NOP, &Opcode::Nop);
972 test_opcode(OP_PUSH_ZERO, &Opcode::PushZero);
973 test_opcode(OP_PUSH_ONE, &Opcode::PushOne);
974 test_opcode(OP_DROP, &Opcode::Drop);
975 test_opcode(OP_DUP, &Opcode::Dup);
976 test_opcode(OP_REV_ROT, &Opcode::RevRot);
977 test_opcode(OP_GE_ZERO, &Opcode::GeZero);
978 test_opcode(OP_GT_ZERO, &Opcode::GtZero);
979 test_opcode(OP_LE_ZERO, &Opcode::LeZero);
980 test_opcode(OP_LT_ZERO, &Opcode::LtZero);
981 test_opcode(OP_EQUAL, &Opcode::Equal);
982 test_opcode(OP_EQUAL_VERIFY, &Opcode::EqualVerify);
983 test_opcode(OP_HASH_SHA3, &Opcode::HashSha3);
984 test_opcode(OP_HASH_BLAKE256, &Opcode::HashBlake256);
985 test_opcode(OP_HASH_SHA256, &Opcode::HashSha256);
986 test_opcode(OP_TO_RISTRETTO_POINT, &Opcode::ToRistrettoPoint);
987 test_opcode(OP_IF_THEN, &Opcode::IfThen);
988 test_opcode(OP_ELSE, &Opcode::Else);
989 test_opcode(OP_END_IF, &Opcode::EndIf);
990 test_opcode(OP_ADD, &Opcode::Add);
991 test_opcode(OP_SUB, &Opcode::Sub);
992 test_opcode(OP_RETURN, &Opcode::Return);
993 }
994
995 #[test]
996 fn serialise_no_param_opcodes() {
997 fn test_opcode(val: u8, opcode: &Opcode) {
998 let mut arr = vec![];
999 assert_eq!(opcode.to_bytes(&mut arr), &[val]);
1000 }
1001 test_opcode(OP_COMPARE_HEIGHT_VERIFY, &Opcode::CompareHeightVerify);
1002 test_opcode(OP_COMPARE_HEIGHT, &Opcode::CompareHeight);
1003 test_opcode(OP_NOP, &Opcode::Nop);
1004 test_opcode(OP_PUSH_ZERO, &Opcode::PushZero);
1005 test_opcode(OP_PUSH_ONE, &Opcode::PushOne);
1006 test_opcode(OP_DROP, &Opcode::Drop);
1007 test_opcode(OP_DUP, &Opcode::Dup);
1008 test_opcode(OP_REV_ROT, &Opcode::RevRot);
1009 test_opcode(OP_GE_ZERO, &Opcode::GeZero);
1010 test_opcode(OP_GT_ZERO, &Opcode::GtZero);
1011 test_opcode(OP_LE_ZERO, &Opcode::LeZero);
1012 test_opcode(OP_LT_ZERO, &Opcode::LtZero);
1013 test_opcode(OP_EQUAL, &Opcode::Equal);
1014 test_opcode(OP_EQUAL_VERIFY, &Opcode::EqualVerify);
1015 test_opcode(OP_HASH_SHA3, &Opcode::HashSha3);
1016 test_opcode(OP_HASH_BLAKE256, &Opcode::HashBlake256);
1017 test_opcode(OP_HASH_SHA256, &Opcode::HashSha256);
1018 test_opcode(OP_TO_RISTRETTO_POINT, &Opcode::ToRistrettoPoint);
1019 test_opcode(OP_IF_THEN, &Opcode::IfThen);
1020 test_opcode(OP_ELSE, &Opcode::Else);
1021 test_opcode(OP_END_IF, &Opcode::EndIf);
1022 test_opcode(OP_ADD, &Opcode::Add);
1023 test_opcode(OP_SUB, &Opcode::Sub);
1024 test_opcode(OP_RETURN, &Opcode::Return);
1025 }
1026
1027 #[test]
1028 fn display() {
1029 fn test_opcode(opcode: &Opcode, expected: &str) {
1030 let s = format!("{opcode}");
1031 assert_eq!(s.as_str(), expected);
1032 }
1033 test_opcode(&Opcode::CompareHeightVerify, "CompareHeightVerify");
1034 test_opcode(&Opcode::CompareHeight, "CompareHeight");
1035 test_opcode(&Opcode::Nop, "Nop");
1036 test_opcode(&Opcode::PushZero, "PushZero");
1037 test_opcode(&Opcode::PushOne, "PushOne");
1038 test_opcode(&Opcode::Drop, "Drop");
1039 test_opcode(&Opcode::Dup, "Dup");
1040 test_opcode(&Opcode::RevRot, "RevRot");
1041 test_opcode(&Opcode::GeZero, "GeZero");
1042 test_opcode(&Opcode::GtZero, "GtZero");
1043 test_opcode(&Opcode::LeZero, "LeZero");
1044 test_opcode(&Opcode::LtZero, "LtZero");
1045 test_opcode(&Opcode::Equal, "Equal");
1046 test_opcode(&Opcode::EqualVerify, "EqualVerify");
1047 test_opcode(&Opcode::HashSha3, "HashSha3");
1048 test_opcode(&Opcode::HashBlake256, "HashBlake256");
1049 test_opcode(&Opcode::HashSha256, "HashSha256");
1050 test_opcode(&Opcode::ToRistrettoPoint, "ToRistrettoPoint");
1051 test_opcode(&Opcode::IfThen, "IfThen");
1052 test_opcode(&Opcode::Else, "Else");
1053 test_opcode(&Opcode::EndIf, "EndIf");
1054 test_opcode(&Opcode::Add, "Add");
1055 test_opcode(&Opcode::Sub, "Sub");
1056 test_opcode(&Opcode::Return, "Return");
1057 }
1058
1059 #[test]
1060 fn test_slice_to_vec_pubkeys() {
1061 let key = CompressedKey::<RistrettoPublicKey>::from_hex(
1062 "6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401",
1063 )
1064 .unwrap();
1065 let bytes = key.as_bytes();
1066 let vec = [bytes, bytes, bytes].concat();
1067 let slice = vec.as_bytes();
1068 let vec = slice_to_vec_pubkeys(slice, 3).unwrap();
1069 for pk in vec {
1070 assert_eq!(key, pk);
1071 }
1072 }
1073
1074 #[test]
1075 fn test_read_multisig_args() {
1076 let key = CompressedKey::<RistrettoPublicKey>::from_hex(
1077 "6c9cb4d3e57351462122310fa22c90b1e6dfb528d64615363d1261a75da3e401",
1078 )
1079 .unwrap();
1080 let bytes = key.as_bytes();
1081 let message = &[
1082 108, 156, 180, 211, 229, 115, 81, 70, 33, 34, 49, 15, 162, 44, 144, 177, 230, 223, 181, 40, 214, 70, 21,
1083 54, 61, 18, 97, 167, 93, 163, 228, 1,
1084 ];
1085 let vec = [&[OP_CHECK_MULTI_SIG, 1, 2], bytes, bytes, message].concat();
1086 let slice = vec.as_bytes();
1087 let (m, n, keys, msg, end) = Opcode::read_multisig_args(slice).unwrap();
1088 assert_eq!(m, 1);
1089 assert_eq!(n, 2);
1090 assert_eq!(*msg, *message);
1091 assert_eq!(end, vec.len());
1092 for p in keys {
1093 assert_eq!(key, p);
1094 }
1095 }
1096
1097 #[test]
1098 fn slice_helpers_reject_wrong_lengths() {
1099 let bytes = [7u8; 33];
1100 assert_eq!(slice_to_hash(&bytes[..32]), Ok([7u8; 32]));
1101 assert_eq!(slice_to_boxed_hash(&bytes[..32]), Ok(Box::new([7u8; 32])));
1102 assert_eq!(slice_to_message(&bytes[..32]), Ok([7u8; 32]));
1103 assert_eq!(slice_to_boxed_message(&bytes[..32]), Ok(Box::new([7u8; 32])));
1104 for len in [0, 1, 31, 33] {
1105 assert_eq!(slice_to_hash(&bytes[..len]), Err(ScriptError::InvalidData));
1106 assert_eq!(slice_to_boxed_hash(&bytes[..len]), Err(ScriptError::InvalidData));
1107 assert_eq!(slice_to_message(&bytes[..len]), Err(ScriptError::InvalidData));
1108 assert_eq!(slice_to_boxed_message(&bytes[..len]), Err(ScriptError::InvalidData));
1109 }
1110 }
1111
1112 #[test]
1116 fn non_minimal_varint_is_accepted_pinned() {
1117 let opcodes = Opcode::parse(&[0x67, 0x80, 0x00], MAX_SCRIPT_OPCODES).unwrap();
1118 assert_eq!(opcodes, vec![Opcode::CheckHeight(0)]);
1119 let mut bytes = Vec::new();
1120 opcodes[0].to_bytes(&mut bytes);
1121 assert_eq!(bytes, vec![0x67, 0x00]);
1122
1123 assert_eq!(
1125 Opcode::parse(&[0x66, 0x81, 0x80, 0x00], MAX_SCRIPT_OPCODES).unwrap(),
1126 vec![Opcode::CheckHeightVerify(1)]
1127 );
1128 assert_eq!(Opcode::parse(&[0x7d, 0x82, 0x00], MAX_SCRIPT_OPCODES).unwrap(), vec![
1130 Opcode::PushInt(1)
1131 ]);
1132 }
1133}