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
//! Easy to use utilities for confirmations.

use std::time::Duration;

use crate::api::{CreateFilter, Eth, EthFilter, FilterStream, Namespace};
use crate::helpers::CallFuture;
use crate::types::{Bytes, TransactionReceipt, TransactionRequest, H256, U256};
use crate::{Error, Transport};
use futures::stream::Skip;
use futures::{Future, IntoFuture, Poll, Stream};

/// Checks whether an event has been confirmed.
pub trait ConfirmationCheck {
    /// Future resolved when is known whether an event has been confirmed.
    type Check: IntoFuture<Item = Option<U256>, Error = Error>;

    /// Should be called to get future which resolves when confirmation state is known.
    fn check(&self) -> Self::Check;
}

impl<F, T> ConfirmationCheck for F
where
    F: Fn() -> T,
    T: IntoFuture<Item = Option<U256>, Error = Error>,
{
    type Check = T;

    fn check(&self) -> Self::Check {
        (*self)()
    }
}

enum WaitForConfirmationsState<F, O> {
    WaitForNextBlock,
    CheckConfirmation(F),
    CompareConfirmations(u64, CallFuture<U256, O>),
}

struct WaitForConfirmations<T, V, F>
where
    T: Transport,
{
    eth: Eth<T>,
    state: WaitForConfirmationsState<F, T::Out>,
    filter_stream: Skip<FilterStream<T, H256>>,
    confirmation_check: V,
    confirmations: usize,
}

impl<T, V, F> Future for WaitForConfirmations<T, V, F::Future>
where
    T: Transport,
    V: ConfirmationCheck<Check = F>,
    F: IntoFuture<Item = Option<U256>, Error = Error>,
{
    type Item = ();
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            let next_state = match self.state {
                WaitForConfirmationsState::WaitForNextBlock => {
                    let _ = try_ready!(self.filter_stream.poll());
                    WaitForConfirmationsState::CheckConfirmation(self.confirmation_check.check().into_future())
                }
                WaitForConfirmationsState::CheckConfirmation(ref mut future) => match try_ready!(future.poll()) {
                    Some(confirmation_block_number) => {
                        let future = self.eth.block_number();
                        WaitForConfirmationsState::CompareConfirmations(confirmation_block_number.low_u64(), future)
                    }
                    None => WaitForConfirmationsState::WaitForNextBlock,
                },
                WaitForConfirmationsState::CompareConfirmations(
                    confirmation_block_number,
                    ref mut block_number_future,
                ) => {
                    let block_number = try_ready!(block_number_future.poll()).low_u64();
                    if confirmation_block_number + self.confirmations as u64 <= block_number {
                        return Ok(().into());
                    } else {
                        WaitForConfirmationsState::WaitForNextBlock
                    }
                }
            };
            self.state = next_state;
        }
    }
}

struct CreateWaitForConfirmations<T: Transport, V> {
    eth: Option<Eth<T>>,
    create_filter: CreateFilter<T, H256>,
    poll_interval: Duration,
    confirmation_check: Option<V>,
    confirmations: usize,
}

enum ConfirmationsState<T: Transport, V, F> {
    Create(CreateWaitForConfirmations<T, V>),
    Wait(WaitForConfirmations<T, V, F>),
}

/// On each new block checks confirmations.
pub struct Confirmations<T: Transport, V, F> {
    state: ConfirmationsState<T, V, F>,
}

impl<T: Transport, V, F> Confirmations<T, V, F> {
    fn new(eth: Eth<T>, eth_filter: EthFilter<T>, poll_interval: Duration, confirmations: usize, check: V) -> Self {
        Confirmations {
            state: ConfirmationsState::Create(CreateWaitForConfirmations {
                eth: Some(eth),
                create_filter: eth_filter.create_blocks_filter(),
                poll_interval,
                confirmation_check: Some(check),
                confirmations,
            }),
        }
    }
}

impl<T, V, F> Future for Confirmations<T, V, F::Future>
where
    T: Transport,
    V: ConfirmationCheck<Check = F>,
    F: IntoFuture<Item = Option<U256>, Error = Error>,
{
    type Item = ();
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            let next_state = match self.state {
                ConfirmationsState::Create(ref mut create) => {
                    let filter = try_ready!(create.create_filter.poll());
                    let future = WaitForConfirmations {
                        eth: create.eth.take().expect("future polled after ready; qed"),
                        state: WaitForConfirmationsState::WaitForNextBlock,
                        filter_stream: filter.stream(create.poll_interval).skip(create.confirmations as u64),
                        confirmation_check: create
                            .confirmation_check
                            .take()
                            .expect("future polled after ready; qed"),
                        confirmations: create.confirmations,
                    };
                    ConfirmationsState::Wait(future)
                }
                ConfirmationsState::Wait(ref mut wait) => return Future::poll(wait),
            };
            self.state = next_state;
        }
    }
}

