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
// 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::{
    collections::HashMap,
    num::NonZeroUsize,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
    time::{Duration, Instant},
};

use async_broadcast::{broadcast, Sender};
use async_compatibility_layer::art::async_spawn;
use async_lock::RwLock;
use async_trait::async_trait;
use committable::{Commitment, Committable};
use futures::{future::BoxFuture, Stream, StreamExt};
use hotshot::{
    traits::BlockPayload,
    types::{Event, EventType, SignatureKey},
};
use hotshot_builder_api::{
    v0_1,
    v0_1::{
        block_info::{AvailableBlockData, AvailableBlockHeaderInput, AvailableBlockInfo},
        builder::{BuildError, Error, Options},
    },
    v0_3,
};
use hotshot_types::{
    bundle::Bundle,
    constants::{LEGACY_BUILDER_MODULE, MARKETPLACE_BUILDER_MODULE},
    traits::{
        block_contents::{BlockHeader, BuilderFee},
        node_implementation::NodeType,
        signature_key::BuilderSignatureKey,
    },
    utils::BuilderCommitment,
    vid::VidCommitment,
};
use lru::LruCache;
use tide_disco::{method::ReadState, App, Url};
use vbs::version::StaticVersionType;

use super::{build_block, run_builder_source, BlockEntry, BuilderTask, TestBuilderImplementation};
use crate::test_builder::BuilderChange;

pub struct SimpleBuilderImplementation;

impl SimpleBuilderImplementation {
    pub async fn create<TYPES: NodeType>(
        num_storage_nodes: usize,
        changes: HashMap<u64, BuilderChange>,
        change_sender: Sender<BuilderChange>,
    ) -> (SimpleBuilderSource<TYPES>, SimpleBuilderTask<TYPES>) {
        let (pub_key, priv_key) =
            TYPES::BuilderSignatureKey::generated_from_seed_indexed([1; 32], 0);

        let transactions = Arc::new(RwLock::new(HashMap::new()));
        let blocks = Arc::new(RwLock::new(HashMap::new()));
        let should_fail_claims = Arc::new(AtomicBool::new(false));

        let source = SimpleBuilderSource {
            pub_key,
            priv_key,
            transactions: transactions.clone(),
            blocks: blocks.clone(),
            num_storage_nodes,
            should_fail_claims: Arc::clone(&should_fail_claims),
        };

        let task = SimpleBuilderTask {
            transactions,
            blocks,
            decided_transactions: LruCache::new(NonZeroUsize::new(u16::MAX.into()).expect("> 0")),
            should_fail_claims,
            change_sender,
            changes,
        };

        (source, task)
    }
}

#[async_trait]
impl<TYPES: NodeType> TestBuilderImplementation<TYPES> for SimpleBuilderImplementation
where
    <TYPES as NodeType>::InstanceState: Default,
{
    type Config = ();

    async fn start(
        num_storage_nodes: usize,
        url: Url,
        _config: Self::Config,
        changes: HashMap<u64, BuilderChange>,
    ) -> Box<dyn BuilderTask<TYPES>> {
        let (change_sender, change_receiver) = broadcast(128);
        let (source, task) = Self::create(num_storage_nodes, changes, change_sender).await;
        run_builder_source(url, change_receiver, source);

        Box::new(task)
    }
}

#[derive(Debug, Clone)]
pub struct SimpleBuilderSource<TYPES: NodeType> {
    pub_key: TYPES::BuilderSignatureKey,
    priv_key: <TYPES::BuilderSignatureKey as BuilderSignatureKey>::BuilderPrivateKey,
    num_storage_nodes: usize,
    #[allow(clippy::type_complexity)]
    transactions: Arc<RwLock<HashMap<Commitment<TYPES::Transaction>, SubmittedTransaction<TYPES>>>>,
    blocks: Arc<RwLock<HashMap<BuilderCommitment, BlockEntry<TYPES>>>>,
    should_fail_claims: Arc<AtomicBool>,
}

#[async_trait]
impl<TYPES: NodeType> ReadState for SimpleBuilderSource<TYPES> {
    type State = Self;

    async fn read<T>(
        &self,
        op: impl Send + for<'a> FnOnce(&'a Self::State) -> BoxFuture<'a, T> + 'async_trait,
    ) -> T {
        op(self).await
    }
}

