Skip to content

Commit

Permalink
Merge branch 'main' of github.com:icon-project/ibc-relay into chore/g…
Browse files Browse the repository at this point in the history
…eneralize-archway-module
  • Loading branch information
viveksharmapoudel committed Jul 20, 2023
2 parents b5bf963 + 895cc72 commit a5137d5
Show file tree
Hide file tree
Showing 15 changed files with 422 additions and 104 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
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
104 changes: 91 additions & 13 deletions relayer/chains/icon/icon_chain_processor.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package icon

import (
"bytes"
"context"
"fmt"
"sort"
Expand Down Expand Up @@ -61,6 +62,14 @@ type IconChainProcessor struct {

// metrics to monitor lifetime of processor
metrics *processor.PrometheusMetrics

verifier *Verifier
}

type Verifier struct {
nextProofContext [][]byte
verifiedHeight int64
prevNetworkSectionHash []byte
}

func NewIconChainProcessor(log *zap.Logger, provider *IconProvider, metrics *processor.PrometheusMetrics) *IconChainProcessor {
Expand Down Expand Up @@ -144,7 +153,7 @@ func (icp *IconChainProcessor) Run(ctx context.Context, initialBlockHistory uint
}

func (icp *IconChainProcessor) initializeConnectionState(ctx context.Context) error {
// TODO:
// TODO: review

Check warning on line 156 in relayer/chains/icon/icon_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/icon_chain_processor.go#L156

Added line #L156 was not covered by tests
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
defer cancel()

Expand Down Expand Up @@ -218,6 +227,7 @@ func (icp *IconChainProcessor) GetLatestHeight() uint64 {
return icp.latestBlock.Height
}

// TODO: review add verifier
func (icp *IconChainProcessor) monitoring(ctx context.Context, persistence *queryCyclePersistence) error {

errCh := make(chan error) // error channel
Expand Down Expand Up @@ -294,11 +304,20 @@ loop:
}(ctxMonitorBlock, cancelMonitorBlock)
case br := <-btpBlockRespCh:
for ; br != nil; processedheight++ {
icp.latestBlockMu.Lock()
// verify BTP Block
err := icp.verifyBlock(ctx, br.Header)
if err != nil {
reconnect()
icp.log.Warn("failed to Verify BTP Block",
zap.Int64("got", br.Height),
zap.Error(err),
)
break

Check warning on line 315 in relayer/chains/icon/icon_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/icon_chain_processor.go#L307-L315

Added lines #L307 - L315 were not covered by tests
}

icp.latestBlock = provider.LatestBlock{
Height: uint64(processedheight),
}
icp.latestBlockMu.Unlock()

ibcMessage := parseIBCMessagesFromEventlog(icp.log, br.EventLogs, uint64(br.Height))
ibcMessageCache := processor.NewIBCMessagesCache()
Expand All @@ -311,16 +330,22 @@ loop:
icp.log.Info("Queried Latest height: ",
zap.String("chain id ", icp.chainProvider.ChainId()),
zap.Int64("height", br.Height))
err := icp.handlePathProcessorUpdate(ctx, br.Header, ibcMessageCache, ibcHeaderCache)
err = icp.handlePathProcessorUpdate(ctx, br.Header, ibcMessageCache, ibcHeaderCache)

Check warning on line 333 in relayer/chains/icon/icon_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/icon_chain_processor.go#L333

Added line #L333 was not covered by tests
if err != nil {
reconnect()
icp.log.Warn("Reconnect: error occured during handle block response ",
zap.Int64("got", br.Height),
)
break
}

// TODO: this is temporary adjustment
// if icp.firstTime {
// time.Sleep(4000 * time.Millisecond)
// } else {
// time.Sleep(100 * time.Millisecond)
// }
icp.firstTime = false
time.Sleep(100 * time.Millisecond)
if br = nil; len(btpBlockRespCh) > 0 {
br = <-btpBlockRespCh
}
Expand All @@ -338,11 +363,6 @@ loop:
for i := int64(0); bn != nil; i++ {
height, err := bn.Height.Value()

// icp.log.Info("for loop when receiving blockNotification",
// zap.Int64("height", height),
// zap.Int64("index", i),
// zap.Int64("processedheight", processedheight))

if err != nil {
return err
} else if height != processedheight+i {
Expand Down Expand Up @@ -419,6 +439,64 @@ loop:
}
}

func (icp *IconChainProcessor) verifyBlock(ctx context.Context, ibcHeader provider.IBCHeader) error {
header, ok := ibcHeader.(IconIBCHeader)
if !ok {
return fmt.Errorf("Provided Header is not compatible with IBCHeader")
}
if icp.firstTime {
proofContext, err := icp.chainProvider.GetProofContextByHeight(int64(header.MainHeight) - 1)
if err != nil {
return err
}
icp.verifier = &Verifier{
nextProofContext: proofContext,
verifiedHeight: int64(header.MainHeight) - 1,
}

Check warning on line 455 in relayer/chains/icon/icon_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/icon_chain_processor.go#L442-L455

Added lines #L442 - L455 were not covered by tests
}

if !ibcHeader.IsCompleteBlock() {
icp.verifier.nextProofContext = header.Validators
icp.verifier.verifiedHeight = int64(header.Height())
return nil
}

Check warning on line 462 in relayer/chains/icon/icon_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/icon_chain_processor.go#L458-L462

Added lines #L458 - L462 were not covered by tests

// prevNetworkSectionHash would be nil for first block
if icp.verifier.prevNetworkSectionHash != nil &&
!bytes.Equal(icp.verifier.prevNetworkSectionHash, header.Header.PrevNetworkSectionHash) {
return fmt.Errorf("failed to match prevNetworkSectionHash")
}

Check warning on line 468 in relayer/chains/icon/icon_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/icon_chain_processor.go#L465-L468

Added lines #L465 - L468 were not covered by tests

sigs, err := icp.chainProvider.GetBTPProof(int64(header.MainHeight))
if err != nil {
return err
}

Check warning on line 473 in relayer/chains/icon/icon_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/icon_chain_processor.go#L470-L473

Added lines #L470 - L473 were not covered by tests

decision := types.NewNetworkTypeSectionDecision(
getSrcNetworkId(icp.chainProvider.PCfg.ICONNetworkID),
icp.chainProvider.PCfg.BTPNetworkTypeID,
int64(header.MainHeight),
header.Header.Round,
types.NetworkTypeSection{
NextProofContextHash: header.Header.NextProofContextHash,
NetworkSectionsRoot: GetNetworkSectionRoot(header.Header),
})

valid, err := VerifyBtpProof(decision, sigs, icp.verifier.nextProofContext)
if err != nil {
return err
}

Check warning on line 488 in relayer/chains/icon/icon_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/icon_chain_processor.go#L475-L488

Added lines #L475 - L488 were not covered by tests

if !valid {
return fmt.Errorf("failed to Verify block")
}

Check warning on line 492 in relayer/chains/icon/icon_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/icon_chain_processor.go#L490-L492

Added lines #L490 - L492 were not covered by tests

icp.verifier.nextProofContext = header.Validators
icp.verifier.verifiedHeight = int64(header.Height())
icp.verifier.prevNetworkSectionHash = types.NewNetworkSection(header.Header).Hash()
return nil

Check warning on line 497 in relayer/chains/icon/icon_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/icon_chain_processor.go#L494-L497

Added lines #L494 - L497 were not covered by tests
}

func (icp *IconChainProcessor) handleBTPBlockRequest(
request *btpBlockRequest, requestCh chan *btpBlockRequest) {
defer func() {
Expand Down Expand Up @@ -563,9 +641,9 @@ func (icp *IconChainProcessor) handlePathProcessorUpdate(ctx context.Context,
// clientState will return the most recent client state if client messages
// have already been observed for the clientID, otherwise it will query for it.
func (icp *IconChainProcessor) clientState(ctx context.Context, clientID string) (provider.ClientState, error) {
// if state, ok := icp.latestClientState[clientID]; ok {
// return state, nil
// }
if state, ok := icp.latestClientState[clientID]; ok {
return state, nil
}

Check warning on line 646 in relayer/chains/icon/icon_chain_processor.go

View check run for this annotation

Codecov / codecov/patch

relayer/chains/icon/icon_chain_processor.go#L644-L646

Added lines #L644 - L646 were not covered by tests
cs, err := icp.chainProvider.QueryClientStateWithoutProof(ctx, int64(icp.latestBlock.Height), clientID)
if err != nil {
return provider.ClientState{}, err
Expand Down
4 changes: 4 additions & 0 deletions relayer/chains/icon/module/app_module.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ func (AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry)
(*MerkleProofState)(nil),
&icon.MerkleProofs{},
)
registry.RegisterImplementations(
(*exported.ClientMessage)(nil),
&icon.SignedHeader{},
)

}

Expand Down
50 changes: 39 additions & 11 deletions relayer/chains/icon/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func GetMockIconProvider(network_id int, contractAddress string) *IconProvider {
BTPNetworkTypeID: 1,
IbcHandlerAddress: contractAddress,
RPCAddr: "http://localhost:9082/api/v3",
// RPCAddr: "http://localhost:9999",
// RPCAddr: "https://berlin.net.solidwallet.io/api/v3",
Timeout: "20s",
}
log, _ := zap.NewProduction()
Expand Down Expand Up @@ -431,13 +431,41 @@ func TestHash(t *testing.T) {
// assert.Equal(common.Sha3keccak256(b))
}

// goloop rpc sendtx call \
// --uri http://localhost:9082/api/v3 \
// --nid 3 \
// --step_limit 1000000000\
// --to cxc3c1f693b1616860d9f709d9c85b5f613ea2dbdb \
// --method sendCallMessage \
// --param _to=eth \
// --param _data=0x6e696c696e \
// --key_store /Users/viveksharmapoudel/keystore/godWallet.json \
// --key_password gochain
// func TestUpdateClientHeader(t *testing.T) {

// p := GetMockIconProvider(2, "dddd")

// height := int64(401)
// header, _ := p.GetBtpHeader(height)
// proofContext, _ := p.GetProofContextByHeight(height - 1)

// cs, _ := p.MsgUpdateClientHeader(NewIconIBCHeader(header, proofContext, height), clienttypes.Height{}, nil)

// signedHeader, ok := cs.(*icon.SignedHeader)
// assert.True(t, ok)

// btpLocalHeader := types.BTPBlockHeader{
// MainHeight: signedHeader.Header.MainHeight,
// Round: int32(signedHeader.Header.Round),
// NextProofContextHash: signedHeader.Header.NextProofContextHash,
// NetworkSectionToRoot: signedHeader.Header.NetworkSectionToRoot,
// NetworkID: signedHeader.Header.NetworkId,
// UpdateNumber: header.UpdateNumber,
// PrevNetworkSectionHash: signedHeader.Header.PrevNetworkSectionHash,
// MessageCount: signedHeader.Header.MessageCount,
// MessageRoot: signedHeader.Header.MessageRoot,
// // NextProofContext: signedHeader.Header.NextProofContext,
// }
// networkSection := types.NewNetworkSection(&btpLocalHeader)
// fmt.Printf("newtworkSection :%x \n", networkSection.Hash())
// decision := types.NewNetworkTypeSectionDecision(getSrcNetworkId(3), 1, height, btpLocalHeader.Round,
// types.NetworkTypeSection{
// NextProofContextHash: btpLocalHeader.NextProofContextHash,
// NetworkSectionsRoot: GetNetworkSectionRoot(&btpLocalHeader),
// })

// isValid, err := VerifyBtpProof(decision, signedHeader.Signatures, proofContext)
// assert.NoError(t, err)

// assert.True(t, isValid)
// }
Loading

0 comments on commit a5137d5

Please sign in to comment.