From 697532bd682b62c95aeb749f02a61f590fe84d42 Mon Sep 17 00:00:00 2001 From: Dave Collins Date: Tue, 8 Oct 2013 00:04:51 -0500 Subject: [PATCH] Add handling for mempool command. --- mempool.go | 17 +++++++++++++++++ peer.go | 26 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/mempool.go b/mempool.go index c9d4a98c..93a0e131 100644 --- a/mempool.go +++ b/mempool.go @@ -771,6 +771,23 @@ func (mp *txMemPool) ProcessTransaction(tx *btcwire.MsgTx) error { return nil } +// TxShas returns a slice containing the hashes of all transactions in the +// memory pool. +func (mp *txMemPool) TxShas() []*btcwire.ShaHash { + mp.lock.Lock() + defer mp.lock.Unlock() + + hashes := make([]*btcwire.ShaHash, len(mp.pool)) + i := 0 + for hash := range mp.pool { + hashCopy := hash + hashes[i] = &hashCopy + i++ + } + + return hashes +} + // newTxMemPool returns a new memory pool for validating and storing standalone // transactions until they are mined into a block. func newTxMemPool(server *server) *txMemPool { diff --git a/peer.go b/peer.go index a5997072..38163cc4 100644 --- a/peer.go +++ b/peer.go @@ -400,6 +400,29 @@ func (p *peer) PushGetBlocksMsg(locator btcchain.BlockLocator, stopHash *btcwire return nil } +// handleMemPoolMsg is invoked when a peer receives a mempool bitcoin message. +// It creates and sends an inventory message with the contents of the memory +// pool up to the maximum inventory allowed per message. +func (p *peer) handleMemPoolMsg(msg *btcwire.MsgMemPool) { + // Generate inventory message with the available transactions in the + // transaction memory pool. Limit it to the max allowed inventory + // per message. + invMsg := btcwire.NewMsgInv() + hashes := p.server.txMemPool.TxShas() + for i, hash := range hashes { + iv := btcwire.NewInvVect(btcwire.InvVect_Tx, hash) + invMsg.AddInvVect(iv) + if i+1 >= btcwire.MaxInvPerMsg { + break + } + } + + // Send the inventory message if there is anything to send. + if len(invMsg.InvList) > 0 { + p.QueueMessage(invMsg) + } +} + // handleTxMsg is invoked when a peer receives a tx bitcoin message. It blocks // until the bitcoin transaction has been fully processed. Unlock the block // handler this does not serialize all transactions through a single thread @@ -912,6 +935,9 @@ out: case *btcwire.MsgAlert: p.server.BroadcastMessage(msg, p) + case *btcwire.MsgMemPool: + p.handleMemPoolMsg(msg) + case *btcwire.MsgTx: p.handleTxMsg(msg)