1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
mod blocks_pool;

use std::time::Duration;

use crate::chainhooks::types::{
    get_canonical_pox_config, get_stacks_canonical_magic_bytes, PoxConfig, StacksOpcodes,
};

#[cfg(feature = "ordinals")]
use crate::hord;
use crate::observer::BitcoinConfig;
use crate::utils::Context;
use bitcoincore_rpc::bitcoin::hashes::hex::FromHex;
use bitcoincore_rpc::bitcoin::hashes::Hash;
use bitcoincore_rpc::bitcoin::{self, Address, Amount, BlockHash};
use bitcoincore_rpc_json::{
    GetRawTransactionResultVinScriptSig, GetRawTransactionResultVoutScriptPubKey,
};
pub use blocks_pool::BitcoinBlockPool;
use chainhook_types::bitcoin::{OutPoint, TxIn, TxOut};
use chainhook_types::{
    BitcoinBlockData, BitcoinBlockMetadata, BitcoinNetwork, BitcoinTransactionData,
    BitcoinTransactionMetadata, BlockCommitmentData, BlockHeader, BlockIdentifier,
    KeyRegistrationData, LockSTXData, PoxReward, StacksBaseChainOperation,
    StacksBlockCommitmentData, TransactionIdentifier, TransferSTXData,
};
use hiro_system_kit::slog;
use serde::Deserialize;

#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BitcoinBlockFullBreakdown {
    pub hash: bitcoin::BlockHash,
    pub height: usize,
    pub merkleroot: bitcoin::TxMerkleNode,
    pub tx: Vec<BitcoinTransactionFullBreakdown>,
    pub time: usize,
    pub nonce: u32,
    pub previousblockhash: Option<bitcoin::BlockHash>,
}

impl BitcoinBlockFullBreakdown {
    pub fn get_block_header(&self) -> BlockHeader {
        // Block id
        let hash = format!("0x{}", self.hash.to_string());
        let block_identifier = BlockIdentifier {
            index: self.height as u64,
            hash: hash,
        };
        // Parent block id
        let hash = format!("0x{}", self.previousblockhash.unwrap().to_string());
        let parent_block_identifier = BlockIdentifier {
            index: (self.height - 1) as u64,
            hash,
        };
        BlockHeader {
            block_identifier,
            parent_block_identifier,
        }
    }
}

#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BitcoinTransactionFullBreakdown {
    pub txid: bitcoin::Txid,
    pub vin: Vec<BitcoinTransactionInputFullBreakdown>,
    pub vout: Vec<BitcoinTransactionOutputFullBreakdown>,
}

#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BitcoinTransactionInputFullBreakdown {
    pub sequence: u32,
    /// The raw scriptSig in case of a coinbase tx.
    #[serde(default, with = "bitcoincore_rpc_json::serde_hex::opt")]
    pub coinbase: Option<Vec<u8>>,
    /// Not provided for coinbase txs.
    pub txid: Option<bitcoin::Txid>,
    /// Not provided for coinbase txs.
    pub vout: Option<u32>,
    /// The scriptSig in case of a non-coinbase tx.
    pub script_sig: Option<GetRawTransactionResultVinScriptSig>,
    /// Not provided for coinbase txs.
    #[serde(default, deserialize_with = "deserialize_hex_array_opt")]
    pub txinwitness: Option<Vec<Vec<u8>>>,
    pub prevout: Option<BitcoinTransactionInputPrevoutFullBreakdown>,
}

impl BitcoinTransactionInputFullBreakdown {
    /// Whether this input is from a coinbase tx.
    /// The [txid], [vout] and [script_sig] fields are not provided
    /// for coinbase transactions.
    pub fn is_coinbase(&self) -> bool {
        self.coinbase.is_some()
    }
}

fn deserialize_hex_array_opt<'de, D>(deserializer: D) -> Result<Option<Vec<Vec<u8>>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use crate::serde::de::Error;

    //TODO(stevenroose) Revisit when issue is fixed:
    // https://github.com/serde-rs/serde/issues/723
    let v: Vec<String> = Vec::deserialize(deserializer)?;
    let mut res = Vec::new();
    for h in v.into_iter() {
        res.push(FromHex::from_hex(&h).map_err(D::Error::custom)?);
    }
    Ok(Some(res))
}

