From 257da78c157c09da04ca951cc002aa9b82ea9a5a Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Wed, 8 Sep 2021 20:27:58 -0500 Subject: [PATCH 01/15] add a validator to pubsub and remove the routine that gossips mempool messages --- node/node.go | 65 +++++++++++++++------------------------------------ p2p/client.go | 13 +++++++++++ 2 files changed, 32 insertions(+), 46 deletions(-) diff --git a/node/node.go b/node/node.go index 27f92a7426..1a1e387dff 100644 --- a/node/node.go +++ b/node/node.go @@ -6,13 +6,14 @@ import ( abci "github.com/lazyledger/lazyledger-core/abci/types" llcfg "github.com/lazyledger/lazyledger-core/config" - "github.com/lazyledger/lazyledger-core/libs/clist" "github.com/lazyledger/lazyledger-core/libs/log" "github.com/lazyledger/lazyledger-core/libs/service" corep2p "github.com/lazyledger/lazyledger-core/p2p" "github.com/lazyledger/lazyledger-core/proxy" lltypes "github.com/lazyledger/lazyledger-core/types" "github.com/libp2p/go-libp2p-core/crypto" + "github.com/libp2p/go-libp2p-core/peer" + pubsub "github.com/libp2p/go-libp2p-pubsub" "go.uber.org/multierr" "github.com/lazyledger/optimint/config" @@ -73,6 +74,7 @@ func NewNode(ctx context.Context, conf config.NodeConfig, nodeKey crypto.PrivKey if err != nil { return nil, err } + client.SetTxValidator(newProxyAppValidator(proxyApp)) // TODO(tzdybal): change after implementing https://github.com/celestiaorg/optimint/issues/67 baseKV := store.NewInMemoryKVStore() @@ -138,50 +140,6 @@ func (n *Node) mempoolReadLoop(ctx context.Context) { } } -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") @@ -194,7 +152,6 @@ func (n *Node) OnStart() error { 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) } @@ -236,3 +193,19 @@ func (n *Node) EventBus() *lltypes.EventBus { func (n *Node) ProxyApp() proxy.AppConns { return n.proxyApp } + +func newProxyAppValidator(app proxy.AppConns) pubsub.Validator { + return func(c context.Context, i peer.ID, m *pubsub.Message) bool { + req := abci.RequestCheckTx{ + Tx: m.Data, + Type: abci.CheckTxType_New, + } + resp, err := app.Mempool().CheckTxSync(c, req) + if err != nil || resp.Code != abci.CodeTypeOK { + // todo(evan): check if we should log this + return false + } + + return true + } +} diff --git a/p2p/client.go b/p2p/client.go index 9aebc183bc..39fc6ff008 100644 --- a/p2p/client.go +++ b/p2p/client.go @@ -50,6 +50,8 @@ type Client struct { txGossip *Gossip + validator pubsub.Validator + // cancel is used to cancel context passed to libp2p functions // it's required because of discovery.Advertise call cancel context.CancelFunc @@ -143,6 +145,11 @@ func (c *Client) SetTxHandler(handler GossipHandler) { c.txGossip.handler = handler } +// SetTxValidator sets the validator function that will be called before gossiping transactions +func (c *Client) SetTxValidator(val pubsub.Validator) { + c.validator = val +} + func (c *Client) listen(ctx context.Context) (host.Host, error) { var err error maddr, err := multiaddr.NewMultiaddr(c.conf.ListenAddress) @@ -245,6 +252,12 @@ func (c *Client) setupGossiping(ctx context.Context) error { if err != nil { return err } + if c.validator != nil { + err = ps.RegisterTopicValidator(c.getTxTopic(), c.validator) + if err != nil { + return err + } + } c.txGossip, err = NewGossip(c.host, ps, c.getTxTopic(), c.logger) if err != nil { return err From cae6a770bcfcf813c09514ebffd66cfcc5c784b9 Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Fri, 10 Sep 2021 15:11:40 -0500 Subject: [PATCH 02/15] broadcast new transactions submitted to the node --- p2p/gossip.go | 1 + rpcclient/local.go | 21 +++++++++++++++++++-- rpcclient/local_test.go | 13 +++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/p2p/gossip.go b/p2p/gossip.go index 8963e89648..ab1808120d 100644 --- a/p2p/gossip.go +++ b/p2p/gossip.go @@ -2,6 +2,7 @@ package p2p import ( "context" + "github.com/libp2p/go-libp2p-core/host" "github.com/libp2p/go-libp2p-core/peer" pubsub "github.com/libp2p/go-libp2p-pubsub" diff --git a/rpcclient/local.go b/rpcclient/local.go index 80ab2d4920..be67e9bd59 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{Context: ctx}) - if err != nil { return nil, err } + // broadcast tx + 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,13 @@ func (l *Local) BroadcastTxSync(ctx context.Context, tx types.Tx) (*ctypes.Resul } res := <-resCh r := res.GetCheckTx() + + // broadcast tx + 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{ Code: r.Code, Data: r.Data, diff --git a/rpcclient/local_test.go b/rpcclient/local_test.go index 972bdecb3e..24e4ee25a9 100644 --- a/rpcclient/local_test.go +++ b/rpcclient/local_test.go @@ -74,6 +74,10 @@ 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) + defer rpc.node.Stop() + res, err := rpc.BroadcastTxAsync(context.Background(), expectedTx) assert.NoError(err) assert.NotNil(res) @@ -102,6 +106,10 @@ func TestBroadcastTxSync(t *testing.T) { mockApp, rpc := getRPC(t) + err := rpc.node.Start() + require.NoError(t, err) + defer rpc.node.Stop() + mockApp.On("CheckTx", abci.RequestCheckTx{Tx: expectedTx}).Return(expectedResponse) res, err := rpc.BroadcastTxSync(context.Background(), expectedTx) @@ -146,6 +154,11 @@ 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) + defer rpc.node.Stop() + go func() { time.Sleep(mockTxProcessingTime) err := rpc.node.EventBus().PublishEventTx(types.EventDataTx{TxResult: abci.TxResult{ From 46f82deb0f06c3117fc2c98de6de39b6fbf467b8 Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Fri, 10 Sep 2021 15:19:15 -0500 Subject: [PATCH 03/15] linter has no chill --- rpcclient/local_test.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/rpcclient/local_test.go b/rpcclient/local_test.go index 24e4ee25a9..f931c097ad 100644 --- a/rpcclient/local_test.go +++ b/rpcclient/local_test.go @@ -76,7 +76,6 @@ func TestBroadcastTxAsync(t *testing.T) { err := rpc.node.Start() require.NoError(t, err) - defer rpc.node.Stop() res, err := rpc.BroadcastTxAsync(context.Background(), expectedTx) assert.NoError(err) @@ -87,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) { @@ -108,7 +110,6 @@ func TestBroadcastTxSync(t *testing.T) { err := rpc.node.Start() require.NoError(t, err) - defer rpc.node.Stop() mockApp.On("CheckTx", abci.RequestCheckTx{Tx: expectedTx}).Return(expectedResponse) @@ -121,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) { @@ -157,7 +161,6 @@ func TestBroadcastTxCommit(t *testing.T) { // in order to broadcast, the node must be started err := rpc.node.Start() require.NoError(err) - defer rpc.node.Stop() go func() { time.Sleep(mockTxProcessingTime) @@ -176,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) { From d88c5fa8fc18fceba0440f93fb1e1b1d2e777bae Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Mon, 13 Sep 2021 14:35:36 -0500 Subject: [PATCH 04/15] refactor tx validator to use mempool's CheckTx method MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ismail Khoffi Co-authored-by: Tomasz Zdybał --- mempool/clist_mempool.go | 2 +- mempool/clist_mempool_test.go | 2 +- mempool/errors.go | 11 +++--- mempool/mempool.go | 2 +- node/node.go | 68 +++++++++++++++++------------------ node/node_test.go | 22 +++++++++--- p2p/client.go | 14 ++++---- p2p/gossip.go | 1 + 8 files changed, 67 insertions(+), 55 deletions(-) diff --git a/mempool/clist_mempool.go b/mempool/clist_mempool.go index 1b6d92af44..3005f04b72 100644 --- a/mempool/clist_mempool.go +++ b/mempool/clist_mempool.go @@ -283,7 +283,7 @@ func (mem *CListMempool) CheckTx(tx types.Tx, cb func(*abci.Response), txInfo Tx // but they can spam the same tx with little cost to them atm. } - return ErrTxInCache + return ErrTxInCache{} } ctx := context.Background() diff --git a/mempool/clist_mempool_test.go b/mempool/clist_mempool_test.go index c870a952fd..5ebe21dd95 100644 --- a/mempool/clist_mempool_test.go +++ b/mempool/clist_mempool_test.go @@ -189,7 +189,7 @@ func TestMempoolUpdate(t *testing.T) { require.NoError(t, err) err = mempool.CheckTx([]byte{0x01}, nil, TxInfo{}) if assert.Error(t, err) { - assert.Equal(t, ErrTxInCache, err) + assert.Equal(t, ErrTxInCache{}, err) } } diff --git a/mempool/errors.go b/mempool/errors.go index e33e14ca31..395ed07e7a 100644 --- a/mempool/errors.go +++ b/mempool/errors.go @@ -1,14 +1,15 @@ package mempool import ( - "errors" "fmt" ) -var ( - // ErrTxInCache is returned to the client if we saw tx earlier - ErrTxInCache = errors.New("tx already exists in cache") -) +// ErrTxInCache is returned to the client if we saw tx earlier +type ErrTxInCache struct{} + +func (e ErrTxInCache) Error() string { + return "tx already exists in cache" +} // ErrTxTooLarge means the tx is too big to be sent in a message to other peers type ErrTxTooLarge struct { diff --git a/mempool/mempool.go b/mempool/mempool.go index 041cdeed45..b070a4523e 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -19,7 +19,7 @@ const UnknownPeerID uint16 = 0 // 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 diff --git a/node/node.go b/node/node.go index 1a1e387dff..fcfdc05c34 100644 --- a/node/node.go +++ b/node/node.go @@ -74,7 +74,6 @@ func NewNode(ctx context.Context, conf config.NodeConfig, nodeKey crypto.PrivKey if err != nil { return nil, err } - client.SetTxValidator(newProxyAppValidator(proxyApp)) // TODO(tzdybal): change after implementing https://github.com/celestiaorg/optimint/issues/67 baseKV := store.NewInMemoryKVStore() @@ -93,6 +92,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 { @@ -111,7 +114,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, @@ -121,25 +124,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), - Context: ctx, - }) - if err != nil { - n.Logger.Error("failed to execute CheckTx", "error", err) - } - case <-ctx.Done(): - return - } - } -} - // OnStart is a part of Service interface. func (n *Node) OnStart() error { n.Logger.Info("starting P2P client") @@ -151,13 +135,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) if n.conf.Aggregator { go n.aggregator.aggregationLoop(n.ctx) } - n.P2P.SetTxHandler(func(tx *p2p.GossipMessage) { - n.incomingTxCh <- tx - }) return nil } @@ -194,18 +174,36 @@ func (n *Node) ProxyApp() proxy.AppConns { return n.proxyApp } -func newProxyAppValidator(app proxy.AppConns) pubsub.Validator { - return func(c context.Context, i peer.ID, m *pubsub.Message) bool { - req := abci.RequestCheckTx{ - Tx: m.Data, - Type: abci.CheckTxType_New, - } - resp, err := app.Mempool().CheckTxSync(c, req) - if err != nil || resp.Code != abci.CodeTypeOK { - // todo(evan): check if we should log this +// 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()), + Context: ctx, + }) + switch err.(type) { + case nil: + case mempool.ErrTxInCache: + return true + case mempool.ErrMempoolIsFull: + return true + case mempool.ErrTxTooLarge: return false + case mempool.ErrPreCheck: + return false + } + res := <-checkTxResCh + checkTxResp := res.GetCheckTx() + if checkTxResp.Code == abci.CodeTypeOK { + return true } - return true + return false } } diff --git a/node/node_test.go b/node/node_test.go index 9f460c58b1..125b8f306a 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -18,8 +18,8 @@ import ( "github.com/libp2p/go-libp2p-core/peer" "github.com/lazyledger/optimint/config" + "github.com/lazyledger/optimint/mempool" "github.com/lazyledger/optimint/mocks" - "github.com/lazyledger/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 39fc6ff008..582b45e109 100644 --- a/p2p/client.go +++ b/p2p/client.go @@ -48,9 +48,8 @@ type Client struct { dht *dht.IpfsDHT disc *discovery.RoutingDiscovery - txGossip *Gossip - - validator pubsub.Validator + txGossip *Gossip + txValidator pubsub.Validator // cancel is used to cancel context passed to libp2p functions // it's required because of discovery.Advertise call @@ -145,9 +144,8 @@ func (c *Client) SetTxHandler(handler GossipHandler) { c.txGossip.handler = handler } -// SetTxValidator sets the validator function that will be called before gossiping transactions func (c *Client) SetTxValidator(val pubsub.Validator) { - c.validator = val + c.txValidator = val } func (c *Client) listen(ctx context.Context) (host.Host, error) { @@ -252,12 +250,14 @@ func (c *Client) setupGossiping(ctx context.Context) error { if err != nil { return err } - if c.validator != nil { - err = ps.RegisterTopicValidator(c.getTxTopic(), c.validator) + + 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 ab1808120d..f2621e55b9 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 From 533add6769ea3482266382b0ca52b39f7c9753d7 Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Mon, 13 Sep 2021 14:58:31 -0500 Subject: [PATCH 05/15] only gossip valid transactions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Tomasz Zdybał --- rpcclient/local.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/rpcclient/local.go b/rpcclient/local.go index be67e9bd59..4bc215bbf5 100644 --- a/rpcclient/local.go +++ b/rpcclient/local.go @@ -169,7 +169,7 @@ func (l *Local) BroadcastTxAsync(ctx context.Context, tx types.Tx) (*ctypes.Resu if err != nil { return nil, err } - // broadcast tx + // 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) @@ -191,10 +191,11 @@ func (l *Local) BroadcastTxSync(ctx context.Context, tx types.Tx) (*ctypes.Resul res := <-resCh r := res.GetCheckTx() - // broadcast tx - 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) + if r.Code == abci.CodeTypeOK { + 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{ From 6dc8e734e5a9ee65a2c3986e5b556594077c5593 Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Mon, 13 Sep 2021 15:03:28 -0500 Subject: [PATCH 06/15] thanks linter --- node/node.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/node/node.go b/node/node.go index fcfdc05c34..a4720fd757 100644 --- a/node/node.go +++ b/node/node.go @@ -200,10 +200,7 @@ func newTxValidator(pool mempool.Mempool, poolIDs *mempoolIDs, logger log.Logger } res := <-checkTxResCh checkTxResp := res.GetCheckTx() - if checkTxResp.Code == abci.CodeTypeOK { - return true - } - return false + return checkTxResp.Code == abci.CodeTypeOK } } From 4097620751907e1bf0f1a4b5839d34b7ffcd5680 Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Mon, 13 Sep 2021 15:53:19 -0500 Subject: [PATCH 07/15] update the mempool interface to accomodate removing txs --- mempool/mempool.go | 2 ++ node/node.go | 2 +- rpcclient/local.go | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/mempool/mempool.go b/mempool/mempool.go index b070a4523e..553b90d64a 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -81,6 +81,8 @@ type Mempool interface { // CloseWAL closes and discards the underlying WAL file. // Any further writes will not be relayed to disk. CloseWAL() + + RemoveTxByKey(txKey [TxKeySize]byte, removeFromCache bool) } //-------------------------------------------------------------------------------- diff --git a/node/node.go b/node/node.go index a4720fd757..32f0a6aeaa 100644 --- a/node/node.go +++ b/node/node.go @@ -188,7 +188,6 @@ func newTxValidator(pool mempool.Mempool, poolIDs *mempoolIDs, logger log.Logger Context: ctx, }) switch err.(type) { - case nil: case mempool.ErrTxInCache: return true case mempool.ErrMempoolIsFull: @@ -197,6 +196,7 @@ func newTxValidator(pool mempool.Mempool, poolIDs *mempoolIDs, logger log.Logger return false case mempool.ErrPreCheck: return false + default: } res := <-checkTxResCh checkTxResp := res.GetCheckTx() diff --git a/rpcclient/local.go b/rpcclient/local.go index 4bc215bbf5..10d2c06fca 100644 --- a/rpcclient/local.go +++ b/rpcclient/local.go @@ -194,6 +194,7 @@ func (l *Local) BroadcastTxSync(ctx context.Context, tx types.Tx) (*ctypes.Resul if r.Code == abci.CodeTypeOK { err = l.node.P2P.GossipTx(ctx, tx) if err != nil { + l.node.Mempool.RemoveTxByKey(mempool.TxKey(tx), true) return nil, fmt.Errorf("tx added to local mempool but failed to gossip: %w", err) } } From ac95d91703b3673093160880aab643ff51e363b1 Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Mon, 13 Sep 2021 16:27:39 -0500 Subject: [PATCH 08/15] add missed comment --- mempool/mempool.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mempool/mempool.go b/mempool/mempool.go index 553b90d64a..169ca3e01d 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -82,6 +82,8 @@ type Mempool interface { // 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) } From fd1a4228391c3e57ef1e15f11338a9daacbcaef8 Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Mon, 13 Sep 2021 16:36:28 -0500 Subject: [PATCH 09/15] fix data race --- node/mempool.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/node/mempool.go b/node/mempool.go index eb77ed14e8..850c81f7d4 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 { From 0b62bb48b43ad146145794dffd90f37fc4350283 Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Mon, 13 Sep 2021 16:43:16 -0500 Subject: [PATCH 10/15] use errors.Is and revert changing ErrTxInCache to it's own type Co-authored-by: Ismail Khoffi --- mempool/clist_mempool.go | 2 +- mempool/clist_mempool_test.go | 2 +- mempool/errors.go | 11 +++++------ node/node.go | 11 ++++++----- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/mempool/clist_mempool.go b/mempool/clist_mempool.go index 3005f04b72..1b6d92af44 100644 --- a/mempool/clist_mempool.go +++ b/mempool/clist_mempool.go @@ -283,7 +283,7 @@ func (mem *CListMempool) CheckTx(tx types.Tx, cb func(*abci.Response), txInfo Tx // but they can spam the same tx with little cost to them atm. } - return ErrTxInCache{} + return ErrTxInCache } ctx := context.Background() diff --git a/mempool/clist_mempool_test.go b/mempool/clist_mempool_test.go index 5ebe21dd95..c870a952fd 100644 --- a/mempool/clist_mempool_test.go +++ b/mempool/clist_mempool_test.go @@ -189,7 +189,7 @@ func TestMempoolUpdate(t *testing.T) { require.NoError(t, err) err = mempool.CheckTx([]byte{0x01}, nil, TxInfo{}) if assert.Error(t, err) { - assert.Equal(t, ErrTxInCache{}, err) + assert.Equal(t, ErrTxInCache, err) } } diff --git a/mempool/errors.go b/mempool/errors.go index 395ed07e7a..e33e14ca31 100644 --- a/mempool/errors.go +++ b/mempool/errors.go @@ -1,15 +1,14 @@ package mempool import ( + "errors" "fmt" ) -// ErrTxInCache is returned to the client if we saw tx earlier -type ErrTxInCache struct{} - -func (e ErrTxInCache) Error() string { - return "tx already exists in cache" -} +var ( + // ErrTxInCache is returned to the client if we saw tx earlier + ErrTxInCache = errors.New("tx already exists in cache") +) // ErrTxTooLarge means the tx is too big to be sent in a message to other peers type ErrTxTooLarge struct { diff --git a/node/node.go b/node/node.go index 32f0a6aeaa..9b7421bc0a 100644 --- a/node/node.go +++ b/node/node.go @@ -2,6 +2,7 @@ package node import ( "context" + "errors" "fmt" abci "github.com/lazyledger/lazyledger-core/abci/types" @@ -187,14 +188,14 @@ func newTxValidator(pool mempool.Mempool, poolIDs *mempoolIDs, logger log.Logger SenderP2PID: corep2p.ID(m.GetFrom()), Context: ctx, }) - switch err.(type) { - case mempool.ErrTxInCache: + switch { + case errors.Is(err, mempool.ErrTxInCache): return true - case mempool.ErrMempoolIsFull: + case errors.Is(err, mempool.ErrMempoolIsFull{}): return true - case mempool.ErrTxTooLarge: + case errors.Is(err, mempool.ErrTxTooLarge{}): return false - case mempool.ErrPreCheck: + case errors.Is(err, mempool.ErrPreCheck{}): return false default: } From 5ca67414eabd728c2079af3bbc5f667e86f44de9 Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Tue, 14 Sep 2021 17:38:55 -0500 Subject: [PATCH 11/15] include a bad transaction in the mempool test --- rpcclient/local_test.go | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/rpcclient/local_test.go b/rpcclient/local_test.go index f931c097ad..0083e56ae1 100644 --- a/rpcclient/local_test.go +++ b/rpcclient/local_test.go @@ -204,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) @@ -244,11 +246,15 @@ 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 bad Tx, this should not be propogated or added to the local mempool + resp, err = local.BroadcastTxSync(ctx, []byte("good")) assert.NoError(err) assert.NotNil(resp) - time.Sleep(1 * time.Second) - assert.Equal(node2.Mempool.TxsBytes(), int64(len("foobar"))) + assert.Equal(node2.Mempool.TxsBytes(), int64(len("good"))) } From 696a3c03a76eab32f09e3ed080062ae69ffefb05 Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Tue, 14 Sep 2021 17:46:38 -0500 Subject: [PATCH 12/15] better document the reasoning behind gossiping in the local rpcclient package --- rpcclient/local.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/rpcclient/local.go b/rpcclient/local.go index 10d2c06fca..f1552c789f 100644 --- a/rpcclient/local.go +++ b/rpcclient/local.go @@ -191,11 +191,18 @@ 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("tx added to local mempool but failed to gossip: %w", err) + return nil, fmt.Errorf("valid tra: %w", err) } } From 609e8c12a341e655c850816a4a71ce0dae868b7d Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Tue, 14 Sep 2021 17:56:22 -0500 Subject: [PATCH 13/15] correct copy past docs --- rpcclient/local_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rpcclient/local_test.go b/rpcclient/local_test.go index 0083e56ae1..5409bbb3fb 100644 --- a/rpcclient/local_test.go +++ b/rpcclient/local_test.go @@ -250,7 +250,7 @@ func TestMempool2Nodes(t *testing.T) { resp, err := local.BroadcastTxSync(ctx, []byte("bad")) assert.NoError(err) assert.NotNil(resp) - // broadcast the bad Tx, this should not be propogated or added to the local mempool + // broadcast the bad Tx, this should be propogated and added to the local mempool resp, err = local.BroadcastTxSync(ctx, []byte("good")) assert.NoError(err) assert.NotNil(resp) From 80fb98baa2cbb1465056fa4c48b17802a6ef10b8 Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Fri, 17 Sep 2021 09:08:18 -0500 Subject: [PATCH 14/15] add extra test to ensure that the same tx cannot be broadcast twice --- rpcclient/local_test.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/rpcclient/local_test.go b/rpcclient/local_test.go index 5409bbb3fb..a1fe62ee04 100644 --- a/rpcclient/local_test.go +++ b/rpcclient/local_test.go @@ -250,10 +250,16 @@ func TestMempool2Nodes(t *testing.T) { resp, err := local.BroadcastTxSync(ctx, []byte("bad")) assert.NoError(err) assert.NotNil(resp) - // broadcast the bad Tx, this should be propogated and added to the local mempool + // 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("good"))) From 14c27f122307dc261832343d2a64c6e5468db52e Mon Sep 17 00:00:00 2001 From: evan-forbes Date: Fri, 17 Sep 2021 09:42:14 -0500 Subject: [PATCH 15/15] go mod tidy and fix merge conflicts --- go.mod | 1 - go.sum | 3 --- node/node.go | 1 - node/node_test.go | 2 +- rpcclient/local.go | 2 +- 5 files changed, 2 insertions(+), 7 deletions(-) diff --git a/go.mod b/go.mod index 2b7885fdf5..9024d87186 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,6 @@ require ( github.com/celestiaorg/celestia-app v0.0.0-00010101000000-000000000000 github.com/cosmos/cosmos-sdk v0.40.0-rc5 github.com/dgraph-io/badger/v3 v3.2011.1 - github.com/fortytw2/leaktest v1.3.0 github.com/go-kit/kit v0.11.0 github.com/gogo/protobuf v1.3.2 github.com/golang/protobuf v1.5.2 diff --git a/go.sum b/go.sum index d4bd5156ac..e933a363ae 100644 --- a/go.sum +++ b/go.sum @@ -287,7 +287,6 @@ github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2 github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.10.0 h1:dXFJfIHVvUcpSgDOV+Ne6t7jXri8Tfv2uOLHUZ2XNuo= github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= github.com/go-kit/kit v0.11.0 h1:IGmIEl7aHTYh6E2HlT+ptILBotjo4xl8PMDl852etiI= github.com/go-kit/kit v0.11.0/go.mod h1:73/6Ixaufkvb5Osvkls8C79vuQ49Ba1rUEUYNSf+FUw= @@ -992,7 +991,6 @@ github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144T github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.8.0/go.mod h1:D6yutnOGMveHEPV7VQOuvI/gXY61bv+9bAOTRnLElKs= -github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5dSQ= github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pelletier/go-toml v1.9.4 h1:tjENF6MfZAg8e4ZmZTeWaWiT2vXtsoO6+iuOjFhECwM= github.com/pelletier/go-toml v1.9.4/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= @@ -1241,7 +1239,6 @@ go.uber.org/goleak v1.0.0/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= -go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.7.0 h1:zaiO/rmgFjbmCXdSYJWQcdvOCsthmdaHfr3Gm2Kx4Ec= go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= diff --git a/node/node.go b/node/node.go index d45456f64b..c609547b73 100644 --- a/node/node.go +++ b/node/node.go @@ -186,7 +186,6 @@ func newTxValidator(pool mempool.Mempool, poolIDs *mempoolIDs, logger log.Logger }, mempool.TxInfo{ SenderID: poolIDs.GetForPeer(m.GetFrom()), SenderP2PID: corep2p.ID(m.GetFrom()), - Context: ctx, }) switch { case errors.Is(err, mempool.ErrTxInCache): diff --git a/node/node_test.go b/node/node_test.go index 15c8fa0181..fee42dd0b1 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/lazyledger/optimint/mempool" + "github.com/celestiaorg/optimint/mempool" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/rpcclient/local.go b/rpcclient/local.go index 65bff6a223..4c0475d513 100644 --- a/rpcclient/local.go +++ b/rpcclient/local.go @@ -165,7 +165,7 @@ func (l *Local) BroadcastTxCommit(ctx context.Context, tx types.Tx) (*ctypes.Res // CheckTx nor DeliverTx results. // 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{Context: ctx}) + err := l.node.Mempool.CheckTx(tx, nil, mempool.TxInfo{}) if err != nil { return nil, err }