Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
evlekht committed Jan 21, 2025
1 parent 422416f commit 0520a74
Show file tree
Hide file tree
Showing 9 changed files with 277 additions and 193 deletions.
10 changes: 5 additions & 5 deletions internal/rpc/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ import (
"fmt"
"net"

"github.com/chain4travel/camino-messenger-bot/config"
"github.com/chain4travel/camino-messenger-bot/internal/messaging"
"github.com/chain4travel/camino-messenger-bot/internal/messaging/types"
"github.com/chain4travel/camino-messenger-bot/internal/metadata"
"github.com/chain4travel/camino-messenger-bot/internal/rpc"
"github.com/chain4travel/camino-messenger-bot/internal/rpc/generated"
"github.com/chain4travel/camino-messenger-bot/internal/tracing"
"github.com/chain4travel/camino-messenger-bot/proto/pb/readiness"
"github.com/chain4travel/camino-messenger-bot/utils/tls"

"github.com/chain4travel/camino-messenger-bot/config"
"github.com/chain4travel/camino-messenger-bot/internal/messaging"
"github.com/chain4travel/camino-messenger-bot/internal/metadata"
utils "github.com/chain4travel/camino-messenger-bot/utils/tls"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"google.golang.org/grpc"
Expand Down Expand Up @@ -52,7 +52,7 @@ func NewServer(
if cfg.Unencrypted {
logger.Warn("Running gRPC server without TLS!")
} else {
creds, err := utils.LoadTLSCredentials(cfg.ServerCertFile, cfg.ServerKeyFile)
creds, err := tls.LoadTLSCredentials(cfg.ServerCertFile, cfg.ServerKeyFile)
if err != nil {
return nil, fmt.Errorf("could not load TLS keys: %w", err)
}
Expand Down
24 changes: 16 additions & 8 deletions tests/e2e/bot/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,26 @@ import (
"github.com/chain4travel/camino-messenger-bot/tests/e2e/process"
"github.com/go-viper/mapstructure/v2"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"gopkg.in/yaml.v3"
)

const botRequestTickerInterval = 500 * time.Millisecond

func StartNewBot(
ctx context.Context,
e2eTmpDir string,
botDir string,
botBinPath string,
config config.UnparsedConfig,
w io.Writer,
) (*Bot, chan error, error) {
// TODO@ ensure that no other cmb is running on this port ?
tmpDir := path.Join(e2eTmpDir, "cmb")
if err := os.RemoveAll(tmpDir); err != nil {
return nil, nil, fmt.Errorf("failed to remove cmb tmp dir: %w", err)
if err := os.RemoveAll(botDir); err != nil {
return nil, nil, fmt.Errorf("failed to remove bot data dir: %w", err)
}

if err := os.MkdirAll(botDir, 0755); err != nil {
return nil, nil, fmt.Errorf("failed to create bot data dir: %w", err)
}

unparsedMap := &map[string]any{}
Expand All @@ -56,7 +60,7 @@ func StartNewBot(
return nil, nil, fmt.Errorf("failed to marshal config map into yaml: %w", err)
}

configPath := path.Join(tmpDir, "config.yaml")
configPath := path.Join(botDir, "config.yaml")

if err := os.WriteFile(configPath, configBytes, 0644); err != nil {
return nil, nil, fmt.Errorf("failed to write config file: %w", err)
Expand All @@ -66,10 +70,14 @@ func StartNewBot(
cmd.Stdout = w

if err := cmd.Start(); err != nil {
return nil, nil, fmt.Errorf("failed to start cmb (%d): %w", cmd.Process.Pid, err)
return nil, nil, fmt.Errorf("failed to start bot (%d): %w", cmd.Process.Pid, err)
}
// opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))

clientConnection, err := grpc.NewClient(fmt.Sprintf("localhost:%d", config.RPCServer.Port))
clientConnection, err := grpc.NewClient(
fmt.Sprintf("localhost:%d", config.RPCServer.Port),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
return nil, nil, fmt.Errorf("failed to create grpc client: %w", err)
}
Expand All @@ -81,7 +89,7 @@ func StartNewBot(

b.awaitReady(ctx)

log.Printf("cmb (%d) started\n", cmd.Process.Pid)
log.Printf("bot (%d) started\n", cmd.Process.Pid)

return b, process.ListenForProcessError(cmd), nil
}
Expand Down
106 changes: 106 additions & 0 deletions tests/e2e/bot/factory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package bot

import (
"context"
"crypto/ecdsa"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"math/big"
"path"
"strconv"

"github.com/chain4travel/camino-messenger-bot/config"
"github.com/chain4travel/camino-messenger-bot/tests/e2e/conduit"
"github.com/chain4travel/camino-messenger-bot/tests/e2e/node"
"github.com/ethereum/go-ethereum/crypto"
)

var DefaultCMAccountOwnerFunds = big.NewInt(0).Mul(node.CAM, big.NewInt(100))

type Factory struct {
dir string
binPath string
migrationsPath string
networkClient *node.Client
matrix *conduit.MatrixServer
}

// NewFactory creates a new bot factory.
func NewFactory(
e2eTmpDir string,
binPath string,
migrationsDir string,
networkClient *node.Client,
matrix *conduit.MatrixServer,
) *Factory {
return &Factory{
dir: path.Join(e2eTmpDir, "cmb"),
binPath: binPath,
migrationsPath: "file://" + migrationsDir,
networkClient: networkClient,
matrix: matrix,
}
}

// CreateBot creates a new bot.
func (f *Factory) CreateBot(ctx context.Context, port uint64, out io.Writer) (*Bot, chan error, error) {
key, err := ecdsa.GenerateKey(crypto.S256(), rand.Reader)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate key: %w", err)
}

ownerAddr := crypto.PubkeyToAddress(key.PublicKey)

cmAccountAddress, _, err := f.networkClient.CreateCMAccount(ctx, key)
if err != nil {
return nil, nil, fmt.Errorf("failed to create CM account: %w", err)
}

if err := f.networkClient.Transfer(ctx, f.networkClient.PrefundedKeys()[0], ownerAddr, DefaultCMAccountOwnerFunds); err != nil {
return nil, nil, fmt.Errorf("failed to transfer funds to cm account owner: %w", err)
}

if err := f.networkClient.AddBotToCMAccount(ctx, cmAccountAddress, key, ownerAddr); err != nil {
return nil, nil, fmt.Errorf("failed to add bot to CM account: %w", err)
}

botDir := path.Join(f.dir, strconv.FormatUint(port, 10)) // TODO@ add some more suffix to make bots form different tests unique 100%

return StartNewBot(
ctx,
botDir,
f.binPath,
config.UnparsedConfig{
DeveloperMode: true,
BotKey: hex.EncodeToString(crypto.FromECDSA(key)),
CMAccountAddress: cmAccountAddress.Hex(),
ChainRPCURL: f.networkClient.ChainRPCURL(),
BookingTokenAddress: f.networkClient.BookingTokenContractAddress().Hex(),
NetworkFeeRecipientBotAddress: f.matrix.NetworkFeeRecipientBotAddress().Hex(),
NetworkFeeRecipientCMAccountAddress: f.matrix.NetworkFeeRecipientCMAccountAddress().Hex(),
ChequeExpirationTime: 3600 * 24 * 30 * 7, // 7 months
MinChequeDurationUntilExpiration: 3600 * 24 * 30 * 6, // 6 months
CashInPeriod: 3600, // 1h
ResponseTimeout: 30000, // 30s
PartnerPlugin: config.PartnerPluginConfig{
Enabled: false,
Host: "",
Unencrypted: true,
},
RPCServer: config.RPCServerConfig{
Enabled: true,
Port: port,
Unencrypted: true,
},
Matrix: config.UnparsedMatrixConfig{Host: f.matrix.Host().String()},
DB: config.UnparsedSQLiteDBConfig{
DBPath: path.Join(botDir, "db"),
MigrationsPath: f.migrationsPath,
},
Tracing: config.TracingConfig{Enabled: false},
},
out,
)
}
34 changes: 24 additions & 10 deletions tests/e2e/conduit/conduit.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"fmt"
"io"
"log"
"math/big"
"net/url"
"os"
"os/exec"
"path"
Expand All @@ -24,18 +26,13 @@ import (

const matrixRequestTickerInterval = 1000 * time.Millisecond

// TODO@ move to common consts pkg?
var defaultCMAccountOwnerFunds = big.NewInt(0).Mul(node.CAM, big.NewInt(100))

// TODO@ if starting conduit will take notable amout of time because it needs to initialize some initial state (e.g. db)
// TODO@ and that state is always the same, we can use some kind of snapshotting to speed up the process

var networkFeeKey *ecdsa.PrivateKey

func init() {
var err error
networkFeeKey, err = crypto.HexToECDSA("7a14fdf6bb1d53e28384f70209280dd8848bdc96b5f9eb7fdde9fcddc7ef1a0d")
if err != nil {
log.Fatalf("failed to parse admin key: %v", err)
}

log.Println("setting common matrix env")
os.Setenv("CONDUIT_CONFIG", "")
os.Setenv("CONDUIT_SERVER_NAME", "localhost")
Expand Down Expand Up @@ -71,9 +68,12 @@ func StartNewMatrixServer(
return nil, nil, fmt.Errorf("failed to create matrix client: %v", err)
}

dbDir := path.Join(matrixDir, "db")
os.MkdirAll(dbDir, 0755)

cmd := exec.Command(matrixBinPath)
cmd.Env = append(os.Environ(),
"CONDUIT_DATABASE_PATH="+path.Join(matrixDir, "db"),
"CONDUIT_DATABASE_PATH="+dbDir,
"CONDUIT_PORT="+portStr,
)
cmd.Stdout = w
Expand All @@ -93,11 +93,20 @@ func StartNewMatrixServer(
return nil, nil, fmt.Errorf("failed to wait for matrix (%d) to be ready: %w", cmd.Process.Pid, err)
}

m.networkFeeCMAccountAddress, _, err = networkClient.CreateCMAccount(ctx, networkFeeKey, networkFeeKey)
// TODO@ move this to e2e ? wrap StartNewMatrixServer func with that logic
m.networkFeeCMAccountAddress, _, err = networkClient.CreateCMAccount(ctx, networkFeeKey)
if err != nil {
return nil, nil, fmt.Errorf("failed to create cm account: %w", err)
}

if err := networkClient.Transfer(ctx, networkClient.PrefundedKeys()[0], m.networkFeeBotAddress, defaultCMAccountOwnerFunds); err != nil {
return nil, nil, fmt.Errorf("failed to transfer funds to cm account owner: %w", err)
}

if err := networkClient.AddBotToCMAccount(ctx, m.networkFeeCMAccountAddress, networkFeeKey, m.networkFeeBotAddress); err != nil {
return nil, nil, fmt.Errorf("failed to add bot to CM account: %w", err)
}

log.Printf("matrix server (%d) started\n", cmd.Process.Pid)

return m, process.ListenForProcessError(cmd), nil
Expand All @@ -112,6 +121,10 @@ type MatrixServer struct {
networkFeeCMAccountAddress common.Address
}

func (m *MatrixServer) Host() *url.URL {
return m.client.HomeserverURL
}

func (m *MatrixServer) Stop(ctx context.Context) error {
if m == nil {
return nil
Expand Down Expand Up @@ -159,6 +172,7 @@ func (m *MatrixServer) awaitReady(ctx context.Context) error {
for {
err := cryptoHelper.Init(ctx)
if err == nil {
log.Printf("succesfully logged in to matrix server\n")
return nil
} else {
log.Printf("failed to login to matrix server: %v\n", err)
Expand Down
Loading

0 comments on commit 0520a74

Please sign in to comment.