#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BitcoinTransactionInputPrevoutFullBreakdown {
    pub height: u64,
    #[serde(with = "bitcoin::util::amount::serde::as_btc")]
    pub value: Amount,
}

#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BitcoinTransactionOutputFullBreakdown {
    #[serde(with = "bitcoin::util::amount::serde::as_btc")]
    pub value: Amount,
    pub n: u32,
    pub script_pub_key: GetRawTransactionResultVoutScriptPubKey,
}

#[derive(Deserialize)]
pub struct NewBitcoinBlock {
    pub burn_block_hash: String,
    pub burn_block_height: u64,
    pub reward_slot_holders: Vec<String>,
    pub reward_recipients: Vec<RewardParticipant>,
    pub burn_amount: u64,
}

#[allow(dead_code)]
#[derive(Deserialize)]
pub struct RewardParticipant {
    recipient: String,
    amt: u64,
}

pub async fn download_and_parse_block_with_retry(
    block_hash: &str,
    bitcoin_config: &BitcoinConfig,
    ctx: &Context,
) -> Result<BitcoinBlockFullBreakdown, String> {
    let mut errors_count = 0;
    let block = loop {
        match download_and_parse_block(block_hash, bitcoin_config, ctx).await {
            Ok(result) => break result,
            Err(e) => {
                errors_count += 1;
                ctx.try_log(|logger| {
                    slog::warn!(
                        logger,
                        "unable to retrieve block #{block_hash} (attempt #{errors_count}): {}",
                        e.to_string()
                    )
                });
                std::thread::sleep(std::time::Duration::from_secs(1));
            }
        }
    };
    Ok(block)
}

pub async fn download_block_with_retry(
    block_hash: &str,
    bitcoin_config: &BitcoinConfig,
    ctx: &Context,
) -> Result<BitcoinBlockFullBreakdown, String> {
    let mut errors_count = 0;
    let block = loop {
        let response = {
            match download_block(block_hash, bitcoin_config, ctx).await {
                Ok(result) => result,
                Err(e) => {
                    errors_count += 1;
                    ctx.try_log(|logger| {
                        slog::warn!(
                            logger,
                            "unable to retrieve block #{block_hash} (attempt #{errors_count}): {}",
                            e.to_string()
                        )
                    });
                    std::thread::sleep(std::time::Duration::from_millis(500));
                    continue;
                }
            }
        };

        match parse_downloaded_block(response) {
            Ok(result) => break result,
            Err(e) => {
                errors_count += 1;
                ctx.try_log(|logger| {
                    slog::warn!(
                        logger,
                        "unable to retrieve block #{block_hash} (attempt #{errors_count}): {}",
                        e.to_string()
                    )
                });
                std::thread::sleep(std::time::Duration::from_millis(500));
                continue;
            }
        };
    };
    Ok(block)
}

pub async fn retrieve_block_hash_with_retry(
    block_height: &u64,
    bitcoin_config: &BitcoinConfig,
    ctx: &Context,
) -> Result<String, String> {
    let mut errors_count = 0;
    let block_hash = loop {
        match retrieve_block_hash(block_height, bitcoin_config, ctx).await {
            Ok(result) => break result,
            Err(e) => {
                errors_count += 1;
                ctx.try_log(|logger| {
                    slog::error!(
                        logger,
                        "unable to retrieve #{block_height} (attempt #{errors_count}): {}",
                        e.to_string()
                    )
                });
                std::thread::sleep(std::time::Duration::from_secs(1));
            }
        }
    };
    Ok(block_hash)
}

pub async fn download_block(
    block_hash: &str,
    bitcoin_config: &BitcoinConfig,
    _ctx: &Context,
) -> Result<Vec<u8>, String> {
    use reqwest::Client as HttpClient;
    let body = json!({
        "jsonrpc": "1.0",
        "id": "chainhook-cli",
        "method": "getblock",
        "params": [block_hash, 3]
    });
    let http_client = HttpClient::builder()
        .timeout(Duration::from_secs(20))
        .build()
        .expect("Unable to build http client");
    let block = http_client
        .post(&bitcoin_config.rpc_url)
        .basic_auth(&bitcoin_config.username, Some(&bitcoin_config.password))
        .header("Content-Type", "application/json")
        .header("Host", &bitcoin_config.rpc_url[7..])
        .json(&body)
        .send()
        .await
        .map_err(|e| format!("unable to send request ({})", e))?
        .bytes()
        .await
        .map_err(|e| format!("unable to get bytes ({})", e))?
        .to_vec();
    Ok(block)
}

