|
| 1 | +package zmq |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/binary" |
| 7 | + "fmt" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/go-zeromq/zmq4" |
| 11 | + "github.com/pactus-project/pactus/types/block" |
| 12 | + "github.com/pactus-project/pactus/util/testsuite" |
| 13 | + "github.com/stretchr/testify/require" |
| 14 | +) |
| 15 | + |
| 16 | +func TestRawBlockPublisher(t *testing.T) { |
| 17 | + port := testsuite.FindFreePort() |
| 18 | + addr := fmt.Sprintf("tcp://localhost:%d", port) |
| 19 | + conf := DefaultConfig() |
| 20 | + conf.ZmqPubRawBlock = addr |
| 21 | + |
| 22 | + td := setup(t, conf) |
| 23 | + defer td.closeServer() |
| 24 | + |
| 25 | + td.server.Publishers() |
| 26 | + |
| 27 | + sub := zmq4.NewSub(context.TODO(), zmq4.WithAutomaticReconnect(false)) |
| 28 | + |
| 29 | + err := sub.Dial(addr) |
| 30 | + require.NoError(t, err) |
| 31 | + |
| 32 | + err = sub.SetOption(zmq4.OptionSubscribe, string(TopicRawBlock.Bytes())) |
| 33 | + require.NoError(t, err) |
| 34 | + |
| 35 | + blk, _ := td.TestSuite.GenerateTestBlock(td.RandHeight()) |
| 36 | + |
| 37 | + td.eventCh <- blk |
| 38 | + |
| 39 | + received, err := sub.Recv() |
| 40 | + require.NoError(t, err) |
| 41 | + |
| 42 | + require.NotNil(t, received.Frames) |
| 43 | + require.GreaterOrEqual(t, len(received.Frames), 1) |
| 44 | + |
| 45 | + msg := received.Frames[0] |
| 46 | + |
| 47 | + topic := msg[:2] |
| 48 | + blockHeader := msg[2 : len(msg)-8] |
| 49 | + height := binary.BigEndian.Uint32(msg[140 : len(msg)-4]) |
| 50 | + seqNo := binary.BigEndian.Uint32(msg[len(msg)-4:]) |
| 51 | + |
| 52 | + buf := bytes.NewBuffer(blockHeader) |
| 53 | + header := new(block.Header) |
| 54 | + |
| 55 | + require.NoError(t, header.Decode(buf)) |
| 56 | + |
| 57 | + require.NotNil(t, header) |
| 58 | + require.Equal(t, uint32(0), seqNo) |
| 59 | + require.Equal(t, blk.Height(), height) |
| 60 | + require.Equal(t, TopicRawBlock.Bytes(), topic) |
| 61 | + require.Equal(t, header.PrevBlockHash(), blk.Header().PrevBlockHash()) |
| 62 | + require.Equal(t, header.StateRoot(), blk.Header().StateRoot()) |
| 63 | + |
| 64 | + require.NoError(t, sub.Close()) |
| 65 | +} |
0 commit comments