#[async_trait]
impl<TYPES: NodeType> v0_3::data_source::BuilderDataSource<TYPES> for SimpleBuilderSource<TYPES>
where
    <TYPES as NodeType>::InstanceState: Default,
{
    /// To get the list of available blocks
    async fn bundle(
        &self,
        _parent_view: u64,
        _parent_hash: &VidCommitment,
        _view_number: u64,
    ) -> Result<Bundle<TYPES>, BuildError> {
        let transactions = self
            .transactions
            .read(|txns| {
                Box::pin(async {
                    txns.values()
                        .filter(|txn| {
                            // We want transactions that are either unclaimed, or claimed long ago
                            // and thus probably not included, or they would've been decided on
                            // already and removed from the queue
                            txn.claimed
                                .map(|claim_time| claim_time.elapsed() > Duration::from_secs(30))
                                .unwrap_or(true)
                        })
                        .cloned()
                        .map(|txn| txn.transaction)
                        .collect::<Vec<TYPES::Transaction>>()
                })
            })
            .await;

        let fee_amount = 1;
        let sequencing_fee: BuilderFee<TYPES> = BuilderFee {
            fee_amount,
            fee_account: self.pub_key.clone(),
            fee_signature: TYPES::BuilderSignatureKey::sign_sequencing_fee_marketplace(
                &self.priv_key.clone(),
                fee_amount,
            )
            .expect("Failed to sign fee!"),
        };

        let signature =
            TYPES::BuilderSignatureKey::sign_bundle::<TYPES>(&self.priv_key, &transactions)
                .unwrap();

        {
            // claim transactions
            let mut transactions_lock = self.transactions.write().await;
            let transaction_hashes = transactions.iter().map(|txn| txn.commit());
            let time = Instant::now();

            for hash in transaction_hashes {
                if let Some(txn) = transactions_lock.get_mut(&hash) {
                    txn.claimed = Some(time);
                }
            }
        }

        Ok(Bundle {
            transactions,
            signature,
            sequencing_fee,
        })
    }

    /// To get the builder's address
    async fn builder_address(&self) -> Result<TYPES::BuilderSignatureKey, BuildError> {
        Ok(self.pub_key.clone())
    }
}

#[async_trait]
impl<TYPES: NodeType> v0_1::data_source::BuilderDataSource<TYPES> for SimpleBuilderSource<TYPES>
where
    <TYPES as NodeType>::InstanceState: Default,
{
    async fn available_blocks(
        &self,
        _for_parent: &VidCommitment,
        _view_number: u64,
        _sender: TYPES::SignatureKey,
        _signature: &<TYPES::SignatureKey as SignatureKey>::PureAssembledSignatureType,
    ) -> Result<Vec<AvailableBlockInfo<TYPES>>, BuildError> {
        let transactions = self
            .transactions
            .read(|txns| {
                Box::pin(async {
                    txns.values()
                        .filter(|txn| {
                            // We want transactions that are either unclaimed, or claimed long ago
                            // and thus probably not included, or they would've been decided on
                            // already and removed from the queue
                            txn.claimed
                                .map(|claim_time| claim_time.elapsed() > Duration::from_secs(30))
                                .unwrap_or(true)
                        })
                        .cloned()
                        .map(|txn| txn.transaction)
                        .collect::<Vec<TYPES::Transaction>>()
                })
            })
            .await;

        if transactions.is_empty() {
            // We don't want to return an empty block if we have no trasnactions, as we would end up
            // driving consensus to produce empty blocks extremely quickly when mempool is empty.
            // Instead, we return no blocks, so that view leader will keep asking for blocks until
            // either we have something non-trivial to propose, or leader runs out of time to propose,
            // in which case view leader will finally propose an empty block themselves.
            return Ok(vec![]);
        }

        let block_entry = build_block(
            transactions,
            self.num_storage_nodes,
            self.pub_key.clone(),
            self.priv_key.clone(),
        )
        .await;

        let metadata = block_entry.metadata.clone();

        self.blocks
            .write()
            .await
            .insert(block_entry.metadata.block_hash.clone(), block_entry);

        Ok(vec![metadata])
    }

    async fn claim_block(
        &self,
        block_hash: &BuilderCommitment,
        _view_number: u64,
        _sender: TYPES::SignatureKey,
        _signature: &<TYPES::SignatureKey as SignatureKey>::PureAssembledSignatureType,
    ) -> Result<AvailableBlockData<TYPES>, BuildError> {
        if self.should_fail_claims.load(Ordering::Relaxed) {
            return Err(BuildError::Missing);
        }

        let payload = {
            let mut blocks = self.blocks.write().await;
            let entry = blocks.get_mut(block_hash).ok_or(BuildError::NotFound)?;
            entry.payload.take().ok_or(BuildError::Missing)?
        };

        let now = Instant::now();

        let claimed_transactions = payload
            .block_payload
            .transaction_commitments(&payload.metadata);

        let mut transactions = self.transactions.write().await;
        for txn_hash in claimed_transactions {
            if let Some(txn) = transactions.get_mut(&txn_hash) {
                txn.claimed = Some(now);
            }
        }

        Ok(payload)
    }

    async fn claim_block_header_input(
        &self,
        block_hash: &BuilderCommitment,
        _view_number: u64,
        _sender: TYPES::SignatureKey,
        _signature: &<TYPES::SignatureKey as SignatureKey>::PureAssembledSignatureType,
    ) -> Result<AvailableBlockHeaderInput<TYPES>, BuildError> {
        if self.should_fail_claims.load(Ordering::Relaxed) {
            return Err(BuildError::Missing);
        }

        let mut blocks = self.blocks.write().await;
        let entry = blocks.get_mut(block_hash).ok_or(BuildError::NotFound)?;
        entry.header_input.take().ok_or(BuildError::Missing)
    }

    async fn builder_address(&self) -> Result<TYPES::BuilderSignatureKey, BuildError> {
        Ok(self.pub_key.clone())
    }
}