pub fn parse_downloaded_block(
    downloaded_block: Vec<u8>,
) -> Result<BitcoinBlockFullBreakdown, String> {
    let block = serde_json::from_slice::<bitcoincore_rpc::jsonrpc::Response>(&downloaded_block[..])
        .map_err(|e| format!("unable to parse jsonrpc payload ({})", e))?
        .result::<BitcoinBlockFullBreakdown>()
        .map_err(|e| format!("unable to parse block ({})", e))?;
    Ok(block)
}

pub async fn download_and_parse_block(
    block_hash: &str,
    bitcoin_config: &BitcoinConfig,
    _ctx: &Context,
) -> Result<BitcoinBlockFullBreakdown, String> {
    let response = download_block(block_hash, bitcoin_config, _ctx).await?;
    parse_downloaded_block(response)
}

pub async fn retrieve_block_hash(
    block_height: &u64,
    bitcoin_config: &BitcoinConfig,
    _ctx: &Context,
) -> Result<String, String> {
    use reqwest::Client as HttpClient;
    let body = json!({
        "jsonrpc": "1.0",
        "id": "chainhook-cli",
        "method": "getblockhash",
        "params": [block_height]
    });
    let http_client = HttpClient::builder()
        .timeout(Duration::from_secs(20))
        .build()
        .expect("Unable to build http client");
    let block_hash = http_client
        .post(&bitcoin_config.rpc_url)
        .basic_auth(&bitcoin_config.username, Some(&bitcoin_config.password))
        .header("Content-Type", "application/json")
        .header("Host", &bitcoin_config.rpc_url[7..])
        .json(&body)
        .send()
        .await
        .map_err(|e| format!("unable to send request ({})", e))?
        .json::<bitcoincore_rpc::jsonrpc::Response>()
        .await
        .map_err(|e| format!("unable to parse response ({})", e))?
        .result::<String>()
        .map_err(|e| format!("unable to parse response ({})", e))?;

    Ok(block_hash)
}

pub fn standardize_bitcoin_block(
    block: BitcoinBlockFullBreakdown,
    network: &BitcoinNetwork,
    ctx: &Context,
) -> Result<BitcoinBlockData, String> {
    let mut transactions = vec![];
    let block_height = block.height as u64;
    let expected_magic_bytes = get_stacks_canonical_magic_bytes(&network);
    let pox_config = get_canonical_pox_config(&network);

    ctx.try_log(|logger| slog::debug!(logger, "Standardizing Bitcoin block {}", block.hash,));

    for mut tx in block.tx.into_iter() {
        let txid = tx.txid.to_string();

        ctx.try_log(|logger| slog::debug!(logger, "Standardizing Bitcoin transaction {txid}"));

        let mut stacks_operations = vec![];
        if let Some(op) = try_parse_stacks_operation(
            block_height,
            &tx.vin,
            &tx.vout,
            &pox_config,
            &expected_magic_bytes,
            ctx,
        ) {
            stacks_operations.push(op);
        }

        let mut ordinal_operations = vec![];

        #[cfg(feature = "ordinals")]
        ordinal_operations.append(&mut hord::parse_ordinal_operations(&tx, ctx));

        let mut inputs = vec![];
        let mut sats_in = 0;
        for (index, input) in tx.vin.drain(..).enumerate() {
            if input.is_coinbase() {
                continue;
            }
            let prevout = input.prevout.as_ref().ok_or(format!(
                "error retrieving prevout for transaction {}, input #{} (block #{})",
                tx.txid, index, block.height
            ))?;

            let txid = input.txid.as_ref().ok_or(format!(
                "error retrieving txid for transaction {}, input #{} (block #{})",
                tx.txid, index, block.height
            ))?;

            let vout = input.vout.ok_or(format!(
                "error retrieving vout for transaction {}, input #{} (block #{})",
                tx.txid, index, block.height
            ))?;

            let script_sig = input.script_sig.ok_or(format!(
                "error retrieving script_sig for transaction {}, input #{} (block #{})",
                tx.txid, index, block.height
            ))?;

            sats_in += prevout.value.to_sat();
            inputs.push(TxIn {
                previous_output: OutPoint {
                    txid: format!("0x{}", txid.to_string()),
                    vout,
                    block_height: prevout.height,
                    value: prevout.value.to_sat(),
                },
                script_sig: format!("0x{}", hex::encode(&script_sig.hex)),
                sequence: input.sequence,
                witness: input
                    .txinwitness
                    .unwrap_or(vec![])
                    .to_vec()
                    .iter()
                    .map(|w| format!("0x{}", hex::encode(w)))
                    .collect::<Vec<_>>(),
            })
        }

        let mut outputs = vec![];
        let mut sats_out = 0;
        for output in tx.vout.drain(..) {
            let value = output.value.to_sat();
            sats_out += value;
            outputs.push(TxOut {
                value,
                script_pubkey: format!("0x{}", hex::encode(&output.script_pub_key.hex)),
            });
        }

        let tx = BitcoinTransactionData {
            transaction_identifier: TransactionIdentifier {
                hash: format!("0x{}", txid),
            },
            operations: vec![],
            metadata: BitcoinTransactionMetadata {
                inputs,
                outputs,
                stacks_operations,
                ordinal_operations,
                proof: None,
                fee: sats_in - sats_out,
            },
        };
        transactions.push(tx);
    }

    Ok(BitcoinBlockData {
        block_identifier: BlockIdentifier {
            hash: format!("0x{}", block.hash),
            index: block_height,
        },
        parent_block_identifier: BlockIdentifier {
            hash: format!(
                "0x{}",
                block.previousblockhash.unwrap_or(BlockHash::all_zeros())
            ),
            index: block_height - 1,
        },
        timestamp: block.time as u32,
        metadata: BitcoinBlockMetadata {
            network: network.clone(),
        },
        transactions,
    })
}

