bitcoind_client/
txoo_follower.rs

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
use crate::follower::{Error, FollowAction, SourceFollower, Tracker};
use crate::BlockSource;
use bitcoin::hash_types::FilterHeader;
use bitcoin::{Block, BlockHash};
use bitcoin::blockdata::block::Header as BlockHeader;
use txoo::proof::TxoProof;
use txoo::source::Error as TxooSourceError;
use txoo::source::Source;

/// The next action to take when following the chain, with SPV proofs
pub enum FollowWithProofAction {
    /// No action required, synced to chain tip
    None,
    /// A block has been added to the chain.
    /// Provides the new block.
    BlockAdded(Block, TxoProof),
    /// The current block has been reorganized out of the chain.
    /// Provides:
    /// - the block that was reorged out
    /// - the TXO proof for the block that was reorged out
    /// - the previous block header
    /// - the previous filter header
    /// Note that the transactions should be "un-processed" in reverse order
    /// in case they have inter-dependencies.
    BlockReorged(Block, TxoProof, BlockHeader, FilterHeader),
}

/// A follower for BlockSource with SPV proofs
pub struct SourceWithTxooProofFollower {
    source_follower: SourceFollower,
    txoo_source: Box<dyn Source>,
}

impl SourceWithTxooProofFollower {
    /// Create a new follower
    pub fn new(block_source: Box<dyn BlockSource>, source: Box<dyn Source>) -> Self {
        SourceWithTxooProofFollower {
            source_follower: SourceFollower::new(block_source),
            txoo_source: source,
        }
    }

    /// Follow the chain, returning the next action to take
    pub async fn follow_with_proof(
        &self,
        current_height: u32,
        current_hash: BlockHash,
        tracker: &impl Tracker,
    ) -> Result<FollowWithProofAction, Error> {
        let action = self
            .source_follower
            .follow(current_height, current_hash)
            .await?;
        match action {
            FollowAction::None => Ok(FollowWithProofAction::None),
            FollowAction::BlockAdded(block) => {
                self.txoo_source
                    .on_new_block(current_height + 1, &block)
                    .await;
                let (attestation, prev_filter_header) =
                    match self.txoo_source.get(current_height + 1, &block).await {
                        Ok(result) => result,
                        Err(TxooSourceError::NotExists) => {
                            // wait for oracle to attest to new block
                            // TODO warn if no attestation after some time
                            return Ok(FollowWithProofAction::None);
                        }
                        Err(e) => return Err(Error::SourceError(format!("{:?}", e))),
                    };
                let pubkey = self.txoo_source.oracle_setup().await.public_key;
                let attestations = vec![(pubkey, attestation)];
                let (txids, outpoints) = tracker.forward_watches().await;
                let proof = TxoProof::prove(
                    attestations,
                    &prev_filter_header,
                    &block,
                    current_height + 1,
                    &outpoints,
                    &txids,
                );
                Ok(FollowWithProofAction::BlockAdded(block, proof))
            }
            FollowAction::BlockReorged(block, prev_block_header) => {
                assert!(current_height > 0);
                let (attestation, prev_filter_header) = self
                    .txoo_source
                    .get(current_height, &block)
                    .await
                    .map_err(|e| {
                        Error::SourceError(format!("error getting current attestation: {:?}", e))
                    })?;
                let pubkey = self.txoo_source.oracle_setup().await.public_key;
                let attestations = vec![(pubkey, attestation)];
                let (txids, outpoints) = tracker.reverse_watches().await;
                let proof = TxoProof::prove(
                    attestations,
                    &prev_filter_header,
                    &block,
                    current_height,
                    &outpoints,
                    &txids,
                );
                Ok(FollowWithProofAction::BlockReorged(
                    block,
                    proof,
                    prev_block_header,
                    prev_filter_header,
                ))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dummy::DummyTxooSource;
    use crate::test_utils::{DummyBlockSource, DummyTracker};
    use bitcoin::hashes::Hash;
    use bitcoin::secp256k1::Secp256k1;
    use bitcoin::hash_types::FilterHeader;

    #[tokio::test]
    async fn follow_with_proof_test() {
        let secp = Secp256k1::new();
        let tracker = DummyTracker();
        let mut source = DummyBlockSource::new();
        let txoo_source = Box::new(DummyTxooSource::new());
        let follower =
            SourceWithTxooProofFollower::new(Box::new(source.clone()), txoo_source.clone());

        let genesis_hash = source.genesis_hash();
        txoo_source
            .on_new_block(0, &source.get_block_sync(&source.genesis_hash()))
            .await;

        if let FollowWithProofAction::None = follower
            .follow_with_proof(0, genesis_hash, &tracker)
            .await
            .unwrap()
        {
        } else {
            panic!("expected None");
        }
        let header1 = source.add();
        //txoo_source.on_new_block(1, &source.get_block_sync(&header1.block_hash()));
        let hash1 = match follower
            .follow_with_proof(0, genesis_hash, &tracker)
            .await
            .unwrap()
        {
            FollowWithProofAction::BlockAdded(block, proof) => {
                proof
                    .verify(1, &header1, None, &FilterHeader::all_zeros(), &[], &secp)
                    .expect("verify");
                block.block_hash()
            }
            _ => panic!("expected block added with proof"),
        };
        if let FollowWithProofAction::None = follower
            .follow_with_proof(1, hash1, &tracker)
            .await
            .unwrap()
        {
        } else {
            panic!("expected None");
        }
        source.remove();
        let action = follower
            .follow_with_proof(1, hash1, &tracker)
            .await
            .unwrap();
        if let FollowWithProofAction::BlockReorged(
            block,
            _proof,
            prev_block_header,
            prev_filter_header,
        ) = action
        {
            assert_eq!(block.block_hash(), hash1);
            assert_eq!(prev_filter_header, FilterHeader::all_zeros());
            assert_eq!(
                prev_block_header,
                source.get_header(&genesis_hash).await.unwrap().header
            );
        } else {
            panic!("expected reorg");
        }
    }
}