Skip to content

Commit

Permalink
Merge branch 'main' into fix/non-adjacent-light-client
Browse files Browse the repository at this point in the history
  • Loading branch information
viveksharmapoudel authored Jul 20, 2023
2 parents 6ff3a6f + 895cc72 commit f38da98
Show file tree
Hide file tree
Showing 15 changed files with 418 additions and 102 deletions.
30 changes: 25 additions & 5 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ import (
"errors"
"fmt"
"io"
"net/url"
"os"
"os/signal"
"path"
"path/filepath"
"runtime/debug"
"strings"
Expand All @@ -34,6 +36,7 @@ import (
"github.com/spf13/viper"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)

const appName = "rly"
Expand Down Expand Up @@ -171,13 +174,32 @@ func Execute() {
}
}

type lumberjackSink struct {
*lumberjack.Logger
}

func (lumberjackSink) Sync() error { return nil }

Check warning on line 181 in cmd/root.go

View check run for this annotation

Codecov / codecov/patch

cmd/root.go#L181

Added line #L181 was not covered by tests

func newRootLogger(format string, debug bool) (*zap.Logger, error) {
config := zap.NewProductionEncoderConfig()
config.EncodeTime = func(ts time.Time, encoder zapcore.PrimitiveArrayEncoder) {
encoder.AppendString(ts.UTC().Format("2006-01-02T15:04:05.000000Z07:00"))
}
config.LevelKey = "lvl"

ll := lumberjack.Logger{
Filename: path.Join(defaultHome, "relay.log"),
MaxSize: 50, //MB
MaxBackups: 30,
MaxAge: 28, //days
Compress: true,
}
zap.RegisterSink("lumberjack", func(*url.URL) (zap.Sink, error) {
return lumberjackSink{
Logger: &ll,
}, nil
})

Check warning on line 201 in cmd/root.go

View check run for this annotation

Codecov / codecov/patch

cmd/root.go#L190-L201

Added lines #L190 - L201 were not covered by tests

var enc zapcore.Encoder
switch format {
case "json":
Expand All @@ -195,15 +217,13 @@ func newRootLogger(format string, debug bool) (*zap.Logger, error) {
level = zap.DebugLevel
}

logFile, _ := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
writer := zapcore.AddSync(logFile)
w := zapcore.AddSync(&ll)

Check warning on line 220 in cmd/root.go

View check run for this annotation

Codecov / codecov/patch

cmd/root.go#L220

Added line #L220 was not covered by tests

core := zapcore.NewTee(
zapcore.NewCore(enc,
writer,
level),
zapcore.NewCore(enc, w, level),

Check warning on line 223 in cmd/root.go

View check run for this annotation

Codecov / codecov/patch

cmd/root.go#L223

Added line #L223 was not covered by tests
zapcore.NewCore(enc, os.Stderr, level),
)

Check warning on line 226 in cmd/root.go

View check run for this annotation

Codecov / codecov/patch

cmd/root.go#L226

Added line #L226 was not covered by tests
return zap.New(core), nil
}

Expand Down
3 changes: 3 additions & 0 deletions cmd/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ func createClientsCmd(a *appState) *cobra.Command {
return fmt.Errorf("key %s not found on dst chain %s", c[dst].ChainProvider.Key(), c[dst].ChainID())
}

// TODO: make iconStartHeight compulsory
// if iconStartHeight is not given it can create confusion as starting relay at any time could miss number of btp block update_client
clientSrc, clientDst, err := c[src].CreateClients(cmd.Context(), c[dst], allowUpdateAfterExpiry, allowUpdateAfterMisbehaviour, override, customClientTrustingPeriod, a.config.memo(cmd), iconStartHeight)
if err != nil {
return err
Expand Down Expand Up @@ -335,6 +337,7 @@ func upgradeClientsCmd(a *appState) *cobra.Command {
return cmd
}

// TODO: method has side_effect
func createConnectionCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "connection path_name",
Expand Down
129 changes: 119 additions & 10 deletions relayer/chains/archway/archway_chain_processor.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package archway

import (
"bytes"
"context"
"errors"
"fmt"
Expand All @@ -16,6 +17,7 @@ import (
"github.com/cosmos/relayer/v2/relayer/provider"

ctypes "github.com/cometbft/cometbft/rpc/core/types"
"github.com/cometbft/cometbft/types"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
)
Expand Down Expand Up @@ -53,6 +55,12 @@ type ArchwayChainProcessor struct {

// parsed gas prices accepted by the chain (only used for metrics)
parsedGasPrices *sdk.DecCoins

verifier *Verifier
}

type Verifier struct {
Header *types.LightBlock
}

func NewArchwayChainProcessor(log *zap.Logger, provider *ArchwayProvider, metrics *processor.PrometheusMetrics) *ArchwayChainProcessor {
Expand All @@ -74,6 +82,7 @@ const (
latestHeightQueryRetryDelay = 1 * time.Second
latestHeightQueryRetries = 5

// TODO: review transfer to providerConfig
defaultMinQueryLoopDuration = 1 * time.Second
defaultBalanceUpdateWaitDuration = 60 * time.Second
inSyncNumBlocksThreshold = 2
Expand Down Expand Up @@ -214,7 +223,6 @@ func (ccp *ArchwayChainProcessor) Run(ctx context.Context, initialBlockHistory u
continue
}
persistence.latestHeight = status.SyncInfo.LatestBlockHeight
// ccp.chainProvider.setCometVersion(ccp.log, status.NodeInfo.Version)
break
}

Expand All @@ -227,6 +235,19 @@ func (ccp *ArchwayChainProcessor) Run(ctx context.Context, initialBlockHistory u

persistence.latestQueriedBlock = latestQueriedBlock

_, lightBlock, err := ccp.chainProvider.QueryLightBlock(ctx, persistence.latestQueriedBlock)
if err != nil {
ccp.log.Error("Failed to get ibcHeader",
zap.Int64("height", persistence.latestQueriedBlock),
zap.Any("error", err),
)
return err
}

Check warning on line 245 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L238-L245

Added lines #L238 - L245 were not covered by tests

ccp.verifier = &Verifier{
Header: lightBlock,
}

Check warning on line 250 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L247-L250

Added lines #L247 - L250 were not covered by tests
var eg errgroup.Group
eg.Go(func() error {
return ccp.initializeConnectionState(ctx)
Expand All @@ -238,7 +259,7 @@ func (ccp *ArchwayChainProcessor) Run(ctx context.Context, initialBlockHistory u
return err
}

ccp.log.Debug("Entering main query loop")
ccp.log.Debug("Entering Archway main query loop")

Check warning on line 262 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L262

Added line #L262 was not covered by tests

ticker := time.NewTicker(persistence.minQueryLoopDuration)
defer ticker.Stop()
Expand Down Expand Up @@ -305,6 +326,7 @@ func (ccp *ArchwayChainProcessor) initializeChannelState(ctx context.Context) er
}

func (ccp *ArchwayChainProcessor) queryCycle(ctx context.Context, persistence *queryCyclePersistence) error {
// TODO : review if redundent remove

Check warning on line 329 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L329

Added line #L329 was not covered by tests
status, err := ccp.nodeStatusWithRetry(ctx)
if err != nil {
// don't want to cause ArchwayChainProcessor to quit here, can retry again next cycle.
Expand Down Expand Up @@ -344,21 +366,20 @@ func (ccp *ArchwayChainProcessor) queryCycle(ctx context.Context, persistence *q
}

ibcMessagesCache := processor.NewIBCMessagesCache()

ibcHeaderCache := make(processor.IBCHeaderCache)

ppChanged := false

var latestHeader ArchwayIBCHeader

newLatestQueriedBlock := persistence.latestQueriedBlock

chainID := ccp.chainProvider.ChainId()
var latestHeader provider.IBCHeader

Check warning on line 375 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L375

Added line #L375 was not covered by tests

// TODO review: max block sync
//

Check warning on line 378 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L377-L378

Added lines #L377 - L378 were not covered by tests
for i := persistence.latestQueriedBlock + 1; i <= persistence.latestHeight; i++ {
var eg errgroup.Group
var blockRes *ctypes.ResultBlockResults
var ibcHeader provider.IBCHeader
var lightBlock *types.LightBlock

Check warning on line 382 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L382

Added line #L382 was not covered by tests
i := i
eg.Go(func() (err error) {
queryCtx, cancelQueryCtx := context.WithTimeout(ctx, blockResultsQueryTimeout)
Expand All @@ -370,7 +391,7 @@ func (ccp *ArchwayChainProcessor) queryCycle(ctx context.Context, persistence *q
eg.Go(func() (err error) {
queryCtx, cancelQueryCtx := context.WithTimeout(ctx, queryTimeout)
defer cancelQueryCtx()
ibcHeader, err = ccp.chainProvider.QueryIBCHeader(queryCtx, i)
latestHeader, lightBlock, err = ccp.chainProvider.QueryLightBlock(queryCtx, i)

Check warning on line 394 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L394

Added line #L394 was not covered by tests
return err
})

Expand All @@ -379,13 +400,18 @@ func (ccp *ArchwayChainProcessor) queryCycle(ctx context.Context, persistence *q
break
}

latestHeader = ibcHeader.(ArchwayIBCHeader)
if err := ccp.Verify(ctx, lightBlock); err != nil {
ccp.log.Error("failed to Verify Archway Header", zap.Int64("Height", blockRes.Height))
return err
}

Check warning on line 406 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L403-L406

Added lines #L403 - L406 were not covered by tests

ccp.log.Debug("Verified block ",
zap.Int64("height", lightBlock.Header.Height))

Check warning on line 409 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L408-L409

Added lines #L408 - L409 were not covered by tests

heightUint64 := uint64(i)

ccp.latestBlock = provider.LatestBlock{
Height: heightUint64,
// Time: latestHeader.SignedHeader.Header.Time,
}

ibcHeaderCache[heightUint64] = latestHeader
Expand Down Expand Up @@ -451,6 +477,8 @@ func (ccp *ArchwayChainProcessor) queryCycle(ctx context.Context, persistence *q
return nil
}

// TODO: review add verifier

func (ccp *ArchwayChainProcessor) CollectMetrics(ctx context.Context, persistence *queryCyclePersistence) {
ccp.CurrentBlockHeight(ctx, persistence)

Expand All @@ -465,6 +493,87 @@ func (ccp *ArchwayChainProcessor) CurrentBlockHeight(ctx context.Context, persis
ccp.metrics.SetLatestHeight(ccp.chainProvider.ChainId(), persistence.latestHeight)
}

func (ccp *ArchwayChainProcessor) Verify(ctx context.Context, untrusted *types.LightBlock) error {

if untrusted.Height != ccp.verifier.Header.Height+1 {
return errors.New("headers must be adjacent in height")
}

Check warning on line 500 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L496-L500

Added lines #L496 - L500 were not covered by tests

if err := verifyNewHeaderAndVals(untrusted.SignedHeader,
untrusted.ValidatorSet,
ccp.verifier.Header.SignedHeader,
time.Now(), 0); err != nil {
return fmt.Errorf("Failed to verify Header: %v", err)
}

Check warning on line 507 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L502-L507

Added lines #L502 - L507 were not covered by tests

if !bytes.Equal(untrusted.Header.ValidatorsHash, ccp.verifier.Header.NextValidatorsHash) {
err := fmt.Errorf("expected old header next validators (%X) to match those from new header (%X)",
ccp.verifier.Header.NextValidatorsHash,
untrusted.Header.ValidatorsHash,
)
return err
}

Check warning on line 515 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L509-L515

Added lines #L509 - L515 were not covered by tests

if !bytes.Equal(untrusted.Header.LastBlockID.Hash.Bytes(), ccp.verifier.Header.Commit.BlockID.Hash.Bytes()) {
err := fmt.Errorf("expected LastBlockId Hash (%X) of current header to match those from trusted Header BlockID hash (%X)",
ccp.verifier.Header.NextValidatorsHash,
untrusted.Header.ValidatorsHash,
)
return err
}

Check warning on line 523 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L517-L523

Added lines #L517 - L523 were not covered by tests

// Ensure that +2/3 of new validators signed correctly.
if err := untrusted.ValidatorSet.VerifyCommitLight(ccp.verifier.Header.ChainID, untrusted.Commit.BlockID,
untrusted.Header.Height, untrusted.Commit); err != nil {
return fmt.Errorf("invalid header: %v", err)
}

Check warning on line 529 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L526-L529

Added lines #L526 - L529 were not covered by tests

ccp.verifier.Header = untrusted
return nil

Check warning on line 532 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L531-L532

Added lines #L531 - L532 were not covered by tests

}

func verifyNewHeaderAndVals(
untrustedHeader *types.SignedHeader,
untrustedVals *types.ValidatorSet,
trustedHeader *types.SignedHeader,
now time.Time,
maxClockDrift time.Duration) error {

if err := untrustedHeader.ValidateBasic(trustedHeader.ChainID); err != nil {
return fmt.Errorf("untrustedHeader.ValidateBasic failed: %w", err)
}

Check warning on line 545 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L541-L545

Added lines #L541 - L545 were not covered by tests

if untrustedHeader.Height <= trustedHeader.Height {
return fmt.Errorf("expected new header height %d to be greater than one of old header %d",
untrustedHeader.Height,
trustedHeader.Height)
}

Check warning on line 551 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L547-L551

Added lines #L547 - L551 were not covered by tests

if !untrustedHeader.Time.After(trustedHeader.Time) {
return fmt.Errorf("expected new header time %v to be after old header time %v",
untrustedHeader.Time,
trustedHeader.Time)
}

Check warning on line 557 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L553-L557

Added lines #L553 - L557 were not covered by tests

if !untrustedHeader.Time.Before(now.Add(maxClockDrift)) {
return fmt.Errorf("new header has a time from the future %v (now: %v; max clock drift: %v)",
untrustedHeader.Time,
now,
maxClockDrift)
}

Check warning on line 564 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L559-L564

Added lines #L559 - L564 were not covered by tests

if !bytes.Equal(untrustedHeader.ValidatorsHash, untrustedVals.Hash()) {
return fmt.Errorf("expected new header validators (%X) to match those that were supplied (%X) at height %d",
untrustedHeader.ValidatorsHash,
untrustedVals.Hash(),
untrustedHeader.Height,
)
}

Check warning on line 572 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L566-L572

Added lines #L566 - L572 were not covered by tests

return nil

Check warning on line 574 in relayer/chains/archway/archway_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/archway_chain_processor.go#L574

Added line #L574 was not covered by tests
}

// func (ccp *ArchwayChainProcessor) CurrentRelayerBalance(ctx context.Context) {
// // memoize the current gas prices to only show metrics for "interesting" denoms
// if ccp.parsedGasPrices == nil {
Expand Down
2 changes: 1 addition & 1 deletion relayer/chains/archway/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func (cc *ArchwayProvider) KeystoreCreated(path string) bool {
// AddKey generates a new mnemonic which is then converted to a private key and BIP-39 HD Path and persists it to the keystore.
// It fails if there is an existing key with the same address.
func (cc *ArchwayProvider) AddKey(name string, coinType uint32, signingAlgorithm string) (output *provider.KeyOutput, err error) {
ko, err := cc.KeyAddOrRestore(name, coinType, signingAlgorithm)
ko, err := cc.KeyAddOrRestore(name, coinType)

Check warning on line 62 in relayer/chains/archway/keys.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/keys.go#L62

Added line #L62 was not covered by tests
if err != nil {
return nil, err
}
Expand Down
12 changes: 12 additions & 0 deletions relayer/chains/archway/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,18 @@ func (ap *ArchwayProvider) QueryIBCHeader(ctx context.Context, h int64) (provide
return NewArchwayIBCHeaderFromLightBlock(lightBlock), nil
}

func (ap *ArchwayProvider) QueryLightBlock(ctx context.Context, h int64) (provider.IBCHeader, *tmtypes.LightBlock, error) {
if h == 0 {
return nil, nil, fmt.Errorf("No header at height 0")
}
lightBlock, err := ap.LightProvider.LightBlock(ctx, h)
if err != nil {
return nil, nil, err
}

Check warning on line 145 in relayer/chains/archway/query.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/query.go#L138-L145

Added lines #L138 - L145 were not covered by tests

return NewArchwayIBCHeaderFromLightBlock(lightBlock), lightBlock, nil

Check warning on line 147 in relayer/chains/archway/query.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/query.go#L147

Added line #L147 was not covered by tests
}

// query packet info for sequence
func (ap *ArchwayProvider) QuerySendPacket(ctx context.Context, srcChanID, srcPortID string, sequence uint64) (provider.PacketInfo, error) {
return provider.PacketInfo{}, fmt.Errorf("Not implemented for Archway")
Expand Down
8 changes: 5 additions & 3 deletions relayer/chains/archway/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ func (ap *ArchwayProvider) TxFactory() tx.Factory {
WithGasAdjustment(ap.PCfg.GasAdjustment).
WithGasPrices(ap.PCfg.GasPrices).
WithKeybase(ap.Keybase).
WithSignMode(ap.PCfg.SignMode())
WithSignMode(ap.PCfg.SignMode()).
WithSimulateAndExecute(true)

Check warning on line 76 in relayer/chains/archway/tx.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/tx.go#L75-L76

Added lines #L75 - L76 were not covered by tests
}

// PrepareFactory mutates the tx factory with the appropriate account number, sequence number, and min gas settings.
Expand Down Expand Up @@ -772,8 +773,9 @@ func (ap *ArchwayProvider) SendMessagesToMempool(
ap.updateNextAccountSequence(sequence + 1)

Check warning on line 773 in relayer/chains/archway/tx.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/archway/tx.go#L773

Added line #L773 was not covered by tests
}

//TODO: comment this on production
SaveMsgToFile(ArchwayDebugMessagePath, msgs)
//uncomment for saving msg
// SaveMsgToFile(ArchwayDebugMessagePath, msgs)

return nil

}
Expand Down
1 change: 0 additions & 1 deletion relayer/chains/icon/cryptoutils/merkle_proof.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"math/bits"

"github.com/cosmos/relayer/v2/relayer/chains/icon/types"

"github.com/cosmos/relayer/v2/relayer/common"
"github.com/icon-project/IBC-Integration/libraries/go/common/icon"
)
Expand Down
2 changes: 2 additions & 0 deletions relayer/chains/icon/event_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ func (pi *packetInfo) parseAttrs(log *zap.Logger, event types.EventLog) {
packetData := event.Indexed[1]
var packet icon.Packet
if err := proto.Unmarshal(packetData, &packet); err != nil {

Check warning on line 35 in relayer/chains/icon/event_parser.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/event_parser.go#L35

Added line #L35 was not covered by tests
log.Error("failed to unmarshal packet")
// TODO: review return if parseAttrs add panic

Check warning on line 37 in relayer/chains/icon/event_parser.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/event_parser.go#L37

Added line #L37 was not covered by tests
}
pi.SourcePort = packet.SourcePort
pi.SourceChannel = packet.SourceChannel
Expand Down
Loading

0 comments on commit f38da98

Please sign in to comment.