From 50ad9c54616cd7f57492a2eaf479f3f9e427d2f4 Mon Sep 17 00:00:00 2001 From: sh-cha Date: Wed, 25 Sep 2024 18:37:24 +0900 Subject: [PATCH] change block height from uint64 to int64 & lint --- challenger/challenger.go | 6 +-- challenger/child/child.go | 8 ++-- challenger/child/deposit.go | 4 +- challenger/child/handler.go | 6 +-- challenger/child/oracle.go | 4 +- challenger/child/status.go | 6 +-- challenger/child/withdraw.go | 14 +++---- challenger/host/deposit.go | 2 +- challenger/host/handler.go | 2 +- challenger/host/host.go | 2 +- challenger/host/oracle.go | 2 +- challenger/host/output.go | 4 +- challenger/types/challenge.go | 16 ++++---- challenger/types/keys.go | 3 +- client/client.go | 12 +----- db/types/utils.go | 7 ++-- executor/batch/batch.go | 8 ++-- executor/batch/handler.go | 48 ++++++++++++------------ executor/batch/status.go | 4 +- executor/celestia/celestia.go | 12 ++++-- executor/child/child.go | 19 ++++------ executor/child/deposit.go | 4 +- executor/child/handler.go | 4 +- executor/child/oracle.go | 4 +- executor/child/status.go | 6 +-- executor/child/withdraw.go | 15 ++++---- executor/executor.go | 6 +-- executor/host/batch.go | 2 +- executor/host/deposit.go | 2 +- executor/host/handler.go | 2 +- executor/host/host.go | 15 +++----- executor/host/oracle.go | 2 +- executor/host/status.go | 2 +- executor/host/withdraw.go | 4 +- executor/types/batch.go | 11 ++++-- executor/types/config.go | 36 ++++++++++++++---- executor/types/db.go | 2 +- executor/types/query.go | 2 +- merkle/merkle.go | 8 ++-- node/broadcaster/broadcaster.go | 4 +- node/broadcaster/db.go | 4 +- node/broadcaster/process.go | 4 +- node/broadcaster/types/db.go | 2 +- node/db.go | 18 ++++----- node/node.go | 6 +-- node/process.go | 20 +++++----- node/rpcclient/client.go | 8 ++-- node/types/handler.go | 20 +++++----- node/types/status.go | 2 +- provider/child/child.go | 13 ++++--- provider/child/msgs.go | 9 +++-- provider/child/parse.go | 9 +++-- provider/child/query.go | 4 +- provider/child/tree.go | 2 +- provider/host/host.go | 6 +-- provider/host/msgs.go | 5 ++- provider/host/parse.go | 11 ++++-- provider/host/query.go | 13 ++++--- types/math.go | 66 +++++++++++++++++++++++++++++++++ 59 files changed, 316 insertions(+), 226 deletions(-) create mode 100644 types/math.go diff --git a/challenger/challenger.go b/challenger/challenger.go index ee55087..1579951 100644 --- a/challenger/challenger.go +++ b/challenger/challenger.go @@ -192,7 +192,7 @@ func (c *Challenger) RegisterQuerier() { }) } -func (c *Challenger) getStartHeights(ctx context.Context, bridgeId uint64) (l1StartHeight uint64, l2StartHeight uint64, startOutputIndex uint64, err error) { +func (c *Challenger) getStartHeights(ctx context.Context, bridgeId uint64) (l1StartHeight int64, l2StartHeight int64, startOutputIndex uint64, err error) { // get the bridge start height from the host l1StartHeight, err = c.host.QueryCreateBridgeHeight(ctx, bridgeId) if err != nil { @@ -205,8 +205,8 @@ func (c *Challenger) getStartHeights(ctx context.Context, bridgeId uint64) (l1St if err != nil { return 0, 0, 0, err } else if output != nil { - l1StartHeight = output.OutputProposal.L1BlockNumber - l2StartHeight = output.OutputProposal.L2BlockNumber + l1StartHeight = types.MustUint64ToInt64(output.OutputProposal.L1BlockNumber) + l2StartHeight = types.MustUint64ToInt64(output.OutputProposal.L2BlockNumber) startOutputIndex = output.OutputIndex + 1 } } diff --git a/challenger/child/child.go b/challenger/child/child.go index eff9d88..fc91ac0 100644 --- a/challenger/child/child.go +++ b/challenger/child/child.go @@ -35,11 +35,11 @@ type Child struct { eventQueue []challengertypes.ChallengeEvent - finalizingBlockHeight uint64 + finalizingBlockHeight int64 // status info - lastUpdatedOracleL1Height uint64 - lastFinalizedDepositL1BlockHeight uint64 + lastUpdatedOracleL1Height int64 + lastFinalizedDepositL1BlockHeight int64 lastFinalizedDepositL1Sequence uint64 lastOutputTime time.Time nextOutputTime time.Time @@ -56,7 +56,7 @@ func NewChildV1( } } -func (ch *Child) Initialize(ctx context.Context, startHeight uint64, startOutputIndex uint64, host hostNode, bridgeInfo opchildtypes.BridgeInfo, challenger challenger) error { +func (ch *Child) Initialize(ctx context.Context, startHeight int64, startOutputIndex uint64, host hostNode, bridgeInfo opchildtypes.BridgeInfo, challenger challenger) error { _, err := ch.BaseChild.Initialize(ctx, startHeight, startOutputIndex, bridgeInfo) if err != nil { return err diff --git a/challenger/child/deposit.go b/challenger/child/deposit.go index 0e2e2a1..cbfc54c 100644 --- a/challenger/child/deposit.go +++ b/challenger/child/deposit.go @@ -24,12 +24,12 @@ func (ch *Child) finalizeDepositHandler(_ context.Context, args nodetypes.EventH return nil } -func (ch *Child) handleFinalizeDeposit(l2BlockTime time.Time, l1BlockHeight uint64, l1Sequence uint64, from string, to string, amount sdk.Coin, baseDenom string) { +func (ch *Child) handleFinalizeDeposit(l2BlockTime time.Time, l1BlockHeight int64, l1Sequence uint64, from string, to string, amount sdk.Coin, baseDenom string) { deposit := challengertypes.NewDeposit(l1Sequence, l1BlockHeight, from, to, baseDenom, amount.String(), l2BlockTime) ch.eventQueue = append(ch.eventQueue, deposit) ch.Logger().Info("finalize token deposit", - zap.Uint64("l1_blockHeight", l1BlockHeight), + zap.Int64("l1_blockHeight", l1BlockHeight), zap.Uint64("l1_sequence", l1Sequence), zap.String("from", from), zap.String("to", to), diff --git a/challenger/child/handler.go b/challenger/child/handler.go index aeb85f4..c089aaa 100644 --- a/challenger/child/handler.go +++ b/challenger/child/handler.go @@ -12,7 +12,7 @@ import ( ) func (ch *Child) beginBlockHandler(ctx context.Context, args nodetypes.BeginBlockArgs) (err error) { - blockHeight := uint64(args.Block.Header.Height) + blockHeight := args.Block.Header.Height ch.eventQueue = ch.eventQueue[:0] err = ch.prepareTree(blockHeight) @@ -28,7 +28,7 @@ func (ch *Child) beginBlockHandler(ctx context.Context, args nodetypes.BeginBloc } func (ch *Child) endBlockHandler(_ context.Context, args nodetypes.EndBlockArgs) error { - blockHeight := uint64(args.Block.Header.Height) + blockHeight := args.Block.Header.Height batchKVs := make([]types.RawKV, 0) pendingChallenges := make([]challengertypes.Challenge, 0) @@ -109,6 +109,6 @@ func (ch *Child) txHandler(_ context.Context, args nodetypes.TxHandlerArgs) erro if !ok { return nil } - ch.oracleTxHandler(args.BlockTime, msg.Sender, msg.Height, msg.Data) + ch.oracleTxHandler(args.BlockTime, msg.Sender, types.MustUint64ToInt64(msg.Height), msg.Data) return nil } diff --git a/challenger/child/oracle.go b/challenger/child/oracle.go index d72476c..c34687f 100644 --- a/challenger/child/oracle.go +++ b/challenger/child/oracle.go @@ -8,14 +8,14 @@ import ( "go.uber.org/zap" ) -func (ch *Child) oracleTxHandler(blockTime time.Time, sender string, l1BlockHeight uint64, oracleDataBytes comettypes.Tx) { +func (ch *Child) oracleTxHandler(blockTime time.Time, sender string, l1BlockHeight int64, oracleDataBytes comettypes.Tx) { checksum := challengertypes.OracleChecksum(oracleDataBytes) oracle := challengertypes.NewOracle(l1BlockHeight, checksum, blockTime) ch.eventQueue = append(ch.eventQueue, oracle) ch.lastUpdatedOracleL1Height = l1BlockHeight ch.Logger().Info("update oracle", - zap.Uint64("l1_blockHeight", l1BlockHeight), + zap.Int64("l1_blockHeight", l1BlockHeight), zap.String("from", sender), ) } diff --git a/challenger/child/status.go b/challenger/child/status.go index fe35a50..5d6c2e3 100644 --- a/challenger/child/status.go +++ b/challenger/child/status.go @@ -9,13 +9,13 @@ import ( type Status struct { Node nodetypes.Status `json:"node"` - LastUpdatedOracleL1Height uint64 `json:"last_updated_oracle_height"` - LastFinalizedDepositL1BlockHeight uint64 `json:"last_finalized_deposit_l1_block_height"` + LastUpdatedOracleL1Height int64 `json:"last_updated_oracle_height"` + LastFinalizedDepositL1BlockHeight int64 `json:"last_finalized_deposit_l1_block_height"` LastFinalizedDepositL1Sequence uint64 `json:"last_finalized_deposit_l1_sequence"` LastWithdrawalL2Sequence uint64 `json:"last_withdrawal_l2_sequence"` WorkingTreeIndex uint64 `json:"working_tree_index"` - FinalizingBlockHeight uint64 `json:"finalizing_block_height"` + FinalizingBlockHeight int64 `json:"finalizing_block_height"` LastOutputSubmissionTime time.Time `json:"last_output_submission_time"` NextOutputSubmissionTime time.Time `json:"next_output_submission_time"` diff --git a/challenger/child/withdraw.go b/challenger/child/withdraw.go index a33246a..e8af9b8 100644 --- a/challenger/child/withdraw.go +++ b/challenger/child/withdraw.go @@ -73,12 +73,12 @@ func (ch *Child) handleInitiateWithdrawal(l2Sequence uint64, from string, to str return nil } -func (ch *Child) prepareTree(blockHeight uint64) error { +func (ch *Child) prepareTree(blockHeight int64) error { if ch.InitializeTree(blockHeight) { return nil } - err := ch.Merkle().LoadWorkingTree(blockHeight - 1) + err := ch.Merkle().LoadWorkingTree(types.MustInt64ToUint64(blockHeight - 1)) if err == dbtypes.ErrNotFound { // must not happened panic(fmt.Errorf("working tree not found at height: %d, current: %d", blockHeight-1, blockHeight)) @@ -110,12 +110,12 @@ func (ch *Child) prepareOutput(ctx context.Context) error { return err } else { ch.nextOutputTime = output.OutputProposal.L1BlockTime - ch.finalizingBlockHeight = output.OutputProposal.L2BlockNumber + ch.finalizingBlockHeight = types.MustUint64ToInt64(output.OutputProposal.L2BlockNumber) } return nil } -func (ch *Child) handleTree(blockHeight uint64, blockHeader cmtproto.Header) (kvs []types.RawKV, storageRoot []byte, err error) { +func (ch *Child) handleTree(blockHeight int64, blockHeader cmtproto.Header) (kvs []types.RawKV, storageRoot []byte, err error) { // panic if we passed the finalizing block height // this must not happened if ch.finalizingBlockHeight != 0 && ch.finalizingBlockHeight < blockHeight { @@ -130,7 +130,7 @@ func (ch *Child) handleTree(blockHeight uint64, blockHeader cmtproto.Header) (kv ch.Logger().Info("finalize working tree", zap.Uint64("tree_index", ch.Merkle().GetWorkingTreeIndex()), - zap.Uint64("height", blockHeight), + zap.Int64("height", blockHeight), zap.Uint64("num_leaves", ch.Merkle().GetWorkingTreeLeafCount()), zap.String("storage_root", base64.StdEncoding.EncodeToString(storageRoot)), ) @@ -139,7 +139,7 @@ func (ch *Child) handleTree(blockHeight uint64, blockHeader cmtproto.Header) (kv ch.lastOutputTime = blockHeader.Time } - err = ch.Merkle().SaveWorkingTree(blockHeight) + err = ch.Merkle().SaveWorkingTree(types.MustInt64ToUint64(blockHeight)) if err != nil { return nil, nil, err } @@ -147,7 +147,7 @@ func (ch *Child) handleTree(blockHeight uint64, blockHeader cmtproto.Header) (kv return kvs, storageRoot, nil } -func (ch *Child) handleOutput(blockTime time.Time, blockHeight uint64, version uint8, blockId []byte, outputIndex uint64, storageRoot []byte) error { +func (ch *Child) handleOutput(blockTime time.Time, blockHeight int64, version uint8, blockId []byte, outputIndex uint64, storageRoot []byte) error { outputRoot := ophosttypes.GenerateOutputRoot(version, storageRoot, blockId) output := challengertypes.NewOutput(blockHeight, outputIndex, outputRoot[:], blockTime) diff --git a/challenger/host/deposit.go b/challenger/host/deposit.go index e84030c..2fadf2a 100644 --- a/challenger/host/deposit.go +++ b/challenger/host/deposit.go @@ -38,7 +38,7 @@ func (h *Host) initiateDepositHandler(_ context.Context, args nodetypes.EventHan func (h *Host) handleInitiateDeposit( l1Sequence uint64, - blockHeight uint64, + blockHeight int64, blockTime time.Time, from string, to string, diff --git a/challenger/host/handler.go b/challenger/host/handler.go index 337b7ff..8cb0e7f 100644 --- a/challenger/host/handler.go +++ b/challenger/host/handler.go @@ -15,7 +15,7 @@ func (h *Host) beginBlockHandler(_ context.Context, args nodetypes.BeginBlockArg } func (h *Host) endBlockHandler(_ context.Context, args nodetypes.EndBlockArgs) error { - blockHeight := uint64(args.Block.Header.Height) + blockHeight := args.Block.Header.Height batchKVs := []types.RawKV{ h.Node().SyncInfoToRawKV(blockHeight), } diff --git a/challenger/host/host.go b/challenger/host/host.go index fc4caf8..a86863a 100644 --- a/challenger/host/host.go +++ b/challenger/host/host.go @@ -55,7 +55,7 @@ func NewHostV1( } } -func (h *Host) Initialize(ctx context.Context, startHeight uint64, child childNode, bridgeInfo opchildtypes.BridgeInfo, challenger challenger) error { +func (h *Host) Initialize(ctx context.Context, startHeight int64, child childNode, bridgeInfo opchildtypes.BridgeInfo, challenger challenger) error { err := h.BaseHost.Initialize(ctx, startHeight, bridgeInfo) if err != nil { return err diff --git a/challenger/host/oracle.go b/challenger/host/oracle.go index 07cadb5..98fd00b 100644 --- a/challenger/host/oracle.go +++ b/challenger/host/oracle.go @@ -8,7 +8,7 @@ import ( challengertypes "github.com/initia-labs/opinit-bots/challenger/types" ) -func (h *Host) oracleTxHandler(blockHeight uint64, blockTime time.Time, oracleDataBytes comettypes.Tx) { +func (h *Host) oracleTxHandler(blockHeight int64, blockTime time.Time, oracleDataBytes comettypes.Tx) { if !h.OracleEnabled() { return } diff --git a/challenger/host/output.go b/challenger/host/output.go index 70eefd2..8636df7 100644 --- a/challenger/host/output.go +++ b/challenger/host/output.go @@ -24,7 +24,7 @@ func (h *Host) proposeOutputHandler(_ context.Context, args nodetypes.EventHandl return h.handleProposeOutput(bridgeId, proposer, outputIndex, l2BlockNumber, outputRoot, args.BlockTime) } -func (h *Host) handleProposeOutput(bridgeId uint64, proposer string, outputIndex uint64, l2BlockNumber uint64, outputRoot []byte, blockTime time.Time) error { +func (h *Host) handleProposeOutput(bridgeId uint64, proposer string, outputIndex uint64, l2BlockNumber int64, outputRoot []byte, blockTime time.Time) error { output := challengertypes.NewOutput(l2BlockNumber, outputIndex, outputRoot[:], blockTime) h.lastOutputIndex = outputIndex @@ -36,7 +36,7 @@ func (h *Host) handleProposeOutput(bridgeId uint64, proposer string, outputIndex zap.Uint64("bridge_id", bridgeId), zap.String("proposer", proposer), zap.Uint64("output_index", outputIndex), - zap.Uint64("l2_block_number", l2BlockNumber), + zap.Int64("l2_block_number", l2BlockNumber), zap.String("output_root", base64.StdEncoding.EncodeToString(outputRoot)), ) return nil diff --git a/challenger/types/challenge.go b/challenger/types/challenge.go index cab7b64..415e112 100644 --- a/challenger/types/challenge.go +++ b/challenger/types/challenge.go @@ -6,6 +6,8 @@ import ( "encoding/json" "fmt" "time" + + "github.com/initia-labs/opinit-bots/types" ) type Challenge struct { @@ -94,7 +96,7 @@ func (e EventType) String() string { type Deposit struct { EventType string `json:"event_type"` Sequence uint64 `json:"sequence"` - L1BlockHeight uint64 `json:"l1_block_height"` + L1BlockHeight int64 `json:"l1_block_height"` From string `json:"from"` To string `json:"to"` L1Denom string `json:"l1_denom"` @@ -105,7 +107,7 @@ type Deposit struct { var _ ChallengeEvent = &Deposit{} -func NewDeposit(sequence, l1BlockHeight uint64, from, to, l1Denom, amount string, time time.Time) *Deposit { +func NewDeposit(sequence uint64, l1BlockHeight int64, from, to, l1Denom, amount string, time time.Time) *Deposit { d := &Deposit{ Sequence: sequence, L1BlockHeight: l1BlockHeight, @@ -169,7 +171,7 @@ func (d Deposit) IsTimeout() bool { type Output struct { EventType string `json:"event_type"` - L2BlockNumber uint64 `json:"l2_block_number"` + L2BlockNumber int64 `json:"l2_block_number"` OutputIndex uint64 `json:"output_index"` OutputRoot []byte `json:"output_root"` Time time.Time `json:"time"` @@ -178,7 +180,7 @@ type Output struct { var _ ChallengeEvent = &Output{} -func NewOutput(l2BlockNumber, outputIndex uint64, outputRoot []byte, time time.Time) *Output { +func NewOutput(l2BlockNumber int64, outputIndex uint64, outputRoot []byte, time time.Time) *Output { o := &Output{ L2BlockNumber: l2BlockNumber, OutputIndex: outputIndex, @@ -235,13 +237,13 @@ func (o Output) IsTimeout() bool { type Oracle struct { EventType string `json:"event_type"` - L1Height uint64 `json:"l1_height"` + L1Height int64 `json:"l1_height"` Data []byte `json:"data"` Time time.Time `json:"time"` Timeout bool `json:"timeout"` } -func NewOracle(l1Height uint64, data []byte, time time.Time) *Oracle { +func NewOracle(l1Height int64, data []byte, time time.Time) *Oracle { o := &Oracle{ L1Height: l1Height, Data: data, @@ -283,7 +285,7 @@ func (o Oracle) EventTime() time.Time { func (o Oracle) Id() ChallengeId { return ChallengeId{ Type: EventTypeOracle, - Id: o.L1Height, + Id: types.MustInt64ToUint64(o.L1Height), } } diff --git a/challenger/types/keys.go b/challenger/types/keys.go index b4e0160..c7baf7b 100644 --- a/challenger/types/keys.go +++ b/challenger/types/keys.go @@ -4,6 +4,7 @@ import ( "time" dbtypes "github.com/initia-labs/opinit-bots/db/types" + "github.com/initia-labs/opinit-bots/types" "github.com/pkg/errors" ) @@ -34,7 +35,7 @@ func PrefixedPendingChallenge(id ChallengeId) []byte { } func PrefixedTimeEventTypeId(eventTime time.Time, id ChallengeId) []byte { - return append(append(dbtypes.FromUint64Key(uint64(eventTime.UnixNano())), dbtypes.Splitter), + return append(append(dbtypes.FromUint64Key(types.MustInt64ToUint64(eventTime.UnixNano())), dbtypes.Splitter), PrefixedEventTypeId(id.Type, id.Id)...) } diff --git a/client/client.go b/client/client.go index c4ee33a..8c408f1 100644 --- a/client/client.go +++ b/client/client.go @@ -120,16 +120,6 @@ func New(remote, wsEndpoint string) (*HTTP, error) { return NewWithClient(remote, wsEndpoint, httpClient) } -// Create timeout enabled http client -func NewWithTimeout(remote, wsEndpoint string, timeout uint) (*HTTP, error) { - httpClient, err := jsonrpcclient.DefaultHTTPClient(remote) - if err != nil { - return nil, err - } - httpClient.Timeout = time.Duration(timeout) * time.Second - return NewWithClient(remote, wsEndpoint, httpClient) -} - // NewWithClient allows for setting a custom http client (See New). // An error is returned on invalid remote. The function panics when remote is nil. func NewWithClient(remote, wsEndpoint string, client *http.Client) (*HTTP, error) { @@ -421,7 +411,7 @@ func (c *baseRPCClient) Block(ctx context.Context, height *int64) (*ctypes.Resul return result, nil } -func (c *baseRPCClient) BlockBulk(ctx context.Context, start *uint64, end *uint64) ([][]byte, error) { +func (c *baseRPCClient) BlockBulk(ctx context.Context, start *int64, end *int64) ([][]byte, error) { result := new(ResultBlockBulk) params := make(map[string]interface{}) if start != nil { diff --git a/db/types/utils.go b/db/types/utils.go index 11e7003..e2771a5 100644 --- a/db/types/utils.go +++ b/db/types/utils.go @@ -12,13 +12,12 @@ func FromInt64(v int64) []byte { return []byte(fmt.Sprintf("%d", v)) } -func ToInt64(v []byte) int64 { +func ToInt64(v []byte) (int64, error) { data, err := strconv.ParseInt(string(v), 10, 64) if err != nil { - // must not happen - panic(err) + return 0, fmt.Errorf("failed to parse uint64 from %s: %w", string(v), err) } - return data + return data, nil } func FromUint64(v uint64) []byte { diff --git a/executor/batch/batch.go b/executor/batch/batch.go index b9ef691..de8bc7f 100644 --- a/executor/batch/batch.go +++ b/executor/batch/batch.go @@ -52,7 +52,7 @@ type BatchSubmitter struct { homePath string // status info - LastBatchEndBlockNumber uint64 + LastBatchEndBlockNumber int64 } func NewBatchSubmitterV1( @@ -96,7 +96,7 @@ func NewBatchSubmitterV1( return ch } -func (bs *BatchSubmitter) Initialize(ctx context.Context, startHeight uint64, host hostNode, bridgeInfo opchildtypes.BridgeInfo) error { +func (bs *BatchSubmitter) Initialize(ctx context.Context, startHeight int64, host hostNode, bridgeInfo opchildtypes.BridgeInfo) error { err := bs.node.Initialize(ctx, startHeight) if err != nil { return err @@ -113,7 +113,7 @@ func (bs *BatchSubmitter) Initialize(ctx context.Context, startHeight uint64, ho return errors.New("no batch info") } for _, batchInfo := range bs.batchInfos { - if len(bs.batchInfos) == 1 || (batchInfo.Output.L2BlockNumber+1) >= bs.node.GetHeight() { + if len(bs.batchInfos) == 1 || types.MustUint64ToInt64(batchInfo.Output.L2BlockNumber+1) >= bs.node.GetHeight() { break } bs.DequeueBatchInfo() @@ -164,7 +164,7 @@ func (bs *BatchSubmitter) SetDANode(da executortypes.DANode) error { } func (bs *BatchSubmitter) Start(ctx context.Context) { - bs.logger.Info("batch start", zap.Uint64("height", bs.node.GetHeight())) + bs.logger.Info("batch start", zap.Int64("height", bs.node.GetHeight())) bs.node.Start(ctx) } diff --git a/executor/batch/handler.go b/executor/batch/handler.go index 8181be5..a3b150f 100644 --- a/executor/batch/handler.go +++ b/executor/batch/handler.go @@ -80,14 +80,14 @@ func (bs *BatchSubmitter) rawBlockHandler(ctx context.Context, args nodetypes.Ra return nil } -func (bs *BatchSubmitter) prepareBatch(blockHeight uint64) error { +func (bs *BatchSubmitter) prepareBatch(blockHeight int64) error { err := bs.loadLocalBatchInfo() if err != nil { return err } // check whether the requested block height is reached to the l2 block number of the next batch info. - if nextBatchInfo := bs.NextBatchInfo(); nextBatchInfo != nil && nextBatchInfo.Output.L2BlockNumber < blockHeight { + if nextBatchInfo := bs.NextBatchInfo(); nextBatchInfo != nil && types.MustUint64ToInt64(nextBatchInfo.Output.L2BlockNumber) < blockHeight { // if the next batch info is reached, finalize the current batch and update the batch info. if bs.batchWriter != nil { err := bs.batchWriter.Close() @@ -105,11 +105,11 @@ func (bs *BatchSubmitter) prepareBatch(blockHeight uint64) error { } // save sync info - err = bs.node.SaveSyncInfo(nextBatchInfo.Output.L2BlockNumber) + err = bs.node.SaveSyncInfo(types.MustUint64ToInt64(nextBatchInfo.Output.L2BlockNumber)) if err != nil { return errors.Wrap(err, "failed to save sync info") } - bs.localBatchInfo.Start = nextBatchInfo.Output.L2BlockNumber + 1 + bs.localBatchInfo.Start = types.MustUint64ToInt64(nextBatchInfo.Output.L2BlockNumber) + 1 bs.localBatchInfo.End = 0 bs.localBatchInfo.BatchFileSize = 0 err = bs.saveLocalBatchInfo() @@ -117,7 +117,7 @@ func (bs *BatchSubmitter) prepareBatch(blockHeight uint64) error { return err } // set last processed block height to l2 block number - bs.node.SetSyncInfo(nextBatchInfo.Output.L2BlockNumber) + bs.node.SetSyncInfo(types.MustUint64ToInt64(nextBatchInfo.Output.L2BlockNumber)) bs.DequeueBatchInfo() // error will restart block process from nextBatchInfo.Output.L2BlockNumber + 1 @@ -150,9 +150,9 @@ func (bs *BatchSubmitter) handleBatch(blockBytes []byte) (int, error) { } // finalize batch and create batch messages -func (bs *BatchSubmitter) finalizeBatch(ctx context.Context, blockHeight uint64) error { +func (bs *BatchSubmitter) finalizeBatch(ctx context.Context, blockHeight int64) error { // write last block's commit to batch file - rawCommit, err := bs.node.GetRPCClient().QueryRawCommit(ctx, int64(blockHeight)) + rawCommit, err := bs.node.GetRPCClient().QueryRawCommit(ctx, blockHeight) if err != nil { return errors.Wrap(err, "failed to query raw commit") } @@ -189,15 +189,15 @@ func (bs *BatchSubmitter) finalizeBatch(ctx context.Context, blockHeight uint64) checksum := executortypes.GetChecksumFromChunk(chunk) checksums = append(checksums, checksum[:]) - if uint64(readLength) < bs.batchCfg.MaxChunkSize { + if int64(readLength) < bs.batchCfg.MaxChunkSize { break } offset += int64(readLength) } headerData := executortypes.MarshalBatchDataHeader( - bs.localBatchInfo.Start, - bs.localBatchInfo.End, + types.MustInt64ToUint64(bs.localBatchInfo.Start), + types.MustInt64ToUint64(bs.localBatchInfo.End), checksums, ) @@ -213,10 +213,10 @@ func (bs *BatchSubmitter) finalizeBatch(ctx context.Context, blockHeight uint64) for i, chunk := range chunks { chunkData := executortypes.MarshalBatchDataChunk( - bs.localBatchInfo.Start, - bs.localBatchInfo.End, - uint64(i), - uint64(len(checksums)), + types.MustInt64ToUint64(bs.localBatchInfo.Start), + types.MustInt64ToUint64(bs.localBatchInfo.End), + types.MustInt64ToUint64(int64(i)), + types.MustInt64ToUint64(int64(len(checksums))), chunk, ) msg, err := bs.da.CreateBatchMsg(chunkData) @@ -231,30 +231,30 @@ func (bs *BatchSubmitter) finalizeBatch(ctx context.Context, blockHeight uint64) } bs.logger.Info("finalize batch", - zap.Uint64("height", blockHeight), - zap.Uint64("batch start", bs.localBatchInfo.Start), - zap.Uint64("batch end", bs.localBatchInfo.End), - zap.Uint64("batch file size ", uint64(bs.localBatchInfo.BatchFileSize)), + zap.Int64("height", blockHeight), + zap.Int64("batch start", bs.localBatchInfo.Start), + zap.Int64("batch end", bs.localBatchInfo.End), + zap.Int64("batch file size ", bs.localBatchInfo.BatchFileSize), zap.Int("chunks", len(checksums)), zap.Int("txs", len(bs.processedMsgs)), ) return nil } -func (bs *BatchSubmitter) checkBatch(ctx context.Context, blockHeight uint64, latestHeight uint64, blockTime time.Time) error { +func (bs *BatchSubmitter) checkBatch(ctx context.Context, blockHeight int64, latestHeight int64, blockTime time.Time) error { fileSize, err := bs.batchFileSize(true) if err != nil { return err } - bs.localBatchInfo.BatchFileSize = fileSize + bs.localBatchInfo.BatchFileSize = fileSize // if the block time is after the last submission time + submission interval * 2/3 // or the block time is after the last submission time + max submission time // or the batch file size is greater than (max chunks - 1) * max chunk size // then finalize the batch if (blockHeight == latestHeight && blockTime.After(bs.localBatchInfo.LastSubmissionTime.Add(bs.bridgeInfo.BridgeConfig.SubmissionInterval*2/3))) || (blockHeight == latestHeight && blockTime.After(bs.localBatchInfo.LastSubmissionTime.Add(time.Duration(bs.batchCfg.MaxSubmissionTime)*time.Second))) || - uint64(fileSize) > (bs.batchCfg.MaxChunks-1)*bs.batchCfg.MaxChunkSize { + fileSize > (bs.batchCfg.MaxChunks-1)*bs.batchCfg.MaxChunkSize { // finalize the batch bs.LastBatchEndBlockNumber = blockHeight @@ -288,12 +288,12 @@ func (bs *BatchSubmitter) batchFileSize(flush bool) (int64, error) { } // UpdateBatchInfo appends the batch info with the given chain, submitter, output index, and l2 block number -func (bs *BatchSubmitter) UpdateBatchInfo(chain string, submitter string, outputIndex uint64, l2BlockNumber uint64) { +func (bs *BatchSubmitter) UpdateBatchInfo(chain string, submitter string, outputIndex uint64, l2BlockNumber int64) { bs.batchInfoMu.Lock() defer bs.batchInfoMu.Unlock() // check if the batch info is already updated - if bs.batchInfos[len(bs.batchInfos)-1].Output.L2BlockNumber >= l2BlockNumber { + if types.MustUint64ToInt64(bs.batchInfos[len(bs.batchInfos)-1].Output.L2BlockNumber) >= l2BlockNumber { return } @@ -303,7 +303,7 @@ func (bs *BatchSubmitter) UpdateBatchInfo(chain string, submitter string, output Submitter: submitter, }, Output: ophosttypes.Output{ - L2BlockNumber: l2BlockNumber, + L2BlockNumber: types.MustInt64ToUint64(l2BlockNumber), }, }) } diff --git a/executor/batch/status.go b/executor/batch/status.go index 172dfb8..935c367 100644 --- a/executor/batch/status.go +++ b/executor/batch/status.go @@ -11,8 +11,8 @@ type Status struct { Node nodetypes.Status `json:"node"` BatchInfo ophosttypes.BatchInfo `json:"batch_info"` CurrentBatchFileSize int64 `json:"current_batch_file_size"` - BatchStartBlockNumber uint64 `json:"batch_start_block_number"` - BatchEndBlockNumber uint64 `json:"batch_end_block_number"` + BatchStartBlockNumber int64 `json:"batch_start_block_number"` + BatchEndBlockNumber int64 `json:"batch_end_block_number"` LastBatchSubmissionTime time.Time `json:"last_batch_submission_time"` } diff --git a/executor/celestia/celestia.go b/executor/celestia/celestia.go index 7a4ab4c..d60eaba 100644 --- a/executor/celestia/celestia.go +++ b/executor/celestia/celestia.go @@ -27,7 +27,7 @@ import ( type batchNode interface { ChainID() string - UpdateBatchInfo(chain string, submitter string, outputIndex uint64, l2BlockNumber uint64) + UpdateBatchInfo(string, string, uint64, int64) } var _ executortypes.DANode = &Celestia{} @@ -136,7 +136,7 @@ func (c Celestia) HasKey() bool { return c.node.HasBroadcaster() } -func (c Celestia) GetHeight() uint64 { +func (c Celestia) GetHeight() int64 { return c.node.GetHeight() } @@ -157,12 +157,18 @@ func (c Celestia) CreateBatchMsg(rawBlob []byte) (sdk.Msg, error) { if err != nil { return nil, err } + + dataLength, err := types.SafeIntToUint32(len(blob.Data())) + if err != nil { + return nil, err + } + return &celestiatypes.MsgPayForBlobsWithBlob{ MsgPayForBlobs: &celestiatypes.MsgPayForBlobs{ Signer: submitter, Namespaces: [][]byte{c.namespace.Bytes()}, ShareCommitments: [][]byte{commitment}, - BlobSizes: []uint32{uint32(len(blob.Data()))}, + BlobSizes: []uint32{dataLength}, ShareVersions: []uint32{uint32(blob.ShareVersion())}, }, Blob: &celestiatypes.Blob{ diff --git a/executor/child/child.go b/executor/child/child.go index 8148619..3250e8e 100644 --- a/executor/child/child.go +++ b/executor/child/child.go @@ -24,14 +24,9 @@ type hostNode interface { BroadcastMsgs(btypes.ProcessedMsgs) ProcessedMsgsToRawKV([]btypes.ProcessedMsgs, bool) ([]types.RawKV, error) QueryLastOutput(context.Context, uint64) (*ophosttypes.QueryOutputProposalResponse, error) - QueryOutput(context.Context, uint64, uint64, uint64) (*ophosttypes.QueryOutputProposalResponse, error) - - GetMsgProposeOutput( - bridgeId uint64, - outputIndex uint64, - l2BlockNumber uint64, - outputRoot []byte, - ) (sdk.Msg, error) + QueryOutput(context.Context, uint64, uint64, int64) (*ophosttypes.QueryOutputProposalResponse, error) + + GetMsgProposeOutput(uint64, uint64, int64, []byte) (sdk.Msg, error) } type Child struct { @@ -40,11 +35,11 @@ type Child struct { host hostNode nextOutputTime time.Time - finalizingBlockHeight uint64 + finalizingBlockHeight int64 // status info - lastUpdatedOracleL1Height uint64 - lastFinalizedDepositL1BlockHeight uint64 + lastUpdatedOracleL1Height int64 + lastFinalizedDepositL1BlockHeight int64 lastFinalizedDepositL1Sequence uint64 lastOutputTime time.Time } @@ -58,7 +53,7 @@ func NewChildV1( } } -func (ch *Child) Initialize(ctx context.Context, startHeight uint64, startOutputIndex uint64, host hostNode, bridgeInfo opchildtypes.BridgeInfo) error { +func (ch *Child) Initialize(ctx context.Context, startHeight int64, startOutputIndex uint64, host hostNode, bridgeInfo opchildtypes.BridgeInfo) error { l2Sequence, err := ch.BaseChild.Initialize(ctx, startHeight, startOutputIndex, bridgeInfo) if err != nil { return err diff --git a/executor/child/deposit.go b/executor/child/deposit.go index df85226..87b0522 100644 --- a/executor/child/deposit.go +++ b/executor/child/deposit.go @@ -21,9 +21,9 @@ func (ch *Child) finalizeDepositHandler(_ context.Context, args nodetypes.EventH return nil } -func (ch *Child) handleFinalizeDeposit(l1BlockHeight uint64, l1Sequence uint64, from string, to string, amount sdk.Coin, baseDenom string) { +func (ch *Child) handleFinalizeDeposit(l1BlockHeight int64, l1Sequence uint64, from string, to string, amount sdk.Coin, baseDenom string) { ch.Logger().Info("finalize token deposit", - zap.Uint64("l1_blockHeight", l1BlockHeight), + zap.Int64("l1_blockHeight", l1BlockHeight), zap.Uint64("l1_sequence", l1Sequence), zap.String("from", from), zap.String("to", to), diff --git a/executor/child/handler.go b/executor/child/handler.go index 0e8d648..58fea56 100644 --- a/executor/child/handler.go +++ b/executor/child/handler.go @@ -10,7 +10,7 @@ import ( ) func (ch *Child) beginBlockHandler(ctx context.Context, args nodetypes.BeginBlockArgs) (err error) { - blockHeight := uint64(args.Block.Header.Height) + blockHeight := args.Block.Header.Height ch.EmptyMsgQueue() ch.EmptyProcessedMsgs() @@ -27,7 +27,7 @@ func (ch *Child) beginBlockHandler(ctx context.Context, args nodetypes.BeginBloc } func (ch *Child) endBlockHandler(_ context.Context, args nodetypes.EndBlockArgs) error { - blockHeight := uint64(args.Block.Header.Height) + blockHeight := args.Block.Header.Height batchKVs := make([]types.RawKV, 0) treeKVs, storageRoot, err := ch.handleTree(blockHeight, args.LatestHeight, args.BlockID, args.Block.Header) if err != nil { diff --git a/executor/child/oracle.go b/executor/child/oracle.go index 4e34479..de46353 100644 --- a/executor/child/oracle.go +++ b/executor/child/oracle.go @@ -19,9 +19,9 @@ func (ch *Child) updateOracleHandler(_ context.Context, args nodetypes.EventHand return nil } -func (ch *Child) handleUpdateOracle(l1BlockHeight uint64, from string) { +func (ch *Child) handleUpdateOracle(l1BlockHeight int64, from string) { ch.Logger().Info("update oracle", - zap.Uint64("l1_blockHeight", l1BlockHeight), + zap.Int64("l1_blockHeight", l1BlockHeight), zap.String("from", from), ) } diff --git a/executor/child/status.go b/executor/child/status.go index f730bd1..3de9200 100644 --- a/executor/child/status.go +++ b/executor/child/status.go @@ -8,13 +8,13 @@ import ( type Status struct { Node nodetypes.Status `json:"node"` - LastUpdatedOracleL1Height uint64 `json:"last_updated_oracle_height"` - LastFinalizedDepositL1BlockHeight uint64 `json:"last_finalized_deposit_l1_block_height"` + LastUpdatedOracleL1Height int64 `json:"last_updated_oracle_height"` + LastFinalizedDepositL1BlockHeight int64 `json:"last_finalized_deposit_l1_block_height"` LastFinalizedDepositL1Sequence uint64 `json:"last_finalized_deposit_l1_sequence"` LastWithdrawalL2Sequence uint64 `json:"last_withdrawal_l2_sequence"` WorkingTreeIndex uint64 `json:"working_tree_index"` // if it is not 0, we are syncing - FinalizingBlockHeight uint64 `json:"finalizing_block_height"` + FinalizingBlockHeight int64 `json:"finalizing_block_height"` LastOutputSubmissionTime time.Time `json:"last_output_submission_time"` NextOutputSubmissionTime time.Time `json:"next_output_submission_time"` } diff --git a/executor/child/withdraw.go b/executor/child/withdraw.go index f6195fc..2ea32e5 100644 --- a/executor/child/withdraw.go +++ b/executor/child/withdraw.go @@ -61,12 +61,12 @@ func (ch *Child) handleInitiateWithdrawal(l2Sequence uint64, from string, to str return nil } -func (ch *Child) prepareTree(blockHeight uint64) error { +func (ch *Child) prepareTree(blockHeight int64) error { if ch.InitializeTree(blockHeight) { return nil } - err := ch.Merkle().LoadWorkingTree(blockHeight - 1) + err := ch.Merkle().LoadWorkingTree(types.MustInt64ToUint64(blockHeight) - 1) if err == dbtypes.ErrNotFound { // must not happened panic(fmt.Errorf("working tree not found at height: %d, current: %d", blockHeight-1, blockHeight)) @@ -99,12 +99,12 @@ func (ch *Child) prepareOutput(ctx context.Context) error { return err } else { // we are syncing - ch.finalizingBlockHeight = output.OutputProposal.L2BlockNumber + ch.finalizingBlockHeight = types.MustUint64ToInt64(output.OutputProposal.L2BlockNumber) } return nil } -func (ch *Child) handleTree(blockHeight uint64, latestHeight uint64, blockId []byte, blockHeader cmtproto.Header) (kvs []types.RawKV, storageRoot []byte, err error) { +func (ch *Child) handleTree(blockHeight int64, latestHeight int64, blockId []byte, blockHeader cmtproto.Header) (kvs []types.RawKV, storageRoot []byte, err error) { // panic if we are syncing and passed the finalizing block height // this must not happened if ch.finalizingBlockHeight != 0 && ch.finalizingBlockHeight < blockHeight { @@ -132,7 +132,7 @@ func (ch *Child) handleTree(blockHeight uint64, latestHeight uint64, blockId []b ch.Logger().Info("finalize working tree", zap.Uint64("tree_index", ch.Merkle().GetWorkingTreeIndex()), - zap.Uint64("height", blockHeight), + zap.Int64("height", blockHeight), zap.Uint64("num_leaves", ch.Merkle().GetWorkingTreeLeafCount()), zap.String("storage_root", base64.StdEncoding.EncodeToString(storageRoot)), ) @@ -147,7 +147,8 @@ func (ch *Child) handleTree(blockHeight uint64, latestHeight uint64, blockId []b ch.nextOutputTime = blockHeader.Time.Add(ch.BridgeInfo().BridgeConfig.SubmissionInterval * 2 / 3) } - err = ch.Merkle().SaveWorkingTree(blockHeight) + version := types.MustInt64ToUint64(blockHeight) + err = ch.Merkle().SaveWorkingTree(version) if err != nil { return nil, nil, err } @@ -155,7 +156,7 @@ func (ch *Child) handleTree(blockHeight uint64, latestHeight uint64, blockId []b return kvs, storageRoot, nil } -func (ch *Child) handleOutput(blockHeight uint64, version uint8, blockId []byte, outputIndex uint64, storageRoot []byte) error { +func (ch *Child) handleOutput(blockHeight int64, version uint8, blockId []byte, outputIndex uint64, storageRoot []byte) error { outputRoot := ophosttypes.GenerateOutputRoot(version, storageRoot, blockId) msg, err := ch.host.GetMsgProposeOutput( ch.BridgeId(), diff --git a/executor/executor.go b/executor/executor.go index 8fef8a4..6b29a0f 100644 --- a/executor/executor.go +++ b/executor/executor.go @@ -201,7 +201,7 @@ func (ex *Executor) makeDANode(ctx context.Context, bridgeInfo opchildtypes.Brid return nil, fmt.Errorf("unsupported chain id for DA: %s", ophosttypes.BatchInfo_ChainType_name[int32(batchInfo.BatchInfo.ChainType)]) } -func (ex *Executor) getStartHeights(ctx context.Context, bridgeId uint64) (l1StartHeight uint64, l2StartHeight uint64, startOutputIndex uint64, batchStartHeight uint64, err error) { +func (ex *Executor) getStartHeights(ctx context.Context, bridgeId uint64) (l1StartHeight int64, l2StartHeight int64, startOutputIndex uint64, batchStartHeight int64, err error) { // get the bridge start height from the host l1StartHeight, err = ex.host.QueryCreateBridgeHeight(ctx, bridgeId) if err != nil { @@ -214,8 +214,8 @@ func (ex *Executor) getStartHeights(ctx context.Context, bridgeId uint64) (l1Sta if err != nil { return 0, 0, 0, 0, err } else if output != nil { - l1StartHeight = output.OutputProposal.L1BlockNumber - l2StartHeight = output.OutputProposal.L2BlockNumber + l1StartHeight = types.MustUint64ToInt64(output.OutputProposal.L1BlockNumber) + l2StartHeight = types.MustUint64ToInt64(output.OutputProposal.L2BlockNumber) startOutputIndex = output.OutputIndex + 1 } } diff --git a/executor/host/batch.go b/executor/host/batch.go index c45cf3b..c0b2cc8 100644 --- a/executor/host/batch.go +++ b/executor/host/batch.go @@ -40,7 +40,7 @@ func (h *Host) updateBatchInfoHandler(_ context.Context, args nodetypes.EventHan zap.String("chain", chain), zap.String("submitter", submitter), zap.Uint64("output_index", outputIndex), - zap.Uint64("l2_block_number", l2BlockNumber), + zap.Int64("l2_block_number", l2BlockNumber), ) h.batch.UpdateBatchInfo(chain, submitter, outputIndex, l2BlockNumber) diff --git a/executor/host/deposit.go b/executor/host/deposit.go index f24868f..94ab88b 100644 --- a/executor/host/deposit.go +++ b/executor/host/deposit.go @@ -45,7 +45,7 @@ func (h *Host) initiateDepositHandler(_ context.Context, args nodetypes.EventHan func (h *Host) handleInitiateDeposit( l1Sequence uint64, - blockHeight uint64, + blockHeight int64, from string, to string, l1Denom string, diff --git a/executor/host/handler.go b/executor/host/handler.go index d183628..e75765c 100644 --- a/executor/host/handler.go +++ b/executor/host/handler.go @@ -20,7 +20,7 @@ func (h *Host) beginBlockHandler(_ context.Context, args nodetypes.BeginBlockArg func (h *Host) endBlockHandler(_ context.Context, args nodetypes.EndBlockArgs) error { // collect more msgs if block height is not latest - blockHeight := uint64(args.Block.Header.Height) + blockHeight := args.Block.Header.Height msgQueue := h.GetMsgQueue() if blockHeight != args.LatestHeight && len(msgQueue) > 0 && len(msgQueue) <= 10 { return nil diff --git a/executor/host/host.go b/executor/host/host.go index 4f0fe12..a5ea223 100644 --- a/executor/host/host.go +++ b/executor/host/host.go @@ -23,17 +23,14 @@ type childNode interface { HasKey() bool BroadcastMsgs(btypes.ProcessedMsgs) ProcessedMsgsToRawKV([]btypes.ProcessedMsgs, bool) ([]types.RawKV, error) - QueryNextL1Sequence(context.Context, uint64) (uint64, error) + QueryNextL1Sequence(context.Context, int64) (uint64, error) - GetMsgFinalizeTokenDeposit(string, string, sdk.Coin, uint64, uint64, string, []byte) (sdk.Msg, error) - GetMsgUpdateOracle( - height uint64, - data []byte, - ) (sdk.Msg, error) + GetMsgFinalizeTokenDeposit(string, string, sdk.Coin, uint64, int64, string, []byte) (sdk.Msg, error) + GetMsgUpdateOracle(int64, []byte) (sdk.Msg, error) } type batchNode interface { - UpdateBatchInfo(chain string, submitter string, outputIndex uint64, l2BlockNumber uint64) + UpdateBatchInfo(string, string, uint64, int64) } var _ executortypes.DANode = &Host{} @@ -48,7 +45,7 @@ type Host struct { // status info lastProposedOutputIndex uint64 - lastProposedOutputL2BlockNumber uint64 + lastProposedOutputL2BlockNumber int64 } func NewHostV1( @@ -64,7 +61,7 @@ func NewHostV1( } } -func (h *Host) Initialize(ctx context.Context, startHeight uint64, child childNode, batch batchNode, bridgeInfo opchildtypes.BridgeInfo) error { +func (h *Host) Initialize(ctx context.Context, startHeight int64, child childNode, batch batchNode, bridgeInfo opchildtypes.BridgeInfo) error { err := h.BaseHost.Initialize(ctx, startHeight, bridgeInfo) if err != nil { return err diff --git a/executor/host/oracle.go b/executor/host/oracle.go index c94f0bb..41a95e5 100644 --- a/executor/host/oracle.go +++ b/executor/host/oracle.go @@ -8,7 +8,7 @@ import ( // If the relay oracle is enabled and the extended commit info contains votes, create a new MsgUpdateOracle message. // Else return nil. -func (h *Host) oracleTxHandler(blockHeight uint64, extCommitBz comettypes.Tx) (sdk.Msg, error) { +func (h *Host) oracleTxHandler(blockHeight int64, extCommitBz comettypes.Tx) (sdk.Msg, error) { if !h.OracleEnabled() { return nil, nil } diff --git a/executor/host/status.go b/executor/host/status.go index 23ec787..1efc703 100644 --- a/executor/host/status.go +++ b/executor/host/status.go @@ -7,7 +7,7 @@ import ( type Status struct { Node nodetypes.Status `json:"node"` LastProposedOutputIndex uint64 `json:"last_proposed_output_index"` - LastProposedOutputL2BlockNumber uint64 `json:"last_proposed_output_l2_block_number"` + LastProposedOutputL2BlockNumber int64 `json:"last_proposed_output_l2_block_number"` } func (h Host) GetStatus() Status { diff --git a/executor/host/withdraw.go b/executor/host/withdraw.go index 91fe844..8bf89e2 100644 --- a/executor/host/withdraw.go +++ b/executor/host/withdraw.go @@ -25,12 +25,12 @@ func (h *Host) proposeOutputHandler(_ context.Context, args nodetypes.EventHandl return nil } -func (h *Host) handleProposeOutput(bridgeId uint64, proposer string, outputIndex uint64, l2BlockNumber uint64, outputRoot []byte) { +func (h *Host) handleProposeOutput(bridgeId uint64, proposer string, outputIndex uint64, l2BlockNumber int64, outputRoot []byte) { h.Logger().Info("propose output", zap.Uint64("bridge_id", bridgeId), zap.String("proposer", proposer), zap.Uint64("output_index", outputIndex), - zap.Uint64("l2_block_number", l2BlockNumber), + zap.Int64("l2_block_number", l2BlockNumber), zap.String("output_root", base64.StdEncoding.EncodeToString(outputRoot)), ) } diff --git a/executor/types/batch.go b/executor/types/batch.go index a584463..6fc911a 100644 --- a/executor/types/batch.go +++ b/executor/types/batch.go @@ -25,9 +25,9 @@ type DANode interface { type LocalBatchInfo struct { // start l2 block height which is included in the batch - Start uint64 `json:"start"` + Start int64 `json:"start"` // last l2 block height which is included in the batch - End uint64 `json:"end"` + End int64 `json:"end"` LastSubmissionTime time.Time `json:"last_submission_time"` BatchFileSize int64 `json:"batch_size"` @@ -86,7 +86,12 @@ func UnmarshalBatchDataHeader(data []byte) (BatchDataHeader, error) { } length := binary.BigEndian.Uint64(data[17:25]) - if (len(data)-25)%32 != 0 || (uint64(len(data)-25)/32) != length { + expectedLength, err := types.SafeInt64ToUint64(int64(len(data)-25) / 32) + if err != nil { + return BatchDataHeader{}, err + } + + if expectedLength != 0 || expectedLength != length { err := fmt.Errorf("invalid checksum length: %d, data length: %d", length, len(data)-25) return BatchDataHeader{}, err } diff --git a/executor/types/config.go b/executor/types/config.go index b10a601..aad1676 100644 --- a/executor/types/config.go +++ b/executor/types/config.go @@ -57,20 +57,20 @@ type Config struct { BridgeExecutor string `json:"bridge_executor"` // MaxChunks is the maximum number of chunks in a batch. - MaxChunks uint64 `json:"max_chunks"` + MaxChunks int64 `json:"max_chunks"` // MaxChunkSize is the maximum size of a chunk in a batch. - MaxChunkSize uint64 `json:"max_chunk_size"` + MaxChunkSize int64 `json:"max_chunk_size"` // MaxSubmissionTime is the maximum time to submit a batch. - MaxSubmissionTime uint64 `json:"max_submission_time"` // seconds + MaxSubmissionTime int64 `json:"max_submission_time"` // seconds // L2StartHeight is the height to start the l2 node. If it is 0, it will start from the latest height. // If the latest height stored in the db is not 0, this config is ignored. // L2 starts from the last submitted output l2 block number + 1 before L2StartHeight. // L1 starts from the block number of the output tx + 1 - L2StartHeight uint64 `json:"l2_start_height"` + L2StartHeight int64 `json:"l2_start_height"` // BatchStartHeight is the height to start the batch. If it is 0, it will start from the latest height. // If the latest height stored in the db is not 0, this config is ignored. - BatchStartHeight uint64 `json:"batch_start_height"` + BatchStartHeight int64 `json:"batch_start_height"` } func DefaultConfig() *Config { @@ -141,6 +141,26 @@ func (cfg Config) Validate() error { if err := cfg.DANode.Validate(); err != nil { return err } + + if cfg.MaxChunks <= 0 { + return errors.New("max chunks must be greater than 0") + } + + if cfg.MaxChunkSize <= 0 { + return errors.New("max chunk size must be greater than 0") + } + + if cfg.MaxSubmissionTime <= 0 { + return errors.New("max submission time must be greater than 0") + } + + if cfg.L2StartHeight < 0 { + return errors.New("l2 start height must be greater than or equal to 0") + } + + if cfg.BatchStartHeight < 0 { + return errors.New("batch start height must be greater than or equal to 0") + } return nil } @@ -218,7 +238,7 @@ func (cfg Config) BatchConfig() BatchConfig { } type BatchConfig struct { - MaxChunks uint64 `json:"max_chunks"` - MaxChunkSize uint64 `json:"max_chunk_size"` - MaxSubmissionTime uint64 `json:"max_submission_time"` // seconds + MaxChunks int64 `json:"max_chunks"` + MaxChunkSize int64 `json:"max_chunk_size"` + MaxSubmissionTime int64 `json:"max_submission_time"` // seconds } diff --git a/executor/types/db.go b/executor/types/db.go index 2ef9772..c69492e 100644 --- a/executor/types/db.go +++ b/executor/types/db.go @@ -10,6 +10,6 @@ type WithdrawalData struct { } type TreeExtraData struct { - BlockNumber uint64 `json:"block_number"` + BlockNumber int64 `json:"block_number"` BlockHash []byte `json:"block_hash"` } diff --git a/executor/types/query.go b/executor/types/query.go index 033b27e..ebe1505 100644 --- a/executor/types/query.go +++ b/executor/types/query.go @@ -13,7 +13,7 @@ type QueryWithdrawalResponse struct { LatestBlockHash []byte `json:"latest_block_hash"` // extra info - BlockNumber uint64 `json:"block_number"` + BlockNumber int64 `json:"block_number"` Receiver string `json:"receiver"` WithdrawalHash []byte `json:"withdrawal_hash"` } diff --git a/merkle/merkle.go b/merkle/merkle.go index c5840c4..d610fe9 100644 --- a/merkle/merkle.go +++ b/merkle/merkle.go @@ -175,11 +175,11 @@ func (m *Merkle) SaveWorkingTree(version uint64) error { // Height returns the height of the working tree. func (m *Merkle) Height() uint8 { - if m.workingTree.LeafCount <= 1 { - return uint8(m.workingTree.LeafCount) + leafCount := m.workingTree.LeafCount + if leafCount <= 1 { + return uint8(leafCount) } - - return uint8(bits.Len64(m.workingTree.LeafCount - 1)) + return types.MustIntToUint8(bits.Len64(leafCount - 1)) } // GetWorkingTreeIndex returns the index of the working tree. diff --git a/node/broadcaster/broadcaster.go b/node/broadcaster/broadcaster.go index d325373..bbff333 100644 --- a/node/broadcaster/broadcaster.go +++ b/node/broadcaster/broadcaster.go @@ -47,7 +47,7 @@ type Broadcaster struct { pendingProcessedMsgs []btypes.ProcessedMsgs - lastProcessedBlockHeight uint64 + lastProcessedBlockHeight int64 } func NewBroadcaster( @@ -229,7 +229,7 @@ func (b *Broadcaster) prepareBroadcaster(ctx context.Context, lastBlockTime time return nil } -func (b *Broadcaster) SetSyncInfo(height uint64) { +func (b *Broadcaster) SetSyncInfo(height int64) { b.lastProcessedBlockHeight = height } diff --git a/node/broadcaster/db.go b/node/broadcaster/db.go index 9c00383..7eb6018 100644 --- a/node/broadcaster/db.go +++ b/node/broadcaster/db.go @@ -82,7 +82,7 @@ func (b Broadcaster) ProcessedMsgsToRawKV(ProcessedMsgs []btypes.ProcessedMsgs, } } kvs = append(kvs, types.RawKV{ - Key: b.db.PrefixedKey(btypes.PrefixedProcessedMsgs(uint64(processedMsgs.Timestamp))), + Key: b.db.PrefixedKey(btypes.PrefixedProcessedMsgs(types.MustInt64ToUint64(processedMsgs.Timestamp))), Value: data, }) } @@ -117,5 +117,5 @@ func (b Broadcaster) loadProcessedMsgs() (ProcessedMsgs []btypes.ProcessedMsgs, } func (b Broadcaster) deleteProcessedMsgs(timestamp int64) error { - return b.db.Delete(btypes.PrefixedProcessedMsgs(uint64(timestamp))) + return b.db.Delete(btypes.PrefixedProcessedMsgs(types.MustInt64ToUint64(timestamp))) } diff --git a/node/broadcaster/process.go b/node/broadcaster/process.go index f713855..7d38039 100644 --- a/node/broadcaster/process.go +++ b/node/broadcaster/process.go @@ -14,12 +14,12 @@ import ( btypes "github.com/initia-labs/opinit-bots/node/broadcaster/types" ) -func (b Broadcaster) GetHeight() uint64 { +func (b Broadcaster) GetHeight() int64 { return b.lastProcessedBlockHeight + 1 } // HandleNewBlock is called when a new block is received. -func (b *Broadcaster) HandleNewBlock(block *rpccoretypes.ResultBlock, blockResult *rpccoretypes.ResultBlockResults, latestChainHeight uint64) error { +func (b *Broadcaster) HandleNewBlock(block *rpccoretypes.ResultBlock, blockResult *rpccoretypes.ResultBlockResults, latestChainHeight int64) error { // check pending txs first for _, tx := range block.Block.Txs { if b.LenLocalPendingTx() == 0 { diff --git a/node/broadcaster/types/db.go b/node/broadcaster/types/db.go index b4c8cf7..a68f533 100644 --- a/node/broadcaster/types/db.go +++ b/node/broadcaster/types/db.go @@ -11,7 +11,7 @@ import ( ) type PendingTxInfo struct { - ProcessedHeight uint64 `json:"height"` + ProcessedHeight int64 `json:"height"` Sequence uint64 `json:"sequence"` Tx []byte `json:"tx"` TxHash string `json:"tx_hash"` diff --git a/node/db.go b/node/db.go index 8d26a37..4ded461 100644 --- a/node/db.go +++ b/node/db.go @@ -7,43 +7,43 @@ import ( "go.uber.org/zap" ) -func (n *Node) SetSyncInfo(height uint64) { +func (n *Node) SetSyncInfo(height int64) { n.lastProcessedBlockHeight = height if n.broadcaster != nil { n.broadcaster.SetSyncInfo(n.lastProcessedBlockHeight) } } -func (n *Node) loadSyncInfo(startHeight uint64) error { +func (n *Node) loadSyncInfo(startHeight int64) error { data, err := n.db.Get(nodetypes.LastProcessedBlockHeightKey) if err == dbtypes.ErrNotFound { n.SetSyncInfo(startHeight) n.startHeightInitialized = true - n.logger.Info("initialize sync info", zap.Uint64("start_height", startHeight+1)) + n.logger.Info("initialize sync info", zap.Int64("start_height", startHeight+1)) return nil } else if err != nil { return err } - lastSyncedHeight, err := dbtypes.ToUint64(data) + lastSyncedHeight, err := dbtypes.ToInt64(data) if err != nil { return err } n.SetSyncInfo(lastSyncedHeight) - n.logger.Debug("load sync info", zap.Uint64("last_processed_height", n.lastProcessedBlockHeight)) + n.logger.Debug("load sync info", zap.Int64("last_processed_height", n.lastProcessedBlockHeight)) return nil } -func (n Node) SaveSyncInfo(height uint64) error { - return n.db.Set(nodetypes.LastProcessedBlockHeightKey, dbtypes.FromUint64(height)) +func (n Node) SaveSyncInfo(height int64) error { + return n.db.Set(nodetypes.LastProcessedBlockHeightKey, dbtypes.FromUint64(types.MustInt64ToUint64(height))) } -func (n Node) SyncInfoToRawKV(height uint64) types.RawKV { +func (n Node) SyncInfoToRawKV(height int64) types.RawKV { return types.RawKV{ Key: n.db.PrefixedKey(nodetypes.LastProcessedBlockHeightKey), - Value: dbtypes.FromUint64(height), + Value: dbtypes.FromUint64(types.MustInt64ToUint64(height)), } } diff --git a/node/node.go b/node/node.go index b28b232..d7c6cd8 100644 --- a/node/node.go +++ b/node/node.go @@ -38,7 +38,7 @@ type Node struct { // status info startHeightInitialized bool - lastProcessedBlockHeight uint64 + lastProcessedBlockHeight int64 running bool } @@ -85,7 +85,7 @@ func NewNode(cfg nodetypes.NodeConfig, db types.DB, logger *zap.Logger, cdc code // StartHeight is the height to start processing. // If it is 0, the latest height is used. // If the latest height exists in the database, this is ignored. -func (n *Node) Initialize(ctx context.Context, startHeight uint64) (err error) { +func (n *Node) Initialize(ctx context.Context, startHeight int64) (err error) { // check if node is catching up status, err := n.rpcClient.Status(ctx) if err != nil { @@ -168,7 +168,7 @@ func (n Node) AccountCodec() address.Codec { return n.cdc.InterfaceRegistry().SigningContext().AddressCodec() } -func (n Node) GetHeight() uint64 { +func (n Node) GetHeight() int64 { return n.lastProcessedBlockHeight + 1 } diff --git a/node/process.go b/node/process.go index e2618c7..5592c55 100644 --- a/node/process.go +++ b/node/process.go @@ -31,7 +31,7 @@ func (n *Node) blockProcessLooper(ctx context.Context, processType nodetypes.Blo continue } - latestChainHeight := uint64(status.SyncInfo.LatestBlockHeight) + latestChainHeight := status.SyncInfo.LatestBlockHeight if n.lastProcessedBlockHeight >= latestChainHeight { continue } @@ -45,7 +45,7 @@ func (n *Node) blockProcessLooper(ctx context.Context, processType nodetypes.Blo case <-timer.C: } // TODO: may fetch blocks in batch - block, blockResult, err := n.fetchNewBlock(ctx, int64(queryHeight)) + block, blockResult, err := n.fetchNewBlock(ctx, queryHeight) if err != nil { // TODO: handle error n.logger.Error("failed to fetch new block", zap.String("error", err.Error())) @@ -120,7 +120,7 @@ func (n *Node) fetchNewBlock(ctx context.Context, height int64) (block *rpccoret return block, blockResult, nil } -func (n *Node) handleNewBlock(ctx context.Context, block *rpccoretypes.ResultBlock, blockResult *rpccoretypes.ResultBlockResults, latestChainHeight uint64) error { +func (n *Node) handleNewBlock(ctx context.Context, block *rpccoretypes.ResultBlock, blockResult *rpccoretypes.ResultBlockResults, latestChainHeight int64) error { protoBlock, err := block.Block.ToProto() if err != nil { return err @@ -148,10 +148,10 @@ func (n *Node) handleNewBlock(ctx context.Context, block *rpccoretypes.ResultBlo for txIndex, tx := range block.Block.Txs { if n.txHandler != nil { err := n.txHandler(ctx, nodetypes.TxHandlerArgs{ - BlockHeight: uint64(block.Block.Height), + BlockHeight: block.Block.Height, BlockTime: block.Block.Time, LatestHeight: latestChainHeight, - TxIndex: uint64(txIndex), + TxIndex: int64(txIndex), Tx: tx, }) if err != nil { @@ -162,7 +162,7 @@ func (n *Node) handleNewBlock(ctx context.Context, block *rpccoretypes.ResultBlo if len(n.eventHandlers) != 0 { events := blockResult.TxsResults[txIndex].GetEvents() for eventIndex, event := range events { - err := n.handleEvent(ctx, uint64(block.Block.Height), block.Block.Time, latestChainHeight, event) + err := n.handleEvent(ctx, block.Block.Height, block.Block.Time, latestChainHeight, event) if err != nil { return fmt.Errorf("failed to handle event: tx_index: %d, event_index: %d; %w", txIndex, eventIndex, err) } @@ -171,7 +171,7 @@ func (n *Node) handleNewBlock(ctx context.Context, block *rpccoretypes.ResultBlo } for eventIndex, event := range blockResult.FinalizeBlockEvents { - err := n.handleEvent(ctx, uint64(block.Block.Height), block.Block.Time, latestChainHeight, event) + err := n.handleEvent(ctx, block.Block.Height, block.Block.Time, latestChainHeight, event) if err != nil { return fmt.Errorf("failed to handle event: finalize block, event_index: %d; %w", eventIndex, err) } @@ -190,12 +190,12 @@ func (n *Node) handleNewBlock(ctx context.Context, block *rpccoretypes.ResultBlo return nil } -func (n *Node) handleEvent(ctx context.Context, blockHeight uint64, blockTime time.Time, latestHeight uint64, event abcitypes.Event) error { +func (n *Node) handleEvent(ctx context.Context, blockHeight int64, blockTime time.Time, latestHeight int64, event abcitypes.Event) error { if n.eventHandlers[event.GetType()] == nil { return nil } - n.logger.Debug("handle event", zap.Uint64("height", blockHeight), zap.String("type", event.GetType())) + n.logger.Debug("handle event", zap.Int64("height", blockHeight), zap.String("type", event.GetType())) return n.eventHandlers[event.Type](ctx, nodetypes.EventHandlerArgs{ BlockHeight: blockHeight, BlockTime: blockTime, @@ -236,7 +236,7 @@ func (n *Node) txChecker(ctx context.Context) error { default: } - err := n.handleEvent(ctx, uint64(res.Height), blockTime, 0, event) + err := n.handleEvent(ctx, res.Height, blockTime, 0, event) if err != nil { n.logger.Error("failed to handle event", zap.String("tx_hash", pendingTx.TxHash), zap.Int("event_index", eventIndex), zap.String("error", err.Error())) break diff --git a/node/rpcclient/client.go b/node/rpcclient/client.go index 3a588c1..be82a68 100644 --- a/node/rpcclient/client.go +++ b/node/rpcclient/client.go @@ -168,25 +168,25 @@ func GetHeightFromMetadata(md metadata.MD) (int64, error) { // Canceling this context releases resources associated with it, so code should // call cancel as soon as the operations running in this [Context] complete: -func GetQueryContext(ctx context.Context, height uint64) (context.Context, context.CancelFunc) { +func GetQueryContext(ctx context.Context, height int64) (context.Context, context.CancelFunc) { // TODO: configurable timeout timeout := 10 * time.Second ctx, cancel := context.WithTimeout(ctx, timeout) - strHeight := strconv.FormatUint(height, 10) + strHeight := strconv.FormatInt(height, 10) ctx = metadata.AppendToOutgoingContext(ctx, grpctypes.GRPCBlockHeightHeader, strHeight) return ctx, cancel } // QueryRawCommit queries the raw commit at a given height. func (q RPCClient) QueryRawCommit(ctx context.Context, height int64) ([]byte, error) { - ctx, cancel := GetQueryContext(ctx, uint64(height)) + ctx, cancel := GetQueryContext(ctx, height) defer cancel() return q.RawCommit(ctx, &height) } // QueryBlockBulk queries blocks in bulk. -func (q RPCClient) QueryBlockBulk(ctx context.Context, start uint64, end uint64) ([][]byte, error) { +func (q RPCClient) QueryBlockBulk(ctx context.Context, start int64, end int64) ([][]byte, error) { ctx, cancel := GetQueryContext(ctx, 0) defer cancel() return q.BlockBulk(ctx, &start, &end) diff --git a/node/types/handler.go b/node/types/handler.go index 184f3be..aee5376 100644 --- a/node/types/handler.go +++ b/node/types/handler.go @@ -10,20 +10,20 @@ import ( ) type EventHandlerArgs struct { - BlockHeight uint64 + BlockHeight int64 BlockTime time.Time - LatestHeight uint64 - TxIndex uint64 + LatestHeight int64 + TxIndex int64 EventAttributes []abcitypes.EventAttribute } type EventHandlerFn func(context.Context, EventHandlerArgs) error type TxHandlerArgs struct { - BlockHeight uint64 + BlockHeight int64 BlockTime time.Time - LatestHeight uint64 - TxIndex uint64 + LatestHeight int64 + TxIndex int64 Tx comettypes.Tx } @@ -32,7 +32,7 @@ type TxHandlerFn func(context.Context, TxHandlerArgs) error type BeginBlockArgs struct { BlockID []byte Block cmtproto.Block - LatestHeight uint64 + LatestHeight int64 } type BeginBlockHandlerFn func(context.Context, BeginBlockArgs) error @@ -40,14 +40,14 @@ type BeginBlockHandlerFn func(context.Context, BeginBlockArgs) error type EndBlockArgs struct { BlockID []byte Block cmtproto.Block - LatestHeight uint64 + LatestHeight int64 } type EndBlockHandlerFn func(context.Context, EndBlockArgs) error type RawBlockArgs struct { - BlockHeight uint64 - LatestHeight uint64 + BlockHeight int64 + LatestHeight int64 BlockBytes []byte } diff --git a/node/types/status.go b/node/types/status.go index 99ed0c7..41b1425 100644 --- a/node/types/status.go +++ b/node/types/status.go @@ -6,6 +6,6 @@ type BroadcasterStatus struct { } type Status struct { - LastBlockHeight uint64 `json:"last_block_height,omitempty"` + LastBlockHeight int64 `json:"last_block_height,omitempty"` Broadcaster *BroadcasterStatus `json:"broadcaster,omitempty"` } diff --git a/provider/child/child.go b/provider/child/child.go index 2cc00c0..2a77441 100644 --- a/provider/child/child.go +++ b/provider/child/child.go @@ -30,7 +30,7 @@ type BaseChild struct { bridgeInfo opchildtypes.BridgeInfo - initializeTreeFn func(uint64) (bool, error) + initializeTreeFn func(int64) (bool, error) cfg nodetypes.NodeConfig db types.DB @@ -89,7 +89,7 @@ func GetCodec(bech32Prefix string) (codec.Codec, client.TxConfig, error) { }) } -func (b *BaseChild) Initialize(ctx context.Context, startHeight uint64, startOutputIndex uint64, bridgeInfo opchildtypes.BridgeInfo) (uint64, error) { +func (b *BaseChild) Initialize(ctx context.Context, startHeight int64, startOutputIndex uint64, bridgeInfo opchildtypes.BridgeInfo) (uint64, error) { err := b.node.Initialize(ctx, startHeight) if err != nil { return 0, err @@ -107,12 +107,13 @@ func (b *BaseChild) Initialize(ctx context.Context, startHeight uint64, startOut return 0, err } - err = b.mk.DeleteFutureWorkingTrees(startHeight + 1) + version := types.MustInt64ToUint64(startHeight) + err = b.mk.DeleteFutureWorkingTrees(version + 1) if err != nil { return 0, err } - b.initializeTreeFn = func(blockHeight uint64) (bool, error) { + b.initializeTreeFn = func(blockHeight int64) (bool, error) { if startHeight+1 == blockHeight { b.logger.Info("initialize tree", zap.Uint64("index", startOutputIndex)) err := b.mk.InitializeWorkingTree(startOutputIndex, 1) @@ -129,7 +130,7 @@ func (b *BaseChild) Initialize(ctx context.Context, startHeight uint64, startOut } func (b *BaseChild) Start(ctx context.Context) { - b.logger.Info("child start", zap.Uint64("height", b.Height())) + b.logger.Info("child start", zap.Int64("height", b.Height())) b.node.Start(ctx) } @@ -169,7 +170,7 @@ func (b BaseChild) BridgeInfo() opchildtypes.BridgeInfo { return b.bridgeInfo } -func (b BaseChild) Height() uint64 { +func (b BaseChild) Height() int64 { return b.node.GetHeight() } diff --git a/provider/child/msgs.go b/provider/child/msgs.go index fc813ba..6e2aa52 100644 --- a/provider/child/msgs.go +++ b/provider/child/msgs.go @@ -2,6 +2,7 @@ package child import ( opchildtypes "github.com/initia-labs/OPinit/x/opchild/types" + "github.com/initia-labs/opinit-bots/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -30,7 +31,7 @@ func (b BaseChild) GetMsgFinalizeTokenDeposit( to string, coin sdk.Coin, l1Sequence uint64, - blockHeight uint64, + blockHeight int64, l1Denom string, data []byte, ) (sdk.Msg, error) { @@ -45,7 +46,7 @@ func (b BaseChild) GetMsgFinalizeTokenDeposit( to, coin, l1Sequence, - blockHeight, + types.MustInt64ToUint64(blockHeight), l1Denom, data, ) @@ -57,7 +58,7 @@ func (b BaseChild) GetMsgFinalizeTokenDeposit( } func (b BaseChild) GetMsgUpdateOracle( - height uint64, + height int64, data []byte, ) (sdk.Msg, error) { sender, err := b.node.MustGetBroadcaster().GetAddressString() @@ -67,7 +68,7 @@ func (b BaseChild) GetMsgUpdateOracle( msg := opchildtypes.NewMsgUpdateOracle( sender, - height, + types.MustInt64ToUint64(height), data, ) err = msg.Validate(b.node.AccountCodec()) diff --git a/provider/child/parse.go b/provider/child/parse.go index 9b2c8ee..0757d62 100644 --- a/provider/child/parse.go +++ b/provider/child/parse.go @@ -12,7 +12,8 @@ import ( ) func ParseFinalizeDeposit(eventAttrs []abcitypes.EventAttribute) ( - l1BlockHeight, l1Sequence uint64, + l1BlockHeight int64, + l1Sequence uint64, from, to, baseDenom string, amount sdk.Coin, err error) { @@ -39,7 +40,7 @@ func ParseFinalizeDeposit(eventAttrs []abcitypes.EventAttribute) ( } amount.Amount = coinAmount case opchildtypes.AttributeKeyFinalizeHeight: - l1BlockHeight, err = strconv.ParseUint(attr.Value, 10, 64) + l1BlockHeight, err = strconv.ParseInt(attr.Value, 10, 64) if err != nil { return } @@ -49,13 +50,13 @@ func ParseFinalizeDeposit(eventAttrs []abcitypes.EventAttribute) ( } func ParseUpdateOracle(eventAttrs []abcitypes.EventAttribute) ( - l1BlockHeight uint64, + l1BlockHeight int64, from string, err error) { for _, attr := range eventAttrs { switch attr.Key { case opchildtypes.AttributeKeyHeight: - l1BlockHeight, err = strconv.ParseUint(attr.Value, 10, 64) + l1BlockHeight, err = strconv.ParseInt(attr.Value, 10, 64) if err != nil { return } diff --git a/provider/child/query.go b/provider/child/query.go index 8aa135c..135c0ee 100644 --- a/provider/child/query.go +++ b/provider/child/query.go @@ -30,7 +30,7 @@ func (b BaseChild) QueryBridgeInfo(ctx context.Context) (opchildtypes.BridgeInfo return res.BridgeInfo, nil } -func (b BaseChild) QueryNextL1Sequence(ctx context.Context, height uint64) (uint64, error) { +func (b BaseChild) QueryNextL1Sequence(ctx context.Context, height int64) (uint64, error) { req := &opchildtypes.QueryNextL1SequenceRequest{} ctx, cancel := rpcclient.GetQueryContext(ctx, height) defer cancel() @@ -42,7 +42,7 @@ func (b BaseChild) QueryNextL1Sequence(ctx context.Context, height uint64) (uint return res.NextL1Sequence, nil } -func (b BaseChild) QueryNextL2Sequence(ctx context.Context, height uint64) (uint64, error) { +func (b BaseChild) QueryNextL2Sequence(ctx context.Context, height int64) (uint64, error) { req := &opchildtypes.QueryNextL2SequenceRequest{} ctx, cancel := rpcclient.GetQueryContext(ctx, height) defer cancel() diff --git a/provider/child/tree.go b/provider/child/tree.go index 8a8c73d..5e976fd 100644 --- a/provider/child/tree.go +++ b/provider/child/tree.go @@ -1,6 +1,6 @@ package child -func (b *BaseChild) InitializeTree(blockHeight uint64) bool { +func (b *BaseChild) InitializeTree(blockHeight int64) bool { if b.initializeTreeFn != nil { ok, err := b.initializeTreeFn(blockHeight) if err != nil { diff --git a/provider/host/host.go b/provider/host/host.go index 31165cc..38607d7 100644 --- a/provider/host/host.go +++ b/provider/host/host.go @@ -79,7 +79,7 @@ func GetCodec(bech32Prefix string) (codec.Codec, client.TxConfig, error) { }) } -func (b *BaseHost) Initialize(ctx context.Context, startHeight uint64, bridgeInfo opchildtypes.BridgeInfo) error { +func (b *BaseHost) Initialize(ctx context.Context, startHeight int64, bridgeInfo opchildtypes.BridgeInfo) error { err := b.node.Initialize(ctx, startHeight) if err != nil { return err @@ -92,7 +92,7 @@ func (b *BaseHost) Start(ctx context.Context) { if b.cfg.ProcessType == nodetypes.PROCESS_TYPE_ONLY_BROADCAST { b.logger.Info("host start") } else { - b.logger.Info("host start", zap.Uint64("height", b.node.GetHeight())) + b.logger.Info("host start", zap.Int64("height", b.node.GetHeight())) } b.node.Start(ctx) } @@ -133,7 +133,7 @@ func (b BaseHost) HasKey() bool { return b.node.HasBroadcaster() } -func (b BaseHost) Height() uint64 { +func (b BaseHost) Height() int64 { return b.node.GetHeight() } diff --git a/provider/host/msgs.go b/provider/host/msgs.go index c11b80d..fcafd1c 100644 --- a/provider/host/msgs.go +++ b/provider/host/msgs.go @@ -2,6 +2,7 @@ package host import ( ophosttypes "github.com/initia-labs/OPinit/x/ophost/types" + "github.com/initia-labs/opinit-bots/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -9,7 +10,7 @@ import ( func (b BaseHost) GetMsgProposeOutput( bridgeId uint64, outputIndex uint64, - l2BlockNumber uint64, + l2BlockNumber int64, outputRoot []byte, ) (sdk.Msg, error) { sender, err := b.node.MustGetBroadcaster().GetAddressString() @@ -21,7 +22,7 @@ func (b BaseHost) GetMsgProposeOutput( sender, bridgeId, outputIndex, - l2BlockNumber, + types.MustInt64ToUint64(l2BlockNumber), outputRoot, ) err = msg.Validate(b.node.AccountCodec()) diff --git a/provider/host/parse.go b/provider/host/parse.go index ee3fedb..93ceda8 100644 --- a/provider/host/parse.go +++ b/provider/host/parse.go @@ -22,7 +22,8 @@ func ParseMsgRecordBatch(eventAttrs []abcitypes.EventAttribute) ( func ParseMsgUpdateBatchInfo(eventAttrs []abcitypes.EventAttribute) ( bridgeId uint64, submitter, chain string, - outputIndex, l2BlockNumber uint64, + outputIndex uint64, + l2BlockNumber int64, err error) { for _, attr := range eventAttrs { switch attr.Key { @@ -41,7 +42,7 @@ func ParseMsgUpdateBatchInfo(eventAttrs []abcitypes.EventAttribute) ( return } case ophosttypes.AttributeKeyFinalizedL2BlockNumber: - l2BlockNumber, err = strconv.ParseUint(attr.Value, 10, 64) + l2BlockNumber, err = strconv.ParseInt(attr.Value, 10, 64) if err != nil { return } @@ -88,7 +89,9 @@ func ParseMsgInitiateDeposit(eventAttrs []abcitypes.EventAttribute) ( } func ParseMsgProposeOutput(eventAttrs []abcitypes.EventAttribute) ( - bridgeId, l2BlockNumber, outputIndex uint64, + bridgeId uint64, + l2BlockNumber int64, + outputIndex uint64, proposer string, outputRoot []byte, err error) { @@ -107,7 +110,7 @@ func ParseMsgProposeOutput(eventAttrs []abcitypes.EventAttribute) ( return } case ophosttypes.AttributeKeyL2BlockNumber: - l2BlockNumber, err = strconv.ParseUint(attr.Value, 10, 64) + l2BlockNumber, err = strconv.ParseInt(attr.Value, 10, 64) if err != nil { return } diff --git a/provider/host/query.go b/provider/host/query.go index 520b1fe..c653ba3 100644 --- a/provider/host/query.go +++ b/provider/host/query.go @@ -73,7 +73,7 @@ func (b BaseHost) QueryLastOutput(ctx context.Context, bridgeId uint64) (*ophost return &res.OutputProposals[0], nil } -func (b BaseHost) QueryOutput(ctx context.Context, bridgeId uint64, outputIndex uint64, height uint64) (*ophosttypes.QueryOutputProposalResponse, error) { +func (b BaseHost) QueryOutput(ctx context.Context, bridgeId uint64, outputIndex uint64, height int64) (*ophosttypes.QueryOutputProposalResponse, error) { req := &ophosttypes.QueryOutputProposalRequest{ BridgeId: bridgeId, OutputIndex: outputIndex, @@ -85,7 +85,7 @@ func (b BaseHost) QueryOutput(ctx context.Context, bridgeId uint64, outputIndex } // QueryOutputByL2BlockNumber queries the last output proposal before the given L2 block number -func (b BaseHost) QueryOutputByL2BlockNumber(ctx context.Context, bridgeId uint64, l2BlockNumber uint64) (*ophosttypes.QueryOutputProposalResponse, error) { +func (b BaseHost) QueryOutputByL2BlockNumber(ctx context.Context, bridgeId uint64, l2BlockHeight int64) (*ophosttypes.QueryOutputProposalResponse, error) { start, err := b.QueryOutput(ctx, bridgeId, 1, 0) if err != nil { if strings.Contains(err.Error(), "not found") { @@ -100,6 +100,7 @@ func (b BaseHost) QueryOutputByL2BlockNumber(ctx context.Context, bridgeId uint6 return nil, nil } + l2BlockNumber := types.MustInt64ToUint64(l2BlockHeight) for { if start.OutputProposal.L2BlockNumber >= l2BlockNumber { if start.OutputIndex != 1 { @@ -126,7 +127,7 @@ func (b BaseHost) QueryOutputByL2BlockNumber(ctx context.Context, bridgeId uint6 } } -func (b BaseHost) QueryCreateBridgeHeight(ctx context.Context, bridgeId uint64) (uint64, error) { +func (b BaseHost) QueryCreateBridgeHeight(ctx context.Context, bridgeId uint64) (int64, error) { ctx, cancel := rpcclient.GetQueryContext(ctx, 0) defer cancel() @@ -144,7 +145,7 @@ func (b BaseHost) QueryCreateBridgeHeight(ctx context.Context, bridgeId uint64) // bridge not found return 0, errors.New("bridge not found") } - return uint64(res.Txs[0].Height), nil + return res.Txs[0].Height, nil } func (b BaseHost) QueryBatchInfos(ctx context.Context, bridgeId uint64) (*ophosttypes.QueryBatchInfosResponse, error) { @@ -156,7 +157,7 @@ func (b BaseHost) QueryBatchInfos(ctx context.Context, bridgeId uint64) (*ophost return b.ophostQueryClient.BatchInfos(ctx, req) } -func (b BaseHost) QueryDepositTxHeight(ctx context.Context, bridgeId uint64, l1Sequence uint64) (uint64, error) { +func (b BaseHost) QueryDepositTxHeight(ctx context.Context, bridgeId uint64, l1Sequence uint64) (int64, error) { if l1Sequence == 0 { return 0, nil } @@ -190,7 +191,7 @@ func (b BaseHost) QueryDepositTxHeight(ctx context.Context, bridgeId uint64, l1S if event.Type == ophosttypes.EventTypeInitiateTokenDeposit { for _, attr := range event.Attributes { if attr.Key == ophosttypes.AttributeKeyBridgeId && attr.Value == strconv.FormatUint(bridgeId, 10) { - return uint64(tx.Height), nil + return tx.Height, nil } } } diff --git a/types/math.go b/types/math.go new file mode 100644 index 0000000..919253e --- /dev/null +++ b/types/math.go @@ -0,0 +1,66 @@ +package types + +import ( + "errors" + "math" +) + +func SafeIntToUint8(v int) (uint8, error) { + if v < 0 || v > math.MaxUint8 { + return 0, errors.New("integer overflow conversion") + } + return uint8(v), nil +} + +func SafeIntToUint32(v int) (uint32, error) { + if v < 0 || v > math.MaxUint32 { + return 0, errors.New("integer overflow conversion") + } + return uint32(v), nil +} + +func SafeInt64ToUint64(v int64) (uint64, error) { + if v < 0 { + return 0, errors.New("integer overflow conversion") + } + return uint64(v), nil +} + +func SafeUint64ToInt64(v uint64) (int64, error) { + if v > math.MaxInt64 { + return 0, errors.New("integer overflow conversion") + } + return int64(v), nil +} + +func MustIntToUint8(v int) uint8 { + ret, err := SafeIntToUint8(v) + if err != nil { + panic(err) + } + return ret +} + +func MustIntToUint32(v int) uint32 { + ret, err := SafeIntToUint32(v) + if err != nil { + panic(err) + } + return ret +} + +func MustInt64ToUint64(v int64) uint64 { + ret, err := SafeInt64ToUint64(v) + if err != nil { + panic(err) + } + return ret +} + +func MustUint64ToInt64(v uint64) int64 { + ret, err := SafeUint64ToInt64(v) + if err != nil { + panic(err) + } + return ret +}