1use crate::primitives::ecdsa::ecdsa_sign;
9use crate::primitives::hash::sha256;
10use crate::primitives::private_key::PrivateKey;
11use crate::primitives::transaction_signature::{SIGHASH_ALL, SIGHASH_FORKID};
12use crate::script::error::ScriptError;
13use crate::script::locking_script::LockingScript;
14use crate::script::op::Op;
15use crate::script::script::Script;
16use crate::script::script_chunk::ScriptChunk;
17use crate::script::templates::{ScriptTemplateLock, ScriptTemplateUnlock};
18use crate::script::unlocking_script::UnlockingScript;
19
20#[derive(Clone, Debug)]
26pub struct PushDrop {
27 pub fields: Vec<Vec<u8>>,
29 pub private_key: Option<PrivateKey>,
31 pub sighash_type: u32,
33}
34
35impl PushDrop {
36 pub fn new(fields: Vec<Vec<u8>>, key: PrivateKey) -> Self {
41 PushDrop {
42 fields,
43 private_key: Some(key),
44 sighash_type: SIGHASH_ALL | SIGHASH_FORKID,
45 }
46 }
47
48 pub fn lock_only(fields: Vec<Vec<u8>>) -> Self {
53 PushDrop {
54 fields,
55 private_key: None,
56 sighash_type: SIGHASH_ALL | SIGHASH_FORKID,
57 }
58 }
59
60 pub fn unlock(&self, preimage: &[u8]) -> Result<UnlockingScript, ScriptError> {
64 let key = self.private_key.as_ref().ok_or_else(|| {
65 ScriptError::InvalidScript("PushDrop: no private key for unlock".into())
66 })?;
67
68 let msg_hash = sha256(preimage);
69 let sig = ecdsa_sign(&msg_hash, key.bn(), true)
70 .map_err(|e| ScriptError::InvalidSignature(format!("ECDSA sign failed: {}", e)))?;
71
72 let mut sig_bytes = sig.to_der();
73 sig_bytes.push(self.sighash_type as u8);
74
75 let chunks = vec![ScriptChunk::new_raw(sig_bytes.len() as u8, Some(sig_bytes))];
76
77 Ok(UnlockingScript::from_script(Script::from_chunks(chunks)))
78 }
79
80 pub fn estimate_unlock_length(&self) -> usize {
85 74
86 }
87
88 pub fn decode(script: &LockingScript) -> Result<PushDrop, ScriptError> {
95 let chunks = script.chunks();
96 if chunks.len() < 3 {
97 return Err(ScriptError::InvalidScript(
98 "PushDrop::decode: script too short".into(),
99 ));
100 }
101
102 let last = &chunks[chunks.len() - 1];
104 if last.op != Op::OpCheckSig {
105 return Err(ScriptError::InvalidScript(
106 "PushDrop::decode: last opcode must be OP_CHECKSIG".into(),
107 ));
108 }
109
110 let pubkey_chunk = &chunks[chunks.len() - 2];
112 if pubkey_chunk.data.is_none() {
113 return Err(ScriptError::InvalidScript(
114 "PushDrop::decode: expected pubkey data push before OP_CHECKSIG".into(),
115 ));
116 }
117
118 let mut drop_field_count = 0usize;
120 let mut pos = chunks.len() - 3; loop {
122 let chunk = &chunks[pos];
123 if chunk.op == Op::Op2Drop {
124 drop_field_count += 2;
125 } else if chunk.op == Op::OpDrop {
126 drop_field_count += 1;
127 } else {
128 break;
129 }
130 if pos == 0 {
131 break;
132 }
133 pos -= 1;
134 }
135
136 if drop_field_count == 0 {
137 return Err(ScriptError::InvalidScript(
138 "PushDrop::decode: no OP_DROP/OP_2DROP found".into(),
139 ));
140 }
141
142 if drop_field_count > pos + 1 {
144 return Err(ScriptError::InvalidScript(
145 "PushDrop::decode: not enough data pushes for drop count".into(),
146 ));
147 }
148
149 let data_end = pos + 1; if data_end != drop_field_count {
155 return Err(ScriptError::InvalidScript(format!(
156 "PushDrop::decode: field count mismatch: {} data chunks but {} drops",
157 data_end, drop_field_count
158 )));
159 }
160
161 let mut fields = Vec::with_capacity(drop_field_count);
162 for chunk in &chunks[0..drop_field_count] {
163 let data = chunk.data.as_ref().ok_or_else(|| {
164 ScriptError::InvalidScript(
165 "PushDrop::decode: expected data push for field".into(),
166 )
167 })?;
168 fields.push(data.clone());
169 }
170
171 Ok(PushDrop {
172 fields,
173 private_key: None,
174 sighash_type: SIGHASH_ALL | SIGHASH_FORKID,
175 })
176 }
177
178 fn make_data_push(data: &[u8]) -> ScriptChunk {
180 let len = data.len();
181 if len < 0x4c {
182 ScriptChunk::new_raw(len as u8, Some(data.to_vec()))
184 } else if len < 256 {
185 ScriptChunk::new_raw(Op::OpPushData1.to_byte(), Some(data.to_vec()))
186 } else if len < 65536 {
187 ScriptChunk::new_raw(Op::OpPushData2.to_byte(), Some(data.to_vec()))
188 } else {
189 ScriptChunk::new_raw(Op::OpPushData4.to_byte(), Some(data.to_vec()))
190 }
191 }
192}
193
194impl ScriptTemplateLock for PushDrop {
195 fn lock(&self) -> Result<LockingScript, ScriptError> {
203 let key = self.private_key.as_ref().ok_or_else(|| {
204 ScriptError::InvalidScript(
205 "PushDrop: need private key to derive pubkey for lock".into(),
206 )
207 })?;
208
209 if self.fields.is_empty() {
210 return Err(ScriptError::InvalidScript(
211 "PushDrop: at least one data field required".into(),
212 ));
213 }
214
215 let mut chunks = Vec::new();
216
217 for field in &self.fields {
219 chunks.push(Self::make_data_push(field));
220 }
221
222 let num_fields = self.fields.len();
225 let num_2drops = num_fields / 2;
226 let num_drops = num_fields % 2;
227
228 for _ in 0..num_2drops {
229 chunks.push(ScriptChunk::new_opcode(Op::Op2Drop));
230 }
231 for _ in 0..num_drops {
232 chunks.push(ScriptChunk::new_opcode(Op::OpDrop));
233 }
234
235 let pubkey = key.to_public_key();
237 let pubkey_bytes = pubkey.to_der();
238 chunks.push(ScriptChunk::new_raw(
239 pubkey_bytes.len() as u8,
240 Some(pubkey_bytes),
241 ));
242 chunks.push(ScriptChunk::new_opcode(Op::OpCheckSig));
243
244 Ok(LockingScript::from_script(Script::from_chunks(chunks)))
245 }
246}
247
248impl ScriptTemplateUnlock for PushDrop {
249 fn sign(&self, preimage: &[u8]) -> Result<UnlockingScript, ScriptError> {
250 self.unlock(preimage)
251 }
252
253 fn estimate_length(&self) -> Result<usize, ScriptError> {
254 Ok(self.estimate_unlock_length())
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261
262 #[test]
267 fn test_pushdrop_decode_roundtrip_one_field() {
268 let key = PrivateKey::from_hex("1").unwrap();
269 let fields = vec![vec![0xca, 0xfe, 0xba, 0xbe]];
270 let pd = PushDrop::new(fields.clone(), key);
271 let lock_script = pd.lock().unwrap();
272
273 let decoded = PushDrop::decode(&lock_script).unwrap();
274 assert_eq!(decoded.fields, fields, "decode should recover 1 field");
275 }
276
277 #[test]
278 fn test_pushdrop_decode_roundtrip_two_fields() {
279 let key = PrivateKey::from_hex("1").unwrap();
280 let fields = vec![vec![0x01, 0x02], vec![0x03, 0x04]];
281 let pd = PushDrop::new(fields.clone(), key);
282 let lock_script = pd.lock().unwrap();
283
284 let decoded = PushDrop::decode(&lock_script).unwrap();
285 assert_eq!(decoded.fields, fields, "decode should recover 2 fields (OP_2DROP)");
286 }
287
288 #[test]
289 fn test_pushdrop_decode_roundtrip_three_fields() {
290 let key = PrivateKey::from_hex("1").unwrap();
291 let fields = vec![vec![0x01], vec![0x02], vec![0x03]];
292 let pd = PushDrop::new(fields.clone(), key);
293 let lock_script = pd.lock().unwrap();
294
295 let decoded = PushDrop::decode(&lock_script).unwrap();
296 assert_eq!(decoded.fields, fields, "decode should recover 3 fields (OP_2DROP + OP_DROP)");
297 }
298
299 #[test]
300 fn test_pushdrop_decode_non_pushdrop_script_errors() {
301 let script = LockingScript::from_binary(&[0x76, 0xa9, 0x14]);
303 assert!(PushDrop::decode(&script).is_err());
304 }
305
306 #[test]
311 fn test_pushdrop_lock_one_field() {
312 let key = PrivateKey::from_hex("1").unwrap();
313 let data = vec![0xca, 0xfe, 0xba, 0xbe];
314 let pd = PushDrop::new(vec![data.clone()], key);
315
316 let lock_script = pd.lock().unwrap();
317 let chunks = lock_script.chunks();
318
319 assert_eq!(chunks.len(), 4, "1-field PushDrop should have 4 chunks");
321
322 assert_eq!(chunks[0].data.as_ref().unwrap(), &data);
324 assert_eq!(chunks[1].op, Op::OpDrop);
326 assert_eq!(chunks[2].data.as_ref().unwrap().len(), 33);
328 assert_eq!(chunks[3].op, Op::OpCheckSig);
330 }
331
332 #[test]
337 fn test_pushdrop_lock_multiple_fields() {
338 let key = PrivateKey::from_hex("1").unwrap();
339 let fields = vec![vec![0x01, 0x02], vec![0x03, 0x04], vec![0x05, 0x06]];
340 let pd = PushDrop::new(fields.clone(), key);
341
342 let lock_script = pd.lock().unwrap();
343 let chunks = lock_script.chunks();
344
345 assert_eq!(chunks.len(), 7, "3-field PushDrop should have 7 chunks");
347
348 assert_eq!(chunks[0].data.as_ref().unwrap(), &fields[0]);
350 assert_eq!(chunks[1].data.as_ref().unwrap(), &fields[1]);
351 assert_eq!(chunks[2].data.as_ref().unwrap(), &fields[2]);
352
353 assert_eq!(chunks[3].op, Op::Op2Drop);
355 assert_eq!(chunks[4].op, Op::OpDrop);
356
357 assert_eq!(chunks[6].op, Op::OpCheckSig);
359 }
360
361 #[test]
366 fn test_pushdrop_lock_even_fields() {
367 let key = PrivateKey::from_hex("1").unwrap();
368 let fields = vec![vec![0x01], vec![0x02]];
369 let pd = PushDrop::new(fields, key);
370
371 let lock_script = pd.lock().unwrap();
372 let chunks = lock_script.chunks();
373
374 assert_eq!(chunks.len(), 5);
376 assert_eq!(chunks[2].op, Op::Op2Drop);
377 }
378
379 #[test]
384 fn test_pushdrop_unlock_produces_signature() {
385 let key = PrivateKey::from_hex("1").unwrap();
386 let pd = PushDrop::new(vec![vec![0xaa]], key);
387
388 let unlock_script = pd.unlock(b"test preimage").unwrap();
389 assert_eq!(
390 unlock_script.chunks().len(),
391 1,
392 "PushDrop unlock should be 1 chunk (just sig)"
393 );
394
395 let sig_data = unlock_script.chunks()[0].data.as_ref().unwrap();
396 assert!(sig_data.len() >= 70 && sig_data.len() <= 74);
398 assert_eq!(
400 *sig_data.last().unwrap(),
401 (SIGHASH_ALL | SIGHASH_FORKID) as u8
402 );
403 }
404
405 #[test]
410 fn test_pushdrop_estimate_length() {
411 let key = PrivateKey::from_hex("1").unwrap();
412 let pd = PushDrop::new(vec![vec![0x01]], key);
413 assert_eq!(pd.estimate_unlock_length(), 74);
414 }
415
416 #[test]
421 fn test_pushdrop_lock_no_key() {
422 let pd = PushDrop::lock_only(vec![vec![0x01]]);
423 assert!(pd.lock().is_err());
424 }
425
426 #[test]
427 fn test_pushdrop_lock_no_fields() {
428 let key = PrivateKey::from_hex("1").unwrap();
429 let pd = PushDrop::new(vec![], key);
430 assert!(pd.lock().is_err());
431 }
432
433 #[test]
434 fn test_pushdrop_unlock_no_key() {
435 let pd = PushDrop::lock_only(vec![vec![0x01]]);
436 assert!(pd.unlock(b"test").is_err());
437 }
438
439 #[test]
444 fn test_pushdrop_trait_sign() {
445 let key = PrivateKey::from_hex("ff").unwrap();
446 let pd = PushDrop::new(vec![vec![0x01, 0x02, 0x03]], key);
447 let unlock_script = pd.sign(b"sighash data").unwrap();
448 assert_eq!(unlock_script.chunks().len(), 1);
449 }
450
451 #[test]
456 fn test_pushdrop_lock_binary_roundtrip() {
457 let key = PrivateKey::from_hex("1").unwrap();
458 let pd = PushDrop::new(vec![vec![0xde, 0xad]], key);
459
460 let lock_script = pd.lock().unwrap();
461 let binary = lock_script.to_binary();
462
463 let reparsed = Script::from_binary(&binary);
465 assert_eq!(
466 reparsed.to_binary(),
467 binary,
468 "binary roundtrip should match"
469 );
470 }
471}