import { P2P } from '../../src' ; import { createNetwork , destroyNetwork } from '../utils/network_setup' ; import { constructPeerId } from '../../src/utils' ; import { EVENT_BAN_PEER } from '../../src/events' ; describe ( 'Peer banning mechanism' , ( ) => { let p2pNodeList = [ ] ; let P2PNode ; beforeEach ( async ( ) => { p2pNodeList = await createNetwork ( { networkSize : 1 } ) ; [ P2PNode ] = p2pNodeList ; } ) ; afterEach ( async ( ) => { await destroyNetwork ( p2pNodeList ) ; } ) ; describe ( '#PeerServer' , ( ) => { describe ( 'Peer Banning' , ( ) => { const peerId = constructPeerId ( '127.0.0.1' , 6000 ) ; it ( `should Re-emit ${ EVENT_BAN_PEER } Event` , ( ) => { const bannedPeerId = [ ] ; P2PNode . on ( EVENT_BAN_PEER , id => { bannedPeerId . push ( id ) ; } ) ; ( P2PNode as any ) . _peerServer . emit ( EVENT_BAN_PEER , peerId ) ; expect ( bannedPeerId [ 0 ] ) . toBe ( peerId ) ; } ) ; it ( 'should call removePeer from PeerPool' , ( ) => { const bannedPeerId = [ ] ; P2PNode . on ( EVENT_BAN_PEER , id => { bannedPeerId . push ( id ) ; } ) ; jest . spyOn ( ( P2PNode as any ) . _peerPool , 'hasPeer' ) . mockReturnValue ( true ) ; jest . spyOn ( ( P2PNode as any ) . _peerPool , 'removePeer' ) ; ( P2PNode as any ) . _peerServer . emit ( EVENT_BAN_PEER , peerId ) ; expect ( ( P2PNode as any ) . _peerPool . hasPeer ) . toHaveBeenCalled ( ) ; expect ( ( P2PNode as any ) . _peerPool . removePeer ) . toHaveBeenCalled ( ) ; } ) ; it ( 'should add unbanTimer into PeerBook' , ( ) => { ( P2PNode as any ) . _peerServer . emit ( EVENT_BAN_PEER , peerId ) ; expect ( ( P2PNode as any ) . _peerBook . _unbanTimers ) . toHaveLength ( 1 ) ; } ) ; } ) ; } ) ; } ) ;