parity-zcash/script/src/builder.rs

57 lines
1.2 KiB
Rust
Raw Normal View History

2016-09-19 05:56:45 -07:00
use bytes::Bytes;
2016-09-19 07:09:05 -07:00
use {Opcode, Script, Num};
2016-09-08 03:20:18 -07:00
2016-09-08 07:40:07 -07:00
#[derive(Default)]
2016-09-08 03:20:18 -07:00
pub struct Builder {
2016-09-18 04:30:00 -07:00
data: Bytes,
2016-09-08 03:20:18 -07:00
}
impl Builder {
2016-09-08 07:40:07 -07:00
pub fn push_opcode(mut self, opcode: Opcode) -> Self {
self.data.push(opcode as u8);
self
2016-09-08 03:20:18 -07:00
}
2016-09-08 07:40:07 -07:00
pub fn push_bool(mut self, value: bool) -> Self {
if value {
self.data.push(Opcode::OP_1 as u8);
} else {
self.data.push(Opcode::OP_0 as u8);
}
2016-09-08 03:20:18 -07:00
self
}
pub fn push_num(self, num: Num) -> Self {
2016-09-18 04:30:00 -07:00
self.push_data(&num.to_bytes())
2016-09-08 07:40:07 -07:00
}
pub fn push_data(mut self, data: &[u8]) -> Self {
let len = data.len();
if len < Opcode::OP_PUSHDATA1 as usize {
self.data.push(len as u8);
} else if len < 0x100 {
self.data.push(Opcode::OP_PUSHDATA1 as u8);
self.data.push(len as u8);
} else if len < 0x10000 {
self.data.push(Opcode::OP_PUSHDATA2 as u8);
self.data.push(len as u8);
self.data.push((len >> 8) as u8);
} else if len < 0x1_0000_0000 {
self.data.push(Opcode::OP_PUSHDATA4 as u8);
self.data.push(len as u8);
self.data.push((len >> 8) as u8);
self.data.push((len >> 16) as u8);
self.data.push((len >> 24) as u8);
} else {
panic!("Cannot push more than 0x1_0000_0000 bytes");
}
self.data.extend_from_slice(data);
self
}
2016-09-08 03:20:18 -07:00
pub fn into_script(self) -> Script {
Script::new(self.data)
}
}