@@ -9,6 +9,7 @@ use std::{
99use actix:: { prelude:: * , ActorFutureExt , WrapFuture } ;
1010use futures:: future:: Either ;
1111
12+ use itertools:: Itertools ;
1213use witnet_data_structures:: {
1314 chain:: {
1415 tapi:: ActiveWips , Block , ChainInfo , ChainState , CheckpointBeacon , ConsensusConstantsWit2 ,
@@ -1542,10 +1543,39 @@ impl Handler<QueryStakes> for ChainManager {
15421543 type Result = <QueryStakes as Message >:: Result ;
15431544
15441545 fn handle ( & mut self , msg : QueryStakes , _ctx : & mut Self :: Context ) -> Self :: Result {
1545- // build address from public key hash
1546- let stakes = self . chain_state . stakes . query_stakes ( msg. filter ) ;
1546+ // query stakes from current chain state
1547+ let mut stakes = self
1548+ . chain_state
1549+ . stakes
1550+ . query_stakes ( msg. filter )
1551+ . map_err ( StakesError :: from) ?;
1552+ // filter out stake entries whose last mining and witnessing epochs are previous to `epoch`
1553+ let epoch: u32 = if msg. limits . since >= 0 {
1554+ msg. limits . since . try_into ( ) . inspect_err ( |& e| {
1555+ log:: warn!( "Invalid 'since' limit on QueryStakes: {}" , e) ;
1556+ } ) ?
1557+ } else {
1558+ ( self . current_epoch . unwrap ( ) as i64 + msg. limits . since )
1559+ . try_into ( )
1560+ . unwrap_or_default ( )
1561+ } ;
1562+ stakes. retain ( |stake| {
1563+ let nonce: u32 = stake. value . nonce . try_into ( ) . unwrap_or_default ( ) ;
1564+ stake. value . epochs . mining >= epoch && stake. value . epochs . mining != nonce
1565+ || ( stake. value . epochs . witnessing >= epoch
1566+ && stake. value . epochs . witnessing != nonce)
1567+ } ) ;
1568+ if msg. limits . distinct {
1569+ // if only distinct validators are required, retain only first appearence in the stakes array:
1570+ let stakes = stakes
1571+ . into_iter ( )
1572+ . unique_by ( |stake| stake. key . validator )
1573+ . collect ( ) ;
15471574
1548- stakes. map_err ( StakesError :: from) . map_err ( Into :: into)
1575+ Ok ( stakes)
1576+ } else {
1577+ Ok ( stakes)
1578+ }
15491579 }
15501580}
15511581
0 commit comments