fn try_parse_stacks_operation(
    block_height: u64,
    _inputs: &Vec<BitcoinTransactionInputFullBreakdown>,
    outputs: &Vec<BitcoinTransactionOutputFullBreakdown>,
    pox_config: &PoxConfig,
    expected_magic_bytes: &[u8; 2],
    ctx: &Context,
) -> Option<StacksBaseChainOperation> {
    if outputs.is_empty() {
        return None;
    }

    // Safely parsing the first 2 bytes (following OP_RETURN + PUSH_DATA)
    let op_return_output = &outputs[0].script_pub_key.hex;
    if op_return_output.len() < 7 {
        return None;
    }
    if op_return_output[3] != expected_magic_bytes[0]
        || op_return_output[4] != expected_magic_bytes[1]
    {
        return None;
    }
    // Safely classifying the Stacks operation;
    let op_type: StacksOpcodes = match op_return_output[5].try_into() {
        Ok(op) => op,
        Err(_) => {
            ctx.try_log(|logger| {
                slog::debug!(
                    logger,
                    "Stacks operation parsing - opcode unknown {}",
                    op_return_output[5]
                )
            });
            return None;
        }
    };
    let op = match op_type {
        StacksOpcodes::KeyRegister => {
            let res = try_parse_key_register_op(&op_return_output[6..])?;
            StacksBaseChainOperation::LeaderRegistered(res)
        }
        StacksOpcodes::PreStx => {
            let _ = try_parse_pre_stx_op(&op_return_output[6..])?;
            return None;
        }
        StacksOpcodes::TransferStx => {
            let res = try_parse_transfer_stx_op(&op_return_output[6..])?;
            StacksBaseChainOperation::StxTransferred(res)
        }
        StacksOpcodes::StackStx => {
            let res = try_parse_stacks_stx_op(&op_return_output[6..])?;
            StacksBaseChainOperation::StxLocked(res)
        }
        StacksOpcodes::BlockCommit => {
            let res = try_parse_block_commit_op(&op_return_output[5..])?;
            let mut pox_sats_burnt = 0;
            let mut pox_sats_transferred = vec![];

            // We need to determine wether the transaction was a PoB or a Pox commitment
            let mining_output_index = if pox_config
                .is_consensus_rewarding_participants_at_block_height(block_height)
            {
                // Output 0 is OP_RETURN
                // Output 1 is rewarding Address 1
                let pox_output_1 = outputs
                    .get(1)
                    .ok_or(format!("expected pox output 1 not found"))
                    .ok()?;
                let pox_script_1 = pox_output_1
                    .script_pub_key
                    .script()
                    .map_err(|_e| format!("expected pox output 1 corrupted"))
                    .ok()?;
                let pox_address_1 = Address::from_script(&pox_script_1, bitcoin::Network::Bitcoin)
                    .map_err(|_e| format!("expected pox output 1 corrupted"))
                    .ok()?;
                if pox_address_1.to_string().eq(&pox_config.get_burn_address()) {
                    pox_sats_burnt += pox_output_1.value.to_sat();
                } else {
                    pox_sats_transferred.push(PoxReward {
                        recipient_address: pox_address_1.to_string(),
                        amount: pox_output_1.value.to_sat(),
                    });
                }
                // Output 2 is rewarding Address 2
                let pox_output_2 = outputs
                    .get(2)
                    .ok_or(format!("expected pox output 2 not found"))
                    .ok()?;
                let pox_script_2 = pox_output_2
                    .script_pub_key
                    .script()
                    .map_err(|_e| format!("expected pox output 2 corrupted"))
                    .ok()?;
                let pox_address_2 = Address::from_script(&pox_script_2, bitcoin::Network::Bitcoin)
                    .map_err(|_e| format!("expected pox output 2 corrupted"))
                    .ok()?;
                if pox_address_2.to_string().eq(&pox_config.get_burn_address()) {
                    pox_sats_burnt += pox_output_2.value.to_sat();
                } else {
                    pox_sats_transferred.push(PoxReward {
                        recipient_address: pox_address_2.to_string(),
                        amount: pox_output_2.value.to_sat(),
                    });
                }
                // Output 3 is used for miner chained commitments
                3
            } else {
                // Output 0 is OP_RETURN
                // Output 1 should be a Burn Address
                let burn_output = outputs
                    .get(1)
                    .ok_or(format!("expected burn address not found"))
                    .ok()?;
                // Todo: Ensure that we're looking at a burn address
                pox_sats_burnt += burn_output.value.to_sat();
                // Output 2 is used for miner chained commitments
                2
            };

            let mut mining_sats_left = 0;
            let mut mining_address_post_commit = None;
            if let Some(mining_post_commit) = outputs.get(mining_output_index) {
                mining_sats_left = mining_post_commit.value.to_sat();
                mining_address_post_commit = match mining_post_commit.script_pub_key.script() {
                    Ok(script) => Address::from_script(&script, bitcoin::Network::Bitcoin)
                        .and_then(|a| Ok(a.to_string()))
                        .ok(),
                    Err(_) => None,
                };
            }

            // let mining_address_pre_commit = match inputs[0].script_sig {
            //     Some(script) => match script.script() {

            //     }

            // }
            // mining_address_post_commit = match inputs.first().and_then(|i| i.script_sig).and_then(|s| s.script()).script_pub_key.script() {
            //     Ok(script) => Address::from_script(&script, bitcoin::Network::Bitcoin).and_then(|a| Ok(a.to_string())).ok(),
            //     Err(_) => None
            // };

            let pox_cycle_index = pox_config.get_pox_cycle_id(block_height);
            let pox_cycle_length = pox_config.get_pox_cycle_len();
            let pox_cycle_position = pox_config.get_pos_in_pox_cycle(block_height);

            StacksBaseChainOperation::BlockCommitted(StacksBlockCommitmentData {
                block_hash: res.stacks_block_hash,
                pox_cycle_index,
                pox_cycle_length,
                pox_cycle_position,
                pox_sats_burnt,
                pox_sats_transferred,
                // mining_address_pre_commit: None,
                mining_address_post_commit,
                mining_sats_left,
            })
        }
    };

    Some(op)
}

