Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion mempool/mempool.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Comment thread
liamsi marked this conversation as resolved.
Resolved
}

//--------------------------------------------------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions node/mempool.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice find. It's obviously not just read here.


id, ok := ids.peerMap[peer]
if !ok {
Expand Down
107 changes: 38 additions & 69 deletions node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand All @@ -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,
Expand All @@ -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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the incomingTxCh unused now?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that is a great point, currently yes it is.

@tzdybal do you think we can remove that, or do we have other plans for it? What about GossipHandlers as well, do we still need those?

Perhaps we can address those in the future proposals that address #100 ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My comment was discarded somehow O_o

I think it's reasonable, to keep handler and validator separate (see #100 (comment)).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

regarding the initial question: incomingTxChis still unused now. @tzdybal are you advocating to keep it because keeping the "handler and validator separate" would reintroduce that channel?

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")
Expand All @@ -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
}
Expand Down Expand Up @@ -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{}):
Comment on lines +191 to +197

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Orthogonal to this PR but the errors should consistently be vars and wrapped using fmt.Errorf and %w to decorate them with the necessary info.

return false
default:
}
res := <-checkTxResCh
checkTxResp := res.GetCheckTx()

return checkTxResp.Code == abci.CodeTypeOK
}
}
26 changes: 19 additions & 7 deletions node/node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
15 changes: 14 additions & 1 deletion p2p/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions p2p/gossip.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 28 additions & 2 deletions rpcclient/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}

Comment on lines +123 to +128

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still think it's weird that the p2p gossiping is now triggered in rpcclient but yeah let's fix this in a followup PR.

// Wait for the tx to be included in a block or timeout.
select {
case msg := <-deliverTxSub.Out(): // The tx was included in a block.
Expand Down Expand Up @@ -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
}

Expand All @@ -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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

now the transaction is removed from the mempool if there's a gossiping error

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I see. This now means that the app said this Tx is valid but no-one will ever see it because gossiping failed (and we out self did not receive it via gossiping but locally)? Is that right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, that's correct

Comment on lines +194 to +204

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added some docs

return nil, fmt.Errorf("valid tra: %w", err)
}
}

return &ctypes.ResultBroadcastTx{
Code: r.Code,
Data: r.Data,
Expand Down
Loading