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
// Copyright (c) 2021-2024 Espresso Systems (espressosys.com)
// This file is part of the HotShot repository.

// You should have received a copy of the MIT License
// along with the HotShot repository. If not, see <https://mit-license.org/>.

use std::time::{Duration, Instant};

use async_compatibility_layer::art::async_sleep;
use hotshot_builder_api::v0_1::{
    block_info::AvailableBlockInfo,
    builder::{BuildError, Error as BuilderApiError},
};
use hotshot_types::{
    constants::LEGACY_BUILDER_MODULE,
    traits::{node_implementation::NodeType, signature_key::SignatureKey},
    vid::VidCommitment,
};
use serde::{Deserialize, Serialize};
use snafu::Snafu;
use surf_disco::{client::HealthStatus, Client, Url};
use tagged_base64::TaggedBase64;
use vbs::version::StaticVersionType;

#[derive(Debug, Snafu, Serialize, Deserialize)]
/// Represents errors than builder client may return
pub enum BuilderClientError {
    // NOTE: folds BuilderError::NotFound & builderError::Missing
    // into one. Maybe we'll want to handle that separately in
    // the future
    /// Block not found
    #[snafu(display("Requested block not found"))]
    NotFound,
    /// Generic error while accessing the API,
    /// i.e. when API isn't available or compatible
    #[snafu(display("Builder API error: {message}"))]
    Api {
        /// Underlying error
        message: String,
    },
}

impl From<BuilderApiError> for BuilderClientError {
    fn from(value: BuilderApiError) -> Self {
        match value {
            BuilderApiError::Request { source } | BuilderApiError::TxnUnpack { source } => {
                Self::Api {
                    message: source.to_string(),
                }
            }
            BuilderApiError::TxnSubmit { source } | BuilderApiError::BuilderAddress { source } => {
                Self::Api {
                    message: source.to_string(),
                }
            }
            BuilderApiError::Custom { message, .. } => Self::Api { message },
            BuilderApiError::BlockAvailable { source, .. }
            | BuilderApiError::BlockClaim { source, .. } => match source {
                BuildError::NotFound | BuildError::Missing => Self::NotFound,
                BuildError::Error { message } => Self::Api { message },
            },
        }
    }
}

/// Client for builder API
pub struct BuilderClient<TYPES: NodeType, Ver: StaticVersionType> {
    /// Underlying surf_disco::Client for the legacy builder api
    client: Client<BuilderApiError, Ver>,
    /// Marker for [`NodeType`] used here
    _marker: std::marker::PhantomData<TYPES>,
}

impl<TYPES: NodeType, Ver: StaticVersionType> BuilderClient<TYPES, Ver> {
    /// Construct a new client from base url
    ///
    /// # Panics
    ///
    /// If the URL is malformed.
    pub fn new(base_url: impl Into<Url>) -> Self {
        let url = base_url.into();

        Self {
            client: Client::builder(url.clone())
                .set_timeout(Some(Duration::from_secs(2)))
                .build(),
            _marker: std::marker::PhantomData,
        }
    }

    /// Wait for server to become available
    /// Returns `false` if server doesn't respond
    /// with OK healthcheck before `timeout`
    pub async fn connect(&self, timeout: Duration) -> bool {
        let timeout = Instant::now() + timeout;
        let mut backoff = Duration::from_millis(50);
        while Instant::now() < timeout {
            if matches!(
                self.client.healthcheck::<HealthStatus>().await,
                Ok(HealthStatus::Available)
            ) {
                return true;
            }
            async_sleep(backoff).await;
            backoff *= 2;
        }
        false
    }

    /// Query builder for available blocks
    ///
    /// # Errors
    /// - [`BuilderClientError::NotFound`] if blocks aren't available for this parent
    /// - [`BuilderClientError::Api`] if API isn't responding or responds incorrectly
    pub async fn available_blocks(
        &self,
        parent: VidCommitment,
        view_number: u64,
        sender: TYPES::SignatureKey,
        signature: &<<TYPES as NodeType>::SignatureKey as SignatureKey>::PureAssembledSignatureType,
    ) -> Result<Vec<AvailableBlockInfo<TYPES>>, BuilderClientError> {
        let encoded_signature: TaggedBase64 = signature.clone().into();
        self.client
            .get(&format!(
                "{LEGACY_BUILDER_MODULE}/availableblocks/{parent}/{view_number}/{sender}/{encoded_signature}"
            ))
            .send()
            .await
            .map_err(Into::into)
    }
}