fn try_parse_block_commit_op(bytes: &[u8]) -> Option<BlockCommitmentData> {
    if bytes.len() < 32 {
        return None;
    }

    Some(BlockCommitmentData {
        stacks_block_hash: format!("0x{}", hex::encode(&bytes[0..32])),
    })
}

fn try_parse_key_register_op(_bytes: &[u8]) -> Option<KeyRegistrationData> {
    Some(KeyRegistrationData {})
}

fn try_parse_pre_stx_op(_bytes: &[u8]) -> Option<()> {
    None
}

fn try_parse_transfer_stx_op(bytes: &[u8]) -> Option<TransferSTXData> {
    if bytes.len() < 16 {
        return None;
    }

    // todo(lgalabru)
    Some(TransferSTXData {
        sender: "".into(),
        recipient: "".into(),
        amount: "".into(),
    })
}

fn try_parse_stacks_stx_op(bytes: &[u8]) -> Option<LockSTXData> {
    if bytes.len() < 16 {
        return None;
    }

    // todo(lgalabru)
    Some(LockSTXData {
        sender: "".into(),
        amount: "".into(),
        duration: 1,
    })
}

#[cfg(test)]
pub mod tests;

// Test vectors
// 1) Devnet PoB
// 2022-10-26T03:06:17.376341Z  INFO chainhook_event_observer::indexer: BitcoinBlockData { block_identifier: BlockIdentifier { index: 104, hash: "0x210d0d095a75d88fc059cb97f453eee33b1833153fb1f81b9c3c031c26bb106b" }, parent_block_identifier: BlockIdentifier { index: 103, hash: "0x5d5a4b8113c35f20fb0b69b1fb1ae1b88461ea57e2a2e4c036f97fae70ca1abb" }, timestamp: 1666753576, transactions: [BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0xfaaac1833dc4883e7ec28f61e35b41f896c395f8d288b1a177155de2abd6052f" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "0000000000000000000000000000000000000000000000000000000000000000", vout: 4294967295 }, script_sig: "01680101", sequence: 4294967295, witness: [] }], outputs: [TxOut { value: 5000017550, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }, TxOut { value: 0, script_pubkey: "6a24aa21a9ed4a190dfdc77e260409c2a693e6d3b8eca43afbc4bffb79ddcdcc9516df804d9b" }], stacks_operations: [] } }, BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0x59193c24cb2325cd2271b89f790f958dcd4065088680ffbc201a0ebb2f3cbf25" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "9eebe848baaf8dd4810e4e4a91168e2e471c949439faf5d768750ca21d067689", vout: 3 }, script_sig: "483045022100a20f90e9e3c3bb7e558ad4fa65902d8cf6ce4bff1f5af0ac0a323b547385069c022021b9877abbc9d1eef175c7f712ac1b2d8f5ce566be542714effe42711e75b83801210239810ebf35e6f6c26062c99f3e183708d377720617c90a986859ec9c95d00be9", sequence: 4294967293, witness: [] }], outputs: [TxOut { value: 0, script_pubkey: "6a4c5069645b1681995f8e568287e0e4f5cbc1d6727dafb5e3a7822a77c69bd04208265aca9424d0337dac7d9e84371a2c91ece1891d67d3554bd9fdbe60afc6924d4b0773d90000006700010000006600012b" }, TxOut { value: 10000, script_pubkey: "76a914000000000000000000000000000000000000000088ac" }, TxOut { value: 10000, script_pubkey: "76a914000000000000000000000000000000000000000088ac" }, TxOut { value: 4999904850, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }], stacks_operations: [PobBlockCommitment(PobBlockCommitmentData { signers: [], stacks_block_hash: "0x5b1681995f8e568287e0e4f5cbc1d6727dafb5e3a7822a77c69bd04208265aca", amount: 10000 })] } }], metadata: BitcoinBlockMetadata }
// 2022-10-26T03:06:21.929157Z  INFO chainhook_event_observer::indexer: BitcoinBlockData { block_identifier: BlockIdentifier { index: 105, hash: "0x0302c4c6063eb7199d3a565351bceeea9df4cb4aa09293194dbab277e46c2979" }, parent_block_identifier: BlockIdentifier { index: 104, hash: "0x210d0d095a75d88fc059cb97f453eee33b1833153fb1f81b9c3c031c26bb106b" }, timestamp: 1666753581, transactions: [BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0xe7de433aa89c1f946f89133b0463b6cfebb26ad73b0771a79fd66c6acbfe3fb9" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "0000000000000000000000000000000000000000000000000000000000000000", vout: 4294967295 }, script_sig: "01690101", sequence: 4294967295, witness: [] }], outputs: [TxOut { value: 5000017600, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }, TxOut { value: 0, script_pubkey: "6a24aa21a9ed98ac3bc4e0c9ed53e3418a3bf3aa511dcd76088cf0e1c4fc71fb9755840d7a08" }], stacks_operations: [] } }, BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0xe654501805d80d59ef0d95b57ad7a924f3be4a4dc0db5a785dfebe1f70c4e23e" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "59193c24cb2325cd2271b89f790f958dcd4065088680ffbc201a0ebb2f3cbf25", vout: 3 }, script_sig: "483045022100b59d2d07f68ea3a4f27a49979080a07b2432cfad9fc90e1edd0241496f0fd83f02205ac233f4cb68ada487f16339abedb7093948b683ba7d76b3b4058b2c0181a68901210239810ebf35e6f6c26062c99f3e183708d377720617c90a986859ec9c95d00be9", sequence: 4294967293, witness: [] }], outputs: [TxOut { value: 0, script_pubkey: "6a4c5069645b351bb015ef4f7dcdce4c9d95cbf157f85a3714626252cfc9078f3f1591ccdb13c3c7e22b34c4ffc2f6064a41df6fcd7f1b759d4f28b2f7cb6b27f283c868406e0000006800010000006600012c" }, TxOut { value: 10000, script_pubkey: "76a914000000000000000000000000000000000000000088ac" }, TxOut { value: 10000, script_pubkey: "76a914000000000000000000000000000000000000000088ac" }, TxOut { value: 4999867250, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }], stacks_operations: [PobBlockCommitment(PobBlockCommitmentData { signers: [], stacks_block_hash: "0x5b351bb015ef4f7dcdce4c9d95cbf157f85a3714626252cfc9078f3f1591ccdb", amount: 10000 })] } }], metadata: BitcoinBlockMetadata }
// 2022-10-26T03:07:53.298531Z  INFO chainhook_event_observer::indexer: BitcoinBlockData { block_identifier: BlockIdentifier { index: 106, hash: "0x52eb2aa15aa99afc4b918a552cef13e8b6eed84b257be097ad954b4f37a7e98d" }, parent_block_identifier: BlockIdentifier { index: 105, hash: "0x0302c4c6063eb7199d3a565351bceeea9df4cb4aa09293194dbab277e46c2979" }, timestamp: 1666753672, transactions: [BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0xd28d7f5411416f94b95e9f999d5ee8ded5543ba9daae9f612b80f01c5107862d" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "0000000000000000000000000000000000000000000000000000000000000000", vout: 4294967295 }, script_sig: "016a0101", sequence: 4294967295, witness: [] }], outputs: [TxOut { value: 5000017500, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }, TxOut { value: 0, script_pubkey: "6a24aa21a9ed71aaf7e5384879a1b112bf623ac8b46dd88b39c3d2c6f8a1d264fc4463e6356a" }], stacks_operations: [] } }, BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0x72e8e43afc4362cf921ccc57fde3e07b4cb6fac5f306525c86d38234c18e21d1" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "e654501805d80d59ef0d95b57ad7a924f3be4a4dc0db5a785dfebe1f70c4e23e", vout: 3 }, script_sig: "4730440220798bb7d7fb14df35610db2ef04e5d5b6588440b7c429bf650a96f8570904052b02204a817e13e7296a24a8f6cc8737bddb55d1835e513ec2b9dcb03424e4536ae34c01210239810ebf35e6f6c26062c99f3e183708d377720617c90a986859ec9c95d00be9", sequence: 4294967293, witness: [] }], outputs: [TxOut { value: 0, script_pubkey: "6a4c5069645b504d310fc27c86a6b65d0b0e0297db1e185d3432fdab9fa96a1053407ed07b537b8b7d23c6309dfd24340e85b75cff11ad685f8b310c1d2098748a0fffb146ec00000069000100000066000128" }, TxOut { value: 20000, script_pubkey: "76a914000000000000000000000000000000000000000088ac" }, TxOut { value: 4999829750, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }], stacks_operations: [PobBlockCommitment(PobBlockCommitmentData { signers: [], stacks_block_hash: "0x5b504d310fc27c86a6b65d0b0e0297db1e185d3432fdab9fa96a1053407ed07b", amount: 20000 })] } }], metadata: BitcoinBlockMetadata }