diff --git a/mempool/mempool.go b/mempool/mempool.go index d01958b539..e76115c4d6 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -14,7 +14,7 @@ import ( // apps can reset their transient state on Commit. type Mempool interface { // CheckTx executes a new transaction against the application to determine - // its validity and whether it should be added to the mempool. + // its validity. If valid, the tx is automatically added to the mempool. CheckTx(tx types.Tx, callback func(*abci.Response), txInfo TxInfo) error // ReapMaxBytesMaxGas reaps transactions from the mempool up to maxBytes @@ -76,6 +76,10 @@ type Mempool interface { // CloseWAL closes and discards the underlying WAL file. // Any further writes will not be relayed to disk. CloseWAL() + + // RemoveTxByKey removes a transaction from the mempool using a transasction's + // key (sha256 hash of the tx bytes) + RemoveTxByKey(txKey [TxKeySize]byte, removeFromCache bool) } //-------------------------------------------------------------------------------- diff --git a/node/mempool.go b/node/mempool.go index 27b6d02126..49eeb194b3 100644 --- a/node/mempool.go +++ b/node/mempool.go @@ -61,8 +61,8 @@ func (ids *mempoolIDs) Reclaim(peer peer.ID) { // GetForPeer returns an ID for the peer. ID is generated if required. func (ids *mempoolIDs) GetForPeer(peer peer.ID) uint16 { - ids.mtx.RLock() - defer ids.mtx.RUnlock() + ids.mtx.Lock() + defer ids.mtx.Unlock() id, ok := ids.peerMap[peer] if !ok { diff --git a/node/node.go b/node/node.go index e9b03c373d..c609547b73 100644 --- a/node/node.go +++ b/node/node.go @@ -2,12 +2,14 @@ package node import ( "context" + "errors" "fmt" "github.com/libp2p/go-libp2p-core/crypto" + "github.com/libp2p/go-libp2p-core/peer" + pubsub "github.com/libp2p/go-libp2p-pubsub" abci "github.com/tendermint/tendermint/abci/types" llcfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/libs/clist" "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/libs/service" corep2p "github.com/tendermint/tendermint/p2p" @@ -91,6 +93,10 @@ func NewNode(ctx context.Context, conf config.NodeConfig, nodeKey crypto.PrivKey } mp := mempool.NewCListMempool(llcfg.DefaultMempoolConfig(), proxyApp.Mempool(), 0) + mpIDs := newMempoolIDs() + + txValidator := newTxValidator(mp, mpIDs, logger) + client.SetTxValidator(txValidator) var aggregator *aggregator = nil if conf.Aggregator { @@ -109,7 +115,7 @@ func NewNode(ctx context.Context, conf config.NodeConfig, nodeKey crypto.PrivKey aggregator: aggregator, dalc: dalc, Mempool: mp, - mempoolIDs: newMempoolIDs(), + mempoolIDs: mpIDs, incomingTxCh: make(chan *p2p.GossipMessage), Store: store, ctx: ctx, @@ -119,68 +125,6 @@ func NewNode(ctx context.Context, conf config.NodeConfig, nodeKey crypto.PrivKey return node, nil } -func (n *Node) mempoolReadLoop(ctx context.Context) { - for { - select { - case tx := <-n.incomingTxCh: - n.Logger.Debug("tx received", "from", tx.From, "bytes", len(tx.Data)) - err := n.Mempool.CheckTx(tx.Data, func(resp *abci.Response) {}, mempool.TxInfo{ - SenderID: n.mempoolIDs.GetForPeer(tx.From), - SenderP2PID: corep2p.ID(tx.From), - }) - if err != nil { - n.Logger.Error("failed to execute CheckTx", "error", err) - } - case <-ctx.Done(): - return - } - } -} - -func (n *Node) mempoolPublishLoop(ctx context.Context) { - rawMempool := n.Mempool.(*mempool.CListMempool) - var next *clist.CElement - - for { - // wait for transactions - if next == nil { - select { - case <-rawMempool.TxsWaitChan(): - if next = rawMempool.TxsFront(); next != nil { - continue - } - case <-ctx.Done(): - return - } - } - - // send transactions - for { - memTx := next.Value.(*mempool.MempoolTx) - tx := memTx.Tx - - err := n.P2P.GossipTx(ctx, tx) - if err != nil { - n.Logger.Error("failed to gossip transaction", "error", err) - continue - } - - nx := next.Next() - if nx == nil { - break - } - next = nx - } - - select { - case <-next.NextWaitChan(): - next = next.Next() - case <-ctx.Done(): - return - } - } -} - // OnStart is a part of Service interface. func (n *Node) OnStart() error { n.Logger.Info("starting P2P client") @@ -192,14 +136,9 @@ func (n *Node) OnStart() error { if err != nil { return fmt.Errorf("error while starting data availability layer client: %w", err) } - go n.mempoolReadLoop(n.ctx) - go n.mempoolPublishLoop(n.ctx) if n.conf.Aggregator { go n.aggregator.aggregationLoop(n.ctx) } - n.P2P.SetTxHandler(func(tx *p2p.GossipMessage) { - n.incomingTxCh <- tx - }) return nil } @@ -235,3 +174,33 @@ func (n *Node) EventBus() *lltypes.EventBus { func (n *Node) ProxyApp() proxy.AppConns { return n.proxyApp } + +// newTxValidator creates a pubsub validator that uses the node's mempool to check the +// transaction. If the transaction is valid, then it is added to the mempool +func newTxValidator(pool mempool.Mempool, poolIDs *mempoolIDs, logger log.Logger) pubsub.Validator { + return func(ctx context.Context, i peer.ID, m *pubsub.Message) bool { + logger.Debug("transaction of size %d recieved", "bytes", len(m.Data)) + checkTxResCh := make(chan *abci.Response, 1) + err := pool.CheckTx(m.Data, func(resp *abci.Response) { + checkTxResCh <- resp + }, mempool.TxInfo{ + SenderID: poolIDs.GetForPeer(m.GetFrom()), + SenderP2PID: corep2p.ID(m.GetFrom()), + }) + switch { + case errors.Is(err, mempool.ErrTxInCache): + return true + case errors.Is(err, mempool.ErrMempoolIsFull{}): + return true + case errors.Is(err, mempool.ErrTxTooLarge{}): + return false + case errors.Is(err, mempool.ErrPreCheck{}): + return false + default: + } + res := <-checkTxResCh + checkTxResp := res.GetCheckTx() + + return checkTxResp.Code == abci.CodeTypeOK + } +} diff --git a/node/node_test.go b/node/node_test.go index 0c79adb835..fee42dd0b1 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -6,20 +6,20 @@ import ( "testing" "time" + "github.com/celestiaorg/optimint/mempool" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/libp2p/go-libp2p-core/crypto" + "github.com/libp2p/go-libp2p-core/peer" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" - "github.com/libp2p/go-libp2p-core/crypto" - "github.com/libp2p/go-libp2p-core/peer" "github.com/celestiaorg/optimint/config" "github.com/celestiaorg/optimint/mocks" - "github.com/celestiaorg/optimint/p2p" ) // simply check that node is starting and stopping without panicking @@ -62,11 +62,23 @@ func TestMempoolDirectly(t *testing.T) { pid, err := peer.IDFromPrivateKey(anotherKey) require.NoError(err) - node.incomingTxCh <- &p2p.GossipMessage{Data: []byte("tx1"), From: pid} - node.incomingTxCh <- &p2p.GossipMessage{Data: []byte("tx2"), From: pid} + err = node.Mempool.CheckTx([]byte("tx1"), func(r *abci.Response) {}, mempool.TxInfo{ + SenderID: node.mempoolIDs.GetForPeer(pid), + }) + require.NoError(err) + err = node.Mempool.CheckTx([]byte("tx2"), func(r *abci.Response) {}, mempool.TxInfo{ + SenderID: node.mempoolIDs.GetForPeer(pid), + }) + require.NoError(err) time.Sleep(100 * time.Millisecond) - node.incomingTxCh <- &p2p.GossipMessage{Data: []byte("tx3"), From: pid} - node.incomingTxCh <- &p2p.GossipMessage{Data: []byte("tx4"), From: pid} + err = node.Mempool.CheckTx([]byte("tx3"), func(r *abci.Response) {}, mempool.TxInfo{ + SenderID: node.mempoolIDs.GetForPeer(pid), + }) + require.NoError(err) + err = node.Mempool.CheckTx([]byte("tx4"), func(r *abci.Response) {}, mempool.TxInfo{ + SenderID: node.mempoolIDs.GetForPeer(pid), + }) + require.NoError(err) time.Sleep(1 * time.Second) diff --git a/p2p/client.go b/p2p/client.go index b9b9ca7426..e49e3aa433 100644 --- a/p2p/client.go +++ b/p2p/client.go @@ -48,7 +48,8 @@ type Client struct { dht *dht.IpfsDHT disc *discovery.RoutingDiscovery - txGossip *Gossip + txGossip *Gossip + txValidator pubsub.Validator // cancel is used to cancel context passed to libp2p functions // it's required because of discovery.Advertise call @@ -143,6 +144,10 @@ func (c *Client) SetTxHandler(handler GossipHandler) { c.txGossip.handler = handler } +func (c *Client) SetTxValidator(val pubsub.Validator) { + c.txValidator = val +} + func (c *Client) listen(ctx context.Context) (host.Host, error) { var err error maddr, err := multiaddr.NewMultiaddr(c.conf.ListenAddress) @@ -245,6 +250,14 @@ func (c *Client) setupGossiping(ctx context.Context) error { if err != nil { return err } + + if c.txValidator != nil { + err = ps.RegisterTopicValidator(c.getTxTopic(), c.txValidator) + if err != nil { + return err + } + } + c.txGossip, err = NewGossip(c.host, ps, c.getTxTopic(), c.logger) if err != nil { return err diff --git a/p2p/gossip.go b/p2p/gossip.go index cfb5bfb845..2107a4f574 100644 --- a/p2p/gossip.go +++ b/p2p/gossip.go @@ -38,6 +38,7 @@ func NewGossip(host host.Host, ps *pubsub.PubSub, topicStr string, logger log.Lo if err != nil { return nil, err } + subscription, err := topic.Subscribe() if err != nil { return nil, err diff --git a/rpcclient/local.go b/rpcclient/local.go index e37a03b45a..4c0475d513 100644 --- a/rpcclient/local.go +++ b/rpcclient/local.go @@ -101,7 +101,7 @@ func (l *Local) BroadcastTxCommit(ctx context.Context, tx types.Tx) (*ctypes.Res } }() - // Broadcast tx and wait for CheckTx result + // add to mempool and wait for CheckTx result checkTxResCh := make(chan *abci.Response, 1) err = l.node.Mempool.CheckTx(tx, func(res *abci.Response) { checkTxResCh <- res @@ -120,6 +120,12 @@ func (l *Local) BroadcastTxCommit(ctx context.Context, tx types.Tx) (*ctypes.Res }, nil } + // broadcast tx + err = l.node.P2P.GossipTx(ctx, tx) + if err != nil { + return nil, fmt.Errorf("tx added to local mempool but failure to broadcast: %w", err) + } + // Wait for the tx to be included in a block or timeout. select { case msg := <-deliverTxSub.Out(): // The tx was included in a block. @@ -160,10 +166,14 @@ func (l *Local) BroadcastTxCommit(ctx context.Context, tx types.Tx) (*ctypes.Res // More: https://docs.tendermint.com/master/rpc/#/Tx/broadcast_tx_async func (l *Local) BroadcastTxAsync(ctx context.Context, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { err := l.node.Mempool.CheckTx(tx, nil, mempool.TxInfo{}) - if err != nil { return nil, err } + // gossipTx optimistically + err = l.node.P2P.GossipTx(ctx, tx) + if err != nil { + return nil, fmt.Errorf("tx added to local mempool but failed to gossip: %w", err) + } return &ctypes.ResultBroadcastTx{Hash: tx.Hash()}, nil } @@ -180,6 +190,22 @@ func (l *Local) BroadcastTxSync(ctx context.Context, tx types.Tx) (*ctypes.Resul } res := <-resCh r := res.GetCheckTx() + + // gossip the transaction if it's in the mempool. + // Note: we have to do this here because, unlike the tendermint mempool reactor, there + // is no routine that gossips transactions after they enter the pool + if r.Code == abci.CodeTypeOK { + err = l.node.P2P.GossipTx(ctx, tx) + if err != nil { + // the transaction must be removed from the mempool if it cannot be gossiped. + // if this does not occur, then the user will not be able to try again using + // this node, as the CheckTx call above will return an error indicating that + // the tx is already in the mempool + l.node.Mempool.RemoveTxByKey(mempool.TxKey(tx), true) + return nil, fmt.Errorf("valid tra: %w", err) + } + } + return &ctypes.ResultBroadcastTx{ Code: r.Code, Data: r.Data, diff --git a/rpcclient/local_test.go b/rpcclient/local_test.go index 47daeced6c..335cea744b 100644 --- a/rpcclient/local_test.go +++ b/rpcclient/local_test.go @@ -74,6 +74,9 @@ func TestBroadcastTxAsync(t *testing.T) { mockApp, rpc := getRPC(t) mockApp.On("CheckTx", abci.RequestCheckTx{Tx: expectedTx}).Return(abci.ResponseCheckTx{}) + err := rpc.node.Start() + require.NoError(t, err) + res, err := rpc.BroadcastTxAsync(context.Background(), expectedTx) assert.NoError(err) assert.NotNil(res) @@ -83,6 +86,9 @@ func TestBroadcastTxAsync(t *testing.T) { assert.Empty(res.Codespace) assert.NotEmpty(res.Hash) mockApp.AssertExpectations(t) + + err = rpc.node.Stop() + require.NoError(t, err) } func TestBroadcastTxSync(t *testing.T) { @@ -102,6 +108,9 @@ func TestBroadcastTxSync(t *testing.T) { mockApp, rpc := getRPC(t) + err := rpc.node.Start() + require.NoError(t, err) + mockApp.On("CheckTx", abci.RequestCheckTx{Tx: expectedTx}).Return(expectedResponse) res, err := rpc.BroadcastTxSync(context.Background(), expectedTx) @@ -113,6 +122,9 @@ func TestBroadcastTxSync(t *testing.T) { assert.Equal(expectedResponse.Codespace, res.Codespace) assert.NotEmpty(res.Hash) mockApp.AssertExpectations(t) + + err = rpc.node.Stop() + require.NoError(t, err) } func TestBroadcastTxCommit(t *testing.T) { @@ -146,6 +158,10 @@ func TestBroadcastTxCommit(t *testing.T) { mockApp.BeginBlock(abci.RequestBeginBlock{}) mockApp.On("CheckTx", abci.RequestCheckTx{Tx: expectedTx}).Return(expectedCheckResp) + // in order to broadcast, the node must be started + err := rpc.node.Start() + require.NoError(err) + go func() { time.Sleep(mockTxProcessingTime) err := rpc.node.EventBus().PublishEventTx(types.EventDataTx{TxResult: abci.TxResult{ @@ -163,6 +179,9 @@ func TestBroadcastTxCommit(t *testing.T) { assert.Equal(expectedCheckResp, res.CheckTx) assert.Equal(expectedDeliverResp, res.DeliverTx) mockApp.AssertExpectations(t) + + err = rpc.node.Stop() + require.NoError(err) } func getRPC(t *testing.T) (*mocks.Application, *Local) { @@ -185,7 +204,9 @@ func TestMempool2Nodes(t *testing.T) { require := require.New(t) app := &mocks.Application{} - app.On("CheckTx", mock.Anything).Return(abci.ResponseCheckTx{}) + // app.On("CheckTx", mock.Anything).Return(abci.ResponseCheckTx{}) + app.On("CheckTx", abci.RequestCheckTx{Tx: []byte("bad")}).Return(abci.ResponseCheckTx{Code: 1}) + app.On("CheckTx", abci.RequestCheckTx{Tx: []byte("good")}).Return(abci.ResponseCheckTx{Code: 0}) key1, _, _ := crypto.GenerateEd25519Key(rand.Reader) key2, _, _ := crypto.GenerateEd25519Key(rand.Reader) @@ -225,11 +246,21 @@ func TestMempool2Nodes(t *testing.T) { local := NewLocal(node1) require.NotNil(local) - resp, err := local.BroadcastTxSync(ctx, []byte("foobar")) + // broadcast the bad Tx, this should not be propogated or added to the local mempool + resp, err := local.BroadcastTxSync(ctx, []byte("bad")) + assert.NoError(err) + assert.NotNil(resp) + // broadcast the good Tx, this should be propogated and added to the local mempool + resp, err = local.BroadcastTxSync(ctx, []byte("good")) assert.NoError(err) assert.NotNil(resp) + // broadcast the good Tx again in the same block, this should not be propogated and + // added to the local mempool + resp, err = local.BroadcastTxSync(ctx, []byte("good")) + assert.Error(err) + assert.Nil(resp) time.Sleep(1 * time.Second) - assert.Equal(node2.Mempool.TxsBytes(), int64(len("foobar"))) + assert.Equal(node2.Mempool.TxsBytes(), int64(len("good"))) }