/// Version 0.1
pub mod v0_1 {
    use hotshot_builder_api::v0_1::block_info::{AvailableBlockData, AvailableBlockHeaderInput};
    pub use hotshot_builder_api::v0_1::Version;
    use hotshot_types::{
        constants::LEGACY_BUILDER_MODULE,
        traits::{node_implementation::NodeType, signature_key::SignatureKey},
        utils::BuilderCommitment,
    };
    use tagged_base64::TaggedBase64;

    use super::BuilderClientError;

    /// Client for builder API
    pub type BuilderClient<TYPES> = super::BuilderClient<TYPES, Version>;

    impl<TYPES: NodeType> BuilderClient<TYPES> {
        /// Claim block header input
        ///
        /// # Errors
        /// - [`BuilderClientError::NotFound`] if block isn't available
        /// - [`BuilderClientError::Api`] if API isn't responding or responds incorrectly
        pub async fn claim_block_header_input(
            &self,
            block_hash: BuilderCommitment,
            view_number: u64,
            sender: TYPES::SignatureKey,
            signature: &<<TYPES as NodeType>::SignatureKey as SignatureKey>::PureAssembledSignatureType,
        ) -> Result<AvailableBlockHeaderInput<TYPES>, BuilderClientError> {
            let encoded_signature: TaggedBase64 = signature.clone().into();
            self.client
                .get(&format!(
                    "{LEGACY_BUILDER_MODULE}/claimheaderinput/{block_hash}/{view_number}/{sender}/{encoded_signature}"
                ))
                .send()
                .await
                .map_err(Into::into)
        }

        /// Claim block
        ///
        /// # Errors
        /// - [`BuilderClientError::NotFound`] if block isn't available
        /// - [`BuilderClientError::Api`] if API isn't responding or responds incorrectly
        pub async fn claim_block(
            &self,
            block_hash: BuilderCommitment,
            view_number: u64,
            sender: TYPES::SignatureKey,
            signature: &<<TYPES as NodeType>::SignatureKey as SignatureKey>::PureAssembledSignatureType,
        ) -> Result<AvailableBlockData<TYPES>, BuilderClientError> {
            let encoded_signature: TaggedBase64 = signature.clone().into();
            self.client
                .get(&format!(
                    "{LEGACY_BUILDER_MODULE}/claimblock/{block_hash}/{view_number}/{sender}/{encoded_signature}"
                ))
                .send()
                .await
                .map_err(Into::into)
        }
    }
}

/// Version 0.2. No changes in API
pub mod v0_2 {
    use vbs::version::StaticVersion;

    pub use super::v0_1::*;

    /// Builder API version
    pub type Version = StaticVersion<0, 2>;
}

/// Version 0.3: marketplace. Bundles.
pub mod v0_3 {
    pub use hotshot_builder_api::v0_3::Version;
    use hotshot_types::{
        bundle::Bundle, constants::MARKETPLACE_BUILDER_MODULE,
        traits::node_implementation::NodeType, vid::VidCommitment,
    };
    use vbs::version::StaticVersion;

    pub use super::BuilderClientError;

    /// Client for builder API
    pub type BuilderClient<TYPES> = super::BuilderClient<TYPES, StaticVersion<0, 3>>;

    impl<TYPES: NodeType> BuilderClient<TYPES> {
        /// Claim block
        ///
        /// # Errors
        /// - [`BuilderClientError::NotFound`] if block isn't available
        /// - [`BuilderClientError::Api`] if API isn't responding or responds incorrectly
        pub async fn bundle(
            &self,
            parent_view: u64,
            parent_hash: VidCommitment,
            view_number: u64,
        ) -> Result<Bundle<TYPES>, BuilderClientError> {
            self.client
                .get(&format!(
                    "{MARKETPLACE_BUILDER_MODULE}/bundle/{parent_view}/{parent_hash}/{view_number}"
                ))
                .send()
                .await
                .map_err(Into::into)
        }
    }
}