/// Should be used to wait for confirmations
pub fn wait_for_confirmations<T, V, F>(
    eth: Eth<T>,
    eth_filter: EthFilter<T>,
    poll_interval: Duration,
    confirmations: usize,
    check: V,
) -> Confirmations<T, V, F::Future>
where
    T: Transport,
    V: ConfirmationCheck<Check = F>,
    F: IntoFuture<Item = Option<U256>, Error = Error>,
{
    Confirmations::new(eth, eth_filter, poll_interval, confirmations, check)
}

struct TransactionReceiptBlockNumber<T: Transport> {
    future: CallFuture<Option<TransactionReceipt>, T::Out>,
}

impl<T: Transport> Future for TransactionReceiptBlockNumber<T> {
    type Item = Option<U256>;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let receipt = try_ready!(self.future.poll());
        Ok(receipt.and_then(|receipt| receipt.block_number).into())
    }
}

struct TransactionReceiptBlockNumberCheck<T: Transport> {
    eth: Eth<T>,
    hash: H256,
}

impl<T: Transport> TransactionReceiptBlockNumberCheck<T> {
    fn new(eth: Eth<T>, hash: H256) -> Self {
        TransactionReceiptBlockNumberCheck { eth, hash }
    }
}

impl<T: Transport> ConfirmationCheck for TransactionReceiptBlockNumberCheck<T> {
    type Check = TransactionReceiptBlockNumber<T>;

    fn check(&self) -> Self::Check {
        TransactionReceiptBlockNumber {
            future: self.eth.transaction_receipt(self.hash),
        }
    }
}

enum SendTransactionWithConfirmationState<T: Transport> {
    Error(Option<Error>),
    SendTransaction(CallFuture<H256, T::Out>),
    WaitForConfirmations(
        H256,
        Confirmations<T, TransactionReceiptBlockNumberCheck<T>, TransactionReceiptBlockNumber<T>>,
    ),
    GetTransactionReceipt(CallFuture<Option<TransactionReceipt>, T::Out>),
}

/// Sends transaction and then checks if has been confirmed.
pub struct SendTransactionWithConfirmation<T: Transport> {
    state: SendTransactionWithConfirmationState<T>,
    transport: T,
    poll_interval: Duration,
    confirmations: usize,
}

impl<T: Transport> SendTransactionWithConfirmation<T> {
    fn new(transport: T, tx: TransactionRequest, poll_interval: Duration, confirmations: usize) -> Self {
        SendTransactionWithConfirmation {
            state: SendTransactionWithConfirmationState::SendTransaction(Eth::new(&transport).send_transaction(tx)),
            transport,
            poll_interval,
            confirmations,
        }
    }

    fn raw(transport: T, tx: Bytes, poll_interval: Duration, confirmations: usize) -> Self {
        SendTransactionWithConfirmation {
            state: SendTransactionWithConfirmationState::SendTransaction(Eth::new(&transport).send_raw_transaction(tx)),
            transport,
            poll_interval,
            confirmations,
        }
    }

    pub(crate) fn from_err<E: Into<Error>>(transport: T, err: E) -> Self {
        SendTransactionWithConfirmation {
            state: SendTransactionWithConfirmationState::Error(Some(err.into())),
            transport,
            poll_interval: Duration::from_secs(1),
            confirmations: 1,
        }
    }
}

impl<T: Transport> Future for SendTransactionWithConfirmation<T> {
    type Item = TransactionReceipt;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            let next_state = match self.state {
                SendTransactionWithConfirmationState::Error(ref mut error) => {
                    return Err(error
                        .take()
                        .expect("Error is initialized initially; future polled only once; qed"));
                }
                SendTransactionWithConfirmationState::SendTransaction(ref mut future) => {
                    let hash = try_ready!(future.poll());
                    if self.confirmations > 0 {
                        let confirmation_check =
                            TransactionReceiptBlockNumberCheck::new(Eth::new(self.transport.clone()), hash);
                        let eth = Eth::new(self.transport.clone());
                        let eth_filter = EthFilter::new(self.transport.clone());
                        let wait = wait_for_confirmations(
                            eth,
                            eth_filter,
                            self.poll_interval,
                            self.confirmations,
                            confirmation_check,
                        );
                        SendTransactionWithConfirmationState::WaitForConfirmations(hash, wait)
                    } else {
                        let receipt_future = Eth::new(&self.transport).transaction_receipt(hash);
                        SendTransactionWithConfirmationState::GetTransactionReceipt(receipt_future)
                    }
                }
                SendTransactionWithConfirmationState::WaitForConfirmations(hash, ref mut future) => {
                    let _confirmed = try_ready!(Future::poll(future));
                    let receipt_future = Eth::new(&self.transport).transaction_receipt(hash);
                    SendTransactionWithConfirmationState::GetTransactionReceipt(receipt_future)
                }
                SendTransactionWithConfirmationState::GetTransactionReceipt(ref mut future) => {
                    let receipt = try_ready!(Future::poll(future))
                        .expect("receipt can't be null after wait for confirmations; qed");
                    return Ok(receipt.into());
                }
            };
            self.state = next_state;
        }
    }
}

