Skip to main content

bsv/script/templates/
push_drop.rs

1//! PushDrop script template for embedding data in Bitcoin scripts.
2//!
3//! PushDrop creates scripts that embed arbitrary data fields followed by
4//! OP_DROP operations to clean the stack, then lock with OP_CHECKSIG.
5//! This enables data storage on-chain while maintaining spending control.
6//! Translates the TS SDK PushDrop.ts (simplified without WalletInterface).
7
8use 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/// PushDrop script template for embedding data with spending control.
21///
22/// Creates a locking script that pushes data fields onto the stack,
23/// drops them with OP_DROP operations, then verifies a signature
24/// against a public key (OP_CHECKSIG).
25#[derive(Clone, Debug)]
26pub struct PushDrop {
27    /// Data fields to embed in the script.
28    pub fields: Vec<Vec<u8>>,
29    /// Private key for signing (used for both lock pubkey and unlock signature).
30    pub private_key: Option<PrivateKey>,
31    /// Sighash scope for signing (default: SIGHASH_ALL | SIGHASH_FORKID).
32    pub sighash_type: u32,
33}
34
35impl PushDrop {
36    /// Create a PushDrop template with data fields and a key for locking and unlocking.
37    ///
38    /// The private key's public key will be used in the locking script,
39    /// and the private key will be used for signing in the unlocking script.
40    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    /// Create a PushDrop template for locking only (no signing capability).
49    ///
50    /// Requires knowing the public key bytes to embed in the script.
51    /// Use `new()` instead if you also need unlock capability.
52    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    /// Create an unlocking script from a sighash preimage.
61    ///
62    /// Produces: `<signature_DER + sighash_byte>`
63    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    /// Estimate the byte length of the unlocking script.
81    ///
82    /// PushDrop unlock is just a signature: approximately 74 bytes
83    /// (1 push opcode + up to 72 DER sig bytes + 1 sighash byte).
84    pub fn estimate_unlock_length(&self) -> usize {
85        74
86    }
87
88    /// Decode a PushDrop locking script, recovering the embedded data fields.
89    ///
90    /// Parses the script pattern:
91    /// `<field_1> <field_2> ... <field_N> OP_DROP|OP_2DROP... <pubkey> OP_CHECKSIG`
92    ///
93    /// Returns a PushDrop with the extracted fields, no private key, and default sighash.
94    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        // Last chunk must be OP_CHECKSIG
103        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        // Second-to-last must be a pubkey data push
111        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        // Walk backwards from before the pubkey to count OP_DROP and OP_2DROP
119        let mut drop_field_count = 0usize;
120        let mut pos = chunks.len() - 3; // start just before pubkey
121        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        // The leading chunks (0..drop_field_count) should be data pushes
143        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        // Data fields are the first `drop_field_count` chunks
150        // pos currently points to the last non-drop chunk before drops, which should be
151        // the last data field. But we need to calculate: data fields end at the chunk
152        // just before the first drop opcode.
153        let data_end = pos + 1; // exclusive end of data field range
154        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    /// Create a data push chunk with appropriate opcode for the data length.
179    fn make_data_push(data: &[u8]) -> ScriptChunk {
180        let len = data.len();
181        if len < 0x4c {
182            // Direct push: opcode IS the length
183            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    /// Create a PushDrop locking script.
196    ///
197    /// Structure: `<field_1> <field_2> ... <field_N> OP_DROP|OP_2DROP... <pubkey> OP_CHECKSIG`
198    ///
199    /// Each field is pushed as data, then removed with OP_DROP (or OP_2DROP
200    /// for pairs). The final element on stack will be verified against the
201    /// embedded public key via OP_CHECKSIG.
202    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        // Push each data field
218        for field in &self.fields {
219            chunks.push(Self::make_data_push(field));
220        }
221
222        // Add OP_DROP for each field to clean the stack
223        // Use OP_2DROP where possible for efficiency
224        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        // Add <pubkey> OP_CHECKSIG
236        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    // -----------------------------------------------------------------------
263    // PushDrop::decode tests
264    // -----------------------------------------------------------------------
265
266    #[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        // A simple P2PKH script should not decode as PushDrop
302        let script = LockingScript::from_binary(&[0x76, 0xa9, 0x14]);
303        assert!(PushDrop::decode(&script).is_err());
304    }
305
306    // -----------------------------------------------------------------------
307    // PushDrop lock: 1 field produces script with data and OP_DROP
308    // -----------------------------------------------------------------------
309
310    #[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        // Should have: <data> OP_DROP <pubkey> OP_CHECKSIG = 4 chunks
320        assert_eq!(chunks.len(), 4, "1-field PushDrop should have 4 chunks");
321
322        // First chunk: data push
323        assert_eq!(chunks[0].data.as_ref().unwrap(), &data);
324        // Second: OP_DROP
325        assert_eq!(chunks[1].op, Op::OpDrop);
326        // Third: pubkey (33 bytes)
327        assert_eq!(chunks[2].data.as_ref().unwrap().len(), 33);
328        // Fourth: OP_CHECKSIG
329        assert_eq!(chunks[3].op, Op::OpCheckSig);
330    }
331
332    // -----------------------------------------------------------------------
333    // PushDrop lock: multiple fields includes all data
334    // -----------------------------------------------------------------------
335
336    #[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        // 3 data pushes + 1 OP_2DROP + 1 OP_DROP + 1 pubkey + 1 OP_CHECKSIG = 7
346        assert_eq!(chunks.len(), 7, "3-field PushDrop should have 7 chunks");
347
348        // Verify data fields are present
349        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        // OP_2DROP for first pair, OP_DROP for odd one
354        assert_eq!(chunks[3].op, Op::Op2Drop);
355        assert_eq!(chunks[4].op, Op::OpDrop);
356
357        // Pubkey + checksig
358        assert_eq!(chunks[6].op, Op::OpCheckSig);
359    }
360
361    // -----------------------------------------------------------------------
362    // PushDrop lock: even number of fields uses OP_2DROP efficiently
363    // -----------------------------------------------------------------------
364
365    #[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        // 2 data pushes + 1 OP_2DROP + 1 pubkey + 1 OP_CHECKSIG = 5 chunks
375        assert_eq!(chunks.len(), 5);
376        assert_eq!(chunks[2].op, Op::Op2Drop);
377    }
378
379    // -----------------------------------------------------------------------
380    // PushDrop unlock: produces valid signature
381    // -----------------------------------------------------------------------
382
383    #[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        // DER signature is typically 70-73 bytes + 1 sighash byte
397        assert!(sig_data.len() >= 70 && sig_data.len() <= 74);
398        // Last byte is sighash
399        assert_eq!(
400            *sig_data.last().unwrap(),
401            (SIGHASH_ALL | SIGHASH_FORKID) as u8
402        );
403    }
404
405    // -----------------------------------------------------------------------
406    // PushDrop: estimate length
407    // -----------------------------------------------------------------------
408
409    #[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    // -----------------------------------------------------------------------
417    // PushDrop: error cases
418    // -----------------------------------------------------------------------
419
420    #[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    // -----------------------------------------------------------------------
440    // PushDrop: trait implementations
441    // -----------------------------------------------------------------------
442
443    #[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    // -----------------------------------------------------------------------
452    // PushDrop: binary roundtrip
453    // -----------------------------------------------------------------------
454
455    #[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        // Re-parse and verify
464        let reparsed = Script::from_binary(&binary);
465        assert_eq!(
466            reparsed.to_binary(),
467            binary,
468            "binary roundtrip should match"
469        );
470    }
471}