Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(zeromq): add block info publisher #1666

Merged
merged 8 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from 6 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
3 changes: 2 additions & 1 deletion node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,6 @@ func (n *Node) Stop() {
// Wait for network to stop
time.Sleep(1 * time.Second)

close(n.eventCh)
n.consMgr.Stop()
n.sync.Stop()
n.state.Close()
Expand All @@ -176,6 +175,8 @@ func (n *Node) Stop() {
n.http.StopServer()
n.jsonrpc.StopServer()
n.zeromq.Close()

close(n.eventCh)
}

// these methods are using by GUI.
Expand Down
5 changes: 4 additions & 1 deletion state/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -752,5 +752,8 @@
return
}

st.eventCh <- msg
select {
b00f marked this conversation as resolved.
Show resolved Hide resolved
case st.eventCh <- msg:
default:

Check warning on line 757 in state/state.go

View check run for this annotation

Codecov / codecov/patch

state/state.go#L755-L757

Added lines #L755 - L757 were not covered by tests
}
}
23 changes: 20 additions & 3 deletions www/zmq/block_info_publisher.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,30 @@
return &blockInfoPub{
basePub: basePub{
topic: BlockInfo,
seqNo: 0,
zmqSocket: socket,
logger: logger,
},
}
}

func (*blockInfoPub) onNewBlock(_ *block.Block) {
// TODO implement me
panic("implement me")
func (b *blockInfoPub) onNewBlock(blk *block.Block) {
rawMsg := b.makeTopicMsg(
blk.Header().ProposerAddress(),
blk.Header().UnixTime(),
uint16(len(blk.Transactions())),
blk.Height(),
)

message := zmq4.NewMsg(rawMsg)

if err := b.zmqSocket.Send(message); err != nil {
b.logger.Error("zmq publish message error", "err", err, "publisher", b.TopicName())
}

Check warning on line 36 in www/zmq/block_info_publisher.go

View check run for this annotation

Codecov / codecov/patch

www/zmq/block_info_publisher.go#L35-L36

Added lines #L35 - L36 were not covered by tests

b.logger.Debug("zmq published message success",
"publisher", b.TopicName(),
"block_height", blk.Height())

b.seqNo++
}
67 changes: 67 additions & 0 deletions www/zmq/block_info_publisher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package zmq

import (
"context"
"encoding/binary"
"fmt"
"testing"
"time"

"github.com/go-zeromq/zmq4"
"github.com/stretchr/testify/require"
)

func TestBlockInfoPublisher(t *testing.T) {
td := setup(t)
defer td.cleanup()
b00f marked this conversation as resolved.
Show resolved Hide resolved

port := td.FindFreePort()
addr := fmt.Sprintf("tcp://localhost:%d", port)

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

conf := DefaultConfig()
conf.ZmqPubBlockInfo = addr

err := td.initServer(ctx, conf)
require.NoError(t, err)

sub := zmq4.NewSub(ctx)
defer func() {
_ = sub.Close()
}()

err = sub.Dial(addr)
require.NoError(t, err)

err = sub.SetOption(zmq4.OptionSubscribe, string(BlockInfo.Bytes()))
require.NoError(t, err)

blk, _ := td.TestSuite.GenerateTestBlock(td.RandHeight())

td.eventCh <- blk

received, err := sub.Recv()
require.NoError(t, err)

require.NotNil(t, received.Frames)
require.GreaterOrEqual(t, len(received.Frames), 1)

msg := received.Frames[0]
require.Len(t, msg, 37)

topic := msg[:2]
proposerBytes := msg[2:23]
timestamp := binary.BigEndian.Uint32(msg[23:27])
txCount := binary.BigEndian.Uint16(msg[27:29])
height := binary.BigEndian.Uint32(msg[29:33])
seqNo := binary.BigEndian.Uint32(msg[33:])

require.Equal(t, BlockInfo.Bytes(), topic)
require.Equal(t, blk.Header().ProposerAddress().Bytes(), proposerBytes)
require.Equal(t, blk.Header().UnixTime(), timestamp)
require.Equal(t, uint16(len(blk.Transactions())), txCount)
require.Equal(t, blk.Height(), height)
require.Equal(t, uint32(0), seqNo)
}
2 changes: 1 addition & 1 deletion www/zmq/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
func validateTopicSocket(socket string) error {
addr, err := url.Parse(socket)
if err != nil {
return errors.New("failed to parse ZmqPub value: " + err.Error())
return errors.New("failed to parse URL: " + err.Error())

Check warning on line 68 in www/zmq/config.go

View check run for this annotation

Codecov / codecov/patch

www/zmq/config.go#L68

Added line #L68 was not covered by tests
}

if addr.Scheme != "tcp" {
Expand Down
2 changes: 1 addition & 1 deletion www/zmq/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func TestBasicCheck(t *testing.T) {
{
name: "Empty host",
config: &Config{
ZmqPubBlockInfo: "tcp://:28332",
ZmqPubTxInfo: "tcp://:28332",
},
expectErr: true,
},
Expand Down
37 changes: 37 additions & 0 deletions www/zmq/publisher.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package zmq

import (
"encoding/binary"

"github.com/go-zeromq/zmq4"
"github.com/pactus-project/pactus/crypto"
"github.com/pactus-project/pactus/types/block"
"github.com/pactus-project/pactus/util/logger"
)
Expand All @@ -15,6 +18,7 @@

type basePub struct {
topic Topic
seqNo uint32
zmqSocket zmq4.Socket
logger *logger.SubLogger
}
Expand All @@ -26,3 +30,36 @@
func (b *basePub) TopicName() string {
return b.topic.String()
}

// makeTopicMsg constructs a ZMQ message with a topic ID, message body, and sequence number.
// The message is constructed as a byte slice with the following structure:
// - Topic ID (2 Bytes)
// - Message body (varies based on provided parts)
// - Sequence number (4 Bytes).
func (b *basePub) makeTopicMsg(parts ...any) []byte {
result := make([]byte, 0, 64)

// Append Topic ID to the message (2 Bytes)
result = append(result, b.topic.Bytes()...)

// Append message body based on the provided parts
for _, part := range parts {
switch castedVal := part.(type) {
case crypto.Address:
result = append(result, castedVal.Bytes()...)
case []byte:
result = append(result, castedVal...)

Check warning on line 51 in www/zmq/publisher.go

View check run for this annotation

Codecov / codecov/patch

www/zmq/publisher.go#L50-L51

Added lines #L50 - L51 were not covered by tests
case uint32:
result = binary.BigEndian.AppendUint32(result, castedVal)
case uint16:
result = binary.BigEndian.AppendUint16(result, castedVal)
default:
panic("implement me!!")

Check warning on line 57 in www/zmq/publisher.go

View check run for this annotation

Codecov / codecov/patch

www/zmq/publisher.go#L56-L57

Added lines #L56 - L57 were not covered by tests
}
}

// Append sequence number to the message (4 Bytes, Big Endian encoding)
result = binary.BigEndian.AppendUint32(result, b.seqNo)

return result
}
46 changes: 22 additions & 24 deletions www/zmq/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,30 +49,28 @@ func (ts *testData) resetServer() {
ts.eventCh = nil
}

func (ts *testData) cleanup() func() {
return func() {
ts.server.Close()
ts.resetServer()
}
func (ts *testData) cleanup() {
ts.server.Close()
ts.resetServer()
}

func TestServerWithDefaultConfig(t *testing.T) {
suite := setup(t)
td := setup(t)

conf := DefaultConfig()

err := suite.initServer(context.TODO(), conf)
t.Cleanup(suite.cleanup())
err := td.initServer(context.TODO(), conf)
defer td.cleanup()

assert.NoError(t, err)
require.NotNil(t, suite.server)
require.NotNil(t, td.server)
}

func TestTopicsWithSameSocket(t *testing.T) {
suite := setup(t)
t.Cleanup(suite.cleanup())
td := setup(t)
defer td.cleanup()

port := suite.FindFreePort()
port := td.FindFreePort()
addr := fmt.Sprintf("tcp://127.0.0.1:%d", port)

conf := DefaultConfig()
Expand All @@ -81,30 +79,30 @@ func TestTopicsWithSameSocket(t *testing.T) {
conf.ZmqPubRawBlock = addr
conf.ZmqPubRawTx = addr

err := suite.initServer(context.TODO(), conf)
err := td.initServer(context.TODO(), conf)
require.NoError(t, err)

require.Len(t, suite.server.publishers, 4)
require.Len(t, td.server.publishers, 4)

expectedAddr := suite.server.publishers[0].Address()
expectedAddr := td.server.publishers[0].Address()

for _, pub := range suite.server.publishers {
for _, pub := range td.server.publishers {
require.Equal(t, expectedAddr, pub.Address(), "All publishers must have the same address")
}
}

func TestTopicsWithDifferentSockets(t *testing.T) {
suite := setup(t)
t.Cleanup(suite.cleanup())
td := setup(t)
defer td.cleanup()

conf := DefaultConfig()
conf.ZmqPubBlockInfo = fmt.Sprintf("tcp://127.0.0.1:%d", suite.FindFreePort())
conf.ZmqPubTxInfo = fmt.Sprintf("tcp://127.0.0.1:%d", suite.FindFreePort())
conf.ZmqPubRawBlock = fmt.Sprintf("tcp://127.0.0.1:%d", suite.FindFreePort())
conf.ZmqPubRawTx = fmt.Sprintf("tcp://127.0.0.1:%d", suite.FindFreePort())
conf.ZmqPubBlockInfo = fmt.Sprintf("tcp://127.0.0.1:%d", td.FindFreePort())
conf.ZmqPubTxInfo = fmt.Sprintf("tcp://127.0.0.1:%d", td.FindFreePort())
conf.ZmqPubRawBlock = fmt.Sprintf("tcp://127.0.0.1:%d", td.FindFreePort())
conf.ZmqPubRawTx = fmt.Sprintf("tcp://127.0.0.1:%d", td.FindFreePort())

err := suite.initServer(context.TODO(), conf)
err := td.initServer(context.TODO(), conf)
require.NoError(t, err)

require.Len(t, suite.server.publishers, 4)
require.Len(t, td.server.publishers, 4)
}
9 changes: 9 additions & 0 deletions www/zmq/topic.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package zmq

import "encoding/binary"

type Topic int16

const (
Expand Down Expand Up @@ -27,3 +29,10 @@ func (t Topic) String() string {
return ""
}
}

func (t Topic) Bytes() []byte {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, uint16(t))

return b
}
Loading