/// Sends transaction and returns future resolved after transaction is confirmed
pub fn send_transaction_with_confirmation<T>(
    transport: T,
    tx: TransactionRequest,
    poll_interval: Duration,
    confirmations: usize,
) -> SendTransactionWithConfirmation<T>
where
    T: Transport,
{
    SendTransactionWithConfirmation::new(transport, tx, poll_interval, confirmations)
}

/// Sends raw transaction and returns future resolved after transaction is confirmed
pub fn send_raw_transaction_with_confirmation<T>(
    transport: T,
    tx: Bytes,
    poll_interval: Duration,
    confirmations: usize,
) -> SendTransactionWithConfirmation<T>
where
    T: Transport,
{
    SendTransactionWithConfirmation::raw(transport, tx, poll_interval, confirmations)
}

#[cfg(test)]
mod tests {
    use super::send_transaction_with_confirmation;
    use crate::helpers::tests::TestTransport;
    use crate::rpc::Value;
    use crate::types::{Address, TransactionReceipt, TransactionRequest, H256, U128};
    use futures::Future;
    use serde_json::json;
    use std::time::Duration;

    #[test]
    fn test_send_transaction_with_confirmation() {
        let mut transport = TestTransport::default();
        let confirmations = 3;
        let transaction_request = TransactionRequest {
            from: Address::from_low_u64_be(0x123),
            to: Some(Address::from_low_u64_be(0x123)),
            gas: None,
            gas_price: Some(1.into()),
            value: Some(1.into()),
            data: None,
            nonce: None,
            condition: None,
        };

        let transaction_receipt = TransactionReceipt {
            transaction_hash: H256::zero(),
            transaction_index: U128::zero(),
            block_hash: Some(H256::zero()),
            block_number: Some(2.into()),
            cumulative_gas_used: 0.into(),
            gas_used: Some(0.into()),
            contract_address: None,
            logs: vec![],
            status: Some(1.into()),
            logs_bloom: Default::default(),
        };

        let poll_interval = Duration::from_secs(0);
        transport.add_response(Value::String(
            r#"0x0000000000000000000000000000000000000000000000000000000000000111"#.into(),
        ));
        transport.add_response(Value::String("0x123".into()));
        transport.add_response(Value::Array(vec![
            Value::String(r#"0x0000000000000000000000000000000000000000000000000000000000000456"#.into()),
            Value::String(r#"0x0000000000000000000000000000000000000000000000000000000000000457"#.into()),
        ]));
        transport.add_response(Value::Array(vec![Value::String(
            r#"0x0000000000000000000000000000000000000000000000000000000000000458"#.into(),
        )]));
        transport.add_response(Value::Array(vec![Value::String(
            r#"0x0000000000000000000000000000000000000000000000000000000000000459"#.into(),
        )]));
        transport.add_response(Value::Null);
        transport.add_response(Value::Array(vec![
            Value::String(r#"0x0000000000000000000000000000000000000000000000000000000000000460"#.into()),
            Value::String(r#"0x0000000000000000000000000000000000000000000000000000000000000461"#.into()),
        ]));
        transport.add_response(Value::Null);
        transport.add_response(json!(transaction_receipt));
        transport.add_response(Value::String("0x6".into()));
        transport.add_response(json!(transaction_receipt));
        transport.add_response(Value::Bool(true));

        let confirmation = {
            let future =
                send_transaction_with_confirmation(&transport, transaction_request, poll_interval, confirmations);
            future.wait()
        };

        transport.assert_request("eth_sendTransaction", &[r#"{"from":"0x0000000000000000000000000000000000000123","gasPrice":"0x1","to":"0x0000000000000000000000000000000000000123","value":"0x1"}"#.into()]);
        transport.assert_request("eth_newBlockFilter", &[]);
        transport.assert_request("eth_getFilterChanges", &[r#""0x123""#.into()]);
        transport.assert_request("eth_getFilterChanges", &[r#""0x123""#.into()]);
        transport.assert_request("eth_getFilterChanges", &[r#""0x123""#.into()]);
        transport.assert_request(
            "eth_getTransactionReceipt",
            &[r#""0x0000000000000000000000000000000000000000000000000000000000000111""#.into()],
        );
        transport.assert_request("eth_getFilterChanges", &[r#""0x123""#.into()]);
        transport.assert_request(
            "eth_getTransactionReceipt",
            &[r#""0x0000000000000000000000000000000000000000000000000000000000000111""#.into()],
        );
        transport.assert_request(
            "eth_getTransactionReceipt",
            &[r#""0x0000000000000000000000000000000000000000000000000000000000000111""#.into()],
        );
        transport.assert_request("eth_blockNumber", &[]);
        transport.assert_request(
            "eth_getTransactionReceipt",
            &[r#""0x0000000000000000000000000000000000000000000000000000000000000111""#.into()],
        );
        transport.assert_no_more_requests();
        assert_eq!(confirmation, Ok(transaction_receipt));
    }
}