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

Wait for logs in blockchain publisher #249

Merged
merged 1 commit into from
Oct 23, 2024
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
26 changes: 17 additions & 9 deletions pkg/api/payer/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"crypto/ecdsa"

"github.com/ethereum/go-ethereum/common"
"github.com/xmtp/xmtpd/pkg/abis"
"github.com/xmtp/xmtpd/pkg/blockchain"
"github.com/xmtp/xmtpd/pkg/constants"
"github.com/xmtp/xmtpd/pkg/envelopes"
Expand Down Expand Up @@ -188,23 +189,30 @@ func (s *Service) publishToBlockchain(
var hash common.Hash
switch kind {
case topic.TOPIC_KIND_GROUP_MESSAGES_V1:
hash, err = s.blockchainPublisher.PublishGroupMessage(ctx, idBytes, payload)
var logMessage *abis.GroupMessagesMessageSent
if logMessage, err = s.blockchainPublisher.PublishGroupMessage(ctx, idBytes, payload); err != nil {
return nil, status.Errorf(codes.Internal, "error publishing group message: %v", err)
}
if logMessage == nil {
return nil, status.Errorf(codes.Internal, "received nil logMessage")
}
hash = logMessage.Raw.TxHash
neekolas marked this conversation as resolved.
Show resolved Hide resolved
case topic.TOPIC_KIND_IDENTITY_UPDATES_V1:
hash, err = s.blockchainPublisher.PublishIdentityUpdate(ctx, idBytes, payload)
var logMessage *abis.IdentityUpdatesIdentityUpdateCreated
if logMessage, err = s.blockchainPublisher.PublishIdentityUpdate(ctx, idBytes, payload); err != nil {
return nil, status.Errorf(codes.Internal, "error publishing identity update: %v", err)
}
if logMessage == nil {
return nil, status.Errorf(codes.Internal, "received nil logMessage")
}
hash = logMessage.Raw.TxHash
neekolas marked this conversation as resolved.
Show resolved Hide resolved
default:
return nil, status.Errorf(
codes.InvalidArgument,
"Unknown blockchain message for topic %s",
targetTopic.String(),
)
}
if err != nil {
return nil, status.Errorf(
codes.Internal,
"error publishing group message: %v",
err,
)
}

return &envelopesProto.OriginatorEnvelope{
UnsignedOriginatorEnvelope: payload,
Expand Down
60 changes: 54 additions & 6 deletions pkg/blockchain/blockchainPublisher.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/xmtp/xmtpd/pkg/abis"
"github.com/xmtp/xmtpd/pkg/config"
Expand Down Expand Up @@ -37,6 +38,7 @@ func NewBlockchainPublisher(
common.HexToAddress(contractOptions.MessagesContractAddress),
client,
)

if err != nil {
return nil, err
}
Expand All @@ -62,46 +64,92 @@ func (m *BlockchainPublisher) PublishGroupMessage(
ctx context.Context,
groupID [32]byte,
message []byte,
) (common.Hash, error) {
) (*abis.GroupMessagesMessageSent, error) {
if len(message) == 0 {
return nil, errors.New("message is empty")
}
tx, err := m.messagesContract.AddMessage(&bind.TransactOpts{
Context: ctx,
From: m.signer.FromAddress(),
Signer: m.signer.SignerFunc(),
}, groupID, message)
if err != nil {
return common.Hash{}, err
return nil, err
}

return WaitForTransaction(
receipt, err := WaitForTransaction(
ctx,
m.logger,
m.client,
2*time.Second,
250*time.Millisecond,
tx.Hash(),
)
neekolas marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil, err
}

if receipt == nil {
return nil, errors.New("transaction receipt is nil")
}

return findLog(receipt, m.messagesContract.ParseMessageSent, "no message sent log found")
}

func (m *BlockchainPublisher) PublishIdentityUpdate(
ctx context.Context,
inboxId [32]byte,
identityUpdate []byte,
) (common.Hash, error) {
) (*abis.IdentityUpdatesIdentityUpdateCreated, error) {
if len(identityUpdate) == 0 {
return nil, errors.New("identity update is empty")
}
tx, err := m.identityUpdateContract.AddIdentityUpdate(&bind.TransactOpts{
Context: ctx,
From: m.signer.FromAddress(),
Signer: m.signer.SignerFunc(),
}, inboxId, identityUpdate)
if err != nil {
return common.Hash{}, err
return nil, err
}

return WaitForTransaction(
receipt, err := WaitForTransaction(
ctx,
m.logger,
m.client,
2*time.Second,
250*time.Millisecond,
tx.Hash(),
)
neekolas marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil, err
}
if receipt == nil {
return nil, errors.New("transaction receipt is nil")
}

return findLog(
receipt,
m.identityUpdateContract.ParseIdentityUpdateCreated,
"no identity update log found",
)
}

func findLog[T any](
receipt *types.Receipt,
parse func(types.Log) (*T, error),
errorMsg string,
) (*T, error) {
for _, logEntry := range receipt.Logs {
if logEntry == nil {
continue
}
event, err := parse(*logEntry)
if err != nil {
continue
}
Comment on lines +143 to +150
Copy link
Contributor

Choose a reason for hiding this comment

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

Can there be multiple logs for the same update type, e.g. submitted by others?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The receipt is scoped to a single transaction, so it will only be your own events.

return event, nil
}

return nil, errors.New(errorMsg)
}
142 changes: 142 additions & 0 deletions pkg/blockchain/blockchainPublisher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package blockchain

import (
"context"
"testing"

"github.com/stretchr/testify/require"
"github.com/xmtp/xmtpd/pkg/testutils"
)

func buildPublisher(t *testing.T) (*BlockchainPublisher, func()) {
ctx, cancel := context.WithCancel(context.Background())
logger := testutils.NewLog(t)
contractsOptions := testutils.GetContractsOptions(t)
// Set the nodes contract address to a random smart contract instead of the fixed deployment
contractsOptions.NodesContractAddress = testutils.DeployNodesContract(t)

signer, err := NewPrivateKeySigner(
testutils.GetPayerOptions(t).PrivateKey,
contractsOptions.ChainID,
)
require.NoError(t, err)

client, err := NewClient(ctx, contractsOptions.RpcUrl)
require.NoError(t, err)

publisher, err := NewBlockchainPublisher(logger, client, signer, contractsOptions)
require.NoError(t, err)

return publisher, func() {
cancel()
client.Close()
}
}

func TestPublishIdentityUpdate(t *testing.T) {
publisher, cleanup := buildPublisher(t)
defer cleanup()
tests := []struct {
name string
inboxId [32]byte
identityUpdate []byte
ctx context.Context
wantErr bool
}{
{
name: "happy path",
inboxId: testutils.RandomGroupID(),
identityUpdate: testutils.RandomBytes(100),
ctx: context.Background(),
wantErr: false,
},
{
name: "empty update",
inboxId: testutils.RandomGroupID(),
identityUpdate: []byte{},
ctx: context.Background(),
wantErr: true,
},
{
name: "cancelled context",
inboxId: testutils.RandomGroupID(),
identityUpdate: testutils.RandomBytes(100),
ctx: testutils.CancelledContext(),
wantErr: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
logMessage, err := publisher.PublishIdentityUpdate(
tt.ctx,
tt.inboxId,
tt.identityUpdate,
)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
require.NotNil(t, logMessage)
require.Equal(t, tt.inboxId, logMessage.InboxId)
require.Equal(t, tt.identityUpdate, logMessage.Update)
require.Greater(t, logMessage.SequenceId, uint64(0))
require.NotNil(t, logMessage.Raw.TxHash)
})
}
}

func TestPublishGroupMessage(t *testing.T) {
publisher, cleanup := buildPublisher(t)
defer cleanup()

tests := []struct {
name string
groupID [32]byte
message []byte
ctx context.Context
wantErr bool
}{
{
name: "happy path",
groupID: testutils.RandomGroupID(),
message: testutils.RandomBytes(100),
ctx: context.Background(),
wantErr: false,
},
{
name: "empty message",
groupID: testutils.RandomGroupID(),
message: []byte{},
ctx: context.Background(),
wantErr: true,
},
{
name: "cancelled context",
groupID: testutils.RandomGroupID(),
message: testutils.RandomBytes(100),
ctx: testutils.CancelledContext(),
wantErr: true,
},
}

for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
logMessage, err := publisher.PublishGroupMessage(tt.ctx, tt.groupID, tt.message)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
require.NotNil(t, logMessage)
require.Equal(t, tt.groupID, logMessage.GroupId)
require.Equal(t, tt.message, logMessage.Message)
require.Greater(t, logMessage.SequenceId, uint64(0))
require.NotNil(t, logMessage.Raw.TxHash)
})
}
}
20 changes: 13 additions & 7 deletions pkg/blockchain/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"time"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"go.uber.org/zap"
)
Expand All @@ -22,7 +23,7 @@ func WaitForTransaction(
timeout time.Duration,
pollSleep time.Duration,
hash common.Hash,
) (common.Hash, error) {
) (*types.Receipt, error) {
neekolas marked this conversation as resolved.
Show resolved Hide resolved
// Enforce the timeout with a context so that slow requests get aborted if the function has
// run out of time
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(timeout))
Expand All @@ -33,18 +34,23 @@ func WaitForTransaction(
defer ticker.Stop()

for {
_, isPending, err := client.TransactionByHash(ctx, hash)
receipt, err := client.TransactionReceipt(ctx, hash)
if err != nil {
logger.Error("waiting for transaction", zap.String("hash", hash.String()))
} else if !isPending {
return hash, nil
if err.Error() != "not found" {
logger.Error("waiting for transaction", zap.String("hash", hash.String()))
}
} else if receipt != nil {
if receipt.Status == types.ReceiptStatusSuccessful {
return receipt, nil
}
return nil, fmt.Errorf("transaction failed")
}

select {
case <-ctx.Done():
return common.Hash{}, fmt.Errorf("timed out")
return nil, fmt.Errorf("timed out")
case <-ticker.C:
continue
}
}

}
9 changes: 7 additions & 2 deletions pkg/blockchain/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/xmtp/xmtpd/pkg/abis"
)

// Construct a raw blockchain listener that can be used to listen for events across many contract event types
Expand Down Expand Up @@ -49,6 +50,10 @@ type IBlockchainPublisher interface {
ctx context.Context,
inboxId [32]byte,
identityUpdate []byte,
) (common.Hash, error)
PublishGroupMessage(ctx context.Context, groupdId [32]byte, message []byte) (common.Hash, error)
) (*abis.IdentityUpdatesIdentityUpdateCreated, error)
PublishGroupMessage(
ctx context.Context,
groupdId [32]byte,
message []byte,
) (*abis.GroupMessagesMessageSent, error)
}
Loading
Loading