impl<TYPES: NodeType> SimpleBuilderSource<TYPES> {
    pub async fn run(self, url: Url)
    where
        <TYPES as NodeType>::InstanceState: Default,
    {
        let builder_api_0_1 = hotshot_builder_api::v0_1::builder::define_api::<
            SimpleBuilderSource<TYPES>,
            TYPES,
        >(&Options::default())
        .expect("Failed to construct the builder API");

        let builder_api_0_3 = hotshot_builder_api::v0_3::builder::define_api::<
            SimpleBuilderSource<TYPES>,
            TYPES,
        >(&Options::default())
        .expect("Failed to construct the builder API");

        let mut app: App<SimpleBuilderSource<TYPES>, Error> = App::with_state(self);
        app.register_module::<Error, _>(LEGACY_BUILDER_MODULE, builder_api_0_1)
            .expect("Failed to register builder API 0.1")
            .register_module::<Error, _>(MARKETPLACE_BUILDER_MODULE, builder_api_0_3)
            .expect("Failed to register builder API 0.3");

        async_spawn(app.serve(url, hotshot_builder_api::v0_1::Version::instance()));
    }
}

#[derive(Debug, Clone)]
struct SubmittedTransaction<TYPES: NodeType> {
    claimed: Option<Instant>,
    transaction: TYPES::Transaction,
}

#[derive(Clone)]
pub struct SimpleBuilderTask<TYPES: NodeType> {
    #[allow(clippy::type_complexity)]
    transactions: Arc<RwLock<HashMap<Commitment<TYPES::Transaction>, SubmittedTransaction<TYPES>>>>,
    blocks: Arc<RwLock<HashMap<BuilderCommitment, BlockEntry<TYPES>>>>,
    decided_transactions: LruCache<Commitment<TYPES::Transaction>, ()>,
    should_fail_claims: Arc<AtomicBool>,
    changes: HashMap<u64, BuilderChange>,
    change_sender: Sender<BuilderChange>,
}

impl<TYPES: NodeType> BuilderTask<TYPES> for SimpleBuilderTask<TYPES> {
    fn start(
        mut self: Box<Self>,
        mut stream: Box<dyn Stream<Item = Event<TYPES>> + std::marker::Unpin + Send + 'static>,
    ) {
        async_spawn(async move {
            let mut should_build_blocks = true;
            loop {
                match stream.next().await {
                    None => {
                        break;
                    }
                    Some(evt) => match evt.event {
                        EventType::ViewFinished { view_number } => {
                            if let Some(change) = self.changes.remove(&view_number) {
                                match change {
                                    BuilderChange::Up => should_build_blocks = true,
                                    BuilderChange::Down => {
                                        should_build_blocks = false;
                                        self.transactions.write().await.clear();
                                        self.blocks.write().await.clear();
                                    }
                                    BuilderChange::FailClaims(value) => {
                                        self.should_fail_claims.store(value, Ordering::Relaxed);
                                    }
                                }
                                let _ = self.change_sender.broadcast(change).await;
                            }
                        }
                        EventType::Decide { leaf_chain, .. } if should_build_blocks => {
                            let mut queue = self.transactions.write().await;
                            for leaf_info in leaf_chain.iter() {
                                if let Some(ref payload) = leaf_info.leaf.block_payload() {
                                    for txn in payload.transaction_commitments(
                                        leaf_info.leaf.block_header().metadata(),
                                    ) {
                                        self.decided_transactions.put(txn, ());
                                        queue.remove(&txn);
                                    }
                                }
                            }
                            self.blocks.write().await.clear();
                        }
                        EventType::DaProposal { proposal, .. } if should_build_blocks => {
                            let payload = TYPES::BlockPayload::from_bytes(
                                &proposal.data.encoded_transactions,
                                &proposal.data.metadata,
                            );
                            let now = Instant::now();

                            let mut queue = self.transactions.write().await;
                            for commitment in
                                payload.transaction_commitments(&proposal.data.metadata)
                            {
                                if let Some(txn) = queue.get_mut(&commitment) {
                                    txn.claimed = Some(now);
                                }
                            }
                        }
                        EventType::Transactions { transactions } if should_build_blocks => {
                            let mut queue = self.transactions.write().await;
                            for transaction in transactions {
                                if !self.decided_transactions.contains(&transaction.commit()) {
                                    queue.insert(
                                        transaction.commit(),
                                        SubmittedTransaction {
                                            claimed: None,
                                            transaction: transaction.clone(),
                                        },
                                    );
                                }
                            }
                        }
                        _ => {}
                    },
                }
            }
        });
    }
}