From ea35b228b4ef7676dcb5ff64217a13527e69582e Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 28 Sep 2023 16:41:46 +0700 Subject: [PATCH 001/132] fix hook request --- hooks/request/types.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/hooks/request/types.go b/hooks/request/types.go index 476f20077..69309140e 100644 --- a/hooks/request/types.go +++ b/hooks/request/types.go @@ -241,9 +241,12 @@ func (r Request) QueryRequestResponse() types.QueryRequestResponse { r.RequestHeight, r.RequestTime, r.ClientID, + 0, rawRequests, ibcChannel, r.ExecuteGas, + "", + nil, ) // Oracle result for the above request From 1be7f24831c130ff9200135261b3b60685bb7c63 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 3 Oct 2023 23:54:11 +0700 Subject: [PATCH 002/132] fix error --- hooks/emitter/decoder_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index 46b4e4fd2..3c7203a8e 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -191,6 +191,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgRequestData() { 1, "cleint_id", testapp.Coins100000000uband, + 0, testapp.TestDefaultPrepareGas, testapp.TestDefaultExecuteGas, SenderAddress, From 7cd8ee24b848c18b57a1b40f330124e4ec849086 Mon Sep 17 00:00:00 2001 From: satawatnack Date: Wed, 4 Oct 2023 16:30:02 +0700 Subject: [PATCH 003/132] init tss db --- app/app.go | 1 + flusher/flusher/db.py | 53 +++++++++++++++++++--- flusher/flusher/handler.py | 46 +++++++++++++------- hooks/emitter/decoder.go | 1 + hooks/emitter/decoder_test.go | 2 +- hooks/emitter/emitter.go | 7 ++- hooks/emitter/handler.go | 7 +++ hooks/emitter/oracle.go | 32 +++++++++++++- hooks/emitter/tss.go | 82 +++++++++++++++++++++++++++++++++++ 9 files changed, 207 insertions(+), 24 deletions(-) create mode 100644 hooks/emitter/tss.go diff --git a/app/app.go b/app/app.go index 64bdde141..3c2833d37 100644 --- a/app/app.go +++ b/app/app.go @@ -571,6 +571,7 @@ func NewBandApp( app.DistrKeeper, app.GovKeeper, app.OracleKeeper, + app.TSSKeeper, app.ICAHostKeeper, app.IBCKeeper.ClientKeeper, app.IBCKeeper.ConnectionKeeper, diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index bf1b6e090..32fc098db 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -29,8 +29,15 @@ class VoteOption(enum.Enum): NoWithVeto = 4 -class CustomResolveStatus(sa.types.TypeDecorator): +class TSSSigningStatus(enum.Enum): + nil = 0 + waiting = 1 + success = 2 + expired = 3 + failed = 4 + +class CustomResolveStatus(sa.types.TypeDecorator): impl = sa.Enum(ResolveStatus) def process_bind_param(self, value, dialect): @@ -38,21 +45,27 @@ def process_bind_param(self, value, dialect): class CustomProposalStatus(sa.types.TypeDecorator): - impl = sa.Enum(ProposalStatus) def process_bind_param(self, value, dialect): return ProposalStatus(value) +# unused class CustomVoteOption(sa.types.TypeDecorator): - impl = sa.Enum(VoteOption) def process_bind_param(self, value, dialect): return VoteOption(value) +class CustomTSSSigningStatus(sa.types.TypeDecorator): + impl = sa.Enum(TSSSigningStatus) + + def process_bind_param(self, value, dialect): + return TSSSigningStatus(value) + + class CustomDateTime(sa.types.TypeDecorator): """Custom DateTime type that accepts Python nanosecond epoch int.""" @@ -61,6 +74,7 @@ class CustomDateTime(sa.types.TypeDecorator): def process_bind_param(self, value, dialect): return datetime.fromtimestamp(value / 1e9) if value != None else None + class CustomBase64(sa.types.TypeDecorator): """Custom LargeBinary type that accepts base64-encoded string.""" @@ -193,6 +207,7 @@ def Column(*args, **kwargs): Column("execute_gas", sa.Integer), Column("execute_gas_used", sa.Integer, default=0), Column("sender", sa.String, nullable=True), + Column("tss_group_id", sa.Integer, default=0), Column("client_id", sa.String), Column("request_time", sa.Integer, nullable=True, index=True), Column("resolve_status", CustomResolveStatus), @@ -200,10 +215,38 @@ def Column(*args, **kwargs): Column("resolve_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True), Column("reason", sa.String, nullable=True), Column("result", CustomBase64, nullable=True), + Column("tss_signing_id", sa.Integer, nullable=True), Column("total_fees", sa.String), Column("is_ibc", sa.Boolean), - sa.Index("ix_requests_oracle_script_id_id", "oracle_script_id", "id", postgresql_include=['transaction_id', 'min_count', 'ask_count', 'resolve_status', 'request_time']), - sa.Index("ix_requests_oracle_script_id_resolve_status_request_time", "oracle_script_id", "resolve_status", "request_time"), + sa.Index( + "ix_requests_oracle_script_id_id", + "oracle_script_id", + "id", + postgresql_include=["transaction_id", "min_count", "ask_count", "resolve_status", "request_time"], + ), + sa.Index( + "ix_requests_oracle_script_id_resolve_status_request_time", + "oracle_script_id", + "resolve_status", + "request_time", + ), +) + +signing_data = sa.Table( + "signing_data", + metadata, + Column("signing_id", sa.Integer, primary_key=True), + Column("group_id", sa.Integer), + Column("group_pub_key", CustomBase64), + Column("msg", CustomBase64), + Column("group_pub_nonce", CustomBase64), + Column("signature", CustomBase64), + Column("fee", sa.String), + Column("status", CustomTSSSigningStatus), + Column("reason", sa.String), + Column("created_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True), + Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), index=True), + sa.Index("ix_group_id_group_pub_key_status", "group_id", "group_pub_key", "status"), ) raw_requests = sa.Table( diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 6fe84ba57..10f85a36f 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -39,6 +39,7 @@ connections, channels, relayer_tx_stat_days, + signing_data, ) @@ -71,12 +72,18 @@ def get_request_count(self, date): def get_oracle_script_requests_count_per_day(self, date, oracle_script_id): return self.conn.execute( - select([oracle_script_requests_per_days.c.count]).where((oracle_script_requests_per_days.c.date == date) & (oracle_script_requests_per_days.c.oracle_script_id == oracle_script_id)) + select([oracle_script_requests_per_days.c.count]).where( + (oracle_script_requests_per_days.c.date == date) + & (oracle_script_requests_per_days.c.oracle_script_id == oracle_script_id) + ) ).scalar() def get_data_source_requests_count_per_day(self, date, data_source_id): return self.conn.execute( - select([data_source_requests_per_days.c.count]).where((data_source_requests_per_days.c.date == date) & (data_source_requests_per_days.c.data_source_id == data_source_id)) + select([data_source_requests_per_days.c.count]).where( + (data_source_requests_per_days.c.date == date) + & (data_source_requests_per_days.c.data_source_id == data_source_id) + ) ).scalar() def get_data_source_id(self, id): @@ -168,7 +175,9 @@ def handle_new_request(self, msg): del msg["tx_hash"] if "timestamp" in msg: self.handle_set_request_count_per_day({"date": msg["timestamp"]}) - self.handle_update_oracle_script_requests_count_per_day({"date": msg["timestamp"], "oracle_script_id": msg["oracle_script_id"]}) + self.handle_update_oracle_script_requests_count_per_day( + {"date": msg["timestamp"], "oracle_script_id": msg["oracle_script_id"]} + ) self.update_oracle_script_last_request(msg["oracle_script_id"], msg["timestamp"]) del msg["timestamp"] self.conn.execute(requests.insert(), msg) @@ -193,7 +202,9 @@ def handle_update_related_ds_os(self, msg): def handle_new_raw_request(self, msg): self.increase_data_source_count(msg["data_source_id"]) if "timestamp" in msg: - self.handle_update_data_source_requests_count_per_day({"date": msg["timestamp"], "data_source_id": msg["data_source_id"]}) + self.handle_update_data_source_requests_count_per_day( + {"date": msg["timestamp"], "data_source_id": msg["data_source_id"]} + ) self.update_data_source_last_request(msg["data_source_id"], msg["timestamp"]) del msg["timestamp"] self.handle_update_related_ds_os( @@ -430,7 +441,9 @@ def handle_update_oracle_script_requests_count_per_day(self, msg): for col in oracle_script_requests_per_days.primary_key.columns.values(): condition = (col == msg[col.name]) & condition self.conn.execute( - oracle_script_requests_per_days.update(condition).values(count=oracle_script_requests_per_days.c.count + 1) + oracle_script_requests_per_days.update(condition).values( + count=oracle_script_requests_per_days.c.count + 1 + ) ) def handle_update_data_source_requests_count_per_day(self, msg): @@ -488,18 +501,10 @@ def increase_oracle_script_count(self, id): ) def update_oracle_script_last_request(self, id, timestamp): - self.conn.execute( - oracle_scripts.update(oracle_scripts.c.id == id).values( - last_request=timestamp - ) - ) + self.conn.execute(oracle_scripts.update(oracle_scripts.c.id == id).values(last_request=timestamp)) def update_data_source_last_request(self, id, timestamp): - self.conn.execute( - data_sources.update(data_sources.c.id == id).values( - last_request=timestamp - ) - ) + self.conn.execute(data_sources.update(data_sources.c.id == id).values(last_request=timestamp)) def handle_new_historical_bonded_token_on_validator(self, msg): self.conn.execute( @@ -559,3 +564,14 @@ def handle_set_relayer_tx_stat_days(self, port, channel, timestamp, address): .where(condition) .values(ibc_received_txs=relayer_tx_stat_days.c.ibc_received_txs + 1, last_update_at=timestamp) ) + + def handle_new_signing(self, msg): + msg["account_id"] = self.get_account_id(msg["requester"]) + del msg["requester"] + self.conn.execute(signing_data.insert(), msg) + + def handle_update_signing(self, msg): + condition = True + for col in signing_data.primary_key.columns.values(): + condition = (col == msg[col.name]) & condition + self.conn.execute(signing_data.update().where(condition).values(**msg)) diff --git a/hooks/emitter/decoder.go b/hooks/emitter/decoder.go index f334afa2e..dfb7085fd 100644 --- a/hooks/emitter/decoder.go +++ b/hooks/emitter/decoder.go @@ -251,6 +251,7 @@ func DecodeMsgRequestData(msg *oracletypes.MsgRequestData, detail common.JsDict) detail["min_count"] = msg.GetMinCount() detail["client_id"] = msg.GetClientID() detail["fee_limit"] = msg.GetFeeLimit() + detail["tss_group_id"] = msg.GetTSSGroupID() detail["prepare_gas"] = msg.GetPrepareGas() detail["execute_gas"] = msg.GetExecuteGas() detail["sender"] = msg.GetSender() diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index 3c7203a8e..d28bc4635 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -199,7 +199,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgRequestData() { emitter.DecodeMsgRequestData(msg, detail) suite.testCompareJson( detail, - "{\"ask_count\":1,\"calldata\":\"Y2FsbGRhdGE=\",\"client_id\":\"cleint_id\",\"execute_gas\":300000,\"fee_limit\":[{\"denom\":\"uband\",\"amount\":\"100000000\"}],\"min_count\":1,\"oracle_script_id\":1,\"prepare_gas\":40000,\"sender\":\"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0\"}", + "{\"ask_count\":1,\"calldata\":\"Y2FsbGRhdGE=\",\"client_id\":\"cleint_id\",\"execute_gas\":300000,\"fee_limit\":[{\"denom\":\"uband\",\"amount\":\"100000000\"}],\"min_count\":1,\"oracle_script_id\":1,\"prepare_gas\":40000,\"sender\":\"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0\",\"tss_group_id\":0}", ) } diff --git a/hooks/emitter/emitter.go b/hooks/emitter/emitter.go index 0fb97c543..68c426a75 100644 --- a/hooks/emitter/emitter.go +++ b/hooks/emitter/emitter.go @@ -33,10 +33,10 @@ import ( "github.com/bandprotocol/chain/v2/app/params" "github.com/bandprotocol/chain/v2/hooks/common" - "github.com/bandprotocol/chain/v2/x/oracle/keeper" oraclekeeper "github.com/bandprotocol/chain/v2/x/oracle/keeper" "github.com/bandprotocol/chain/v2/x/oracle/types" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" + tsskeeper "github.com/bandprotocol/chain/v2/x/tss/keeper" ) // Hook uses Kafka functionality to act as an event producer for all events in the blockchains. @@ -59,6 +59,7 @@ type Hook struct { distrKeeper distrkeeper.Keeper govKeeper govkeeper.Keeper oracleKeeper oraclekeeper.Keeper + tssKeeper tsskeeper.Keeper icahostKeeper icahostkeeper.Keeper //ibc keeper @@ -78,7 +79,8 @@ func NewHook( mintKeeper mintkeeper.Keeper, distrKeeper distrkeeper.Keeper, govKeeper govkeeper.Keeper, - oracleKeeper keeper.Keeper, + oracleKeeper oraclekeeper.Keeper, + tssKeeper tsskeeper.Keeper, icahostKeeper icahostkeeper.Keeper, clientkeeper clientkeeper.Keeper, connectionkeeper connectionkeeper.Keeper, @@ -105,6 +107,7 @@ func NewHook( distrKeeper: distrKeeper, govKeeper: govKeeper, oracleKeeper: oracleKeeper, + tssKeeper: tssKeeper, icahostKeeper: icahostKeeper, clientkeeper: clientkeeper, connectionkeeper: connectionkeeper, diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index 28cf31f1a..7ade1cfd9 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -18,6 +18,7 @@ import ( "github.com/bandprotocol/chain/v2/hooks/common" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" + tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) func parseEvents(events sdk.StringEvents) common.EvMap { @@ -145,6 +146,12 @@ func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) h.handleEventTypeTransfer(evMap) case channeltypes.EventTypeSendPacket: h.handleEventSendPacket(ctx, evMap) + case tsstypes.EventTypeRequestSignature: + h.handleEventRequestSignature(ctx, evMap) + case tsstypes.EventTypeSigningSuccess: + h.handleEventSigningSuccess(ctx, evMap) + case tsstypes.EventTypeSigningFailed: + h.handleEventSigningFailed(ctx, evMap) default: break } diff --git a/hooks/emitter/oracle.go b/hooks/emitter/oracle.go index 4693d98cd..e7979660d 100644 --- a/hooks/emitter/oracle.go +++ b/hooks/emitter/oracle.go @@ -106,7 +106,33 @@ func (app *Hook) emitReportAndRawReport( } } -func (h *Hook) emitUpdateResult(ctx sdk.Context, id types.RequestID, executeGasUsed uint64, reason string) { +func (h *Hook) emitUpdateResult( + ctx sdk.Context, + id types.RequestID, + executeGasUsed uint64, + reason string, +) { + result := h.oracleKeeper.MustGetResult(ctx, id) + + h.Write("UPDATE_REQUEST", common.JsDict{ + "id": id, + "execute_gas_used": executeGasUsed, + "request_time": result.RequestTime, + "resolve_time": result.ResolveTime, + "resolve_status": result.ResolveStatus, + "resolve_height": ctx.BlockHeight(), + "reason": reason, + "result": parseBytes(result.Result), + }) +} + +func (h *Hook) emitUpdateResultTSS( + ctx sdk.Context, + id types.RequestID, + tssSigningID uint64, + executeGasUsed uint64, + reason string, +) { result := h.oracleKeeper.MustGetResult(ctx, id) h.Write("UPDATE_REQUEST", common.JsDict{ @@ -118,6 +144,7 @@ func (h *Hook) emitUpdateResult(ctx sdk.Context, id types.RequestID, executeGasU "resolve_height": ctx.BlockHeight(), "reason": reason, "result": parseBytes(result.Result), + "tss_signing_id": tssSigningID, }) } @@ -141,6 +168,7 @@ func (h *Hook) handleMsgRequestData( "ask_count": msg.AskCount, "min_count": msg.MinCount, "sender": msg.Sender, + "tss_group_id": msg.TSSGroupID, "client_id": msg.ClientID, "resolve_status": types.RESOLVE_STATUS_OPEN, "timestamp": ctx.BlockTime().UnixNano(), @@ -232,6 +260,8 @@ func (h *Hook) handleEventRequestExecute(ctx sdk.Context, evMap common.EvMap) { executeGasUsed, reasons[0], ) + } else if tssSid, ok := evMap[types.EventTypeResolve+"."+types.AttributeKeySigningID]; ok { + h.emitUpdateResultTSS(ctx, types.RequestID(common.Atoi(evMap[types.EventTypeResolve+"."+types.AttributeKeyID][0])), uint64(common.Atoi(tssSid[0])), executeGasUsed, "") } else { h.emitUpdateResult(ctx, types.RequestID(common.Atoi(evMap[types.EventTypeResolve+"."+types.AttributeKeyID][0])), executeGasUsed, "") } diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go new file mode 100644 index 000000000..5424ad3ec --- /dev/null +++ b/hooks/emitter/tss.go @@ -0,0 +1,82 @@ +package emitter + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/hooks/common" + "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/bandprotocol/chain/v2/x/oracle/types" + tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" +) + +func (h *Hook) emitNewSigning(signing tsstypes.Signing) { + h.Write("NEW_SIGNING", common.JsDict{ + "signing_id": signing.SigningID, + "group_id": signing.GroupID, + "group_pub_key": parseBytes(signing.GroupPubKey), + "msg": parseBytes(signing.Message), + "group_pub_nonce": parseBytes(signing.GroupPubNonce), + "fee": signing.Fee.String(), + "status": int(signing.Status), + "created_height": signing.CreatedHeight, + "requester": signing.Requester, + }) +} + +func (h *Hook) emitUpdateSigningSuccess(signing tsstypes.Signing) { + h.Write("UPDATE_SIGNING", common.JsDict{ + "signing_id": signing.SigningID, + "status": int(signing.Status), + "signature": parseBytes(signing.Signature), + }) +} + +func (h *Hook) emitUpdateSigningFailed(reason string, signing tsstypes.Signing) { + h.Write("UPDATE_SIGNING", common.JsDict{ + "signing_id": signing.SigningID, + "status": int(signing.Status), + "reason": reason, + }) +} + +// future use +func (h *Hook) emitUpdateSigningExpired(signing tsstypes.Signing) { + h.Write("UPDATE_SIGNING", common.JsDict{ + "signing_id": signing.SigningID, + "status": int(signing.Status), + }) +} + +// handleEventRequestSignature implements emitter handler for RequestSignature event. +func (h *Hook) handleEventRequestSignature(ctx sdk.Context, evMap common.EvMap) { + id := tss.SigningID(common.Atoi(evMap[tsstypes.EventTypeRequestSignature+"."+types.AttributeKeySigningID][0])) + signing := h.tssKeeper.MustGetSigning(ctx, id) + + h.emitNewSigning(signing) +} + +// handleEventSigningSuccess implements emitter handler for SigningSuccess event. +func (h *Hook) handleEventSigningSuccess(ctx sdk.Context, evMap common.EvMap) { + id := tss.SigningID(common.Atoi(evMap[tsstypes.EventTypeSigningSuccess+"."+types.AttributeKeySigningID][0])) + signing := h.tssKeeper.MustGetSigning(ctx, id) + + h.emitUpdateSigningSuccess(signing) +} + +// handleEventSigningFailed implements emitter handler for SigningSuccess event. +func (h *Hook) handleEventSigningFailed(ctx sdk.Context, evMap common.EvMap) { + id := tss.SigningID(common.Atoi(evMap[tsstypes.EventTypeSigningFailed+"."+types.AttributeKeySigningID][0])) + signing := h.tssKeeper.MustGetSigning(ctx, id) + + if reason, ok := evMap[tsstypes.EventTypeSigningFailed+"."+tsstypes.AttributeKeyReason]; ok { + h.emitUpdateSigningFailed( + reason[0], + signing, + ) + } else { + h.emitUpdateSigningFailed( + "failed with on reason", + signing, + ) + } +} From 8fc4555912379e7554247d4c277971b37cb526ba Mon Sep 17 00:00:00 2001 From: satawatnack Date: Wed, 4 Oct 2023 16:56:18 +0700 Subject: [PATCH 004/132] add init tss --- hooks/emitter/emitter.go | 3 +++ hooks/emitter/tss.go | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/hooks/emitter/emitter.go b/hooks/emitter/emitter.go index 68c426a75..44bec9ad7 100644 --- a/hooks/emitter/emitter.go +++ b/hooks/emitter/emitter.go @@ -276,6 +276,9 @@ func (h *Hook) AfterInitChain(ctx sdk.Context, req abci.RequestInitChain, res ab h.emitSetVoteWeighted(setVoteWeighted, vote.Options) } + // TSS module + h.handleInitTssModule(ctx) + // Oracle module var oracleState oracletypes.GenesisState h.cdc.MustUnmarshalJSON(genesisState[oracletypes.ModuleName], &oracleState) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 5424ad3ec..615756e18 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -47,6 +47,24 @@ func (h *Hook) emitUpdateSigningExpired(signing tsstypes.Signing) { }) } +// handleInitTssModule implements emitter handler for initializing tss module. +func (h *Hook) handleInitTssModule(ctx sdk.Context) { + for _, signing := range h.tssKeeper.GetAllReplacementSigning(ctx) { + h.Write("NEW_SIGNING", common.JsDict{ + "signing_id": signing.SigningID, + "group_id": signing.GroupID, + "group_pub_key": parseBytes(signing.GroupPubKey), + "msg": parseBytes(signing.Message), + "group_pub_nonce": parseBytes(signing.GroupPubNonce), + "signature": parseBytes(signing.Signature), + "fee": signing.Fee.String(), + "status": int(signing.Status), + "created_height": signing.CreatedHeight, + "requester": signing.Requester, + }) + } +} + // handleEventRequestSignature implements emitter handler for RequestSignature event. func (h *Hook) handleEventRequestSignature(ctx sdk.Context, evMap common.EvMap) { id := tss.SigningID(common.Atoi(evMap[tsstypes.EventTypeRequestSignature+"."+types.AttributeKeySigningID][0])) From a17d63f07f16f459f08efd0aecc0acc7515f6b04 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 4 Oct 2023 16:59:15 +0700 Subject: [PATCH 005/132] fix null --- flusher/flusher/db.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index 32fc098db..503fb28e0 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -240,7 +240,7 @@ def Column(*args, **kwargs): Column("group_pub_key", CustomBase64), Column("msg", CustomBase64), Column("group_pub_nonce", CustomBase64), - Column("signature", CustomBase64), + Column("signature", CustomBase64, nullable=True), Column("fee", sa.String), Column("status", CustomTSSSigningStatus), Column("reason", sa.String), From 0c8d841ebd9c539a08dae95a187155f20912f797 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 4 Oct 2023 17:03:51 +0700 Subject: [PATCH 006/132] nullable --- flusher/flusher/db.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index 503fb28e0..2b9e95dea 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -243,7 +243,7 @@ def Column(*args, **kwargs): Column("signature", CustomBase64, nullable=True), Column("fee", sa.String), Column("status", CustomTSSSigningStatus), - Column("reason", sa.String), + Column("reason", sa.String, nullable=True), Column("created_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True), Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), index=True), sa.Index("ix_group_id_group_pub_key_status", "group_id", "group_pub_key", "status"), From 247d9c83cd473347769bd04ea619bf6cf2a8bf5a Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 4 Oct 2023 17:16:14 +0700 Subject: [PATCH 007/132] adjust hasura --- hasura/hasura-metadata/tables.yaml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index 1f2e87d04..1b636befc 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -76,6 +76,13 @@ table: name: reports schema: public + - name: signing_data + using: + foreign_key_constraint_on: + column: account_id + table: + name: signing_data + schema: public - name: unbonding_delegations using: foreign_key_constraint_on: @@ -119,6 +126,13 @@ table: name: requests schema: public + - name: signing_data + using: + foreign_key_constraint_on: + column: created_height + table: + name: signing_data + schema: public - name: transactions using: foreign_key_constraint_on: @@ -591,6 +605,16 @@ table: name: val_requests schema: public +- table: + name: signing_data + schema: public + object_relationships: + - name: account + using: + foreign_key_constraint_on: account_id + - name: block + using: + foreign_key_constraint_on: created_height - table: name: tracking schema: public From cb78aba0792bb6733b932df7c921e6952cc0a787 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 4 Oct 2023 17:30:25 +0700 Subject: [PATCH 008/132] add foreign --- flusher/flusher/db.py | 4 ++-- hooks/emitter/tss.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index 2b9e95dea..27f6468b3 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -215,7 +215,7 @@ def Column(*args, **kwargs): Column("resolve_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True), Column("reason", sa.String, nullable=True), Column("result", CustomBase64, nullable=True), - Column("tss_signing_id", sa.Integer, nullable=True), + Column("tss_signing_id", sa.Integer, sa.ForeignKey("signing_data.id"), nullable=True), Column("total_fees", sa.String), Column("is_ibc", sa.Boolean), sa.Index( @@ -235,7 +235,7 @@ def Column(*args, **kwargs): signing_data = sa.Table( "signing_data", metadata, - Column("signing_id", sa.Integer, primary_key=True), + Column("id", sa.Integer, primary_key=True), Column("group_id", sa.Integer), Column("group_pub_key", CustomBase64), Column("msg", CustomBase64), diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 615756e18..f7614ce94 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -11,7 +11,7 @@ import ( func (h *Hook) emitNewSigning(signing tsstypes.Signing) { h.Write("NEW_SIGNING", common.JsDict{ - "signing_id": signing.SigningID, + "id": signing.SigningID, "group_id": signing.GroupID, "group_pub_key": parseBytes(signing.GroupPubKey), "msg": parseBytes(signing.Message), @@ -51,7 +51,7 @@ func (h *Hook) emitUpdateSigningExpired(signing tsstypes.Signing) { func (h *Hook) handleInitTssModule(ctx sdk.Context) { for _, signing := range h.tssKeeper.GetAllReplacementSigning(ctx) { h.Write("NEW_SIGNING", common.JsDict{ - "signing_id": signing.SigningID, + "id": signing.SigningID, "group_id": signing.GroupID, "group_pub_key": parseBytes(signing.GroupPubKey), "msg": parseBytes(signing.Message), From 2fbc95b00a7cd9955bd464e0b042a6cc88f8e806 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 4 Oct 2023 17:34:49 +0700 Subject: [PATCH 009/132] add relation --- hasura/hasura-metadata/tables.yaml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index 1b636befc..784ced95b 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -580,6 +580,9 @@ - name: oracle_script using: foreign_key_constraint_on: oracle_script_id + - name: signing_datum + using: + foreign_key_constraint_on: tss_signing_id - name: transaction using: foreign_key_constraint_on: transaction_id @@ -615,6 +618,14 @@ - name: block using: foreign_key_constraint_on: created_height + array_relationships: + - name: requests + using: + foreign_key_constraint_on: + column: tss_signing_id + table: + name: requests + schema: public - table: name: tracking schema: public From 5d576398ceecdb21181dc89f787565cf801548d0 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 4 Oct 2023 17:40:16 +0700 Subject: [PATCH 010/132] fix id --- hooks/emitter/tss.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index f7614ce94..6a5f36d8d 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -25,25 +25,25 @@ func (h *Hook) emitNewSigning(signing tsstypes.Signing) { func (h *Hook) emitUpdateSigningSuccess(signing tsstypes.Signing) { h.Write("UPDATE_SIGNING", common.JsDict{ - "signing_id": signing.SigningID, - "status": int(signing.Status), - "signature": parseBytes(signing.Signature), + "id": signing.SigningID, + "status": int(signing.Status), + "signature": parseBytes(signing.Signature), }) } func (h *Hook) emitUpdateSigningFailed(reason string, signing tsstypes.Signing) { h.Write("UPDATE_SIGNING", common.JsDict{ - "signing_id": signing.SigningID, - "status": int(signing.Status), - "reason": reason, + "id": signing.SigningID, + "status": int(signing.Status), + "reason": reason, }) } // future use func (h *Hook) emitUpdateSigningExpired(signing tsstypes.Signing) { h.Write("UPDATE_SIGNING", common.JsDict{ - "signing_id": signing.SigningID, - "status": int(signing.Status), + "id": signing.SigningID, + "status": int(signing.Status), }) } From 1e2585ade94a48469f24c0ab185de2f6f6286c6e Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 5 Oct 2023 11:53:43 +0700 Subject: [PATCH 011/132] add tss in docker --- docker-config/start_docker.sh | 61 +++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 289966373..346278956 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -38,6 +38,15 @@ echo "smile stem oven genius cave resource better lunar nasty moon company ridge echo "audit silver absorb involve more aspect girl report open gather excite mirror bar hammer clay tackle negative example gym group finger shop stool seminar" \ | bandd keys add relayer --recover --keyring-backend test +echo "drop video mention casual soldier ostrich resemble harvest casual step design gasp grunt lab meadow buzz envelope today spy cliff column habit fall eyebrow" \ + | bandd keys add tss1 --recover --keyring-backend test + +echo "enlist electric thumb valve inherit visa ecology trust cake argue forward hidden thing analyst science treat ice lend pumpkin today ticket purchase process pioneer" \ + | bandd keys add tss2 --recover --keyring-backend test + +echo "measure fence mail fluid olive cute empower fossil ahead manage snow marble dash citizen tourist skate assist solution bonus spend tip negative try eyebrow" \ + | bandd keys add tss3 --recover --keyring-backend test + # add accounts to genesis bandd genesis add-genesis-account validator1 10000000000000uband --keyring-backend test bandd genesis add-genesis-account validator2 10000000000000uband --keyring-backend test @@ -45,6 +54,9 @@ bandd genesis add-genesis-account validator3 10000000000000uband --keyring-backe bandd genesis add-genesis-account validator4 10000000000000uband --keyring-backend test bandd genesis add-genesis-account requester 100000000000000uband --keyring-backend test bandd genesis add-genesis-account relayer 100000000000000uband --keyring-backend test +bandd genesis add-genesis-account tss1 100000000000000uband --keyring-backend test +bandd genesis add-genesis-account tss2 100000000000000uband --keyring-backend test +bandd genesis add-genesis-account tss3 100000000000000uband --keyring-backend test # create copy of config.toml cp ~/.band/config/config.toml ~/.band/config/config.toml.temp @@ -150,6 +162,55 @@ do docker start bandchain_oracle${v} done +sleep 10 + +for v in {1..3} +do + rm -rf ~/.cylinder + cylinder config node tcp://multi-validator$v-node:26657 + cylinder config chain-id bandchain + cylinder config granter $(bandd keys show tss$v -a --keyring-backend test) + cylinder config max-messages 10 + cylinder config broadcast-timeout "5m" + cylinder config rpc-poll-interval "1s" + cylinder config max-try 5 + cylinder config gas-prices "0.0025uband" + cylinder config min-de 20 + cylinder config gas-adjust-start 1.6 + cylinder config gas-adjust-step 0.2 + cylinder config random-secret "$(openssl rand -hex 32)" + cylinder config active-period "12h" + + # activate tss + echo "y" | bandd tx tss activate --from tss$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync + + # wait for activation transaction success + sleep 4 + + for i in $(eval echo {1..1}) + do + # add signer key + cylinder keys add signer$i + done + + # send band tokens to signers + echo "y" | bandd tx bank send tss$v $(cylinder keys list -a) 1000000uband --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync + + # wait for sending band tokens transaction success + sleep 4 + + # add reporter to bandchain + echo "y" | bandd tx tss add-grantees $(cylinder keys list -a) --from tss$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync + + # wait for addding reporter transaction success + sleep 4 + + docker create --network chain_bandchain --name bandchain_cylinder${v} band-validator:latest cylinder run + docker cp ~/.cylinder bandchain_cylinder${v}:/root/.cylinder + docker start bandchain_cylinder${v} +done + + # Create faucet container rm -rf ~/.faucet faucet config chain-id bandchain From 687416c5955e9294a09cc608aae0b54eede8c430 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Fri, 6 Oct 2023 12:03:34 +0700 Subject: [PATCH 012/132] update --- hooks/emitter/tss.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 6a5f36d8d..1097e2754 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -11,7 +11,7 @@ import ( func (h *Hook) emitNewSigning(signing tsstypes.Signing) { h.Write("NEW_SIGNING", common.JsDict{ - "id": signing.SigningID, + "id": signing.ID, "group_id": signing.GroupID, "group_pub_key": parseBytes(signing.GroupPubKey), "msg": parseBytes(signing.Message), @@ -25,7 +25,7 @@ func (h *Hook) emitNewSigning(signing tsstypes.Signing) { func (h *Hook) emitUpdateSigningSuccess(signing tsstypes.Signing) { h.Write("UPDATE_SIGNING", common.JsDict{ - "id": signing.SigningID, + "id": signing.ID, "status": int(signing.Status), "signature": parseBytes(signing.Signature), }) @@ -33,7 +33,7 @@ func (h *Hook) emitUpdateSigningSuccess(signing tsstypes.Signing) { func (h *Hook) emitUpdateSigningFailed(reason string, signing tsstypes.Signing) { h.Write("UPDATE_SIGNING", common.JsDict{ - "id": signing.SigningID, + "id": signing.ID, "status": int(signing.Status), "reason": reason, }) @@ -42,7 +42,7 @@ func (h *Hook) emitUpdateSigningFailed(reason string, signing tsstypes.Signing) // future use func (h *Hook) emitUpdateSigningExpired(signing tsstypes.Signing) { h.Write("UPDATE_SIGNING", common.JsDict{ - "id": signing.SigningID, + "id": signing.ID, "status": int(signing.Status), }) } @@ -51,7 +51,7 @@ func (h *Hook) emitUpdateSigningExpired(signing tsstypes.Signing) { func (h *Hook) handleInitTssModule(ctx sdk.Context) { for _, signing := range h.tssKeeper.GetAllReplacementSigning(ctx) { h.Write("NEW_SIGNING", common.JsDict{ - "id": signing.SigningID, + "id": signing.ID, "group_id": signing.GroupID, "group_pub_key": parseBytes(signing.GroupPubKey), "msg": parseBytes(signing.Message), From be703dc149240197481b0f936bed18c6bf01d4da Mon Sep 17 00:00:00 2001 From: satawatnack Date: Fri, 6 Oct 2023 17:25:00 +0700 Subject: [PATCH 013/132] init full db --- flusher/flusher/db.py | 32 -------- flusher/flusher/handler.py | 35 +++++++++ flusher/flusher/tss_db.py | 147 +++++++++++++++++++++++++++++++++++++ hooks/emitter/handler.go | 10 +++ hooks/emitter/tss.go | 60 +++++++++++++++ x/tss/keeper/msg_server.go | 2 + 6 files changed, 254 insertions(+), 32 deletions(-) create mode 100644 flusher/flusher/tss_db.py diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index 27f6468b3..70f646e64 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -29,14 +29,6 @@ class VoteOption(enum.Enum): NoWithVeto = 4 -class TSSSigningStatus(enum.Enum): - nil = 0 - waiting = 1 - success = 2 - expired = 3 - failed = 4 - - class CustomResolveStatus(sa.types.TypeDecorator): impl = sa.Enum(ResolveStatus) @@ -59,13 +51,6 @@ def process_bind_param(self, value, dialect): return VoteOption(value) -class CustomTSSSigningStatus(sa.types.TypeDecorator): - impl = sa.Enum(TSSSigningStatus) - - def process_bind_param(self, value, dialect): - return TSSSigningStatus(value) - - class CustomDateTime(sa.types.TypeDecorator): """Custom DateTime type that accepts Python nanosecond epoch int.""" @@ -232,23 +217,6 @@ def Column(*args, **kwargs): ), ) -signing_data = sa.Table( - "signing_data", - metadata, - Column("id", sa.Integer, primary_key=True), - Column("group_id", sa.Integer), - Column("group_pub_key", CustomBase64), - Column("msg", CustomBase64), - Column("group_pub_nonce", CustomBase64), - Column("signature", CustomBase64, nullable=True), - Column("fee", sa.String), - Column("status", CustomTSSSigningStatus), - Column("reason", sa.String, nullable=True), - Column("created_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True), - Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), index=True), - sa.Index("ix_group_id_group_pub_key_status", "group_id", "group_pub_key", "status"), -) - raw_requests = sa.Table( "raw_requests", metadata, diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 10f85a36f..a0f924378 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -39,7 +39,15 @@ connections, channels, relayer_tx_stat_days, +) + +from .tss_db import ( signing_data, + groups, + tss_accounts, + members, + assigned_members, + replacements, ) @@ -65,6 +73,11 @@ def get_account_id(self, address): return self.conn.execute(select([accounts.c.id]).where(accounts.c.address == address)).scalar() return id + def have_tss_account(self, account_id): + return ( + self.conn.execute(select([tss_accounts.c.id]).where(tss_accounts.c.id == account_id)).scalar() is not None + ) + def get_request_count(self, date): return self.conn.execute( select([request_count_per_days.c.count]).where(request_count_per_days.c.date == date) @@ -575,3 +588,25 @@ def handle_update_signing(self, msg): for col in signing_data.primary_key.columns.values(): condition = (col == msg[col.name]) & condition self.conn.execute(signing_data.update().where(condition).values(**msg)) + + def handle_set_tss_account_status(self, msg): + msg["account_id"] = self.get_account_id(msg["address"]) + del msg["address"] + + if not self.have_tss_account(msg["account_id"]): + self.conn.execute(tss_accounts.insert(), msg) + else: + condition = True + for col in tss_accounts.primary_key.columns.values(): + condition = (col == msg[col.name]) & condition + self.conn.execute(tss_accounts.update().where(condition).values(**msg)) + + def handle_set_member(self, msg): + msg["account_id"] = self.get_account_id(msg["address"]) + del msg["address"] + self.conn.execute(members.insert(), msg) + + def handle_set_group(self, msg): + if msg["latest_replacement_id"] == 0: + msg["latest_replacement_id"] = None + self.conn.execute(groups.insert(), msg) diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py new file mode 100644 index 000000000..0f6383e52 --- /dev/null +++ b/flusher/flusher/tss_db.py @@ -0,0 +1,147 @@ +import sqlalchemy as sa +import enum + +from .db import ( + metadata, + Column, + CustomBase64, + CustomDateTime, +) + + +class SigningStatus(enum.Enum): + nil = 0 + waiting = 1 + success = 2 + expired = 3 + failed = 4 + + +class GroupStatus(enum.Enum): + nil = 0 + round1 = 1 + round2 = 2 + round3 = 3 + active = 4 + expired = 5 + failed = 6 + + +class TSSAccountStatus(enum.Enum): + nil = 0 + active = 1 + inactive = 2 + jail = 3 + + +class ReplacementStatus(enum.Enum): + nil = 0 + waiting = 1 + success = 2 + fallen = 3 + + +class CustomSigningStatus(sa.types.TypeDecorator): + impl = sa.Enum(SigningStatus) + + def process_bind_param(self, value, dialect): + return SigningStatus(value) + + +class CustomGroupStatus(sa.types.TypeDecorator): + impl = sa.Enum(GroupStatus) + + def process_bind_param(self, value, dialect): + return GroupStatus(value) + + +class CustomTSSAccountStatus(sa.types.TypeDecorator): + impl = sa.Enum(TSSAccountStatus) + + def process_bind_param(self, value, dialect): + return TSSAccountStatus(value) + + +class CustomReplacementStatus(sa.types.TypeDecorator): + impl = sa.Enum(ReplacementStatus) + + def process_bind_param(self, value, dialect): + return ReplacementStatus(value) + + +signing_data = sa.Table( + "signing_data", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("group_id", sa.Integer), + Column("group_pub_key", CustomBase64), + Column("msg", CustomBase64), + Column("group_pub_nonce", CustomBase64), + Column("signature", CustomBase64, nullable=True), + Column("fee", sa.String), + Column("status", CustomSigningStatus), + Column("reason", sa.String, nullable=True), + Column("created_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True), + Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), index=True), + sa.Index("ix_group_id_group_pub_key_status", "group_id", "group_pub_key", "status"), +) + +groups = sa.Table( + "groups", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("size", sa.Integer), + Column("threshold", sa.Integer), + Column("dkg_context", CustomBase64), + Column("pub_key", CustomBase64, nullable=True), + Column("status", CustomGroupStatus), + Column("fee", sa.String), + # if zero set it to nil + Column("latest_replacement_id", sa.integer, sa.ForeignKey("replacements.id"), nullable=True), + Column("created_height", sa.Integer, index=True), +) + +tss_accounts = sa.Table( + "tss_accounts", + metadata, + Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), + Column("status", CustomTSSAccountStatus), + Column("since", CustomDateTime), + Column("last_active", CustomDateTime), +) + +members = sa.Table( + "members", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("group_id", sa.Integer, sa.ForeignKey("groups.id"), primary_key=True), + Column("account_id", sa.integer, sa.ForeignKey("tss_accounts.account_id")), + Column("pub_key", CustomBase64, nullable=True), + Column("is_malicious", sa.Boolean), +) + +assigned_members = sa.Table( + "assigned_members", + metadata, + Column("signing_id", sa.Integer, sa.ForeignKey("signing_data.id"), primary_key=True), + Column("member_id", sa.Integer, primary_key=True), + Column("group_id", sa.Integer, primary_key=True), + Column("pub_d", CustomBase64), + Column("pub_e", CustomBase64), + Column("binding_factor", CustomBase64), + Column("pub_nonce", CustomBase64), + sa.ForeignKeyConstraint(["member_id", "group_id"], ["members.id", "members.group_id"]), +) + +replacements = sa.Table( + "replacements", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("signing_id", sa.Integer, sa.Foreignkey("signing_data.id")), + Column("from_group_id", sa.Integer, sa.Foreignkey("groups.id")), + Column("from_pub_key", CustomBase64), + Column("to_group_id", sa.Integer, sa.ForeignKey("groups.id")), + Column("to_pub_key", CustomBase64), + Column("exec_time", CustomDateTime), + Column("status", ReplacementStatus), +) diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index 7ade1cfd9..c8602a6fb 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -152,6 +152,16 @@ func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) h.handleEventSigningSuccess(ctx, evMap) case tsstypes.EventTypeSigningFailed: h.handleEventSigningFailed(ctx, evMap) + case tsstypes.EventTypeActivate: + h.handleEventActivateTSSAccount(ctx, evMap) + case tsstypes.EventTypeCreateGroup, + tsstypes.EventTypeRound2Success, + tsstypes.EventTypeComplainSuccess, + tsstypes.EventTypeComplainFailed, + tsstypes.EventTypeRound3Success, + // TODO: event UpdateGroupFee + tsstypes.EventTypeReplaceSuccess: + h.handleEventSetGroup(ctx, evMap) default: break } diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 1097e2754..ef7fd908f 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -47,6 +47,39 @@ func (h *Hook) emitUpdateSigningExpired(signing tsstypes.Signing) { }) } +func (h *Hook) emitSetTSSAccountStatus(status tsstypes.Status) { + h.Write("SET_TSS_ACCOUNT_STATUS", common.JsDict{ + "address": status.Address, + "status": int(status.Status), + "since": status.Since.Unix(), + "last_active": status.LastActive.Unix(), + }) +} + +func (h *Hook) emitSetGroup(group tsstypes.Group, dkgContext []byte) { + h.Write("SET_GROUP", common.JsDict{ + "id": group.GroupID, + "size": group.Size_, + "threshold": group.Threshold, + "dkg_context": parseBytes(dkgContext), + "pub_key": parseBytes(group.PubKey), + "status": int(group.Status), + "fee": group.Fee.String(), + "latest_replacement_id": group.LatestReplacementID, + "created_height": group.CreatedHeight, + }) +} + +func (h *Hook) emitSetMember(member tsstypes.Member) { + h.Write("Set_MEMBER", common.JsDict{ + "id": member.ID, + "group_id": member.GroupID, + "address": member.Address, + "pub_key": parseBytes(member.PubKey), + "is_malicious": member.IsMalicious, + }) +} + // handleInitTssModule implements emitter handler for initializing tss module. func (h *Hook) handleInitTssModule(ctx sdk.Context) { for _, signing := range h.tssKeeper.GetAllReplacementSigning(ctx) { @@ -70,6 +103,8 @@ func (h *Hook) handleEventRequestSignature(ctx sdk.Context, evMap common.EvMap) id := tss.SigningID(common.Atoi(evMap[tsstypes.EventTypeRequestSignature+"."+types.AttributeKeySigningID][0])) signing := h.tssKeeper.MustGetSigning(ctx, id) + // TODO: emit assigned member + h.emitNewSigning(signing) } @@ -98,3 +133,28 @@ func (h *Hook) handleEventSigningFailed(ctx sdk.Context, evMap common.EvMap) { ) } } + +// handleEventActivateTSSAccount implements emitter handler for tss account activate event. +func (h *Hook) handleEventActivateTSSAccount(ctx sdk.Context, evMap common.EvMap) { + address := sdk.MustAccAddressFromBech32(evMap[tsstypes.EventTypeActivate+"."+tsstypes.AttributeKeyMember][0]) + status := h.tssKeeper.GetStatus(ctx, address) + + h.emitSetTSSAccountStatus(status) +} + +// handleEventSetGroup implements emitter handler for events related to groups. +func (h *Hook) handleEventSetGroup(ctx sdk.Context, evMap common.EvMap) { + gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeCreateGroup+"."+tsstypes.AttributeKeyGroupID][0])) + group := h.tssKeeper.MustGetGroup(ctx, gid) + dkgContext, err := h.tssKeeper.GetDKGContext(ctx, gid) + if err != nil { + panic(err) + } + + h.emitSetGroup(group, dkgContext) + + members := h.tssKeeper.MustGetMembers(ctx, gid) + for _, m := range members { + h.emitSetMember(m) + } +} diff --git a/x/tss/keeper/msg_server.go b/x/tss/keeper/msg_server.go index 43403cf02..338c98e86 100644 --- a/x/tss/keeper/msg_server.go +++ b/x/tss/keeper/msg_server.go @@ -216,6 +216,8 @@ func (k msgServer) UpdateGroupFee( group.Fee = req.Fee.Sort() k.SetGroup(ctx, group) + // TODO: add event + return &types.MsgUpdateGroupFeeResponse{}, nil } From 48d62398f5902b7bea9ab5132b60ae4d6313af7d Mon Sep 17 00:00:00 2001 From: satawatnack Date: Fri, 6 Oct 2023 18:31:10 +0700 Subject: [PATCH 014/132] add err code space --- flusher/flusher/db.py | 2 ++ flusher/flusher/handler.py | 4 ++++ hooks/emitter/oracle.go | 49 ++++++++++++++++++++++++++++---------- 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index 27f6468b3..7a87e8dfd 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -216,6 +216,8 @@ def Column(*args, **kwargs): Column("reason", sa.String, nullable=True), Column("result", CustomBase64, nullable=True), Column("tss_signing_id", sa.Integer, sa.ForeignKey("signing_data.id"), nullable=True), + Column("tss_signing_error_codespace", sa.String, nullable=True), + Column("tss_signing_error_code", sa.Integer, nullable=True), Column("total_fees", sa.String), Column("is_ibc", sa.Boolean), sa.Index( diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 10f85a36f..aa213efc3 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -187,6 +187,10 @@ def handle_update_request(self, msg): if "tx_hash" in msg: msg["transaction_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] + + if msg["tss_signing_id"] == 0: + del msg["tss_signing_id"] + condition = True for col in requests.primary_key.columns.values(): condition = (col == msg[col.name]) & condition diff --git a/hooks/emitter/oracle.go b/hooks/emitter/oracle.go index e7979660d..0543cd352 100644 --- a/hooks/emitter/oracle.go +++ b/hooks/emitter/oracle.go @@ -129,22 +129,26 @@ func (h *Hook) emitUpdateResult( func (h *Hook) emitUpdateResultTSS( ctx sdk.Context, id types.RequestID, - tssSigningID uint64, executeGasUsed uint64, reason string, + tssSigningID uint64, + tssSigningErrorCodespace string, + tssSigningErrorCode uint64, ) { result := h.oracleKeeper.MustGetResult(ctx, id) h.Write("UPDATE_REQUEST", common.JsDict{ - "id": id, - "execute_gas_used": executeGasUsed, - "request_time": result.RequestTime, - "resolve_time": result.ResolveTime, - "resolve_status": result.ResolveStatus, - "resolve_height": ctx.BlockHeight(), - "reason": reason, - "result": parseBytes(result.Result), - "tss_signing_id": tssSigningID, + "id": id, + "execute_gas_used": executeGasUsed, + "request_time": result.RequestTime, + "resolve_time": result.ResolveTime, + "resolve_status": result.ResolveStatus, + "resolve_height": ctx.BlockHeight(), + "reason": reason, + "result": parseBytes(result.Result), + "tss_signing_id": tssSigningID, + "tss_signing_error_codespace": tssSigningErrorCodespace, + "tss_signing_error_code": tssSigningErrorCode, }) } @@ -253,17 +257,36 @@ func (h *Hook) handleEventRequestExecute(ctx sdk.Context, evMap common.EvMap) { executeGasUsed = oraclekeeper.ConvertToGas(common.Atoui(eventResolveGasUsed[0])) } + rid := types.RequestID(common.Atoi(evMap[types.EventTypeResolve+"."+types.AttributeKeyID][0])) if reasons, ok := evMap[types.EventTypeResolve+"."+types.AttributeKeyReason]; ok { h.emitUpdateResult( ctx, - types.RequestID(common.Atoi(evMap[types.EventTypeResolve+"."+types.AttributeKeyID][0])), + rid, executeGasUsed, reasons[0], ) + } else if tssErrCodespace, ok := evMap[types.EventTypeResolve+"."+types.AttributeKeySigningErrCodespace]; ok { + h.emitUpdateResultTSS( + ctx, + rid, + executeGasUsed, + "", + 0, + tssErrCodespace[0], + uint64(common.Atoi(evMap[types.EventTypeResolve+"."+types.AttributeKeySigningErrCode][0])), + ) } else if tssSid, ok := evMap[types.EventTypeResolve+"."+types.AttributeKeySigningID]; ok { - h.emitUpdateResultTSS(ctx, types.RequestID(common.Atoi(evMap[types.EventTypeResolve+"."+types.AttributeKeyID][0])), uint64(common.Atoi(tssSid[0])), executeGasUsed, "") + h.emitUpdateResultTSS( + ctx, + rid, + executeGasUsed, + "", + uint64(common.Atoi(tssSid[0])), + "", + 0, + ) } else { - h.emitUpdateResult(ctx, types.RequestID(common.Atoi(evMap[types.EventTypeResolve+"."+types.AttributeKeyID][0])), executeGasUsed, "") + h.emitUpdateResult(ctx, rid, executeGasUsed, "") } } From 5433965cc34c7525e109a87b2b06517596fe6308 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Fri, 6 Oct 2023 18:46:39 +0700 Subject: [PATCH 015/132] fix error --- flusher/flusher/handler.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index aa213efc3..80c9e62d5 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -188,8 +188,9 @@ def handle_update_request(self, msg): msg["transaction_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] - if msg["tss_signing_id"] == 0: - del msg["tss_signing_id"] + if "tss_signing_id" in msg: + if msg["tss_signing_id"] == 0: + del msg["tss_signing_id"] condition = True for col in requests.primary_key.columns.values(): From 46db1f79672fe1ce66b5f118e5ad9d9a55becd74 Mon Sep 17 00:00:00 2001 From: satawatnack Date: Mon, 9 Oct 2023 10:39:07 +0700 Subject: [PATCH 016/132] add new assigned_members --- flusher/flusher/handler.py | 3 +++ hooks/emitter/tss.go | 18 ++++++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 723cd1a90..9fb913912 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -615,3 +615,6 @@ def handle_set_group(self, msg): if msg["latest_replacement_id"] == 0: msg["latest_replacement_id"] = None self.conn.execute(groups.insert(), msg) + + def handle_new_assigned_members(self, msg): + self.conn.execute(assigned_members.insert(), msg) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index ef7fd908f..2b5aabf67 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -71,7 +71,7 @@ func (h *Hook) emitSetGroup(group tsstypes.Group, dkgContext []byte) { } func (h *Hook) emitSetMember(member tsstypes.Member) { - h.Write("Set_MEMBER", common.JsDict{ + h.Write("SET_MEMBER", common.JsDict{ "id": member.ID, "group_id": member.GroupID, "address": member.Address, @@ -80,6 +80,18 @@ func (h *Hook) emitSetMember(member tsstypes.Member) { }) } +func (h *Hook) emitNewAssignedMember(sid tss.SigningID, gid tss.GroupID, am tsstypes.AssignedMember) { + h.Write("NEW_ASSIGNED_MEMBER", common.JsDict{ + "signing_id": sid, + "member_id": am.MemberID, + "group_id": gid, + "pub_d": parseBytes(am.PubD), + "pub_e": parseBytes(am.PubE), + "binding_factor": parseBytes(am.PubKey), + "pub_nonce": parseBytes(am.PubNonce), + }) +} + // handleInitTssModule implements emitter handler for initializing tss module. func (h *Hook) handleInitTssModule(ctx sdk.Context) { for _, signing := range h.tssKeeper.GetAllReplacementSigning(ctx) { @@ -103,7 +115,9 @@ func (h *Hook) handleEventRequestSignature(ctx sdk.Context, evMap common.EvMap) id := tss.SigningID(common.Atoi(evMap[tsstypes.EventTypeRequestSignature+"."+types.AttributeKeySigningID][0])) signing := h.tssKeeper.MustGetSigning(ctx, id) - // TODO: emit assigned member + for _, am := range signing.AssignedMembers { + h.emitNewAssignedMember(signing.ID, signing.GroupID, am) + } h.emitNewSigning(signing) } From 6d1a4f87323cca799822fbfcbea0c6c8443061bd Mon Sep 17 00:00:00 2001 From: satawatnack Date: Mon, 9 Oct 2023 15:45:57 +0700 Subject: [PATCH 017/132] add replacement --- flusher/flusher/handler.py | 19 ++++++++--- hooks/emitter/emitter.go | 2 +- hooks/emitter/handler.go | 53 ++++++++++++++++++++++++----- hooks/emitter/tss.go | 69 ++++++++++++++++++++++++++++++++------ 4 files changed, 118 insertions(+), 25 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 9fb913912..e57968f6e 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -606,15 +606,24 @@ def handle_set_tss_account_status(self, msg): condition = (col == msg[col.name]) & condition self.conn.execute(tss_accounts.update().where(condition).values(**msg)) - def handle_set_member(self, msg): - msg["account_id"] = self.get_account_id(msg["address"]) - del msg["address"] - self.conn.execute(members.insert(), msg) - def handle_set_group(self, msg): if msg["latest_replacement_id"] == 0: msg["latest_replacement_id"] = None self.conn.execute(groups.insert(), msg) + def handle_set_member(self, msg): + msg["account_id"] = self.get_account_id(msg["address"]) + del msg["address"] + self.conn.execute(members.insert(), msg) + def handle_new_assigned_members(self, msg): self.conn.execute(assigned_members.insert(), msg) + + def handle_new_replacement(self, msg): + self.conn.execute(replacements.insert(), msg) + + def handle_update_replacement_status(self, msg): + condition = True + for col in signing_data.primary_key.columns.values(): + condition = (col == msg[col.name]) & condition + self.conn.execute(replacements.update().where(condition).values(**msg)) diff --git a/hooks/emitter/emitter.go b/hooks/emitter/emitter.go index 44bec9ad7..0d1e710b1 100644 --- a/hooks/emitter/emitter.go +++ b/hooks/emitter/emitter.go @@ -277,7 +277,7 @@ func (h *Hook) AfterInitChain(ctx sdk.Context, req abci.RequestInitChain, res ab } // TSS module - h.handleInitTssModule(ctx) + h.handleInitTSSModule(ctx) // Oracle module var oracleState oracletypes.GenesisState diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index c8602a6fb..214fd60b0 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -17,6 +17,7 @@ import ( channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" "github.com/bandprotocol/chain/v2/hooks/common" + "github.com/bandprotocol/chain/v2/pkg/tss" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) @@ -152,16 +153,50 @@ func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) h.handleEventSigningSuccess(ctx, evMap) case tsstypes.EventTypeSigningFailed: h.handleEventSigningFailed(ctx, evMap) + case tsstypes.EventTypeExpiredSigning: + h.handleEventExpiredSigning(ctx, evMap) case tsstypes.EventTypeActivate: - h.handleEventActivateTSSAccount(ctx, evMap) - case tsstypes.EventTypeCreateGroup, - tsstypes.EventTypeRound2Success, - tsstypes.EventTypeComplainSuccess, - tsstypes.EventTypeComplainFailed, - tsstypes.EventTypeRound3Success, - // TODO: event UpdateGroupFee - tsstypes.EventTypeReplaceSuccess: - h.handleEventSetGroup(ctx, evMap) + address := sdk.MustAccAddressFromBech32(evMap[tsstypes.EventTypeActivate+"."+tsstypes.AttributeKeyAddress][0]) + h.handleUpdateStatusTSSAccount(ctx, address) + case tsstypes.EventTypeActive: + address := sdk.MustAccAddressFromBech32(evMap[tsstypes.EventTypeActive+"."+tsstypes.AttributeKeyAddress][0]) + h.handleUpdateStatusTSSAccount(ctx, address) + case tsstypes.EventTypeInactive: + address := sdk.MustAccAddressFromBech32(evMap[tsstypes.EventTypeInactive+"."+tsstypes.AttributeKeyAddress][0]) + h.handleUpdateStatusTSSAccount(ctx, address) + case tsstypes.EventTypeCreateGroup: + gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeCreateGroup+"."+tsstypes.AttributeKeyGroupID][0])) + h.handleSetGroup(ctx, gid) + case tsstypes.EventTypeRound2Success: + gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeRound2Success+"."+tsstypes.AttributeKeyGroupID][0])) + h.handleSetGroup(ctx, gid) + case tsstypes.EventTypeComplainSuccess: + gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeComplainSuccess+"."+tsstypes.AttributeKeyGroupID][0])) + h.handleSetGroup(ctx, gid) + case tsstypes.EventTypeComplainFailed: + gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeComplainFailed+"."+tsstypes.AttributeKeyGroupID][0])) + h.handleSetGroup(ctx, gid) + case tsstypes.EventTypeRound3Success: + gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeRound3Success+"."+tsstypes.AttributeKeyGroupID][0])) + h.handleSetGroup(ctx, gid) + case tsstypes.EventTypeExpiredGroup: + gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeExpiredGroup+"."+tsstypes.AttributeKeyGroupID][0])) + h.handleSetGroup(ctx, gid) + case tsstypes.EventTypeUpdateGroupFee: + gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeUpdateGroupFee+"."+tsstypes.AttributeKeyGroupID][0])) + h.handleSetGroup(ctx, gid) + case tsstypes.EventTypeReplacement: + h.handleInitReplacement(ctx, evMap) + case tsstypes.EventTypeReplacementSuccess: + rid := uint64( + common.Atoi(evMap[tsstypes.EventTypeReplacementSuccess+"."+tsstypes.AttributeKeyReplacementID][0]), + ) + h.handleUpdateReplacementStatus(ctx, rid) + case tsstypes.EventTypeReplacementFailed: + rid := uint64( + common.Atoi(evMap[tsstypes.EventTypeReplacementFailed+"."+tsstypes.AttributeKeyReplacementID][0]), + ) + h.handleUpdateReplacementStatus(ctx, rid) default: break } diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 2b5aabf67..3cb7678bc 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -39,8 +39,7 @@ func (h *Hook) emitUpdateSigningFailed(reason string, signing tsstypes.Signing) }) } -// future use -func (h *Hook) emitUpdateSigningExpired(signing tsstypes.Signing) { +func (h *Hook) emitUpdateSigningStatus(signing tsstypes.Signing) { h.Write("UPDATE_SIGNING", common.JsDict{ "id": signing.ID, "status": int(signing.Status), @@ -92,8 +91,28 @@ func (h *Hook) emitNewAssignedMember(sid tss.SigningID, gid tss.GroupID, am tsst }) } -// handleInitTssModule implements emitter handler for initializing tss module. -func (h *Hook) handleInitTssModule(ctx sdk.Context) { +func (h *Hook) emitNewReplacement(replacement tsstypes.Replacement) { + h.Write("NEW_REPLACEMENT", common.JsDict{ + "id": replacement.ID, + "signing_id": replacement.SigningID, + "from_group_id": replacement.FromGroupID, + "from_pub_key": parseBytes(replacement.FromPubKey), + "to_group_id": replacement.ToGroupID, + "to_pub_key": parseBytes(replacement.ToPubKey), + "exec_time": replacement.ExecTime.Unix(), + "status": int(replacement.Status), + }) +} + +func (h *Hook) emitUpdateReplacementStatus(ctx sdk.Context, id uint64, status tsstypes.ReplacementStatus) { + h.Write("UPDATE_REPLACEMENT_STATUS", common.JsDict{ + "id": id, + "status": int(status), + }) +} + +// handleInitTSSModule implements emitter handler for initializing tss module. +func (h *Hook) handleInitTSSModule(ctx sdk.Context) { for _, signing := range h.tssKeeper.GetAllReplacementSigning(ctx) { h.Write("NEW_SIGNING", common.JsDict{ "id": signing.ID, @@ -148,17 +167,23 @@ func (h *Hook) handleEventSigningFailed(ctx sdk.Context, evMap common.EvMap) { } } -// handleEventActivateTSSAccount implements emitter handler for tss account activate event. -func (h *Hook) handleEventActivateTSSAccount(ctx sdk.Context, evMap common.EvMap) { - address := sdk.MustAccAddressFromBech32(evMap[tsstypes.EventTypeActivate+"."+tsstypes.AttributeKeyMember][0]) +// handleEventExpiredSigning implements emitter handler for ExpiredSigning event. +func (h *Hook) handleEventExpiredSigning(ctx sdk.Context, evMap common.EvMap) { + id := tss.SigningID(common.Atoi(evMap[tsstypes.EventTypeExpiredSigning+"."+types.AttributeKeySigningID][0])) + signing := h.tssKeeper.MustGetSigning(ctx, id) + + h.emitUpdateSigningStatus(signing) +} + +// handleUpdateStatusTSSAccount implements emitter handler for update tss account status. +func (h *Hook) handleUpdateStatusTSSAccount(ctx sdk.Context, address sdk.AccAddress) { status := h.tssKeeper.GetStatus(ctx, address) h.emitSetTSSAccountStatus(status) } -// handleEventSetGroup implements emitter handler for events related to groups. -func (h *Hook) handleEventSetGroup(ctx sdk.Context, evMap common.EvMap) { - gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeCreateGroup+"."+tsstypes.AttributeKeyGroupID][0])) +// handleSetGroup implements emitter handler events related to group. +func (h *Hook) handleSetGroup(ctx sdk.Context, gid tss.GroupID) { group := h.tssKeeper.MustGetGroup(ctx, gid) dkgContext, err := h.tssKeeper.GetDKGContext(ctx, gid) if err != nil { @@ -172,3 +197,27 @@ func (h *Hook) handleEventSetGroup(ctx sdk.Context, evMap common.EvMap) { h.emitSetMember(m) } } + +// handleInitReplacement implements emitter handler for init replacement event. +func (h *Hook) handleInitReplacement(ctx sdk.Context, evMap common.EvMap) { + rid := common.Atoi(evMap[tsstypes.EventTypeReplacement+"."+tsstypes.AttributeKeyReplacementID][0]) + r, err := h.tssKeeper.GetReplacement(ctx, uint64(rid)) + if err != nil { + panic(err) + } + + h.emitNewReplacement(r) +} + +// handleUpdateReplacementStatus implements emitter handler events related to replacements. +func (h *Hook) handleUpdateReplacementStatus(ctx sdk.Context, rid uint64) { + r, err := h.tssKeeper.GetReplacement(ctx, rid) + if err != nil { + panic(err) + } + if r.Status == tsstypes.REPLACEMENT_STATUS_SUCCESS { + h.handleSetGroup(ctx, r.ToGroupID) + } + + h.emitUpdateReplacementStatus(ctx, rid, r.Status) +} From 702edbb09dcf106f9733ab0ddc85a7471d93102d Mon Sep 17 00:00:00 2001 From: satawatnack Date: Mon, 9 Oct 2023 16:12:49 +0700 Subject: [PATCH 018/132] merge --- hooks/emitter/handler.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index 214fd60b0..9f1d15283 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -158,8 +158,10 @@ func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) case tsstypes.EventTypeActivate: address := sdk.MustAccAddressFromBech32(evMap[tsstypes.EventTypeActivate+"."+tsstypes.AttributeKeyAddress][0]) h.handleUpdateStatusTSSAccount(ctx, address) - case tsstypes.EventTypeActive: - address := sdk.MustAccAddressFromBech32(evMap[tsstypes.EventTypeActive+"."+tsstypes.AttributeKeyAddress][0]) + case tsstypes.EventTypeHealthCheck: + address := sdk.MustAccAddressFromBech32( + evMap[tsstypes.EventTypeHealthCheck+"."+tsstypes.AttributeKeyAddress][0], + ) h.handleUpdateStatusTSSAccount(ctx, address) case tsstypes.EventTypeInactive: address := sdk.MustAccAddressFromBech32(evMap[tsstypes.EventTypeInactive+"."+tsstypes.AttributeKeyAddress][0]) From 8ac38c6a2eb265a05edb4d7422946b13990a9789 Mon Sep 17 00:00:00 2001 From: satawatnack Date: Mon, 9 Oct 2023 16:23:46 +0700 Subject: [PATCH 019/132] add gid --- flusher/flusher/tss_db.py | 147 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 flusher/flusher/tss_db.py diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py new file mode 100644 index 000000000..eb5cff25d --- /dev/null +++ b/flusher/flusher/tss_db.py @@ -0,0 +1,147 @@ +import sqlalchemy as sa +import enum + +from .db import ( + metadata, + Column, + CustomBase64, + CustomDateTime, +) + + +class SigningStatus(enum.Enum): + nil = 0 + waiting = 1 + success = 2 + expired = 3 + failed = 4 + + +class GroupStatus(enum.Enum): + nil = 0 + round1 = 1 + round2 = 2 + round3 = 3 + active = 4 + expired = 5 + failed = 6 + + +class TSSAccountStatus(enum.Enum): + nil = 0 + active = 1 + inactive = 2 + jail = 3 + + +class ReplacementStatus(enum.Enum): + nil = 0 + waiting = 1 + success = 2 + fallen = 3 + + +class CustomSigningStatus(sa.types.TypeDecorator): + impl = sa.Enum(SigningStatus) + + def process_bind_param(self, value, dialect): + return SigningStatus(value) + + +class CustomGroupStatus(sa.types.TypeDecorator): + impl = sa.Enum(GroupStatus) + + def process_bind_param(self, value, dialect): + return GroupStatus(value) + + +class CustomTSSAccountStatus(sa.types.TypeDecorator): + impl = sa.Enum(TSSAccountStatus) + + def process_bind_param(self, value, dialect): + return TSSAccountStatus(value) + + +class CustomReplacementStatus(sa.types.TypeDecorator): + impl = sa.Enum(ReplacementStatus) + + def process_bind_param(self, value, dialect): + return ReplacementStatus(value) + + +signing_data = sa.Table( + "signing_data", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("group_id", sa.Integer, sa.ForeignKey("groups.id")), + Column("group_pub_key", CustomBase64), + Column("msg", CustomBase64), + Column("group_pub_nonce", CustomBase64), + Column("signature", CustomBase64, nullable=True), + Column("fee", sa.String), + Column("status", CustomSigningStatus), + Column("reason", sa.String, nullable=True), + Column("created_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True), + Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), index=True), + sa.Index("ix_group_id_group_pub_key_status", "group_id", "group_pub_key", "status"), +) + +groups = sa.Table( + "groups", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("size", sa.Integer), + Column("threshold", sa.Integer), + Column("dkg_context", CustomBase64), + Column("pub_key", CustomBase64, nullable=True), + Column("status", CustomGroupStatus), + Column("fee", sa.String), + # if zero set it to nil + Column("latest_replacement_id", sa.integer, sa.ForeignKey("replacements.id"), nullable=True), + Column("created_height", sa.Integer, index=True), +) + +tss_accounts = sa.Table( + "tss_accounts", + metadata, + Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), + Column("status", CustomTSSAccountStatus), + Column("since", CustomDateTime), + Column("last_active", CustomDateTime), +) + +members = sa.Table( + "members", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("group_id", sa.Integer, sa.ForeignKey("groups.id"), primary_key=True), + Column("account_id", sa.integer, sa.ForeignKey("tss_accounts.account_id")), + Column("pub_key", CustomBase64, nullable=True), + Column("is_malicious", sa.Boolean), +) + +assigned_members = sa.Table( + "assigned_members", + metadata, + Column("signing_id", sa.Integer, sa.ForeignKey("signing_data.id"), primary_key=True), + Column("member_id", sa.Integer, primary_key=True), + Column("group_id", sa.Integer, primary_key=True), + Column("pub_d", CustomBase64), + Column("pub_e", CustomBase64), + Column("binding_factor", CustomBase64), + Column("pub_nonce", CustomBase64), + sa.ForeignKeyConstraint(["member_id", "group_id"], ["members.id", "members.group_id"]), +) + +replacements = sa.Table( + "replacements", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("signing_id", sa.Integer, sa.Foreignkey("signing_data.id")), + Column("from_group_id", sa.Integer, sa.Foreignkey("groups.id")), + Column("from_pub_key", CustomBase64), + Column("to_group_id", sa.Integer, sa.ForeignKey("groups.id")), + Column("to_pub_key", CustomBase64), + Column("exec_time", CustomDateTime), + Column("status", ReplacementStatus), +) From 10890d952f8eb8315164acfeccece7563932f3a0 Mon Sep 17 00:00:00 2001 From: satawatnack Date: Mon, 9 Oct 2023 16:33:36 +0700 Subject: [PATCH 020/132] add pk --- flusher/flusher/tss_db.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index eb5cff25d..c956c38cc 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -124,8 +124,8 @@ def process_bind_param(self, value, dialect): "assigned_members", metadata, Column("signing_id", sa.Integer, sa.ForeignKey("signing_data.id"), primary_key=True), - Column("member_id", sa.Integer, primary_key=True), Column("group_id", sa.Integer, primary_key=True), + Column("member_id", sa.Integer, primary_key=True), Column("pub_d", CustomBase64), Column("pub_e", CustomBase64), Column("binding_factor", CustomBase64), From dd7976cc2084a92dae197b5a69ccba11de093e7b Mon Sep 17 00:00:00 2001 From: satawatnack Date: Mon, 9 Oct 2023 16:34:35 +0700 Subject: [PATCH 021/132] add fk --- flusher/flusher/tss_db.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index 9ccb4902b..c956c38cc 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -73,11 +73,7 @@ def process_bind_param(self, value, dialect): "signing_data", metadata, Column("id", sa.Integer, primary_key=True), -<<<<<<< HEAD - Column("group_id", sa.Integer), -======= Column("group_id", sa.Integer, sa.ForeignKey("groups.id")), ->>>>>>> extra/rest-tss-update Column("group_pub_key", CustomBase64), Column("msg", CustomBase64), Column("group_pub_nonce", CustomBase64), From e58d06802eeee882e7b84513c18033e978ed5640 Mon Sep 17 00:00:00 2001 From: satawatnack Date: Mon, 9 Oct 2023 16:35:52 +0700 Subject: [PATCH 022/132] add depguard --- .golangci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.golangci.yml b/.golangci.yml index 7b61b0ebe..cc2e0c3df 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -4,6 +4,7 @@ linters: disable-all: true enable: - bodyclose + - depguard - gofmt - goimports - misspell From 82d8e4c78331393333095c209cf5b8e442bf5e9d Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 10 Oct 2023 15:44:48 +0700 Subject: [PATCH 023/132] fix error --- hooks/emitter/tss.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 1097e2754..10c22a324 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -49,7 +49,7 @@ func (h *Hook) emitUpdateSigningExpired(signing tsstypes.Signing) { // handleInitTssModule implements emitter handler for initializing tss module. func (h *Hook) handleInitTssModule(ctx sdk.Context) { - for _, signing := range h.tssKeeper.GetAllReplacementSigning(ctx) { + for _, signing := range h.tssKeeper.GetSignings(ctx) { h.Write("NEW_SIGNING", common.JsDict{ "id": signing.ID, "group_id": signing.GroupID, From 8f0a1e8c65e9a707f743399678e77c426b1708f7 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 21 Dec 2023 14:10:30 +0700 Subject: [PATCH 024/132] update and fix test --- hooks/emitter/decoder_test.go | 3 ++- hooks/request/types.go | 3 ++- x/oracle/keeper/report.go | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index 3c7203a8e..fd5684773 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -191,10 +191,11 @@ func (suite *DecoderTestSuite) TestDecodeMsgRequestData() { 1, "cleint_id", testapp.Coins100000000uband, - 0, testapp.TestDefaultPrepareGas, testapp.TestDefaultExecuteGas, SenderAddress, + 0, + 0, ) emitter.DecodeMsgRequestData(msg, detail) suite.testCompareJson( diff --git a/hooks/request/types.go b/hooks/request/types.go index 69309140e..4251f7a68 100644 --- a/hooks/request/types.go +++ b/hooks/request/types.go @@ -241,10 +241,11 @@ func (r Request) QueryRequestResponse() types.QueryRequestResponse { r.RequestHeight, r.RequestTime, r.ClientID, - 0, rawRequests, ibcChannel, r.ExecuteGas, + 0, + 0, "", nil, ) diff --git a/x/oracle/keeper/report.go b/x/oracle/keeper/report.go index 08bd2626d..1cd649261 100644 --- a/x/oracle/keeper/report.go +++ b/x/oracle/keeper/report.go @@ -14,7 +14,7 @@ func (k Keeper) HasReport(ctx sdk.Context, rid types.RequestID, val sdk.ValAddre func (k Keeper) GetReport(ctx sdk.Context, rid types.RequestID, val sdk.ValAddress) (types.Report, error) { bz := ctx.KVStore(k.storeKey).Get(types.ReportsOfValidatorPrefixKey(rid, val)) if bz == nil { - return types.Report{}, sdkerrors.Wrapf(types.ErrReportNotFound, "reqID: %d, valAddr: %s", rid, val.String()) + return types.Report{}, types.ErrReportNotFound.Wrapf("reqID: %d, valAddr: %s", rid, val.String()) } var report types.Report k.cdc.MustUnmarshal(bz, &report) From f4673c8c6eeb0b3c195ec055ed38f7066366f483 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 11 Jan 2024 11:32:45 +0700 Subject: [PATCH 025/132] fix --- hooks/emitter/tss.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index ce9a8f759..0ba2dacbf 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -57,7 +57,7 @@ func (h *Hook) emitSetTSSAccountStatus(status tsstypes.Status) { func (h *Hook) emitSetGroup(group tsstypes.Group, dkgContext []byte) { h.Write("SET_GROUP", common.JsDict{ - "id": group.GroupID, + "id": group.ID, "size": group.Size_, "threshold": group.Threshold, "dkg_context": parseBytes(dkgContext), From d645cd863c5d789eb8a41a7992388713e02e1c4f Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 11 Jan 2024 14:57:52 +0700 Subject: [PATCH 026/132] remove unused --- flusher/flusher/db.py | 150 ++++++++++++++++++++++++++++++------------ 1 file changed, 107 insertions(+), 43 deletions(-) diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index 95a92de34..5de4369e6 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -21,14 +21,6 @@ class ProposalStatus(enum.Enum): Inactive = 6 -class VoteOption(enum.Enum): - Empty = 0 - Yes = 1 - Abstain = 2 - No = 3 - NoWithVeto = 4 - - class CustomResolveStatus(sa.types.TypeDecorator): impl = sa.Enum(ResolveStatus) @@ -43,14 +35,6 @@ def process_bind_param(self, value, dialect): return ProposalStatus(value) -# unused -class CustomVoteOption(sa.types.TypeDecorator): - impl = sa.Enum(VoteOption) - - def process_bind_param(self, value, dialect): - return VoteOption(value) - - class CustomDateTime(sa.types.TypeDecorator): """Custom DateTime type that accepts Python nanosecond epoch int.""" @@ -157,7 +141,9 @@ def Column(*args, **kwargs): Column("executable", CustomBase64), Column("treasury", sa.String), Column("fee", sa.String), - Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True), + Column( + "transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True + ), Column("accumulated_revenue", sa.BigInteger), Column("last_request", CustomDateTime, nullable=True), ) @@ -172,7 +158,9 @@ def Column(*args, **kwargs): Column("schema", sa.String), Column("codehash", sa.String), Column("source_code_url", sa.String), - Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True), + Column( + "transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True + ), Column("version", sa.Integer, nullable=True), Column("last_request", CustomDateTime, nullable=True), ) @@ -197,10 +185,18 @@ def Column(*args, **kwargs): Column("request_time", sa.Integer, nullable=True, index=True), Column("resolve_status", CustomResolveStatus), Column("resolve_time", sa.Integer, nullable=True), - Column("resolve_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True), + Column( + "resolve_height", + sa.Integer, + sa.ForeignKey("blocks.height"), + nullable=True, + index=True, + ), Column("reason", sa.String, nullable=True), Column("result", CustomBase64, nullable=True), - Column("tss_signing_id", sa.Integer, sa.ForeignKey("signing_data.id"), nullable=True), + Column( + "tss_signing_id", sa.Integer, sa.ForeignKey("signing_data.id"), nullable=True + ), Column("tss_signing_error_codespace", sa.String, nullable=True), Column("tss_signing_error_code", sa.Integer, nullable=True), Column("total_fees", sa.String), @@ -209,7 +205,13 @@ def Column(*args, **kwargs): "ix_requests_oracle_script_id_id", "oracle_script_id", "id", - postgresql_include=["transaction_id", "min_count", "ask_count", "resolve_status", "request_time"], + postgresql_include=[ + "transaction_id", + "min_count", + "ask_count", + "resolve_status", + "request_time", + ], ), sa.Index( "ix_requests_oracle_script_id_resolve_status_request_time", @@ -227,14 +229,18 @@ def Column(*args, **kwargs): Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), index=True), Column("fee", sa.BigInteger), Column("calldata", CustomBase64), - sa.Index("ix_raw_requests_data_source_id_request_id", "data_source_id", "request_id"), + sa.Index( + "ix_raw_requests_data_source_id_request_id", "data_source_id", "request_id" + ), ) val_requests = sa.Table( "val_requests", metadata, Column("request_id", sa.Integer, sa.ForeignKey("requests.id"), primary_key=True), - Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), + Column( + "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True + ), ) reports = sa.Table( @@ -242,7 +248,9 @@ def Column(*args, **kwargs): metadata, Column("request_id", sa.Integer, sa.ForeignKey("requests.id"), primary_key=True), Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id")), - Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), + Column( + "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True + ), Column("reporter_id", sa.Integer, sa.ForeignKey("accounts.id")), sa.Index("ix_reports_validator_id_request_id", "validator_id", "request_id"), ) @@ -255,8 +263,13 @@ def Column(*args, **kwargs): Column("external_id", sa.BigInteger, primary_key=True), Column("data", CustomBase64), Column("exit_code", sa.BigInteger), - sa.ForeignKeyConstraint(["request_id", "validator_id"], ["reports.request_id", "reports.validator_id"]), - sa.ForeignKeyConstraint(["request_id", "external_id"], ["raw_requests.request_id", "raw_requests.external_id"]), + sa.ForeignKeyConstraint( + ["request_id", "validator_id"], ["reports.request_id", "reports.validator_id"] + ), + sa.ForeignKeyConstraint( + ["request_id", "external_id"], + ["raw_requests.request_id", "raw_requests.external_id"], + ), ) validators = sa.Table( @@ -288,7 +301,9 @@ def Column(*args, **kwargs): delegations = sa.Table( "delegations", metadata, - Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), + Column( + "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True + ), Column("delegator_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), Column("shares", sa.DECIMAL), Column("last_ratio", sa.DECIMAL), @@ -297,8 +312,15 @@ def Column(*args, **kwargs): validator_votes = sa.Table( "validator_votes", metadata, - Column("block_height", sa.Integer, sa.ForeignKey("blocks.height"), primary_key=True), - Column("consensus_address", sa.String, sa.ForeignKey("validators.consensus_address"), primary_key=True), + Column( + "block_height", sa.Integer, sa.ForeignKey("blocks.height"), primary_key=True + ), + Column( + "consensus_address", + sa.String, + sa.ForeignKey("validators.consensus_address"), + primary_key=True, + ), Column("voted", sa.Boolean), ) @@ -307,7 +329,9 @@ def Column(*args, **kwargs): metadata, Column("delegator_id", sa.Integer, sa.ForeignKey("accounts.id")), Column("validator_id", sa.Integer, sa.ForeignKey("validators.id")), - Column("creation_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True), + Column( + "creation_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True + ), Column("completion_time", CustomDateTime), Column("amount", sa.DECIMAL), ) @@ -325,9 +349,15 @@ def Column(*args, **kwargs): account_transactions = sa.Table( "account_transactions", metadata, - Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), primary_key=True), + Column( + "transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), primary_key=True + ), Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), - sa.Index("ix_account_transactions_account_id_transaction_id", "account_id", "transaction_id"), + sa.Index( + "ix_account_transactions_account_id_transaction_id", + "account_id", + "transaction_id", + ), ) proposals = sa.Table( @@ -377,7 +407,9 @@ def Column(*args, **kwargs): historical_bonded_token_on_validators = sa.Table( "historical_bonded_token_on_validators", metadata, - Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), + Column( + "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True + ), Column("bonded_tokens", sa.DECIMAL), Column("timestamp", CustomDateTime, primary_key=True), ) @@ -392,8 +424,15 @@ def Column(*args, **kwargs): related_data_source_oracle_scripts = sa.Table( "related_data_source_oracle_scripts", metadata, - Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True), - Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True), + Column( + "data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True + ), + Column( + "oracle_script_id", + sa.Integer, + sa.ForeignKey("oracle_scripts.id"), + primary_key=True, + ), ) historical_oracle_statuses = sa.Table( @@ -407,7 +446,9 @@ def Column(*args, **kwargs): data_source_requests = sa.Table( "data_source_requests", metadata, - Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True), + Column( + "data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True + ), Column("count", sa.Integer), ) @@ -415,14 +456,21 @@ def Column(*args, **kwargs): "data_source_requests_per_days", metadata, Column("date", CustomDate, primary_key=True), - Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True), + Column( + "data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True + ), Column("count", sa.Integer), ) oracle_script_requests = sa.Table( "oracle_script_requests", metadata, - Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True), + Column( + "oracle_script_id", + sa.Integer, + sa.ForeignKey("oracle_scripts.id"), + primary_key=True, + ), Column("count", sa.Integer), ) @@ -430,7 +478,12 @@ def Column(*args, **kwargs): "oracle_script_requests_per_days", metadata, Column("date", CustomDate, primary_key=True), - Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True), + Column( + "oracle_script_id", + sa.Integer, + sa.ForeignKey("oracle_scripts.id"), + primary_key=True, + ), Column("count", sa.Integer), ) @@ -454,7 +507,9 @@ def Column(*args, **kwargs): Column("type", sa.String, nullable=True), Column("data", sa.JSON, nullable=True), Column("acknowledgement", sa.JSON, nullable=True), - sa.ForeignKeyConstraint(["dst_port", "dst_channel"], ["channels.port", "channels.channel"]), + sa.ForeignKeyConstraint( + ["dst_port", "dst_channel"], ["channels.port", "channels.channel"] + ), ) outgoing_packets = sa.Table( @@ -470,15 +525,24 @@ def Column(*args, **kwargs): Column("type", sa.String, nullable=True), Column("data", sa.JSON, nullable=True), Column("acknowledgement", sa.JSON, nullable=True), - sa.ForeignKeyConstraint(["src_port", "src_channel"], ["channels.port", "channels.channel"]), + sa.ForeignKeyConstraint( + ["src_port", "src_channel"], ["channels.port", "channels.channel"] + ), ) -counterparty_chains = sa.Table("counterparty_chains", metadata, Column("chain_id", sa.String, primary_key=True)) +counterparty_chains = sa.Table( + "counterparty_chains", metadata, Column("chain_id", sa.String, primary_key=True) +) connections = sa.Table( "connections", metadata, - Column("counterparty_chain_id", sa.String, sa.ForeignKey("counterparty_chains.chain_id"), primary_key=True), + Column( + "counterparty_chain_id", + sa.String, + sa.ForeignKey("counterparty_chains.chain_id"), + primary_key=True, + ), Column("counterparty_connection_id", sa.String), Column("client_id", sa.String), Column("counterparty_client_id", sa.String), From fb6040e387f65fe9aa653b3577f852491b15720c Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 11 Jan 2024 17:28:19 +0700 Subject: [PATCH 027/132] fix typo --- flusher/flusher/tss_db.py | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index c956c38cc..01c5c4179 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -81,7 +81,13 @@ def process_bind_param(self, value, dialect): Column("fee", sa.String), Column("status", CustomSigningStatus), Column("reason", sa.String, nullable=True), - Column("created_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True), + Column( + "created_height", + sa.Integer, + sa.ForeignKey("blocks.height"), + nullable=True, + index=True, + ), Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), index=True), sa.Index("ix_group_id_group_pub_key_status", "group_id", "group_pub_key", "status"), ) @@ -97,7 +103,12 @@ def process_bind_param(self, value, dialect): Column("status", CustomGroupStatus), Column("fee", sa.String), # if zero set it to nil - Column("latest_replacement_id", sa.integer, sa.ForeignKey("replacements.id"), nullable=True), + Column( + "latest_replacement_id", + sa.Integer, + sa.ForeignKey("replacements.id"), + nullable=True, + ), Column("created_height", sa.Integer, index=True), ) @@ -115,7 +126,7 @@ def process_bind_param(self, value, dialect): metadata, Column("id", sa.Integer, primary_key=True), Column("group_id", sa.Integer, sa.ForeignKey("groups.id"), primary_key=True), - Column("account_id", sa.integer, sa.ForeignKey("tss_accounts.account_id")), + Column("account_id", sa.Integer, sa.ForeignKey("tss_accounts.account_id")), Column("pub_key", CustomBase64, nullable=True), Column("is_malicious", sa.Boolean), ) @@ -123,25 +134,29 @@ def process_bind_param(self, value, dialect): assigned_members = sa.Table( "assigned_members", metadata, - Column("signing_id", sa.Integer, sa.ForeignKey("signing_data.id"), primary_key=True), + Column( + "signing_id", sa.Integer, sa.ForeignKey("signing_data.id"), primary_key=True + ), Column("group_id", sa.Integer, primary_key=True), Column("member_id", sa.Integer, primary_key=True), Column("pub_d", CustomBase64), Column("pub_e", CustomBase64), Column("binding_factor", CustomBase64), Column("pub_nonce", CustomBase64), - sa.ForeignKeyConstraint(["member_id", "group_id"], ["members.id", "members.group_id"]), + sa.ForeignKeyConstraint( + ["member_id", "group_id"], ["members.id", "members.group_id"] + ), ) replacements = sa.Table( "replacements", metadata, Column("id", sa.Integer, primary_key=True), - Column("signing_id", sa.Integer, sa.Foreignkey("signing_data.id")), - Column("from_group_id", sa.Integer, sa.Foreignkey("groups.id")), + Column("signing_id", sa.Integer, sa.ForeignKey("signing_data.id")), + Column("from_group_id", sa.Integer, sa.ForeignKey("groups.id")), Column("from_pub_key", CustomBase64), Column("to_group_id", sa.Integer, sa.ForeignKey("groups.id")), Column("to_pub_key", CustomBase64), Column("exec_time", CustomDateTime), - Column("status", ReplacementStatus), + Column("status", CustomReplacementStatus), ) From 89a0d179f538c2983403a2c27a6694f7f8fdc9e2 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Fri, 12 Jan 2024 23:35:54 +0700 Subject: [PATCH 028/132] fix --- flusher/flusher/db.py | 2 +- flusher/flusher/handler.py | 282 +++++++++++++++++++++++++++---------- flusher/flusher/tss_db.py | 76 ++++++---- hooks/emitter/handler.go | 38 ++--- hooks/emitter/tss.go | 223 +++++++++++++++++------------ 5 files changed, 406 insertions(+), 215 deletions(-) diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index 5de4369e6..9ab2700c3 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -195,7 +195,7 @@ def Column(*args, **kwargs): Column("reason", sa.String, nullable=True), Column("result", CustomBase64, nullable=True), Column( - "tss_signing_id", sa.Integer, sa.ForeignKey("signing_data.id"), nullable=True + "tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id"), nullable=True ), Column("tss_signing_error_codespace", sa.String, nullable=True), Column("tss_signing_error_code", sa.Integer, nullable=True), diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index e57968f6e..1df0e9fd5 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -42,12 +42,12 @@ ) from .tss_db import ( - signing_data, - groups, - tss_accounts, - members, - assigned_members, - replacements, + tss_signings, + tss_groups, + tss_group_members, + tss_assigned_members, + tss_statuses, + tss_replacements, ) @@ -56,38 +56,60 @@ def __init__(self, conn): self.conn = conn def get_transaction_id(self, tx_hash): - return self.conn.execute(select([transactions.c.id]).where(transactions.c.hash == tx_hash)).scalar() + return self.conn.execute( + select([transactions.c.id]).where(transactions.c.hash == tx_hash) + ).scalar() def get_transaction_sender(self, id): - return self.conn.execute(select([transactions.c.sender]).where(transactions.c.id == id)).scalar() + return self.conn.execute( + select([transactions.c.sender]).where(transactions.c.id == id) + ).scalar() def get_validator_id(self, val): - return self.conn.execute(select([validators.c.id]).where(validators.c.operator_address == val)).scalar() + return self.conn.execute( + select([validators.c.id]).where(validators.c.operator_address == val) + ).scalar() def get_account_id(self, address): if address is None: return None - id = self.conn.execute(select([accounts.c.id]).where(accounts.c.address == address)).scalar() + id = self.conn.execute( + select([accounts.c.id]).where(accounts.c.address == address) + ).scalar() if id is None: - self.conn.execute(accounts.insert(), {"address": address, "balance": "0uband"}) - return self.conn.execute(select([accounts.c.id]).where(accounts.c.address == address)).scalar() + self.conn.execute( + accounts.insert(), {"address": address, "balance": "0uband"} + ) + return self.conn.execute( + select([accounts.c.id]).where(accounts.c.address == address) + ).scalar() return id def have_tss_account(self, account_id): return ( - self.conn.execute(select([tss_accounts.c.id]).where(tss_accounts.c.id == account_id)).scalar() is not None + self.conn.execute( + select([tss_statuses.c.account_id]).where( + tss_statuses.c.account_id == account_id + ) + ).scalar() + is not None ) def get_request_count(self, date): return self.conn.execute( - select([request_count_per_days.c.count]).where(request_count_per_days.c.date == date) + select([request_count_per_days.c.count]).where( + request_count_per_days.c.date == date + ) ).scalar() def get_oracle_script_requests_count_per_day(self, date, oracle_script_id): return self.conn.execute( select([oracle_script_requests_per_days.c.count]).where( (oracle_script_requests_per_days.c.date == date) - & (oracle_script_requests_per_days.c.oracle_script_id == oracle_script_id) + & ( + oracle_script_requests_per_days.c.oracle_script_id + == oracle_script_id + ) ) ).scalar() @@ -100,10 +122,14 @@ def get_data_source_requests_count_per_day(self, date, data_source_id): ).scalar() def get_data_source_id(self, id): - return self.conn.execute(select([data_sources.c.id]).where(data_sources.c.id == id)).scalar() + return self.conn.execute( + select([data_sources.c.id]).where(data_sources.c.id == id) + ).scalar() def get_oracle_script_id(self, id): - return self.conn.execute(select([oracle_scripts.c.id]).where(oracle_scripts.c.id == id)).scalar() + return self.conn.execute( + select([oracle_scripts.c.id]).where(oracle_scripts.c.id == id) + ).scalar() def get_ibc_received_txs(self, date, port, channel, address): msg = {"date": date, "port": port, "channel": channel, "address": address} @@ -111,15 +137,21 @@ def get_ibc_received_txs(self, date, port, channel, address): for col in relayer_tx_stat_days.primary_key.columns.values(): condition = (col == msg[col.name]) & condition - return self.conn.execute(select([relayer_tx_stat_days.c.ibc_received_txs]).where(condition)).scalar() + return self.conn.execute( + select([relayer_tx_stat_days.c.ibc_received_txs]).where(condition) + ).scalar() def handle_new_block(self, msg): self.conn.execute(blocks.insert(), msg) def handle_new_transaction(self, msg): - msg["fee_payer"] = msg["fee_payer"] if "fee_payer" in msg and len(msg["fee_payer"]) else None + msg["fee_payer"] = ( + msg["fee_payer"] if "fee_payer" in msg and len(msg["fee_payer"]) else None + ) self.conn.execute( - insert(transactions).values(**msg).on_conflict_do_update(constraint="transactions_pkey", set_=msg) + insert(transactions) + .values(**msg) + .on_conflict_do_update(constraint="transactions_pkey", set_=msg) ) def handle_set_related_transaction(self, msg): @@ -128,7 +160,12 @@ def handle_set_related_transaction(self, msg): for account in related_tx_accounts: self.conn.execute( insert(account_transactions) - .values({"transaction_id": tx_id, "account_id": self.get_account_id(account)}) + .values( + { + "transaction_id": tx_id, + "account_id": self.get_account_id(account), + } + ) .on_conflict_do_nothing(constraint="account_transactions_pkey") ) @@ -191,7 +228,9 @@ def handle_new_request(self, msg): self.handle_update_oracle_script_requests_count_per_day( {"date": msg["timestamp"], "oracle_script_id": msg["oracle_script_id"]} ) - self.update_oracle_script_last_request(msg["oracle_script_id"], msg["timestamp"]) + self.update_oracle_script_last_request( + msg["oracle_script_id"], msg["timestamp"] + ) del msg["timestamp"] self.conn.execute(requests.insert(), msg) self.increase_oracle_script_count(msg["oracle_script_id"]) @@ -214,7 +253,9 @@ def handle_update_related_ds_os(self, msg): self.conn.execute( insert(related_data_source_oracle_scripts) .values(**msg) - .on_conflict_do_nothing(constraint="related_data_source_oracle_scripts_pkey") + .on_conflict_do_nothing( + constraint="related_data_source_oracle_scripts_pkey" + ) ) def handle_new_raw_request(self, msg): @@ -223,12 +264,16 @@ def handle_new_raw_request(self, msg): self.handle_update_data_source_requests_count_per_day( {"date": msg["timestamp"], "data_source_id": msg["data_source_id"]} ) - self.update_data_source_last_request(msg["data_source_id"], msg["timestamp"]) + self.update_data_source_last_request( + msg["data_source_id"], msg["timestamp"] + ) del msg["timestamp"] self.handle_update_related_ds_os( { "oracle_script_id": self.conn.execute( - select([requests.c.oracle_script_id]).where(requests.c.id == msg["request_id"]) + select([requests.c.oracle_script_id]).where( + requests.c.id == msg["request_id"] + ) ).scalar(), "data_source_id": msg["data_source_id"], } @@ -294,7 +339,9 @@ def handle_update_validator(self, msg): ) del msg["last_update"] self.conn.execute( - validators.update().where(validators.c.operator_address == msg["operator_address"]).values(**msg) + validators.update() + .where(validators.c.operator_address == msg["operator_address"]) + .values(**msg) ) def handle_set_delegation(self, msg): @@ -303,7 +350,9 @@ def handle_set_delegation(self, msg): msg["validator_id"] = self.get_validator_id(msg["operator_address"]) del msg["operator_address"] self.conn.execute( - insert(delegations).values(**msg).on_conflict_do_update(constraint="delegations_pkey", set_=msg) + insert(delegations) + .values(**msg) + .on_conflict_do_update(constraint="delegations_pkey", set_=msg) ) def handle_update_delegation(self, msg): @@ -338,7 +387,9 @@ def handle_new_unbonding_delegation(self, msg): def handle_remove_unbonding(self, msg): self.conn.execute( - unbonding_delegations.delete().where(unbonding_delegations.c.completion_time <= msg["timestamp"]) + unbonding_delegations.delete().where( + unbonding_delegations.c.completion_time <= msg["timestamp"] + ) ) def handle_new_redelegation(self, msg): @@ -351,7 +402,11 @@ def handle_new_redelegation(self, msg): self.conn.execute(insert(redelegations).values(**msg)) def handle_remove_redelegation(self, msg): - self.conn.execute(redelegations.delete().where(redelegations.c.completion_time <= msg["timestamp"])) + self.conn.execute( + redelegations.delete().where( + redelegations.c.completion_time <= msg["timestamp"] + ) + ) def handle_new_proposal(self, msg): msg["proposer_id"] = self.get_account_id(msg["proposer"]) @@ -363,14 +418,22 @@ def handle_set_deposit(self, msg): del msg["depositor"] msg["tx_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] - self.conn.execute(insert(deposits).values(**msg).on_conflict_do_update(constraint="deposits_pkey", set_=msg)) + self.conn.execute( + insert(deposits) + .values(**msg) + .on_conflict_do_update(constraint="deposits_pkey", set_=msg) + ) def handle_set_vote_weighted(self, msg): msg["voter_id"] = self.get_account_id(msg["voter"]) del msg["voter"] msg["tx_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] - self.conn.execute(insert(votes).values(**msg).on_conflict_do_update(constraint="votes_pkey", set_=msg)) + self.conn.execute( + insert(votes) + .values(**msg) + .on_conflict_do_update(constraint="votes_pkey", set_=msg) + ) def handle_update_proposal(self, msg): condition = True @@ -384,7 +447,9 @@ def handle_set_historical_bonded_token_on_validator(self, msg): self.conn.execute( insert(historical_bonded_token_on_validators) .values(**msg) - .on_conflict_do_update(constraint="historical_bonded_token_on_validators_pkey", set_=msg) + .on_conflict_do_update( + constraint="historical_bonded_token_on_validators_pkey", set_=msg + ) ) def handle_set_reporter(self, msg): @@ -392,7 +457,11 @@ def handle_set_reporter(self, msg): del msg["validator"] msg["reporter_id"] = self.get_account_id(msg["reporter"]) del msg["reporter"] - self.conn.execute(insert(reporters).values(msg).on_conflict_do_nothing(constraint="reporters_pkey")) + self.conn.execute( + insert(reporters) + .values(msg) + .on_conflict_do_nothing(constraint="reporters_pkey") + ) def handle_remove_reporter(self, msg): msg["operator_address"] = msg["validator"] @@ -408,7 +477,9 @@ def handle_set_historical_validator_status(self, msg): self.conn.execute( insert(historical_oracle_statuses) .values(**msg) - .on_conflict_do_update(constraint="historical_oracle_statuses_pkey", set_=msg) + .on_conflict_do_update( + constraint="historical_oracle_statuses_pkey", set_=msg + ) ) def init_data_source_request_count(self, id): @@ -420,9 +491,9 @@ def init_data_source_request_count(self, id): def increase_data_source_count(self, id): self.conn.execute( - data_source_requests.update(data_source_requests.c.data_source_id == id).values( - count=data_source_requests.c.count + 1 - ) + data_source_requests.update( + data_source_requests.c.data_source_id == id + ).values(count=data_source_requests.c.count + 1) ) def init_oracle_script_request_count(self, id): @@ -436,7 +507,11 @@ def handle_update_oracle_script_request(self, msg): condition = True for col in oracle_script_requests.primary_key.columns.values(): condition = (col == msg[col.name]) & condition - self.conn.execute(oracle_script_requests.update(condition).values(count=oracle_script_requests.c.count + 1)) + self.conn.execute( + oracle_script_requests.update(condition).values( + count=oracle_script_requests.c.count + 1 + ) + ) def handle_set_request_count_per_day(self, msg): if self.get_request_count(msg["date"]) is None: @@ -447,11 +522,18 @@ def handle_set_request_count_per_day(self, msg): for col in request_count_per_days.primary_key.columns.values(): condition = (col == msg[col.name]) & condition self.conn.execute( - request_count_per_days.update(condition).values(count=request_count_per_days.c.count + 1) + request_count_per_days.update(condition).values( + count=request_count_per_days.c.count + 1 + ) ) def handle_update_oracle_script_requests_count_per_day(self, msg): - if self.get_oracle_script_requests_count_per_day(msg["date"], msg["oracle_script_id"]) is None: + if ( + self.get_oracle_script_requests_count_per_day( + msg["date"], msg["oracle_script_id"] + ) + is None + ): msg["count"] = 1 self.conn.execute(oracle_script_requests_per_days.insert(), msg) else: @@ -465,7 +547,12 @@ def handle_update_oracle_script_requests_count_per_day(self, msg): ) def handle_update_data_source_requests_count_per_day(self, msg): - if self.get_data_source_requests_count_per_day(msg["date"], msg["data_source_id"]) is None: + if ( + self.get_data_source_requests_count_per_day( + msg["date"], msg["data_source_id"] + ) + is None + ): msg["count"] = 1 self.conn.execute(data_source_requests_per_days.insert(), msg) else: @@ -473,37 +560,51 @@ def handle_update_data_source_requests_count_per_day(self, msg): for col in data_source_requests_per_days.primary_key.columns.values(): condition = (col == msg[col.name]) & condition self.conn.execute( - data_source_requests_per_days.update(condition).values(count=data_source_requests_per_days.c.count + 1) + data_source_requests_per_days.update(condition).values( + count=data_source_requests_per_days.c.count + 1 + ) ) def handle_new_incoming_packet(self, msg): - self.update_last_update_channel(msg["dst_port"], msg["dst_channel"], msg["block_time"]) + self.update_last_update_channel( + msg["dst_port"], msg["dst_channel"], msg["block_time"] + ) msg["tx_id"] = self.get_transaction_id(msg["hash"]) del msg["hash"] msg["sender"] = self.get_transaction_sender(msg["tx_id"]) - self.handle_set_relayer_tx_stat_days(msg["dst_port"], msg["dst_channel"], msg["block_time"], msg["sender"]) + self.handle_set_relayer_tx_stat_days( + msg["dst_port"], msg["dst_channel"], msg["block_time"], msg["sender"] + ) del msg["block_time"] del msg["sender"] self.conn.execute( - insert(incoming_packets).values(**msg).on_conflict_do_nothing(constraint="incoming_packets_pkey") + insert(incoming_packets) + .values(**msg) + .on_conflict_do_nothing(constraint="incoming_packets_pkey") ) def handle_new_outgoing_packet(self, msg): - self.update_last_update_channel(msg["src_port"], msg["src_channel"], msg["block_time"]) + self.update_last_update_channel( + msg["src_port"], msg["src_channel"], msg["block_time"] + ) del msg["block_time"] msg["tx_id"] = self.get_transaction_id(msg["hash"]) del msg["hash"] self.conn.execute( - insert(outgoing_packets).values(**msg).on_conflict_do_nothing(constraint="outgoing_packets_pkey") + insert(outgoing_packets) + .values(**msg) + .on_conflict_do_nothing(constraint="outgoing_packets_pkey") ) def handle_update_outgoing_packet(self, msg): - self.update_last_update_channel(msg["src_port"], msg["src_channel"], msg["block_time"]) + self.update_last_update_channel( + msg["src_port"], msg["src_channel"], msg["block_time"] + ) del msg["block_time"] condition = True @@ -513,22 +614,30 @@ def handle_update_outgoing_packet(self, msg): def increase_oracle_script_count(self, id): self.conn.execute( - oracle_script_requests.update(oracle_script_requests.c.oracle_script_id == id).values( - count=oracle_script_requests.c.count + 1 - ) + oracle_script_requests.update( + oracle_script_requests.c.oracle_script_id == id + ).values(count=oracle_script_requests.c.count + 1) ) def update_oracle_script_last_request(self, id, timestamp): - self.conn.execute(oracle_scripts.update(oracle_scripts.c.id == id).values(last_request=timestamp)) + self.conn.execute( + oracle_scripts.update(oracle_scripts.c.id == id).values( + last_request=timestamp + ) + ) def update_data_source_last_request(self, id, timestamp): - self.conn.execute(data_sources.update(data_sources.c.id == id).values(last_request=timestamp)) + self.conn.execute( + data_sources.update(data_sources.c.id == id).values(last_request=timestamp) + ) def handle_new_historical_bonded_token_on_validator(self, msg): self.conn.execute( insert(historical_bonded_token_on_validators) .values(**msg) - .on_conflict_do_update(constraint="historical_bonded_token_on_validators_pkey", set_=msg) + .on_conflict_do_update( + constraint="historical_bonded_token_on_validators_pkey", set_=msg + ) ) def handle_set_counterparty_chain(self, msg): @@ -540,11 +649,17 @@ def handle_set_counterparty_chain(self, msg): def handle_set_connection(self, msg): self.conn.execute( - insert(connections).values(**msg).on_conflict_do_update(constraint="connections_pkey", set_=msg) + insert(connections) + .values(**msg) + .on_conflict_do_update(constraint="connections_pkey", set_=msg) ) def handle_set_channel(self, msg): - self.conn.execute(insert(channels).values(**msg).on_conflict_do_update(constraint="channels_pkey", set_=msg)) + self.conn.execute( + insert(channels) + .values(**msg) + .on_conflict_do_update(constraint="channels_pkey", set_=msg) + ) def update_last_update_channel(self, port, channel, timestamp): self.conn.execute( @@ -580,50 +695,63 @@ def handle_set_relayer_tx_stat_days(self, port, channel, timestamp, address): self.conn.execute( relayer_tx_stat_days.update() .where(condition) - .values(ibc_received_txs=relayer_tx_stat_days.c.ibc_received_txs + 1, last_update_at=timestamp) + .values( + ibc_received_txs=relayer_tx_stat_days.c.ibc_received_txs + 1, + last_update_at=timestamp, + ) ) - def handle_new_signing(self, msg): + def handle_new_tss_signing(self, msg): msg["account_id"] = self.get_account_id(msg["requester"]) del msg["requester"] - self.conn.execute(signing_data.insert(), msg) + self.conn.execute(tss_signings.insert(), msg) - def handle_update_signing(self, msg): + def handle_update_tss_signing(self, msg): condition = True - for col in signing_data.primary_key.columns.values(): + for col in tss_signings.primary_key.columns.values(): condition = (col == msg[col.name]) & condition - self.conn.execute(signing_data.update().where(condition).values(**msg)) + self.conn.execute(tss_signings.update().where(condition).values(**msg)) - def handle_set_tss_account_status(self, msg): + def handle_set_tss_status(self, msg): msg["account_id"] = self.get_account_id(msg["address"]) del msg["address"] if not self.have_tss_account(msg["account_id"]): - self.conn.execute(tss_accounts.insert(), msg) + self.conn.execute(tss_statuses.insert(), msg) else: condition = True - for col in tss_accounts.primary_key.columns.values(): + for col in tss_statuses.primary_key.columns.values(): condition = (col == msg[col.name]) & condition - self.conn.execute(tss_accounts.update().where(condition).values(**msg)) + self.conn.execute(tss_statuses.update().where(condition).values(**msg)) - def handle_set_group(self, msg): + def handle_set_tss_group(self, msg): if msg["latest_replacement_id"] == 0: msg["latest_replacement_id"] = None - self.conn.execute(groups.insert(), msg) - def handle_set_member(self, msg): + self.conn.execute( + insert(tss_groups) + .values(**msg) + .on_conflict_do_update(constraint="tss_groups_pkey", set_=msg) + ) + + def handle_set_tss_group_member(self, msg): msg["account_id"] = self.get_account_id(msg["address"]) del msg["address"] - self.conn.execute(members.insert(), msg) - def handle_new_assigned_members(self, msg): - self.conn.execute(assigned_members.insert(), msg) + self.conn.execute( + insert(tss_group_members) + .values(**msg) + .on_conflict_do_update(constraint="tss_group_members_pkey", set_=msg) + ) + + def handle_new_tss_assigned_member(self, msg): + self.conn.execute(tss_assigned_members.insert(), msg) - def handle_new_replacement(self, msg): - self.conn.execute(replacements.insert(), msg) + def handle_new_tss_replacement(self, msg): + self.conn.execute(tss_replacements.insert(), msg) - def handle_update_replacement_status(self, msg): + def handle_update_tss_replacement_status(self, msg): condition = True - for col in signing_data.primary_key.columns.values(): + for col in tss_signings.primary_key.columns.values(): condition = (col == msg[col.name]) & condition - self.conn.execute(replacements.update().where(condition).values(**msg)) + self.conn.execute(tss_replacements.update().where(condition).values(**msg)) diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index 01c5c4179..5c09ba554 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -27,11 +27,12 @@ class GroupStatus(enum.Enum): failed = 6 -class TSSAccountStatus(enum.Enum): +class TSSStatus(enum.Enum): nil = 0 active = 1 - inactive = 2 - jail = 3 + paused = 2 + inactive = 3 + jail = 4 class ReplacementStatus(enum.Enum): @@ -55,11 +56,11 @@ def process_bind_param(self, value, dialect): return GroupStatus(value) -class CustomTSSAccountStatus(sa.types.TypeDecorator): - impl = sa.Enum(TSSAccountStatus) +class CustomTSSStatus(sa.types.TypeDecorator): + impl = sa.Enum(TSSStatus) def process_bind_param(self, value, dialect): - return TSSAccountStatus(value) + return TSSStatus(value) class CustomReplacementStatus(sa.types.TypeDecorator): @@ -69,11 +70,11 @@ def process_bind_param(self, value, dialect): return ReplacementStatus(value) -signing_data = sa.Table( - "signing_data", +tss_signings = sa.Table( + "tss_signings", metadata, Column("id", sa.Integer, primary_key=True), - Column("group_id", sa.Integer, sa.ForeignKey("groups.id")), + Column("tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), Column("group_pub_key", CustomBase64), Column("msg", CustomBase64), Column("group_pub_nonce", CustomBase64), @@ -89,11 +90,13 @@ def process_bind_param(self, value, dialect): index=True, ), Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), index=True), - sa.Index("ix_group_id_group_pub_key_status", "group_id", "group_pub_key", "status"), + sa.Index( + "ix_group_id_group_pub_key_status", "tss_group_id", "group_pub_key", "status" + ), ) -groups = sa.Table( - "groups", +tss_groups = sa.Table( + "tss_groups", metadata, Column("id", sa.Integer, primary_key=True), Column("size", sa.Integer), @@ -106,56 +109,67 @@ def process_bind_param(self, value, dialect): Column( "latest_replacement_id", sa.Integer, - sa.ForeignKey("replacements.id"), + sa.ForeignKey("tss_replacements.id"), nullable=True, ), Column("created_height", sa.Integer, index=True), ) -tss_accounts = sa.Table( - "tss_accounts", +tss_statuses = sa.Table( + "tss_statuses", metadata, Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), - Column("status", CustomTSSAccountStatus), + Column("status", CustomTSSStatus), Column("since", CustomDateTime), Column("last_active", CustomDateTime), ) -members = sa.Table( - "members", +tss_group_members = sa.Table( + "tss_group_members", metadata, Column("id", sa.Integer, primary_key=True), - Column("group_id", sa.Integer, sa.ForeignKey("groups.id"), primary_key=True), - Column("account_id", sa.Integer, sa.ForeignKey("tss_accounts.account_id")), + Column( + "tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id"), primary_key=True + ), + Column("account_id", sa.Integer, sa.ForeignKey("accounts.id")), Column("pub_key", CustomBase64, nullable=True), Column("is_malicious", sa.Boolean), ) -assigned_members = sa.Table( - "assigned_members", +tss_assigned_members = sa.Table( + "tss_assigned_members", metadata, Column( - "signing_id", sa.Integer, sa.ForeignKey("signing_data.id"), primary_key=True + "tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id"), primary_key=True + ), + Column( + "tss_group_id", + sa.Integer, + primary_key=True, + ), + Column( + "tss_group_member_id", + sa.Integer, + primary_key=True, ), - Column("group_id", sa.Integer, primary_key=True), - Column("member_id", sa.Integer, primary_key=True), Column("pub_d", CustomBase64), Column("pub_e", CustomBase64), Column("binding_factor", CustomBase64), Column("pub_nonce", CustomBase64), sa.ForeignKeyConstraint( - ["member_id", "group_id"], ["members.id", "members.group_id"] + ["tss_group_id", "tss_group_member_id"], + ["tss_group_members.tss_group_id", "tss_group_members.id"], ), ) -replacements = sa.Table( - "replacements", +tss_replacements = sa.Table( + "tss_replacements", metadata, Column("id", sa.Integer, primary_key=True), - Column("signing_id", sa.Integer, sa.ForeignKey("signing_data.id")), - Column("from_group_id", sa.Integer, sa.ForeignKey("groups.id")), + Column("signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), + Column("from_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), Column("from_pub_key", CustomBase64), - Column("to_group_id", sa.Integer, sa.ForeignKey("groups.id")), + Column("to_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), Column("to_pub_key", CustomBase64), Column("exec_time", CustomDateTime), Column("status", CustomReplacementStatus), diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index 9f1d15283..a9d4f2d47 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -120,6 +120,14 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, log sdk.AB h.handleMsgRevoke(msg, detail) case *authz.MsgExec: h.handleMsgExec(ctx, txHash, msg, log, detail) + case *tsstypes.MsgActivate: + h.handleTSSMsgActivate(ctx, msg) + case *tsstypes.MsgHealthCheck: + h.handleTSSMsgHealthCheck(ctx, msg) + case *tsstypes.MsgSubmitDEs: + h.handleTSSMsgSubmitDEs(ctx, msg) + case *tsstypes.MsgRequestSignature: + h.handleEventRequestSignature(ctx, evMap) default: break } @@ -155,50 +163,42 @@ func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) h.handleEventSigningFailed(ctx, evMap) case tsstypes.EventTypeExpiredSigning: h.handleEventExpiredSigning(ctx, evMap) - case tsstypes.EventTypeActivate: - address := sdk.MustAccAddressFromBech32(evMap[tsstypes.EventTypeActivate+"."+tsstypes.AttributeKeyAddress][0]) - h.handleUpdateStatusTSSAccount(ctx, address) - case tsstypes.EventTypeHealthCheck: - address := sdk.MustAccAddressFromBech32( - evMap[tsstypes.EventTypeHealthCheck+"."+tsstypes.AttributeKeyAddress][0], - ) - h.handleUpdateStatusTSSAccount(ctx, address) case tsstypes.EventTypeInactive: address := sdk.MustAccAddressFromBech32(evMap[tsstypes.EventTypeInactive+"."+tsstypes.AttributeKeyAddress][0]) - h.handleUpdateStatusTSSAccount(ctx, address) + h.handleUpdateTSSStatus(ctx, address) case tsstypes.EventTypeCreateGroup: gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeCreateGroup+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetGroup(ctx, gid) + h.handleSetTSSGroup(ctx, gid) case tsstypes.EventTypeRound2Success: gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeRound2Success+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetGroup(ctx, gid) + h.handleSetTSSGroup(ctx, gid) case tsstypes.EventTypeComplainSuccess: gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeComplainSuccess+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetGroup(ctx, gid) + h.handleSetTSSGroup(ctx, gid) case tsstypes.EventTypeComplainFailed: gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeComplainFailed+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetGroup(ctx, gid) + h.handleSetTSSGroup(ctx, gid) case tsstypes.EventTypeRound3Success: gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeRound3Success+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetGroup(ctx, gid) + h.handleSetTSSGroup(ctx, gid) case tsstypes.EventTypeExpiredGroup: gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeExpiredGroup+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetGroup(ctx, gid) + h.handleSetTSSGroup(ctx, gid) case tsstypes.EventTypeUpdateGroupFee: gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeUpdateGroupFee+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetGroup(ctx, gid) + h.handleSetTSSGroup(ctx, gid) case tsstypes.EventTypeReplacement: - h.handleInitReplacement(ctx, evMap) + h.handleInitTSSReplacement(ctx, evMap) case tsstypes.EventTypeReplacementSuccess: rid := uint64( common.Atoi(evMap[tsstypes.EventTypeReplacementSuccess+"."+tsstypes.AttributeKeyReplacementID][0]), ) - h.handleUpdateReplacementStatus(ctx, rid) + h.handleUpdateTSSReplacementStatus(ctx, rid) case tsstypes.EventTypeReplacementFailed: rid := uint64( common.Atoi(evMap[tsstypes.EventTypeReplacementFailed+"."+tsstypes.AttributeKeyReplacementID][0]), ) - h.handleUpdateReplacementStatus(ctx, rid) + h.handleUpdateTSSReplacementStatus(ctx, rid) default: break } diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 0ba2dacbf..1147c920b 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -5,14 +5,13 @@ import ( "github.com/bandprotocol/chain/v2/hooks/common" "github.com/bandprotocol/chain/v2/pkg/tss" - "github.com/bandprotocol/chain/v2/x/oracle/types" - tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" + "github.com/bandprotocol/chain/v2/x/tss/types" ) -func (h *Hook) emitNewSigning(signing tsstypes.Signing) { - h.Write("NEW_SIGNING", common.JsDict{ +func (h *Hook) emitNewTSSSigning(signing types.Signing) { + h.Write("NEW_TSS_SIGNING", common.JsDict{ "id": signing.ID, - "group_id": signing.GroupID, + "tss_group_id": signing.GroupID, "group_pub_key": parseBytes(signing.GroupPubKey), "msg": parseBytes(signing.Message), "group_pub_nonce": parseBytes(signing.GroupPubNonce), @@ -23,40 +22,40 @@ func (h *Hook) emitNewSigning(signing tsstypes.Signing) { }) } -func (h *Hook) emitUpdateSigningSuccess(signing tsstypes.Signing) { - h.Write("UPDATE_SIGNING", common.JsDict{ +func (h *Hook) emitUpdateTSSSigningSuccess(signing types.Signing) { + h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, "status": int(signing.Status), "signature": parseBytes(signing.Signature), }) } -func (h *Hook) emitUpdateSigningFailed(reason string, signing tsstypes.Signing) { - h.Write("UPDATE_SIGNING", common.JsDict{ +func (h *Hook) emitUpdateTSSSigningFailed(reason string, signing types.Signing) { + h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, "status": int(signing.Status), "reason": reason, }) } -func (h *Hook) emitUpdateSigningStatus(signing tsstypes.Signing) { - h.Write("UPDATE_SIGNING", common.JsDict{ +func (h *Hook) emitUpdateTSSSigningStatus(signing types.Signing) { + h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, "status": int(signing.Status), }) } -func (h *Hook) emitSetTSSAccountStatus(status tsstypes.Status) { - h.Write("SET_TSS_ACCOUNT_STATUS", common.JsDict{ +func (h *Hook) emitSetTSSStatus(status types.Status) { + h.Write("SET_TSS_STATUS", common.JsDict{ "address": status.Address, "status": int(status.Status), - "since": status.Since.Unix(), - "last_active": status.LastActive.Unix(), + "since": status.Since.UnixNano(), + "last_active": status.LastActive.UnixNano(), }) } -func (h *Hook) emitSetGroup(group tsstypes.Group, dkgContext []byte) { - h.Write("SET_GROUP", common.JsDict{ +func (h *Hook) emitSetTSSGroup(group types.Group, dkgContext []byte) { + h.Write("SET_TSS_GROUP", common.JsDict{ "id": group.ID, "size": group.Size_, "threshold": group.Threshold, @@ -69,43 +68,43 @@ func (h *Hook) emitSetGroup(group tsstypes.Group, dkgContext []byte) { }) } -func (h *Hook) emitSetMember(member tsstypes.Member) { - h.Write("SET_MEMBER", common.JsDict{ +func (h *Hook) emitSetTSSGroupMember(member types.Member) { + h.Write("SET_TSS_GROUP_MEMBER", common.JsDict{ "id": member.ID, - "group_id": member.GroupID, + "tss_group_id": member.GroupID, "address": member.Address, "pub_key": parseBytes(member.PubKey), "is_malicious": member.IsMalicious, }) } -func (h *Hook) emitNewAssignedMember(sid tss.SigningID, gid tss.GroupID, am tsstypes.AssignedMember) { - h.Write("NEW_ASSIGNED_MEMBER", common.JsDict{ - "signing_id": sid, - "member_id": am.MemberID, - "group_id": gid, - "pub_d": parseBytes(am.PubD), - "pub_e": parseBytes(am.PubE), - "binding_factor": parseBytes(am.PubKey), - "pub_nonce": parseBytes(am.PubNonce), +func (h *Hook) emitNewTSSAssignedMember(sid tss.SigningID, gid tss.GroupID, am types.AssignedMember) { + h.Write("NEW_TSS_ASSIGNED_MEMBER", common.JsDict{ + "signing_id": sid, + "tss_group_member_id": am.MemberID, + "tss_group_id": gid, + "pub_d": parseBytes(am.PubD), + "pub_e": parseBytes(am.PubE), + "binding_factor": parseBytes(am.PubKey), + "pub_nonce": parseBytes(am.PubNonce), }) } -func (h *Hook) emitNewReplacement(replacement tsstypes.Replacement) { - h.Write("NEW_REPLACEMENT", common.JsDict{ - "id": replacement.ID, - "signing_id": replacement.SigningID, - "from_group_id": replacement.FromGroupID, - "from_pub_key": parseBytes(replacement.FromPubKey), - "to_group_id": replacement.ToGroupID, - "to_pub_key": parseBytes(replacement.ToPubKey), - "exec_time": replacement.ExecTime.Unix(), - "status": int(replacement.Status), +func (h *Hook) emitNewTSSReplacement(replacement types.Replacement) { + h.Write("NEW_TSS_REPLACEMENT", common.JsDict{ + "id": replacement.ID, + "tss_signing_id": replacement.SigningID, + "from_group_id": replacement.FromGroupID, + "from_pub_key": parseBytes(replacement.FromPubKey), + "to_group_id": replacement.ToGroupID, + "to_pub_key": parseBytes(replacement.ToPubKey), + "exec_time": replacement.ExecTime.UnixNano(), + "status": int(replacement.Status), }) } -func (h *Hook) emitUpdateReplacementStatus(ctx sdk.Context, id uint64, status tsstypes.ReplacementStatus) { - h.Write("UPDATE_REPLACEMENT_STATUS", common.JsDict{ +func (h *Hook) emitUpdateTSSReplacementStatus(ctx sdk.Context, id uint64, status types.ReplacementStatus) { + h.Write("UPDATE_TSS_REPLACEMENT_STATUS", common.JsDict{ "id": id, "status": int(status), }) @@ -114,9 +113,9 @@ func (h *Hook) emitUpdateReplacementStatus(ctx sdk.Context, id uint64, status ts // handleInitTSSModule implements emitter handler for initializing tss module. func (h *Hook) handleInitTSSModule(ctx sdk.Context) { for _, signing := range h.tssKeeper.GetSignings(ctx) { - h.Write("NEW_SIGNING", common.JsDict{ + h.Write("NEW_TSS_SIGNING", common.JsDict{ "id": signing.ID, - "group_id": signing.GroupID, + "tss_group_id": signing.GroupID, "group_pub_key": parseBytes(signing.GroupPubKey), "msg": parseBytes(signing.Message), "group_pub_nonce": parseBytes(signing.GroupPubNonce), @@ -131,93 +130,143 @@ func (h *Hook) handleInitTSSModule(ctx sdk.Context) { // handleEventRequestSignature implements emitter handler for RequestSignature event. func (h *Hook) handleEventRequestSignature(ctx sdk.Context, evMap common.EvMap) { - id := tss.SigningID(common.Atoi(evMap[tsstypes.EventTypeRequestSignature+"."+types.AttributeKeySigningID][0])) - signing := h.tssKeeper.MustGetSigning(ctx, id) + sids := evMap[types.EventTypeRequestSignature+"."+types.AttributeKeySigningID] + for _, sid := range sids { + id := tss.SigningID(common.Atoi(sid)) + signing := h.tssKeeper.MustGetSigning(ctx, id) - for _, am := range signing.AssignedMembers { - h.emitNewAssignedMember(signing.ID, signing.GroupID, am) - } + for _, am := range signing.AssignedMembers { + h.emitNewTSSAssignedMember(signing.ID, signing.GroupID, am) + } - h.emitNewSigning(signing) + h.emitNewTSSSigning(signing) + } } // handleEventSigningSuccess implements emitter handler for SigningSuccess event. func (h *Hook) handleEventSigningSuccess(ctx sdk.Context, evMap common.EvMap) { - id := tss.SigningID(common.Atoi(evMap[tsstypes.EventTypeSigningSuccess+"."+types.AttributeKeySigningID][0])) - signing := h.tssKeeper.MustGetSigning(ctx, id) + sids := evMap[types.EventTypeSigningSuccess+"."+types.AttributeKeySigningID] + for _, sid := range sids { + id := tss.SigningID(common.Atoi(sid)) + signing := h.tssKeeper.MustGetSigning(ctx, id) - h.emitUpdateSigningSuccess(signing) + h.emitUpdateTSSSigningSuccess(signing) + } } // handleEventSigningFailed implements emitter handler for SigningSuccess event. func (h *Hook) handleEventSigningFailed(ctx sdk.Context, evMap common.EvMap) { - id := tss.SigningID(common.Atoi(evMap[tsstypes.EventTypeSigningFailed+"."+types.AttributeKeySigningID][0])) - signing := h.tssKeeper.MustGetSigning(ctx, id) - - if reason, ok := evMap[tsstypes.EventTypeSigningFailed+"."+tsstypes.AttributeKeyReason]; ok { - h.emitUpdateSigningFailed( - reason[0], - signing, - ) - } else { - h.emitUpdateSigningFailed( - "failed with on reason", - signing, - ) + sids := evMap[types.EventTypeSigningFailed+"."+types.AttributeKeySigningID] + for _, sid := range sids { + id := tss.SigningID(common.Atoi(sid)) + signing := h.tssKeeper.MustGetSigning(ctx, id) + + if reason, ok := evMap[types.EventTypeSigningFailed+"."+types.AttributeKeyReason]; ok { + h.emitUpdateTSSSigningFailed( + reason[0], + signing, + ) + } else { + h.emitUpdateTSSSigningFailed( + "failed with on reason", + signing, + ) + } } } // handleEventExpiredSigning implements emitter handler for ExpiredSigning event. func (h *Hook) handleEventExpiredSigning(ctx sdk.Context, evMap common.EvMap) { - id := tss.SigningID(common.Atoi(evMap[tsstypes.EventTypeExpiredSigning+"."+types.AttributeKeySigningID][0])) - signing := h.tssKeeper.MustGetSigning(ctx, id) + sids := evMap[types.EventTypeExpiredSigning+"."+types.AttributeKeySigningID] + for _, sid := range sids { + id := tss.SigningID(common.Atoi(sid)) + signing := h.tssKeeper.MustGetSigning(ctx, id) - h.emitUpdateSigningStatus(signing) + h.emitUpdateTSSSigningStatus(signing) + } } -// handleUpdateStatusTSSAccount implements emitter handler for update tss account status. -func (h *Hook) handleUpdateStatusTSSAccount(ctx sdk.Context, address sdk.AccAddress) { +// handleUpdateTSSStatus implements emitter handler for update tss status. +func (h *Hook) handleUpdateTSSStatus(ctx sdk.Context, address sdk.AccAddress) { status := h.tssKeeper.GetStatus(ctx, address) - - h.emitSetTSSAccountStatus(status) + h.emitSetTSSStatus(status) } -// handleSetGroup implements emitter handler events related to group. -func (h *Hook) handleSetGroup(ctx sdk.Context, gid tss.GroupID) { +// handleSetTSSGroup implements emitter handler events related to group. +func (h *Hook) handleSetTSSGroup(ctx sdk.Context, gid tss.GroupID) { group := h.tssKeeper.MustGetGroup(ctx, gid) dkgContext, err := h.tssKeeper.GetDKGContext(ctx, gid) if err != nil { panic(err) } - h.emitSetGroup(group, dkgContext) + h.emitSetTSSGroup(group, dkgContext) members := h.tssKeeper.MustGetMembers(ctx, gid) for _, m := range members { - h.emitSetMember(m) + h.emitSetTSSGroupMember(m) + } +} + +// handleInitTSSReplacement implements emitter handler for init replacement event. +func (h *Hook) handleInitTSSReplacement(ctx sdk.Context, evMap common.EvMap) { + rids := evMap[types.EventTypeReplacement+"."+types.AttributeKeyReplacementID] + for _, rid := range rids { + id := uint64(common.Atoi(rid)) + r, err := h.tssKeeper.GetReplacement(ctx, id) + if err != nil { + panic(err) + } + + h.emitNewTSSReplacement(r) + } +} + +// handleUpdateTSSReplacementStatus implements emitter handler events related to replacements. +func (h *Hook) handleUpdateTSSReplacementStatus(ctx sdk.Context, rid uint64) { + r, err := h.tssKeeper.GetReplacement(ctx, rid) + if err != nil { + panic(err) + } + if r.Status == types.REPLACEMENT_STATUS_SUCCESS { + h.handleSetTSSGroup(ctx, r.ToGroupID) } + + h.emitUpdateTSSReplacementStatus(ctx, rid, r.Status) } -// handleInitReplacement implements emitter handler for init replacement event. -func (h *Hook) handleInitReplacement(ctx sdk.Context, evMap common.EvMap) { - rid := common.Atoi(evMap[tsstypes.EventTypeReplacement+"."+tsstypes.AttributeKeyReplacementID][0]) - r, err := h.tssKeeper.GetReplacement(ctx, uint64(rid)) +// handleTSSMsgActivate implements emitter handler for MsgActivate of TSS. +func (h *Hook) handleTSSMsgActivate( + ctx sdk.Context, msg *types.MsgActivate, +) { + acc, err := sdk.AccAddressFromBech32(msg.Address) if err != nil { panic(err) } - h.emitNewReplacement(r) + h.handleUpdateTSSStatus(ctx, acc) } -// handleUpdateReplacementStatus implements emitter handler events related to replacements. -func (h *Hook) handleUpdateReplacementStatus(ctx sdk.Context, rid uint64) { - r, err := h.tssKeeper.GetReplacement(ctx, rid) +// handleTSSMsgHealthCheck implements emitter handler for MsgHealthCheck of TSS. +func (h *Hook) handleTSSMsgHealthCheck( + ctx sdk.Context, msg *types.MsgHealthCheck, +) { + acc, err := sdk.AccAddressFromBech32(msg.Address) if err != nil { panic(err) } - if r.Status == tsstypes.REPLACEMENT_STATUS_SUCCESS { - h.handleSetGroup(ctx, r.ToGroupID) + + h.handleUpdateTSSStatus(ctx, acc) +} + +// handleTSSMsgSubmitDEs implements emitter handler for MsgSubmitDEs of TSS. +func (h *Hook) handleTSSMsgSubmitDEs( + ctx sdk.Context, msg *types.MsgSubmitDEs, +) { + acc, err := sdk.AccAddressFromBech32(msg.Address) + if err != nil { + panic(err) } - h.emitUpdateReplacementStatus(ctx, rid, r.Status) + h.handleUpdateTSSStatus(ctx, acc) } From e46f99a01297c5cee55a0b48027498c42eafc02a Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Sat, 13 Jan 2024 01:10:49 +0700 Subject: [PATCH 029/132] fix and refactor --- flusher/flusher/tss_db.py | 2 +- hooks/emitter/handler.go | 35 +++++++++---------------- hooks/emitter/tss.go | 8 +++--- scripts/tss/proposal_replace_group.json | 2 +- 4 files changed, 19 insertions(+), 28 deletions(-) diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index 5c09ba554..80b74125d 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -166,7 +166,7 @@ def process_bind_param(self, value, dialect): "tss_replacements", metadata, Column("id", sa.Integer, primary_key=True), - Column("signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), + Column("tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), Column("from_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), Column("from_pub_key", CustomBase64), Column("to_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index a9d4f2d47..f95939357 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -163,29 +163,20 @@ func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) h.handleEventSigningFailed(ctx, evMap) case tsstypes.EventTypeExpiredSigning: h.handleEventExpiredSigning(ctx, evMap) - case tsstypes.EventTypeInactive: - address := sdk.MustAccAddressFromBech32(evMap[tsstypes.EventTypeInactive+"."+tsstypes.AttributeKeyAddress][0]) + case tsstypes.EventTypeInactiveStatus: + address := sdk.MustAccAddressFromBech32( + evMap[tsstypes.EventTypeInactiveStatus+"."+tsstypes.AttributeKeyAddress][0], + ) h.handleUpdateTSSStatus(ctx, address) - case tsstypes.EventTypeCreateGroup: - gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeCreateGroup+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetTSSGroup(ctx, gid) - case tsstypes.EventTypeRound2Success: - gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeRound2Success+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetTSSGroup(ctx, gid) - case tsstypes.EventTypeComplainSuccess: - gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeComplainSuccess+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetTSSGroup(ctx, gid) - case tsstypes.EventTypeComplainFailed: - gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeComplainFailed+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetTSSGroup(ctx, gid) - case tsstypes.EventTypeRound3Success: - gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeRound3Success+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetTSSGroup(ctx, gid) - case tsstypes.EventTypeExpiredGroup: - gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeExpiredGroup+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetTSSGroup(ctx, gid) - case tsstypes.EventTypeUpdateGroupFee: - gid := tss.GroupID(common.Atoi(evMap[tsstypes.EventTypeUpdateGroupFee+"."+tsstypes.AttributeKeyGroupID][0])) + case tsstypes.EventTypeCreateGroup, + tsstypes.EventTypeRound2Success, + tsstypes.EventTypeRound3Success, + tsstypes.EventTypeComplainSuccess, + tsstypes.EventTypeComplainFailed, + tsstypes.EventTypeExpiredGroup, + tsstypes.EventTypeUpdateGroupFee: + + gid := tss.GroupID(common.Atoi(evMap[event.Type+"."+tsstypes.AttributeKeyGroupID][0])) h.handleSetTSSGroup(ctx, gid) case tsstypes.EventTypeReplacement: h.handleInitTSSReplacement(ctx, evMap) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 1147c920b..ea4d2f826 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -80,9 +80,9 @@ func (h *Hook) emitSetTSSGroupMember(member types.Member) { func (h *Hook) emitNewTSSAssignedMember(sid tss.SigningID, gid tss.GroupID, am types.AssignedMember) { h.Write("NEW_TSS_ASSIGNED_MEMBER", common.JsDict{ - "signing_id": sid, - "tss_group_member_id": am.MemberID, + "tss_signing_id": sid, "tss_group_id": gid, + "tss_group_member_id": am.MemberID, "pub_d": parseBytes(am.PubD), "pub_e": parseBytes(am.PubE), "binding_factor": parseBytes(am.PubKey), @@ -135,11 +135,11 @@ func (h *Hook) handleEventRequestSignature(ctx sdk.Context, evMap common.EvMap) id := tss.SigningID(common.Atoi(sid)) signing := h.tssKeeper.MustGetSigning(ctx, id) + h.emitNewTSSSigning(signing) + for _, am := range signing.AssignedMembers { h.emitNewTSSAssignedMember(signing.ID, signing.GroupID, am) } - - h.emitNewTSSSigning(signing) } } diff --git a/scripts/tss/proposal_replace_group.json b/scripts/tss/proposal_replace_group.json index 5b2fd9503..9414b1176 100644 --- a/scripts/tss/proposal_replace_group.json +++ b/scripts/tss/proposal_replace_group.json @@ -4,7 +4,7 @@ "@type": "/tss.v1beta1.MsgReplaceGroup", "from_group_id": "2", "to_group_id": "1", - "exec_time": "2023-11-11T14:13:00+00:00", + "exec_time": "2024-01-12T18:00:00+00:00", "authority": "band10d07y265gmmuvt4z0w9aw880jnsr700jrdn8wm" } ], From 810a301ed05708d66eb6d9c7ac108fe72c14a323 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Mon, 12 Feb 2024 00:49:37 +0700 Subject: [PATCH 030/132] fix naming --- flusher/flusher/tss_db.py | 8 ++++---- hooks/emitter/tss.go | 18 +++++++++--------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index 80b74125d..ac25a4a06 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -167,10 +167,10 @@ def process_bind_param(self, value, dialect): metadata, Column("id", sa.Integer, primary_key=True), Column("tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), - Column("from_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), - Column("from_pub_key", CustomBase64), - Column("to_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), - Column("to_pub_key", CustomBase64), + Column("new_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), + Column("new_pub_key", CustomBase64), + Column("current_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), + Column("current_pub_key", CustomBase64), Column("exec_time", CustomDateTime), Column("status", CustomReplacementStatus), ) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index ea4d2f826..b3340565c 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -92,14 +92,14 @@ func (h *Hook) emitNewTSSAssignedMember(sid tss.SigningID, gid tss.GroupID, am t func (h *Hook) emitNewTSSReplacement(replacement types.Replacement) { h.Write("NEW_TSS_REPLACEMENT", common.JsDict{ - "id": replacement.ID, - "tss_signing_id": replacement.SigningID, - "from_group_id": replacement.FromGroupID, - "from_pub_key": parseBytes(replacement.FromPubKey), - "to_group_id": replacement.ToGroupID, - "to_pub_key": parseBytes(replacement.ToPubKey), - "exec_time": replacement.ExecTime.UnixNano(), - "status": int(replacement.Status), + "id": replacement.ID, + "tss_signing_id": replacement.SigningID, + "new_group_id": replacement.NewGroupID, + "new_pub_key": parseBytes(replacement.NewPubKey), + "current_group_id": replacement.CurrentGroupID, + "current_pub_key": parseBytes(replacement.CurrentPubKey), + "exec_time": replacement.ExecTime.UnixNano(), + "status": int(replacement.Status), }) } @@ -229,7 +229,7 @@ func (h *Hook) handleUpdateTSSReplacementStatus(ctx sdk.Context, rid uint64) { panic(err) } if r.Status == types.REPLACEMENT_STATUS_SUCCESS { - h.handleSetTSSGroup(ctx, r.ToGroupID) + h.handleSetTSSGroup(ctx, r.CurrentGroupID) } h.emitUpdateTSSReplacementStatus(ctx, rid, r.Status) From 7404a89599ab708c27e0daf27f0576a6a615d516 Mon Sep 17 00:00:00 2001 From: Natthakun Kitthaworn <30922676+nkitlabs@users.noreply.github.com> Date: Wed, 14 Feb 2024 17:33:22 +0700 Subject: [PATCH 031/132] fix conflict (#69) --- .github/workflows/golangci-lint.yml | 2 +- .golangci.yml | 103 +++++++- app/app.go | 17 +- app/export.go | 31 ++- app/migrate.go | 4 +- app/upgrades/v2_4/upgrades.go | 4 +- app/upgrades/v2_5/upgrades.go | 4 +- app/upgrades/v2_6/upgrades.go | 10 +- benchmark/README.md | 30 +-- benchmark/app_test.go | 19 +- benchmark/bench_test.go | 18 +- benchmark/helper_test.go | 37 +-- client/grpc/node/service.go | 11 +- client/grpc/oracle/proof/result.go | 6 +- client/grpc/oracle/proof/signature.go | 2 +- cmd/bandd/cmd/genaccounts.go | 3 +- cmd/bandd/cmd/gends.go | 1 - cmd/bandd/cmd/multi_send.go | 2 +- cmd/bandd/cmd/root.go | 11 +- cmd/cylinder/context.go | 3 +- cmd/cylinder/export.go | 6 +- cmd/cylinder/import.go | 4 +- cmd/cylinder/keys.go | 3 +- cmd/cylinder/run.go | 25 +- cmd/faucet/handler.go | 7 +- cmd/faucet/run.go | 14 +- cylinder/client/signing_response.go | 2 +- cylinder/context.go | 5 +- cylinder/run.go | 4 +- cylinder/worker.go | 2 +- cylinder/workers/de/de.go | 4 +- cylinder/workers/group/group.go | 8 +- cylinder/workers/group/round1.go | 4 +- cylinder/workers/group/round2.go | 4 +- cylinder/workers/group/round3.go | 4 +- cylinder/workers/healthcheck/healthcheck.go | 4 +- cylinder/workers/sender/sender.go | 4 +- cylinder/workers/signing/signing.go | 4 +- hooks/common/query.go | 6 +- hooks/emitter/channel.go | 9 +- hooks/emitter/client.go | 3 +- hooks/emitter/decoder.go | 4 +- hooks/emitter/decoder_test.go | 11 +- hooks/emitter/emitter.go | 27 +- hooks/emitter/gov.go | 18 +- hooks/emitter/oracle.go | 6 +- hooks/emitter/transfer.go | 2 +- hooks/price/price.go | 5 +- hooks/request/request.go | 14 +- hooks/request/types.go | 2 +- pkg/bandrng/sampling.go | 4 +- pkg/filecache/filecache.go | 2 +- pkg/filecache/filecache_test.go | 12 +- pkg/gzip/gzip_test.go | 6 +- pkg/obi/decode.go | 4 +- pkg/obi/encode.go | 4 +- pkg/obi/encode_test.go | 3 +- pkg/obi/schema_test.go | 20 +- pkg/tss/elgamal_bench_test.go | 15 +- pkg/tss/hash.go | 4 +- pkg/tss/hash_paper.go | 32 +-- pkg/tss/hash_paper_test.go | 3 +- pkg/tss/internal/lagrange/lagrange.go | 4 +- pkg/tss/internal/lagrange/lagrange_test.go | 3 +- pkg/tss/internal/schnorr/signature.go | 26 +- pkg/tss/operation_bench_test.go | 30 ++- pkg/tss/operation_test.go | 3 +- pkg/tss/round1.go | 4 +- pkg/tss/round3.go | 4 +- pkg/tss/round3_test.go | 2 +- pkg/tss/schnorr.go | 3 +- pkg/tss/schnorr_bench_test.go | 16 +- pkg/tss/schnorr_test.go | 12 +- pkg/tss/signing.go | 7 +- pkg/tss/testutil/suite.go | 3 +- pkg/tss/tss_test.go | 3 +- pkg/tss/types.go | 3 +- pkg/tss/types_test.go | 3 +- testing/chain.go | 23 +- testing/coordinator.go | 6 +- testing/endpoint.go | 22 +- testing/events.go | 3 +- testing/testapp/setup.go | 32 +-- testing/testapp/wasm_1_simple.go | 4 +- testing/testapp/wasm_2_return_in_prepare.go | 2 +- testing/testapp/wasm_3_do_nothing.go | 2 +- testing/testapp/wasm_4_complex.go | 2 +- testing/testapp/wasm_extras.go | 10 +- testing/testapp/wasm_util.go | 8 +- testing/value.go | 3 +- x/bank/keeper/keeper.go | 7 +- x/globalfee/feechecker/feechecker_test.go | 26 +- x/globalfee/keeper/genesis.go | 8 +- x/globalfee/keeper/genesis_test.go | 6 +- x/globalfee/keeper/grpc_query_test.go | 12 +- x/globalfee/keeper/keeper_test.go | 3 +- x/globalfee/module.go | 6 +- x/globalfee/types/keys.go | 4 +- x/oracle/abci_test.go | 36 ++- x/oracle/app_test.go | 4 +- x/oracle/genesis.go | 6 +- x/oracle/handler_test.go | 77 +++--- x/oracle/ibc_test.go | 43 ++-- x/oracle/keeper/grpc_query.go | 20 +- x/oracle/keeper/grpc_query_test.go | 7 +- x/oracle/keeper/oracle_script_test.go | 2 +- x/oracle/keeper/owasm.go | 2 +- x/oracle/keeper/owasm_test.go | 49 ++-- x/oracle/keeper/params_test.go | 11 +- x/oracle/keeper/request.go | 2 +- x/oracle/keeper/request_test.go | 26 +- x/oracle/keeper/result.go | 4 +- x/oracle/keeper/validator_status_test.go | 9 +- x/oracle/module.go | 9 +- x/oracle/types/channel.go | 6 +- x/oracle/types/codec.go | 2 +- x/oracle/types/constants.go | 6 +- x/oracle/types/events.go | 1 - x/oracle/types/exec_env.go | 2 +- x/oracle/types/exec_env_test.go | 23 +- x/oracle/types/msgs.go | 270 ++++++++++---------- x/oracle/types/oracle_script.go | 24 +- x/oracle/types/params.go | 1 - x/oracle/types/params_legacy.go | 1 - x/oracle/types/report.go | 24 +- x/oracle/types/request.go | 12 +- x/oracle/types/result.go | 8 +- x/oracle/types/validator_status.go | 8 +- x/rollingseed/abci_test.go | 3 +- x/rollingseed/module.go | 4 +- x/tss/client/cli/tx.go | 4 +- x/tss/genesis.go | 4 +- x/tss/keeper/de_test.go | 9 +- x/tss/keeper/grpc_query.go | 1 - x/tss/keeper/grpc_query_test.go | 18 +- x/tss/keeper/keeper.go | 4 +- x/tss/keeper/keeper_test.go | 3 +- x/tss/keeper/msg_server_test.go | 7 +- x/tss/keeper/params.go | 3 +- x/tss/keeper/params_test.go | 3 +- x/tss/keeper/signing_test.go | 3 +- x/tss/keeper/validator_test.go | 36 ++- x/tss/module.go | 6 +- x/tss/types/helpers_test.go | 3 +- x/tss/types/keys.go | 5 +- x/tss/types/router.go | 3 +- yoda/execute.go | 6 +- yoda/executor/docker.go | 4 +- yoda/executor/executor.go | 2 +- yoda/executor/rest.go | 2 - yoda/executor/rest_test.go | 24 +- yoda/gas.go | 2 +- yoda/handler.go | 4 +- yoda/keys.go | 2 +- yoda/metrics.go | 11 +- yoda/run.go | 23 +- 156 files changed, 1066 insertions(+), 785 deletions(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 06dedc1f2..5c2e1328f 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -12,5 +12,5 @@ jobs: - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: - version: v1.49 + version: v1.55.2 args: --timeout=5m0s diff --git a/.golangci.yml b/.golangci.yml index 7b61b0ebe..38f8ae660 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,15 +1,104 @@ -linters-settings: +run: + timeout: 5m + go: "1.19" + skip-files: + - ".*\\.pb\\.go$" + - ".*\\.pb\\.gw\\.\\.go$" + - ".*\\.pulsar\\.go$" linters: disable-all: true enable: - bodyclose - - gofmt - - goimports + - whitespace + - errcheck + - exportloopref + - gci + - gocritic + - gofumpt + - gosec + - gosimple + - govet + - ineffassign - misspell + - nolintlint + - revive + - staticcheck + - stylecheck + - unconvert - typecheck - - whitespace -run: - timeout: 5m - go: "1.19" +issues: + exclude-rules: + - text: "Use of weak random number generator" + linters: + - gosec + - text: "ST1003:" + linters: + - stylecheck + +linters-settings: + gci: + custom-order: true + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - prefix(github.com/bandprotocol/chain) + gocritic: + disabled-checks: + - regexpMust + - appendAssign + - ifElseChain + - singleCaseSwitch + maligned: + # print struct with more effective memory layout or not, false by default + suggest-new: true + nolintlint: + allow-unused: false + allow-leading-space: true + require-explanation: false + require-specific: false + revive: + rules: + - name: unused-parameter + disabled: true + gosec: + # To select a subset of rules to run. + # Available rules: https://github.com/securego/gosec#available-rules + # Default: [] - means include all rules + includes: + # - G101 # Look for hard coded credentials + - G102 # Bind to all interfaces + - G103 # Audit the use of unsafe block + - G104 # Audit errors not checked + - G106 # Audit the use of ssh.InsecureIgnoreHostKey + - G107 # Url provided to HTTP request as taint input + - G108 # Profiling endpoint automatically exposed on /debug/pprof + - G109 # Potential Integer overflow made by strconv.Atoi result conversion to int16/32 + - G110 # Potential DoS vulnerability via decompression bomb + - G111 # Potential directory traversal + - G112 # Potential slowloris attack + - G113 # Usage of Rat.SetString in math/big with an overflow (CVE-2022-23772) + - G114 # Use of net/http serve function that has no support for setting timeouts + - G201 # SQL query construction using format string + - G202 # SQL query construction using string concatenation + - G203 # Use of unescaped data in HTML templates + - G204 # Audit use of command execution + - G301 # Poor file permissions used when creating a directory + - G302 # Poor file permissions used with chmod + - G303 # Creating tempfile using a predictable path + - G304 # File path provided as taint input + - G305 # File traversal when extracting zip/tar archive + - G306 # Poor file permissions used when writing to a new file + - G307 # Deferring a method which returns an error + - G401 # Detect the usage of DES, RC4, MD5 or SHA1 + - G402 # Look for bad TLS connection settings + - G403 # Ensure minimum RSA key length of 2048 bits + - G404 # Insecure random number source (rand) + - G501 # Import blocklist: crypto/md5 + - G502 # Import blocklist: crypto/des + - G503 # Import blocklist: crypto/rc4 + - G504 # Import blocklist: net/http/cgi + - G505 # Import blocklist: crypto/sha1 + - G601 # Implicit memory aliasing of items from a range statement + diff --git a/app/app.go b/app/app.go index ec2c9b291..ee46953c8 100644 --- a/app/app.go +++ b/app/app.go @@ -330,6 +330,7 @@ func NewBandApp( if err != nil { panic(err) } + // Initialize params keeper and module subspaces. app.ParamsKeeper = initParamsKeeper( appCodec, @@ -367,6 +368,7 @@ func NewBandApp( Bech32MainPrefix, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + // wrappedBankerKeeper overrides burn token behavior to instead transfer to community pool. app.BankKeeper = bandbankkeeper.NewWrappedBankKeeperBurnToCommunityPool( bankkeeper.NewBaseKeeper( @@ -378,6 +380,7 @@ func NewBandApp( ), app.AccountKeeper, ) + app.StakingKeeper = stakingkeeper.NewKeeper( appCodec, keys[stakingtypes.StoreKey], @@ -385,6 +388,7 @@ func NewBandApp( app.BankKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + app.MintKeeper = mintkeeper.NewKeeper( appCodec, keys[minttypes.StoreKey], @@ -394,6 +398,7 @@ func NewBandApp( authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + app.DistrKeeper = distrkeeper.NewKeeper( appCodec, keys[distrtypes.StoreKey], @@ -405,6 +410,7 @@ func NewBandApp( ) // DistrKeeper must be set afterward due to the circular reference between banker-staking-distr. app.BankKeeper.SetDistrKeeper(&app.DistrKeeper) + app.SlashingKeeper = slashingkeeper.NewKeeper( appCodec, legacyAmino, @@ -515,7 +521,6 @@ func NewBandApp( scopedICAHostKeeper, app.MsgServiceRouter(), ) - icaModule := ica.NewAppModule(nil, &app.ICAHostKeeper) icaHostIBCModule := icahost.NewIBCModule(app.ICAHostKeeper) @@ -725,11 +730,11 @@ func NewBandApp( tssModule, globalfee.NewAppModule(app.GlobalfeeKeeper), ) + // NOTE: Oracle module must occur before distr as it takes some fee to distribute to active oracle validators. // NOTE: During begin block slashing happens after distr.BeginBlocker so that there is nothing left // over in the validator fee pool, so as to keep the CanWithdrawInvariant invariant. // NOTE: capability module's beginblocker must come before any modules using capabilities (e.g. IBC) - app.mm.SetOrderBeginBlockers( upgradetypes.ModuleName, capabilitytypes.ModuleName, @@ -757,6 +762,7 @@ func NewBandApp( consensusparamtypes.ModuleName, globalfeetypes.ModuleName, ) + app.mm.SetOrderEndBlockers( crisistypes.ModuleName, govtypes.ModuleName, @@ -896,6 +902,7 @@ func NewBandApp( app.ScopedIBCKeeper = scopedIBCKeeper app.ScopedTransferKeeper = scopedTransferKeeper app.ScopedOracleKeeper = scopedOracleKeeper + app.ScopedICAHostKeeper = scopedICAHostKeeper return app } @@ -1112,7 +1119,7 @@ func initParamsKeeper( paramsKeeper.Subspace(minttypes.ModuleName) paramsKeeper.Subspace(distrtypes.ModuleName) paramsKeeper.Subspace(slashingtypes.ModuleName) - paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable()) + paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable()) //nolint:staticcheck paramsKeeper.Subspace(crisistypes.ModuleName) paramsKeeper.Subspace(ibcexported.ModuleName) paramsKeeper.Subspace(ibctransfertypes.ModuleName) @@ -1147,9 +1154,9 @@ func (app *BandApp) setupUpgradeStoreLoaders() { return } - for _, upgrade := range Upgrades { + for idx, upgrade := range Upgrades { if upgradeInfo.Name == upgrade.UpgradeName { - app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &upgrade.StoreUpgrades)) + app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &Upgrades[idx].StoreUpgrades)) } } } diff --git a/app/export.go b/app/export.go index 5652ecbdd..77ed8652f 100644 --- a/app/export.go +++ b/app/export.go @@ -2,10 +2,10 @@ package band import ( "encoding/json" + "fmt" "log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -88,7 +88,10 @@ func (app *BandApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ if err != nil { panic(err) } - _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) + + if _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr); err != nil { + panic(err) + } } // clear validator slash events @@ -109,7 +112,9 @@ func (app *BandApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) app.DistrKeeper.SetFeePool(ctx, feePool) - app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) + if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()); err != nil { + panic(err) + } return false }) @@ -119,12 +124,17 @@ func (app *BandApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ if err != nil { panic(err) } - delAddr, err := sdk.AccAddressFromBech32(del.DelegatorAddress) - if err != nil { - panic(err) + delAddr := sdk.MustAccAddressFromBech32(del.DelegatorAddress) + + if err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil { + // never called as BeforeDelegationCreated always returns nil + panic(fmt.Errorf("error while incrementing period: %w", err)) + } + + if err := app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil { + // never called as AfterDelegationModified always returns nil + panic(fmt.Errorf("error while creating a new delegation period record: %w", err)) } - app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) - app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) } // reset context height @@ -175,7 +185,10 @@ func (app *BandApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ counter++ } - iter.Close() + if err := iter.Close(); err != nil { + app.Logger().Error("error while closing the key-value store reverse prefix iterator: ", err) + return + } _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) if err != nil { diff --git a/app/migrate.go b/app/migrate.go index 2d7beefd6..6ad84c8b2 100644 --- a/app/migrate.go +++ b/app/migrate.go @@ -2,7 +2,7 @@ package band import ( "fmt" - "io/ioutil" + "os" tmtypes "github.com/cometbft/cometbft/types" ) @@ -15,7 +15,7 @@ const ( // GenesisDocFromFile reads JSON data from a file and unmarshalls it into a GenesisDoc. func GenesisDocFromFile(genDocFile string) (*tmtypes.GenesisDoc, error) { - jsonBlob, err := ioutil.ReadFile(genDocFile) + jsonBlob, err := os.ReadFile(genDocFile) if err != nil { return nil, fmt.Errorf("couldn't read GenesisDoc file: %w", err) } diff --git a/app/upgrades/v2_4/upgrades.go b/app/upgrades/v2_4/upgrades.go index be937898e..0f9716b47 100644 --- a/app/upgrades/v2_4/upgrades.go +++ b/app/upgrades/v2_4/upgrades.go @@ -86,7 +86,9 @@ func CreateUpgradeHandler( } // Oracle DefaultParams only upgrade BaseRequestGas to 50000 - keepers.OracleKeeper.SetParams(ctx, oracletypes.DefaultParams()) + if err := keepers.OracleKeeper.SetParams(ctx, oracletypes.DefaultParams()); err != nil { + return nil, err + } consensusParam := am.GetConsensusParams(ctx) consensusParam.Block.MaxGas = 50_000_000 diff --git a/app/upgrades/v2_5/upgrades.go b/app/upgrades/v2_5/upgrades.go index fb85bc65c..1aaa025a6 100644 --- a/app/upgrades/v2_5/upgrades.go +++ b/app/upgrades/v2_5/upgrades.go @@ -12,8 +12,8 @@ import ( func CreateUpgradeHandler( mm *module.Manager, configurator module.Configurator, - _ upgrades.AppManager, - _ *keepers.AppKeepers, + am upgrades.AppManager, + keepers *keepers.AppKeepers, ) upgradetypes.UpgradeHandler { return func(ctx sdk.Context, _ upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) { ctx.Logger().Info("Starting module migrations...") diff --git a/app/upgrades/v2_6/upgrades.go b/app/upgrades/v2_6/upgrades.go index fd2e6b236..ce52e0bda 100644 --- a/app/upgrades/v2_6/upgrades.go +++ b/app/upgrades/v2_6/upgrades.go @@ -1,7 +1,6 @@ package v2_6 import ( - oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -21,6 +20,7 @@ import ( "github.com/bandprotocol/chain/v2/app/keepers" "github.com/bandprotocol/chain/v2/app/upgrades" globalfeetypes "github.com/bandprotocol/chain/v2/x/globalfee/types" + oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" ) func CreateUpgradeHandler( @@ -41,7 +41,7 @@ func CreateUpgradeHandler( case banktypes.ModuleName: keyTable = banktypes.ParamKeyTable() //nolint:staticcheck case stakingtypes.ModuleName: - keyTable = stakingtypes.ParamKeyTable() //nolint:staticcheck + keyTable = stakingtypes.ParamKeyTable() case minttypes.ModuleName: keyTable = minttypes.ParamKeyTable() //nolint:staticcheck case distrtypes.ModuleName: @@ -54,11 +54,11 @@ func CreateUpgradeHandler( keyTable = crisistypes.ParamKeyTable() //nolint:staticcheck // ibc types case ibctransfertypes.ModuleName: - keyTable = ibctransfertypes.ParamKeyTable() //nolint:staticcheck + keyTable = ibctransfertypes.ParamKeyTable() case icahosttypes.SubModuleName: - keyTable = icahosttypes.ParamKeyTable() //nolint:staticcheck + keyTable = icahosttypes.ParamKeyTable() case oracletypes.ModuleName: - keyTable = oracletypes.ParamKeyTable() //nolint:staticcheck + keyTable = oracletypes.ParamKeyTable() default: continue } diff --git a/benchmark/README.md b/benchmark/README.md index 7bcc2ab33..8703a9f87 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -2,7 +2,7 @@ ## Benchmark Oracle Script Spec -This oracle script will act as a proxy. We have to send scenario number and value with it to execute the specified type of code. +This oracle script will act as a proxy. We have to send the scenario number and value with it to execute the specified type of code. ``` Input { @@ -35,42 +35,42 @@ Output { - Value = Size of memory ### Execute scenarios -- Scenario 0: nothing +- Scenario 0: Nothing - Value = - - Scenario 101: infinite_loop - Value = - - Scenario 102: arithmetic_ops - - Value = Number of loop + - Value = Number of loops - Scenario 103: allocate_mem - Value = Size of memory - Scenario 104: find_median - - Value = Number of loop + - Value = Number of loops - Scenario 105: finite_loop - - Value = Number of loop + - Value = Number of loops - Scenario 106: set_local_var - Value = Size of memory - Scenario 201: get_ask_count - - Value = Number of loop + - Value = Number of loops - Scenario 202: get_min_count - - Value = Number of loop + - Value = Number of loops - Scenario 203: get_prepare_time - - Value = Number of loop + - Value = Number of loops - Scenario 204: get_execute_time - - Value = Number of loop + - Value = Number of loops - Scenario 205: get_ans_count - - Value = Number of loop + - Value = Number of loops - Scenario 206: get_calldata - - Value = Number of loop + - Value = Number of loops - Scenario 207: save_return_data - - Value = Number of loop + - Value = Number of loops - Scenario 208: get_external_data - - Value = Number of loop + - Value = Number of loops - Scenario 209: ecvrf_verify - - Value = Number of loop + - Value = Number of loops - Scenario 210: base_import - Value = - -## How to run benchmark +## How to run the benchmark ``` cd benchmark diff --git a/benchmark/app_test.go b/benchmark/app_test.go index 560e972ad..dd443d5a2 100644 --- a/benchmark/app_test.go +++ b/benchmark/app_test.go @@ -55,7 +55,7 @@ func GetDEs() []tsstypes.DE { return delist } -func InitializeBenchmarkApp(b testing.TB, maxGasPerBlock int64) *BenchmarkApp { +func InitializeBenchmarkApp(tb testing.TB, maxGasPerBlock int64) *BenchmarkApp { ba := &BenchmarkApp{ TestingApp: testapp.NewTestApp("", log.NewNopLogger()), Sender: &Account{ @@ -68,7 +68,7 @@ func InitializeBenchmarkApp(b testing.TB, maxGasPerBlock int64) *BenchmarkApp { Num: 5, Seq: 0, }, - TB: b, + TB: tb, } ba.Ctx = ba.NewUncachedContext(false, tmproto.Header{}) ba.TSSMsgSrvr = tsskeeper.NewMsgServerImpl(&ba.TestingApp.TSSKeeper) @@ -85,11 +85,11 @@ func InitializeBenchmarkApp(b testing.TB, maxGasPerBlock int64) *BenchmarkApp { // create oracle script oCode, err := GetBenchmarkWasm() - require.NoError(b, err) + require.NoError(tb, err) _, res, err := ba.DeliverMsg(ba.Sender, GenMsgCreateOracleScript(ba.Sender, oCode)) - require.NoError(b, err) + require.NoError(tb, err) oid, err := GetFirstAttributeOfLastEventValue(res.Events) - require.NoError(b, err) + require.NoError(tb, err) ba.Oid = uint64(oid) // set group ID @@ -99,13 +99,14 @@ func InitializeBenchmarkApp(b testing.TB, maxGasPerBlock int64) *BenchmarkApp { // create data source dCode := []byte("hello") _, res, err = ba.DeliverMsg(ba.Sender, GenMsgCreateDataSource(ba.Sender, dCode)) - require.NoError(b, err) + require.NoError(tb, err) did, err := GetFirstAttributeOfLastEventValue(res.Events) - require.NoError(b, err) + require.NoError(tb, err) ba.Did = uint64(did) // activate oracle - _, _, _ = ba.DeliverMsg(ba.Validator, GenMsgActivate(ba.Validator)) + _, _, err = ba.DeliverMsg(ba.Validator, GenMsgActivate(ba.Validator)) + require.NoError(tb, err) ba.CallEndBlock() ba.Commit() @@ -141,7 +142,7 @@ func (ba *BenchmarkApp) AddMaxMsgRequests(msg []sdk.Msg) { for block := 0; block < 10; block++ { ba.CallBeginBlock() - var totalGas uint64 = 0 + totalGas := uint64(0) for { tx := GenSequenceOfTxs( ba.TxConfig, diff --git a/benchmark/bench_test.go b/benchmark/bench_test.go index 6dbb2e8ce..b4586b314 100644 --- a/benchmark/bench_test.go +++ b/benchmark/bench_test.go @@ -152,11 +152,13 @@ var CacheCases = map[string]uint32{ "cache": 1, } -var PrepareGasLimit uint64 = 7_500_000 -var ExecuteGasLimit uint64 = 7_500_000 -var BlockMaxGas int64 = 50_000_000 -var GasRanges []int = []int{1, 1_000, 10_000, 100_000, 1_000_000, 7_900_000} -var NumRequestRanges []int = []int{0, 1, 5, 10, 20} +var ( + PrepareGasLimit uint64 = 7_500_000 + ExecuteGasLimit uint64 = 7_500_000 + BlockMaxGas int64 = 50_000_000 + GasRanges = []int{1, 1_000, 10_000, 100_000, 1_000_000, 7_900_000} + NumRequestRanges = []int{0, 1, 5, 10, 20} +) // benchmark test for prepare function of owasm vm func BenchmarkOwasmVMPrepare(b *testing.B) { @@ -334,7 +336,7 @@ func BenchmarkRequestDataEndBlock(b *testing.B) { ba.Oid, ba.Did, tc.scenario, - uint64(pm), + pm, strlen, 10000, ExecuteGasLimit, @@ -438,7 +440,7 @@ func benchmarkBlockNormalMsg(b *testing.B) { ba.CallBeginBlock() b.StopTimer() - var totalGas uint64 = 0 + totalGas := uint64(0) for { tx := GenSequenceOfTxs( ba.TxConfig, @@ -503,7 +505,7 @@ func benchmarkBlockReportMsg(b *testing.B) { b.StopTimer() res := ba.GetAllPendingRequests(ba.Validator) - var totalGas uint64 = 0 + totalGas := uint64(0) reqChunks := ChunkSlice(res.RequestIDs, reportSize) for _, reqChunk := range reqChunks { diff --git a/benchmark/helper_test.go b/benchmark/helper_test.go index 710442911..9dbbba428 100644 --- a/benchmark/helper_test.go +++ b/benchmark/helper_test.go @@ -33,7 +33,7 @@ type Account struct { } type BenchmarkCalldata struct { - DataSourceId uint64 + DataSourceID uint64 Scenario uint64 Value uint64 Text string @@ -46,8 +46,8 @@ func GetBenchmarkWasm() ([]byte, error) { func GenMsgRequestData( sender *Account, - oracleScriptId uint64, - dataSourceId uint64, + oracleScriptID uint64, + dataSourceID uint64, scenario uint64, value uint64, stringLength int, @@ -55,9 +55,9 @@ func GenMsgRequestData( executeGas uint64, ) []sdk.Msg { msg := oracletypes.MsgRequestData{ - OracleScriptID: oracletypes.OracleScriptID(oracleScriptId), + OracleScriptID: oracletypes.OracleScriptID(oracleScriptID), Calldata: obi.MustEncode(BenchmarkCalldata{ - DataSourceId: dataSourceId, + DataSourceID: dataSourceID, Scenario: scenario, Value: value, Text: strings.Repeat("#", stringLength), @@ -225,7 +225,7 @@ func GenSequenceOfTxs( []uint64{account.Seq}, account.PrivKey, ) - account.Seq += 1 + account.Seq++ } return txs @@ -241,7 +241,7 @@ func DecodeEvents(events []types.Event) []Event { for _, event := range events { attrs := make(map[string]string, 0) for _, attributes := range event.Attributes { - attrs[string(attributes.Key)] = string(attributes.Value) + attrs[attributes.Key] = attributes.Value } evs = append(evs, Event{ Type: event.Type, @@ -252,27 +252,16 @@ func DecodeEvents(events []types.Event) []Event { return evs } -func LogEvents(b testing.TB, events []types.Event) { - evs := DecodeEvents(events) - for i, ev := range evs { - b.Logf("Event %d: %+v\n", i, ev) - } - - if len(evs) == 0 { - b.Logf("No Event") - } -} - func GetFirstAttributeOfLastEventValue(events []types.Event) (int, error) { evt := events[len(events)-1] attr := evt.Attributes[0] - value, err := strconv.Atoi(string(attr.Value)) + value, err := strconv.Atoi(attr.Value) return value, err } func InitOwasmTestEnv( - b testing.TB, + tb testing.TB, cacheSize uint32, scenario uint64, parameter uint64, @@ -280,18 +269,18 @@ func InitOwasmTestEnv( ) (*owasm.Vm, []byte, oracletypes.Request) { // prepare owasm vm owasmVM, err := owasm.NewVm(cacheSize) - require.NoError(b, err) + require.NoError(tb, err) // prepare owasm code oCode, err := GetBenchmarkWasm() - require.NoError(b, err) + require.NoError(tb, err) compiledCode, err := owasmVM.Compile(oCode, oracletypes.MaxCompiledWasmCodeSize) - require.NoError(b, err) + require.NoError(tb, err) // prepare request req := oracletypes.NewRequest( 1, obi.MustEncode(BenchmarkCalldata{ - DataSourceId: 1, + DataSourceID: 1, Scenario: scenario, Value: parameter, Text: strings.Repeat("#", stringLength), diff --git a/client/grpc/node/service.go b/client/grpc/node/service.go index 9eda1b68b..5e4e63655 100644 --- a/client/grpc/node/service.go +++ b/client/grpc/node/service.go @@ -5,12 +5,11 @@ import ( "fmt" "github.com/cometbft/cometbft/crypto/secp256k1" + "github.com/cosmos/cosmos-sdk/client" + sdk "github.com/cosmos/cosmos-sdk/types" gogogrpc "github.com/cosmos/gogoproto/grpc" "github.com/ethereum/go-ethereum/crypto" "github.com/grpc-ecosystem/grpc-gateway/runtime" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" ) // RegisterNodeService registers the node gRPC service on the provided gRPC router. @@ -21,7 +20,7 @@ func RegisterNodeService(clientCtx client.Context, server gogogrpc.Server) { // RegisterGRPCGatewayRoutes mounts the node gRPC service's GRPC-gateway routes // on the given mux object. func RegisterGRPCGatewayRoutes(clientConn gogogrpc.ClientConn, mux *runtime.ServeMux) { - RegisterServiceHandlerClient(context.Background(), mux, NewServiceClient(clientConn)) + _ = RegisterServiceHandlerClient(context.Background(), mux, NewServiceClient(clientConn)) } // to check queryServer implements ServiceServer @@ -59,8 +58,8 @@ func (s queryServer) EVMValidators( } // Get top 100 validators for now - var page int = 1 - var perPage int = 100 + page := 1 + perPage := 100 validators, err := node.Validators(context.Background(), nil, &page, &perPage) if err != nil { return nil, err diff --git a/client/grpc/oracle/proof/result.go b/client/grpc/oracle/proof/result.go index 51e408492..f61f484ce 100644 --- a/client/grpc/oracle/proof/result.go +++ b/client/grpc/oracle/proof/result.go @@ -24,10 +24,10 @@ func transformResult(r oracletypes.Result) ResultEthereum { ClientID: r.ClientID, OracleScriptID: uint64(r.OracleScriptID), Params: r.Calldata, - AskCount: uint64(r.AskCount), - MinCount: uint64(r.MinCount), + AskCount: r.AskCount, + MinCount: r.MinCount, RequestID: uint64(r.RequestID), - AnsCount: uint64(r.AnsCount), + AnsCount: r.AnsCount, RequestTime: uint64(r.RequestTime), ResolveTime: uint64(r.ResolveTime), ResolveStatus: uint8(r.ResolveStatus), diff --git a/client/grpc/oracle/proof/signature.go b/client/grpc/oracle/proof/signature.go index cb8b85ab3..3c9577dd1 100644 --- a/client/grpc/oracle/proof/signature.go +++ b/client/grpc/oracle/proof/signature.go @@ -32,7 +32,7 @@ func (signature *TMSignature) encodeToEthFormat() TMSignatureEthereum { func recoverETHAddress(msg, sig, signer []byte) ([]byte, uint8, error) { for i := uint8(0); i < 2; i++ { - pubuc, err := crypto.SigToPub(tmhash.Sum(msg), append(sig, byte(i))) + pubuc, err := crypto.SigToPub(tmhash.Sum(msg), append(sig, i)) if err != nil { return nil, 0, err } diff --git a/cmd/bandd/cmd/genaccounts.go b/cmd/bandd/cmd/genaccounts.go index 7a917f60d..463e2d618 100644 --- a/cmd/bandd/cmd/genaccounts.go +++ b/cmd/bandd/cmd/genaccounts.go @@ -6,8 +6,6 @@ import ( "errors" "fmt" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -18,6 +16,7 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/genutil" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" + "github.com/spf13/cobra" ) const ( diff --git a/cmd/bandd/cmd/gends.go b/cmd/bandd/cmd/gends.go index 70128c2ec..0ba3a395d 100644 --- a/cmd/bandd/cmd/gends.go +++ b/cmd/bandd/cmd/gends.go @@ -62,7 +62,6 @@ func AddGenesisDataSourceCmd(defaultNodeHome string) *cobra.Command { owner, args[0], args[1], filename, fee, treasury, )) oracleGenStateBz, err := cdc.MarshalJSON(oracleGenState) - if err != nil { return fmt.Errorf("failed to marshal auth genesis state: %w", err) } diff --git a/cmd/bandd/cmd/multi_send.go b/cmd/bandd/cmd/multi_send.go index ee364ae80..b624e3c6f 100644 --- a/cmd/bandd/cmd/multi_send.go +++ b/cmd/bandd/cmd/multi_send.go @@ -21,7 +21,7 @@ func MultiSendTxCmd() *cobra.Command { if err != nil { return err } - sender := sdk.AccAddress(clientCtx.GetFromAddress()) + sender := clientCtx.GetFromAddress() // Parse the coins we are trying to send coins, err := sdk.ParseCoinsNormalized(args[0]) diff --git a/cmd/bandd/cmd/root.go b/cmd/bandd/cmd/root.go index 9e549fe54..6f9d6a81e 100644 --- a/cmd/bandd/cmd/root.go +++ b/cmd/bandd/cmd/root.go @@ -214,8 +214,15 @@ func newApp( } func appExport( - logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, - appOpts servertypes.AppOptions, modulesToExport []string) (servertypes.ExportedApp, error) { + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + height int64, + forZeroHeight bool, + jailAllowedAddrs []string, + appOpts servertypes.AppOptions, + modulesToExport []string, +) (servertypes.ExportedApp, error) { homePath, ok := appOpts.Get(flags.FlagHome).(string) if !ok || homePath == "" { return servertypes.ExportedApp{}, errors.New("application home not set") diff --git a/cmd/cylinder/context.go b/cmd/cylinder/context.go index ad7968547..354bed272 100644 --- a/cmd/cylinder/context.go +++ b/cmd/cylinder/context.go @@ -1,8 +1,9 @@ package main import ( - "github.com/bandprotocol/chain/v2/cylinder" "github.com/cosmos/cosmos-sdk/crypto/keyring" + + "github.com/bandprotocol/chain/v2/cylinder" ) // Context represents the application context. diff --git a/cmd/cylinder/export.go b/cmd/cylinder/export.go index 893fe838a..63b505f3a 100644 --- a/cmd/cylinder/export.go +++ b/cmd/cylinder/export.go @@ -108,7 +108,7 @@ func exportGroupsCmd(ctx *Context) *cobra.Command { cmd.Flags().Bool(flagAll, false, "To get all groups") cmd.Flags().String(flagOutput, "", "Specific output filename") - cmd.MarkFlagRequired(flagOutput) + _ = cmd.MarkFlagRequired(flagOutput) return cmd } @@ -187,7 +187,7 @@ func exportDKGsCmd(ctx *Context) *cobra.Command { cmd.Flags().Bool(flagAll, false, "To get all DKGs") cmd.Flags().String(flagOutput, "", "Specific output filename") - cmd.MarkFlagRequired(flagOutput) + _ = cmd.MarkFlagRequired(flagOutput) return cmd } @@ -242,7 +242,7 @@ func exportDEsCmd(ctx *Context) *cobra.Command { cmd.Flags().String(flagOutput, "", "Specific output filename") - cmd.MarkFlagRequired(flagOutput) + _ = cmd.MarkFlagRequired(flagOutput) return cmd } diff --git a/cmd/cylinder/import.go b/cmd/cylinder/import.go index 769096caf..74e89bd49 100644 --- a/cmd/cylinder/import.go +++ b/cmd/cylinder/import.go @@ -144,7 +144,9 @@ func importDEsCmd(ctx *Context) *cobra.Command { // unmarshal json to data var des []store.DE - json.Unmarshal(bytes, &des) + if err := json.Unmarshal(bytes, &des); err != nil { + panic(err) + } // create context c, err := cylinder.NewContext(ctx.config, ctx.keyring, ctx.home) diff --git a/cmd/cylinder/keys.go b/cmd/cylinder/keys.go index 3a58908b2..fd847d9d0 100644 --- a/cmd/cylinder/keys.go +++ b/cmd/cylinder/keys.go @@ -195,6 +195,7 @@ func keysListCmd(ctx *Context) *cobra.Command { context.Background(), &types.QueryIsGranteeRequest{Granter: ctx.config.Granter, Grantee: address.String()}, ) + s := ":question:" if err == nil { if r.IsGrantee { @@ -202,8 +203,8 @@ func keysListCmd(ctx *Context) *cobra.Command { } else { s = ":x:" } - emoji.Printf("%s%s => %s\n", s, key.Name, address.String()) } + emoji.Printf("%s%s => %s\n", s, key.Name, address.String()) } } diff --git a/cmd/cylinder/run.go b/cmd/cylinder/run.go index cb7a688e2..6fbf743d2 100644 --- a/cmd/cylinder/run.go +++ b/cmd/cylinder/run.go @@ -86,20 +86,17 @@ func runCmd(ctx *Context) *cobra.Command { cmd.Flags().BytesHex(flagRandomSecret, nil, "The secret value that is used for random D,E") cmd.Flags().String(flagActivePeriod, "12h", "The time period that cylinder will send active status to chain") - viper.BindPFlag(flags.FlagChainID, cmd.Flags().Lookup(flags.FlagChainID)) - viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode)) - viper.BindPFlag(flagGranter, cmd.Flags().Lookup(flagGranter)) - viper.BindPFlag(flags.FlagGasPrices, cmd.Flags().Lookup(flags.FlagGasPrices)) - viper.BindPFlag(flagLogLevel, cmd.Flags().Lookup(flagLogLevel)) - viper.BindPFlag(flagMaxMessages, cmd.Flags().Lookup(flagMaxMessages)) - viper.BindPFlag(flagBroadcastTimeout, cmd.Flags().Lookup(flagBroadcastTimeout)) - viper.BindPFlag(flagRPCPollInterval, cmd.Flags().Lookup(flagRPCPollInterval)) - viper.BindPFlag(flagMaxTry, cmd.Flags().Lookup(flagMaxTry)) - viper.BindPFlag(flagMinDE, cmd.Flags().Lookup(flagMinDE)) - viper.BindPFlag(flagGasAdjustStart, cmd.Flags().Lookup(flagGasAdjustStart)) - viper.BindPFlag(flagGasAdjustStep, cmd.Flags().Lookup(flagGasAdjustStep)) - viper.BindPFlag(flagRandomSecret, cmd.Flags().Lookup(flagRandomSecret)) - viper.BindPFlag(flagActivePeriod, cmd.Flags().Lookup(flagActivePeriod)) + flagNames := []string{ + flags.FlagChainID, flags.FlagNode, flagGranter, flags.FlagGasPrices, flagLogLevel, + flagMaxMessages, flagBroadcastTimeout, flagRPCPollInterval, flagMaxTry, flagMinDE, + flagGasAdjustStart, flagGasAdjustStep, flagRandomSecret, flagActivePeriod, + } + + for _, flagName := range flagNames { + if err := viper.BindPFlag(flagName, cmd.Flags().Lookup(flagName)); err != nil { + panic(err) + } + } return cmd } diff --git a/cmd/faucet/handler.go b/cmd/faucet/handler.go index 3c5cc57d3..8b21b52c3 100644 --- a/cmd/faucet/handler.go +++ b/cmd/faucet/handler.go @@ -23,9 +23,7 @@ type Response struct { TxHash string `json:"txHash"` } -var ( - cdc, _ = band.MakeCodecs() -) +var cdc, _ = band.MakeCodecs() func handleRequest(gc *gin.Context, c *Context) { key := <-c.keys @@ -110,7 +108,8 @@ func handleRequest(gc *gin.Context, c *Context) { gc.JSON(http.StatusInternalServerError, gin.H{ "error": fmt.Sprintf(":exploding_head: Tx returned nonzero code %d with log %s, tx hash: %s", res.Code, res.RawLog, res.TxHash, - )}) + ), + }) return } gc.JSON(200, Response{ diff --git a/cmd/faucet/run.go b/cmd/faucet/run.go index 5c1ab6e85..4ce1f3d63 100644 --- a/cmd/faucet/run.go +++ b/cmd/faucet/run.go @@ -21,14 +21,14 @@ func runCmd(c *Context) *cobra.Command { Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { if cfg.ChainID == "" { - return errors.New("Chain ID must not be empty") + return errors.New("chain ID must not be empty") } keys, err := keybase.List() if err != nil { return err } if len(keys) == 0 { - return errors.New("No key available") + return errors.New("no key available") } c.keys = make(chan keyring.Record, len(keys)) for _, key := range keys { @@ -85,10 +85,10 @@ func runCmd(c *Context) *cobra.Command { cmd.Flags().String(flags.FlagGasPrices, "", "gas prices for report transaction") cmd.Flags().String(flagPort, "5005", "port of faucet service") cmd.Flags().Int64(flagAmount, 10000000, "amount in uband for each request") - viper.BindPFlag(flags.FlagChainID, cmd.Flags().Lookup(flags.FlagChainID)) - viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode)) - viper.BindPFlag(flags.FlagGasPrices, cmd.Flags().Lookup(flags.FlagGasPrices)) - viper.BindPFlag(flagPort, cmd.Flags().Lookup(flagPort)) - viper.BindPFlag(flagAmount, cmd.Flags().Lookup(flagAmount)) + _ = viper.BindPFlag(flags.FlagChainID, cmd.Flags().Lookup(flags.FlagChainID)) + _ = viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode)) + _ = viper.BindPFlag(flags.FlagGasPrices, cmd.Flags().Lookup(flags.FlagGasPrices)) + _ = viper.BindPFlag(flagPort, cmd.Flags().Lookup(flagPort)) + _ = viper.BindPFlag(flagAmount, cmd.Flags().Lookup(flagAmount)) return cmd } diff --git a/cylinder/client/signing_response.go b/cylinder/client/signing_response.go index aaa8b80fa..c5551e79a 100644 --- a/cylinder/client/signing_response.go +++ b/cylinder/client/signing_response.go @@ -19,7 +19,7 @@ func NewSigningResponse(gr *types.QuerySigningResponse) *SigningResponse { // GetMemberIDs returns all assigned member's id of the assigned members func (sr SigningResponse) GetMemberIDs() []tss.MemberID { - return types.AssignedMembers(sr.Signing.AssignedMembers).MemberIDs() + return sr.Signing.AssignedMembers.MemberIDs() } // GetAssignedMember returns assigned member of the specific address diff --git a/cylinder/context.go b/cylinder/context.go index 9136620e0..82bab1df7 100644 --- a/cylinder/context.go +++ b/cylinder/context.go @@ -3,12 +3,13 @@ package cylinder import ( "path/filepath" - "github.com/bandprotocol/chain/v2/cylinder/store" - "github.com/bandprotocol/chain/v2/pkg/logger" dbm "github.com/cometbft/cometbft-db" "github.com/cometbft/cometbft/libs/log" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/cylinder/store" + "github.com/bandprotocol/chain/v2/pkg/logger" ) // Context holds the context information for the Cylinder process. diff --git a/cylinder/run.go b/cylinder/run.go index 7c452ada9..983c537b3 100644 --- a/cylinder/run.go +++ b/cylinder/run.go @@ -13,7 +13,9 @@ func Run(c *Context, workers Workers) error { // Stop all workers if there was an error for _, worker := range workers { - worker.Stop() + if err := worker.Stop(); err != nil { + return err + } } return err diff --git a/cylinder/worker.go b/cylinder/worker.go index 021020021..5d236cc9f 100644 --- a/cylinder/worker.go +++ b/cylinder/worker.go @@ -6,5 +6,5 @@ type Workers []Worker // Worker defines the interface for a worker that can be started and stopped. type Worker interface { Start() - Stop() + Stop() error } diff --git a/cylinder/workers/de/de.go b/cylinder/workers/de/de.go index 4daccec6a..b8a160f67 100644 --- a/cylinder/workers/de/de.go +++ b/cylinder/workers/de/de.go @@ -170,7 +170,7 @@ func (de *DE) Start() { } // Stop stops the DE worker. -func (de *DE) Stop() { +func (de *DE) Stop() error { de.logger.Info("stop") - de.client.Stop() + return de.client.Stop() } diff --git a/cylinder/workers/group/group.go b/cylinder/workers/group/group.go index f5f5a87eb..389b497c4 100644 --- a/cylinder/workers/group/group.go +++ b/cylinder/workers/group/group.go @@ -49,8 +49,12 @@ func (g *Group) Start() { } // Stop stops the each round's worker. -func (g *Group) Stop() { +func (g *Group) Stop() error { for _, w := range g.workers { - w.Stop() + if err := w.Stop(); err != nil { + return err + } } + + return nil } diff --git a/cylinder/workers/group/round1.go b/cylinder/workers/group/round1.go index 7cb162e39..7ba9ebb3e 100644 --- a/cylinder/workers/group/round1.go +++ b/cylinder/workers/group/round1.go @@ -164,7 +164,7 @@ func (r *Round1) Start() { } // Stop stops the Round1 worker. -func (r *Round1) Stop() { +func (r *Round1) Stop() error { r.logger.Info("stop") - r.client.Stop() + return r.client.Stop() } diff --git a/cylinder/workers/group/round2.go b/cylinder/workers/group/round2.go index 6893f441a..96819a0b2 100644 --- a/cylinder/workers/group/round2.go +++ b/cylinder/workers/group/round2.go @@ -163,7 +163,7 @@ func (r *Round2) Start() { } // Stop stops the Round2 worker. -func (r *Round2) Stop() { +func (r *Round2) Stop() error { r.logger.Info("stop") - r.client.Stop() + return r.client.Stop() } diff --git a/cylinder/workers/group/round3.go b/cylinder/workers/group/round3.go index 94c98a8e4..4b9e37f50 100644 --- a/cylinder/workers/group/round3.go +++ b/cylinder/workers/group/round3.go @@ -183,7 +183,7 @@ func (r *Round3) Start() { } // Stop stops the Round3 worker. -func (r *Round3) Stop() { +func (r *Round3) Stop() error { r.logger.Info("stop") - r.client.Stop() + return r.client.Stop() } diff --git a/cylinder/workers/healthcheck/healthcheck.go b/cylinder/workers/healthcheck/healthcheck.go index a13bfdf6b..ceb90bb98 100644 --- a/cylinder/workers/healthcheck/healthcheck.go +++ b/cylinder/workers/healthcheck/healthcheck.go @@ -73,7 +73,7 @@ func (a *HealthCheck) Start() { } // Stop stops the HealthCheck worker. -func (a *HealthCheck) Stop() { +func (a *HealthCheck) Stop() error { a.logger.Info("stop") - a.client.Stop() + return a.client.Stop() } diff --git a/cylinder/workers/sender/sender.go b/cylinder/workers/sender/sender.go index 50c539a1f..323601f9f 100644 --- a/cylinder/workers/sender/sender.go +++ b/cylinder/workers/sender/sender.go @@ -102,7 +102,7 @@ func (s *Sender) sendMsgs(key *keyring.Record, msgs []sdk.Msg) { } // Stop stops the Sender worker. -func (s *Sender) Stop() { +func (s *Sender) Stop() error { s.logger.Info("stop") - s.client.Stop() + return s.client.Stop() } diff --git a/cylinder/workers/signing/signing.go b/cylinder/workers/signing/signing.go index c1ddf0ab2..bc7d9f6fd 100644 --- a/cylinder/workers/signing/signing.go +++ b/cylinder/workers/signing/signing.go @@ -200,7 +200,7 @@ func (s *Signing) Start() { } // Stop stops the Signing worker. -func (s *Signing) Stop() { +func (s *Signing) Stop() error { s.logger.Info("stop") - s.client.Stop() + return s.client.Stop() } diff --git a/hooks/common/query.go b/hooks/common/query.go index 1757d3e3f..56cb2d29c 100644 --- a/hooks/common/query.go +++ b/hooks/common/query.go @@ -1,12 +1,12 @@ package common import ( + errorsmod "cosmossdk.io/errors" abci "github.com/cometbft/cometbft/abci/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) func QueryResultError(err error) abci.ResponseQuery { - space, code, log := sdkerrors.ABCIInfo(err, true) + space, code, log := errorsmod.ABCIInfo(err, true) return abci.ResponseQuery{ Code: code, Codespace: space, @@ -15,7 +15,7 @@ func QueryResultError(err error) abci.ResponseQuery { } func QueryResultSuccess(value []byte, height int64) abci.ResponseQuery { - space, code, log := sdkerrors.ABCIInfo(nil, true) + space, code, log := errorsmod.ABCIInfo(nil, true) return abci.ResponseQuery{ Code: code, Codespace: space, diff --git a/hooks/emitter/channel.go b/hooks/emitter/channel.go index ac447cf01..e90587bb8 100644 --- a/hooks/emitter/channel.go +++ b/hooks/emitter/channel.go @@ -8,7 +8,6 @@ import ( icatypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/types" ibcxfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" "github.com/bandprotocol/chain/v2/hooks/common" oraclekeeper "github.com/bandprotocol/chain/v2/x/oracle/keeper" @@ -157,7 +156,7 @@ func (h *Hook) extractFungibleTokenPacket( } else { packet["acknowledgement"] = common.JsDict{ "status": "failure", - "reason": evMap[types.EventTypeWriteAck+"."+types.AttributeKeyAck][0], + "reason": evMap[types.EventTypeWriteAck+"."+types.AttributeKeyAckHex][0], } } } else { @@ -250,7 +249,7 @@ func (h *Hook) extractOracleRequestPacket( "execute_gas": data.ExecuteGas, "fee_limit": data.FeeLimit.String(), } - reasons, ok := evMap[channeltypes.EventTypeWriteAck+"."+channeltypes.AttributeKeyAck] + reasons, ok := evMap[types.EventTypeWriteAck+"."+types.AttributeKeyAckHex] if !ok { detail["skip"] = true return false @@ -364,7 +363,7 @@ func (h *Hook) handleMsgRecvPacket( msg.Packet.DestinationChannel, txHash, ) - if _, ok := evMap[channeltypes.EventTypeWriteAck+"."+channeltypes.AttributeKeyData]; ok { + if _, ok := evMap[types.EventTypeWriteAck+"."+types.AttributeKeyDataHex]; ok { if ok := h.extractOracleRequestPacket(ctx, txHash, msg.Signer, msg.Packet.Data, evMap, detail, packet, msg.Packet.DestinationPort, msg.Packet.DestinationChannel); ok { h.Write("NEW_INCOMING_PACKET", packet) return @@ -385,7 +384,7 @@ func (h *Hook) extractOracleResponsePacket( ) bool { var data oracletypes.OracleResponsePacketData err := oracletypes.ModuleCdc.UnmarshalJSON( - []byte(evMap[types.EventTypeSendPacket+"."+types.AttributeKeyData][0]), + []byte(evMap[types.EventTypeSendPacket+"."+types.AttributeKeyDataHex][0]), &data, ) if err == nil { diff --git a/hooks/emitter/client.go b/hooks/emitter/client.go index 73f2d8ee4..e7e386d01 100644 --- a/hooks/emitter/client.go +++ b/hooks/emitter/client.go @@ -3,7 +3,6 @@ package emitter import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" "github.com/cosmos/ibc-go/v7/modules/core/exported" solomachinetypes "github.com/cosmos/ibc-go/v7/modules/light-clients/06-solomachine" ibctmtypes "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint" @@ -29,7 +28,7 @@ func (h *Hook) getChainIdFromClientId(ctx sdk.Context, clientId string) string { func (h *Hook) handleMsgCreatClient(ctx sdk.Context, msg *types.MsgCreateClient, detail common.JsDict) { // h.clientkeeper.GetClientConsensusState(ctx,msg.ClientState) - clientState, _ := clienttypes.UnpackClientState(msg.ClientState) + clientState, _ := types.UnpackClientState(msg.ClientState) chainId := getChainId(clientState) h.Write("SET_COUNTERPARTY_CHAIN", common.JsDict{ "chain_id": chainId, diff --git a/hooks/emitter/decoder.go b/hooks/emitter/decoder.go index dfb7085fd..bf5e79751 100644 --- a/hooks/emitter/decoder.go +++ b/hooks/emitter/decoder.go @@ -457,7 +457,7 @@ func DecodeMsgConnectionOpenInit(msg *connectiontypes.MsgConnectionOpenInit, det func DecodeMsgConnectionOpenTry(msg *connectiontypes.MsgConnectionOpenTry, detail common.JsDict) { clientState, _ := clienttypes.UnpackClientState(msg.ClientState) detail["client_id"] = msg.ClientId - detail["previous_connection_id"] = msg.PreviousConnectionId + detail["previous_connection_id"] = "" detail["client_state"] = clientState detail["counterparty"] = msg.Counterparty detail["delay_period"] = msg.DelayPeriod @@ -499,7 +499,7 @@ func DecodeMsgChannelOpenInit(msg *channeltypes.MsgChannelOpenInit, detail commo func DecodeMsgChannelOpenTry(msg *channeltypes.MsgChannelOpenTry, detail common.JsDict) { detail["port_id"] = msg.PortId - detail["previous_channel_id"] = msg.PreviousChannelId + detail["previous_channel_id"] = "" detail["channel"] = msg.Channel detail["counterparty_version"] = msg.CounterpartyVersion detail["proof_init"] = msg.ProofInit diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index 77b2a1fbd..88222754a 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -208,7 +208,15 @@ func (suite *DecoderTestSuite) TestDecodeReportData() { detail := make(common.JsDict) msg := oracletypes.NewMsgReportData( 1, - []oracletypes.RawReport{{1, 1, []byte("data1")}, {2, 2, []byte("data2")}}, + []oracletypes.RawReport{{ + ExternalID: 1, + ExitCode: 1, + Data: []byte("data1"), + }, { + ExternalID: 2, + ExitCode: 2, + Data: []byte("data2"), + }}, ValAddress, ) emitter.DecodeMsgReportData(msg, detail) @@ -455,6 +463,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgBeginRedelegate() { "{\"amount\":{\"denom\":\"uband\",\"amount\":\"1\"},\"delegator_address\":\"band1g3jkcet8v96x7usqqqqqqqqqqqqqqqqqus6d5g\",\"validator_dst_address\":\"bandvaloper12eskc6tyv96x7usqqqqqqqqqqqqqqqqqw09xqg\",\"validator_src_address\":\"bandvaloper12eskc6tyv96x7usqqqqqqqqqqqqqqqqqw09xqg\"}", ) } + func (suite *DecoderTestSuite) TestDecodeMsgUpdateClient() { detail := make(common.JsDict) msg, _ := clienttypes.NewMsgUpdateClient( diff --git a/hooks/emitter/emitter.go b/hooks/emitter/emitter.go index 0d1e710b1..283050c09 100644 --- a/hooks/emitter/emitter.go +++ b/hooks/emitter/emitter.go @@ -20,8 +20,7 @@ import ( govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -34,7 +33,6 @@ import ( "github.com/bandprotocol/chain/v2/app/params" "github.com/bandprotocol/chain/v2/hooks/common" oraclekeeper "github.com/bandprotocol/chain/v2/x/oracle/keeper" - "github.com/bandprotocol/chain/v2/x/oracle/types" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" tsskeeper "github.com/bandprotocol/chain/v2/x/tss/keeper" ) @@ -62,7 +60,7 @@ type Hook struct { tssKeeper tsskeeper.Keeper icahostKeeper icahostkeeper.Keeper - //ibc keeper + // ibc keeper clientkeeper clientkeeper.Keeper connectionkeeper connectionkeeper.Keeper channelkeeper channelkeeper.Keeper @@ -222,8 +220,8 @@ func (h *Hook) AfterInitChain(ctx sdk.Context, req abci.RequestInitChain, res ab for _, proposal := range govState.Proposals { msgs, _ := proposal.GetMsgs() switch subMsg := msgs[0].(type) { - case *v1.MsgExecLegacyContent: - content := subMsg.Content.GetCachedValue().(v1beta1.Content) + case *govv1.MsgExecLegacyContent: + content := subMsg.Content.GetCachedValue().(govv1beta1.Content) h.Write("NEW_PROPOSAL", common.JsDict{ "id": proposal.Id, "proposer": nil, @@ -284,7 +282,7 @@ func (h *Hook) AfterInitChain(ctx sdk.Context, req abci.RequestInitChain, res ab h.cdc.MustUnmarshalJSON(genesisState[oracletypes.ModuleName], &oracleState) for idx, ds := range oracleState.DataSources { h.Write("NEW_DATA_SOURCE", common.JsDict{ - "id": types.DataSourceID(idx + 1), + "id": oracletypes.DataSourceID(idx + 1), "name": ds.Name, "description": ds.Description, "owner": ds.Owner, @@ -295,7 +293,7 @@ func (h *Hook) AfterInitChain(ctx sdk.Context, req abci.RequestInitChain, res ab }) } for idx, os := range oracleState.OracleScripts { - h.emitSetOracleScript(types.OracleScriptID(idx+1), os, nil) + h.emitSetOracleScript(oracletypes.OracleScriptID(idx+1), os, nil) } var authzState authz.GenesisState @@ -399,7 +397,7 @@ func (h *Hook) AfterDeliverTx(ctx sdk.Context, req abci.RequestDeliverTx, res ab logs, _ := sdk.ParseABCILogs(res.Log) // Error must always be nil if res.IsOK is true. messages := []map[string]interface{}{} for idx, msg := range tx.GetMsgs() { - var detail = make(common.JsDict) + detail := make(common.JsDict) DecodeMsg(msg, detail) if res.IsOK() { h.handleMsg(ctx, txHash, msg, logs[idx], detail) @@ -443,18 +441,23 @@ func (h *Hook) AfterEndBlock(ctx sdk.Context, req abci.RequestEndBlock, res abci Value: common.JsDict{ "address": acc, "balance": h.bankKeeper.GetAllBalances(ctx, acc).String(), - }}) + }, + }) } h.msgs = append(modifiedMsgs, h.msgs[1:]...) h.Write("COMMIT", common.JsDict{"height": req.Height}) } -func (h *Hook) RequestSearch(req *types.QueryRequestSearchRequest) (*types.QueryRequestSearchResponse, bool, error) { +func (h *Hook) RequestSearch( + req *oracletypes.QueryRequestSearchRequest, +) (*oracletypes.QueryRequestSearchResponse, bool, error) { return nil, false, nil } -func (h *Hook) RequestPrice(req *types.QueryRequestPriceRequest) (*types.QueryRequestPriceResponse, bool, error) { +func (h *Hook) RequestPrice( + req *oracletypes.QueryRequestPriceRequest, +) (*oracletypes.QueryRequestPriceResponse, bool, error) { return nil, false, nil } diff --git a/hooks/emitter/gov.go b/hooks/emitter/gov.go index 520f14ead..4e64926d7 100644 --- a/hooks/emitter/gov.go +++ b/hooks/emitter/gov.go @@ -81,17 +81,17 @@ func (h *Hook) emitV1beta1SetVoteWeighted(setVoteWeighted common.JsDict, options } // handleMsgSubmitProposal implements emitter handler for MsgSubmitProposal. -func (app *Hook) handleMsgSubmitProposal( +func (h *Hook) handleMsgSubmitProposal( ctx sdk.Context, txHash []byte, msg *v1.MsgSubmitProposal, evMap common.EvMap, detail common.JsDict, ) { proposalId := uint64(common.Atoi(evMap[types.EventTypeSubmitProposal+"."+types.AttributeKeyProposalID][0])) - proposal, _ := app.govKeeper.GetProposal(ctx, proposalId) + proposal, _ := h.govKeeper.GetProposal(ctx, proposalId) subMsg := proposal.Messages[0].GetCachedValue() switch subMsg := subMsg.(type) { case *v1.MsgExecLegacyContent: content := subMsg.Content.GetCachedValue().(v1beta1.Content) - app.Write("NEW_PROPOSAL", common.JsDict{ + h.Write("NEW_PROPOSAL", common.JsDict{ "id": proposalId, "proposer": msg.Proposer, "type": content.ProposalType(), @@ -107,7 +107,7 @@ func (app *Hook) handleMsgSubmitProposal( "content": content, }) case sdk.Msg: - app.Write("NEW_PROPOSAL", common.JsDict{ + h.Write("NEW_PROPOSAL", common.JsDict{ "id": proposalId, "proposer": msg.Proposer, "type": sdk.MsgTypeURL(subMsg), @@ -127,19 +127,19 @@ func (app *Hook) handleMsgSubmitProposal( } proposer, _ := sdk.AccAddressFromBech32(msg.Proposer) - app.emitSetDeposit(ctx, txHash, proposalId, proposer) + h.emitSetDeposit(ctx, txHash, proposalId, proposer) detail["proposal_id"] = proposalId } // handleV1beta1MsgSubmitProposal implements emitter handler for MsgSubmitProposal v1beta1. -func (app *Hook) handleV1beta1MsgSubmitProposal( +func (h *Hook) handleV1beta1MsgSubmitProposal( ctx sdk.Context, txHash []byte, msg *v1beta1.MsgSubmitProposal, evMap common.EvMap, detail common.JsDict, ) { proposalId := uint64(common.Atoi(evMap[types.EventTypeSubmitProposal+"."+types.AttributeKeyProposalID][0])) - proposal, _ := app.govKeeper.GetProposal(ctx, proposalId) + proposal, _ := h.govKeeper.GetProposal(ctx, proposalId) content := msg.GetContent() - app.Write("NEW_PROPOSAL", common.JsDict{ + h.Write("NEW_PROPOSAL", common.JsDict{ "id": proposalId, "proposer": msg.Proposer, "type": content.ProposalType(), @@ -155,7 +155,7 @@ func (app *Hook) handleV1beta1MsgSubmitProposal( "content": content, }) proposer, _ := sdk.AccAddressFromBech32(msg.Proposer) - app.emitSetDeposit(ctx, txHash, proposalId, proposer) + h.emitSetDeposit(ctx, txHash, proposalId, proposer) detail["proposal_id"] = proposalId } diff --git a/hooks/emitter/oracle.go b/hooks/emitter/oracle.go index 0543cd352..8243c7bf1 100644 --- a/hooks/emitter/oracle.go +++ b/hooks/emitter/oracle.go @@ -82,21 +82,21 @@ func (h *Hook) emitRawRequestAndValRequest( } } -func (app *Hook) emitReportAndRawReport( +func (h *Hook) emitReportAndRawReport( txHash []byte, rid types.RequestID, validator sdk.ValAddress, reporter sdk.AccAddress, rawReports []types.RawReport, ) { - app.Write("NEW_REPORT", common.JsDict{ + h.Write("NEW_REPORT", common.JsDict{ "tx_hash": txHash, "request_id": rid, "validator": validator.String(), "reporter": reporter.String(), }) for _, data := range rawReports { - app.Write("NEW_RAW_REPORT", common.JsDict{ + h.Write("NEW_RAW_REPORT", common.JsDict{ "request_id": rid, "validator": validator.String(), "external_id": data.ExternalID, diff --git a/hooks/emitter/transfer.go b/hooks/emitter/transfer.go index 883f2585b..e314d680f 100644 --- a/hooks/emitter/transfer.go +++ b/hooks/emitter/transfer.go @@ -16,7 +16,7 @@ func (h *Hook) handleMsgTransfer( evMap common.EvMap, detail common.JsDict, ) { - if events, ok := evMap[channeltypes.EventTypeSendPacket+"."+channeltypes.AttributeKeyData]; ok { + if events, ok := evMap[channeltypes.EventTypeSendPacket+"."+channeltypes.AttributeKeyDataHex]; ok { packet := newPacket( ctx, evMap[channeltypes.EventTypeSendPacket+"."+channeltypes.AttributeKeySrcPort][0], diff --git a/hooks/price/price.go b/hooks/price/price.go index 9ad20ea57..529d5ea47 100644 --- a/hooks/price/price.go +++ b/hooks/price/price.go @@ -116,15 +116,14 @@ func (h *Hook) RequestPrice(req *types.QueryRequestPriceRequest) (*types.QueryRe bz, err := h.db.Get([]byte(fmt.Sprintf("%d,%d,%s", req.AskCount, req.MinCount, symbol)), nil) if err != nil { if errors.Is(err, leveldb.ErrNotFound) { - return nil, true, sdkerrors.Wrapf( - sdkerrors.ErrKeyNotFound, + return nil, true, sdkerrors.ErrKeyNotFound.Wrapf( "price not found for %s with %d/%d counts", symbol, req.AskCount, req.MinCount, ) } - return nil, true, sdkerrors.Wrapf(sdkerrors.ErrLogic, + return nil, true, sdkerrors.ErrLogic.Wrapf( "unable to get price of %s with %d/%d counts", symbol, req.AskCount, diff --git a/hooks/request/request.go b/hooks/request/request.go index 2f1beb05b..7862710ab 100644 --- a/hooks/request/request.go +++ b/hooks/request/request.go @@ -5,17 +5,14 @@ import ( "errors" "strings" + abci "github.com/cometbft/cometbft/abci/types" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "gorm.io/gorm" - - // DB driver _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3" - - abci "github.com/cometbft/cometbft/abci/types" + "gorm.io/gorm" "github.com/bandprotocol/chain/v2/hooks/common" "github.com/bandprotocol/chain/v2/x/oracle/keeper" @@ -136,7 +133,7 @@ func (h *Hook) AfterEndBlock(ctx sdk.Context, req abci.RequestEndBlock, res abci func (h *Hook) RequestSearch(req *types.QueryRequestSearchRequest) (*types.QueryRequestSearchResponse, bool, error) { calldata, err := hex.DecodeString(req.Calldata) if err != nil { - return nil, true, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "unable to parse calldata: %s", err) + return nil, true, sdkerrors.ErrInvalidRequest.Wrapf("unable to parse calldata: %s", err) } // Query oracle requests from database @@ -146,13 +143,12 @@ func (h *Hook) RequestSearch(req *types.QueryRequestSearchRequest) (*types.Query req.AskCount, req.MinCount, ) - // check query results if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return nil, true, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, "request not found") + return nil, true, sdkerrors.ErrKeyNotFound.Wrap("request not found") } - return nil, true, sdkerrors.Wrap(sdkerrors.ErrLogic, "unable to query latest request from database") + return nil, true, sdkerrors.ErrLogic.Wrap("unable to query latest request from database") } queryResponse := oracleReq.QueryRequestResponse() diff --git a/hooks/request/types.go b/hooks/request/types.go index 4251f7a68..59dda3cdf 100644 --- a/hooks/request/types.go +++ b/hooks/request/types.go @@ -147,7 +147,7 @@ func NewRequest( AskCount: askCount, AnsCount: ansCount, RequestHeight: requestHeight, - RequestTime: time.Unix(int64(requestTimeUnix), 0), + RequestTime: time.Unix(requestTimeUnix, 0), ClientID: clientID, RawRequests: rawRequests, Reports: reports, diff --git a/pkg/bandrng/sampling.go b/pkg/bandrng/sampling.go index 81cf46adf..f2813bdf6 100644 --- a/pkg/bandrng/sampling.go +++ b/pkg/bandrng/sampling.go @@ -55,8 +55,8 @@ func ChooseSome(rng *Rng, weights []uint64, cnt int) []int { // ChooseSomeMaxWeight performs ChooseSome "tries" times and returns the sampling with the // highest weight sum among all tries. func ChooseSomeMaxWeight(rng *Rng, weights []uint64, cnt int, tries int) []int { - var maxWeightSum uint64 = 0 - var maxWeightResult []int = nil + var maxWeightSum uint64 + var maxWeightResult []int for each := 0; each < tries; each++ { candidate := ChooseSome(rng, weights, cnt) candidateWeightSum := uint64(0) diff --git a/pkg/filecache/filecache.go b/pkg/filecache/filecache.go index 5bee07abb..5772a0827 100644 --- a/pkg/filecache/filecache.go +++ b/pkg/filecache/filecache.go @@ -32,7 +32,7 @@ func GetFilename(data []byte) string { func (c Cache) AddFile(data []byte) string { filename := GetFilename(data) if !c.fileCache.Has(filename) { - c.fileCache.Write(filename, data) + _ = c.fileCache.Write(filename, data) } return filename } diff --git a/pkg/filecache/filecache_test.go b/pkg/filecache/filecache_test.go index 779f6d328..8b2ba8f79 100644 --- a/pkg/filecache/filecache_test.go +++ b/pkg/filecache/filecache_test.go @@ -125,7 +125,7 @@ func TestMustGetFileGoodContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd55" // Correct filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0666) + err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0o600) require.NoError(t, err) content := f.MustGetFile(filename) @@ -147,7 +147,7 @@ func TestGetFileGoodContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd55" // Correct filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0666) + err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0o600) require.NoError(t, err) content, err := f.GetFile(filename) @@ -170,7 +170,7 @@ func TestMustGetFileBadContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd56" // Not correct filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0666) + err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0o600) require.NoError(t, err) require.Panics(t, func() { @@ -193,7 +193,7 @@ func TesGetFileBadContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd56" // Not correct filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0666) + err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0o600) require.NoError(t, err) _, err = f.GetFile(filename) @@ -215,7 +215,7 @@ func TestMustGetFileInconsistentContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd55" filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("INCONSISTENT"), 0666) // Not consistent with name + err = os.WriteFile(filepath, []byte("INCONSISTENT"), 0o600) // Not consistent with name require.NoError(t, err) require.Panics(t, func() { _ = f.MustGetFile(filename) @@ -237,7 +237,7 @@ func TestGetFileInconsistentContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd55" filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("INCONSISTENT"), 0666) // Not consistent with name + err = os.WriteFile(filepath, []byte("INCONSISTENT"), 0o600) // Not consistent with name require.NoError(t, err) _, err = f.GetFile(filename) require.Error(t, err) diff --git a/pkg/gzip/gzip_test.go b/pkg/gzip/gzip_test.go index c7890a37d..da721d3ac 100644 --- a/pkg/gzip/gzip_test.go +++ b/pkg/gzip/gzip_test.go @@ -14,7 +14,8 @@ func TestUncompress(t *testing.T) { file1 := []byte("file") var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(file1) + _, err := zw.Write(file1) + require.NoError(t, err) zw.Close() gzipFile := buf.Bytes() @@ -73,7 +74,8 @@ func TestIsGzip(t *testing.T) { file1 := []byte("file") var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(file1) + _, err := zw.Write(file1) + require.NoError(t, err) zw.Close() gzipFile := buf.Bytes() require.True(t, gzip.IsGzipped(gzipFile)) diff --git a/pkg/obi/decode.go b/pkg/obi/decode.go index 65880d251..f0753b1e2 100644 --- a/pkg/obi/decode.go +++ b/pkg/obi/decode.go @@ -28,7 +28,7 @@ func decodeImpl(data []byte, v interface{}) ([]byte, error) { return rem, err case reflect.Uint64: val, rem, err := DecodeUnsigned64(data) - ev.SetUint(uint64(val)) + ev.SetUint(val) return rem, err case reflect.Int8: val, rem, err := DecodeSigned8(data) @@ -44,7 +44,7 @@ func decodeImpl(data []byte, v interface{}) ([]byte, error) { return rem, err case reflect.Int64: val, rem, err := DecodeSigned64(data) - ev.SetInt(int64(val)) + ev.SetInt(val) return rem, err case reflect.String: val, rem, err := DecodeString(data) diff --git a/pkg/obi/encode.go b/pkg/obi/encode.go index 88eaaa1d3..c976aba45 100644 --- a/pkg/obi/encode.go +++ b/pkg/obi/encode.go @@ -17,7 +17,7 @@ func encodeImpl(v interface{}) ([]byte, error) { case reflect.Uint32: return EncodeUnsigned32(uint32(rv.Uint())), nil case reflect.Uint64: - return EncodeUnsigned64(uint64(rv.Uint())), nil + return EncodeUnsigned64(rv.Uint()), nil case reflect.Int8: return EncodeSigned8(int8(rv.Int())), nil case reflect.Int16: @@ -25,7 +25,7 @@ func encodeImpl(v interface{}) ([]byte, error) { case reflect.Int32: return EncodeSigned32(int32(rv.Int())), nil case reflect.Int64: - return EncodeSigned64(int64(rv.Int())), nil + return EncodeSigned64(rv.Int()), nil case reflect.String: return EncodeString(rv.String()), nil case reflect.Slice: diff --git a/pkg/obi/encode_test.go b/pkg/obi/encode_test.go index f502d8ef5..2cbee77a3 100644 --- a/pkg/obi/encode_test.go +++ b/pkg/obi/encode_test.go @@ -40,6 +40,7 @@ func TestEncodeBytes(t *testing.T) { Arr: []int16{10, 11}, }), []byte{0x0, 0x0, 0x0, 0x3, 0x42, 0x54, 0x43, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x23, 0x28, 0x1, 0x2, 0x0, 0x0, 0x0, 0x2, 0x0, 0xa, 0x0, 0xb}) } + func TestEncodeBytesMulti(t *testing.T) { require.Equal(t, MustEncode(SimpleData{X: 1, Y: 2}, ExampleData{ Symbol: "BTC", @@ -190,7 +191,7 @@ func TestEncodeString(t *testing.T) { 0x6f, 0x62, } - require.Equal(t, []byte(expectedEncodeBytes), MustEncode(testString)) + require.Equal(t, expectedEncodeBytes, MustEncode(testString)) } func TestEncodeSlice(t *testing.T) { diff --git a/pkg/obi/schema_test.go b/pkg/obi/schema_test.go index 7ba68b5e9..f7d7d5850 100644 --- a/pkg/obi/schema_test.go +++ b/pkg/obi/schema_test.go @@ -9,7 +9,7 @@ import ( type EmptySchema struct{} type NoOBITagStruct struct { - NoOBITag string `"noOBItag"` //missing obi + NoOBITag string `"noOBItag"` //nolint:govet // missing obi } type NotSupportedStruct struct { @@ -28,14 +28,16 @@ type AllData struct { NumInt64 int64 `obi:"numInt64"` } -type Uint8ID uint8 -type Uint16ID uint16 -type Uint32ID uint32 -type Uint64ID uint64 -type Int8ID int8 -type Int16ID int16 -type Int32ID int32 -type Int64ID int64 +type ( + Uint8ID uint8 + Uint16ID uint16 + Uint32ID uint32 + Uint64ID uint64 + Int8ID int8 + Int16ID int16 + Int32ID int32 + Int64ID int64 +) type AllDataAlias struct { NumUint8 Uint8ID `obi:"numUint8"` diff --git a/pkg/tss/elgamal_bench_test.go b/pkg/tss/elgamal_bench_test.go index 63bf88994..a1b4f4055 100644 --- a/pkg/tss/elgamal_bench_test.go +++ b/pkg/tss/elgamal_bench_test.go @@ -1,7 +1,7 @@ package tss_test import ( - "math/rand" + "crypto/rand" "testing" "github.com/bandprotocol/chain/v2/pkg/tss" @@ -15,7 +15,9 @@ func BenchmarkEncrypt(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - tss.Encrypt(value, key, rng) + if _, err := tss.Encrypt(value, key, rng); err != nil { + b.Fatal(err) + } } } @@ -28,7 +30,9 @@ func BenchmarkDecrypt(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - tss.Decrypt(enc, key) + if _, err := tss.Decrypt(enc, key); err != nil { + b.Fatal(err) + } } } @@ -58,9 +62,10 @@ func BenchmarkHash(b *testing.B) { for _, test := range tests { b.Run(test.name, func(b *testing.B) { - rand.Seed(0) bytes := make([]byte, test.numOfBytes) - rand.Read(bytes) + if _, err := rand.Read(bytes); err != nil { + b.Fatal(err) + } b.ResetTimer() diff --git a/pkg/tss/hash.go b/pkg/tss/hash.go index ad82fde2f..a216b2098 100644 --- a/pkg/tss/hash.go +++ b/pkg/tss/hash.go @@ -147,15 +147,13 @@ func HashChallenge(rawGroupPubNonce, rawGroupPubKey Point, data []byte) (Scalar, return nil, NewError(err, "parse group pubic key") } - parity := uint8(rawGroupPubKey[0]) - scalar, err := NewScalar(Hash( []byte(ContextString), []byte{0}, []byte("challenge"), []byte{0}, rAddress, - []byte{parity + 25}, + []byte{rawGroupPubKey[0] + 25}, groupPubKey.X().Bytes(), Hash(data), )) diff --git a/pkg/tss/hash_paper.go b/pkg/tss/hash_paper.go index 52526f7a2..4575b96b1 100644 --- a/pkg/tss/hash_paper.go +++ b/pkg/tss/hash_paper.go @@ -81,7 +81,7 @@ func strxor(str1, str2 []byte) ([]byte, error) { // provided H meets the requirements above. // // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#name-expand_message_xmd -func ExpandMessageXMD(H func(data ...[]byte) []byte, msg []byte, DST []byte, len_in_bytes int) ([]byte, error) { +func ExpandMessageXMD(h func(data ...[]byte) []byte, msg []byte, dst []byte, len_in_bytes int) ([]byte, error) { // b_in_bytes, b / 8 for b the output size of H in bits. For example, for b = 256, b_in_bytes = 32 b_in_bytes := 32 // s_in_bytes, the input block size of H, measured in bytes. For example, for SHA-256, s_in_bytes = 64 @@ -91,16 +91,16 @@ func ExpandMessageXMD(H func(data ...[]byte) []byte, msg []byte, DST []byte, len ell := (len_in_bytes + b_in_bytes - 1) / b_in_bytes // 2. ABORT if ell > 255 or len_in_bytes > 65535 or len(DST) > 255 - if ell > 255 || len_in_bytes > 65535 || len(DST) > 255 { + if ell > 255 || len_in_bytes > 65535 || len(dst) > 255 { return nil, errors.New("ExpandMessageXMD: input is not within the permissible limits") } // 3. DST_prime = DST || I2OSP(len(DST), 1) - dstPrime, err := I2OSP(len(DST), 1) + dstPrime, err := I2OSP(len(dst), 1) if err != nil { return nil, err } - dstPrime = append(DST, dstPrime...) + dstPrime = append(dst, dstPrime...) // 4. Z_pad = I2OSP(0, s_in_bytes) zPad, err := I2OSP(0, s_in_bytes) @@ -119,10 +119,10 @@ func ExpandMessageXMD(H func(data ...[]byte) []byte, msg []byte, DST []byte, len msgPrime := append(append(append(zPad, msg...), liBStr...), append([]byte{0}, dstPrime...)...) // 7. b_0 = H(msg_prime) - b0 := H(msgPrime) + b0 := h(msgPrime) // 8. b_1 = H(b_0 || I2OSP(1, 1) || DST_prime) // I2OSP(1, 1) -> []byte{1} - b := H(append(b0, append([]byte{1}, dstPrime...)...)) + b := h(append(b0, append([]byte{1}, dstPrime...)...)) if len(b) < b_in_bytes { return nil, errors.New("ExpandMessageXMD: the initial len of b must be >= b_in_bytes") @@ -136,7 +136,7 @@ func ExpandMessageXMD(H func(data ...[]byte) []byte, msg []byte, DST []byte, len return nil, err } // I2OSP(i, 1) -> []byte{i} ; i ∈ {1,2,3,...,255} - bi := H(append(b0_xor_bi_1, append([]byte{uint8(i)}, dstPrime...)...)) + bi := h(append(b0_xor_bi_1, append([]byte{uint8(i)}, dstPrime...)...)) // 11. uniform_bytes = b_1 || ... || b_ell b = append(b, bi...) @@ -173,11 +173,11 @@ func HashToField( count int, p *big.Int, m int, - L int, + l int, expand func([]byte, int) ([]byte, error), ) ([][]*big.Int, error) { - // 1. len_in_bytes = count * m * L - lenInBytes := count * m * L + // 1. len_in_bytes = count * m * l + lenInBytes := count * m * l // 2. uniform_bytes = expand_message(msg, DST, len_in_bytes) uniformBytes, err := expand(msg, lenInBytes) if err != nil { @@ -189,10 +189,10 @@ func HashToField( eVals := make([]*big.Int, m) // 4. for j in (0, ..., m - 1): for j := 0; j < m; j++ { - // 5. elm_offset = L * (j + i * m) - elmOffset := L * (j + i*m) - // 6. tv = substr(uniform_bytes, elm_offset, L) - tv := uniformBytes[elmOffset : elmOffset+L] + // 5. elm_offset = l * (j + i * m) + elmOffset := l * (j + i*m) + // 6. tv = substr(uniform_bytes, elm_offset, l) + tv := uniformBytes[elmOffset : elmOffset+l] tvInt := OS2IP(tv) // 7. e_j = OS2IP(tv) mod p eVals[j] = tvInt.Mod(tvInt, p) @@ -223,7 +223,7 @@ func HashToField( // - A slice of field elements, each represented as a *big.Int. // - An error if the HashToField function returns an error. func H_M1_L48( - H func(data ...[]byte) []byte, + h func(data ...[]byte) []byte, count int, p *big.Int, msg []byte, @@ -231,7 +231,7 @@ func H_M1_L48( ) ([][]*big.Int, error) { expand := func(message []byte, lenInBytes int) ([]byte, error) { DST := []byte(contextString) - return ExpandMessageXMD(H, message, DST, lenInBytes) + return ExpandMessageXMD(h, message, DST, lenInBytes) } // m = 1, L = 48 fieldElements, err := HashToField(msg, count, p, 1, 48, expand) diff --git a/pkg/tss/hash_paper_test.go b/pkg/tss/hash_paper_test.go index 571445ee6..c8cca265e 100644 --- a/pkg/tss/hash_paper_test.go +++ b/pkg/tss/hash_paper_test.go @@ -4,8 +4,9 @@ import ( "crypto/sha256" "fmt" - "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/ethereum/go-ethereum/crypto" + + "github.com/bandprotocol/chain/v2/pkg/tss" ) func (suite *TSSTestSuite) TestI2OSP() { diff --git a/pkg/tss/internal/lagrange/lagrange.go b/pkg/tss/internal/lagrange/lagrange.go index 55d80a20b..d11e2911b 100644 --- a/pkg/tss/internal/lagrange/lagrange.go +++ b/pkg/tss/internal/lagrange/lagrange.go @@ -62,9 +62,9 @@ func ComputeCoefficient(i int64, s []int64) *big.Int { } // 𝚷(j) - numerator.Mul(big.NewInt(int64(j)), numerator) + numerator.Mul(big.NewInt(j), numerator) // 𝚷(j-i) - denominator.Mul(big.NewInt(int64(j-i)), denominator) + denominator.Mul(big.NewInt(j-i), denominator) } // Multiply the numerator by the modular inverse of the denominator. diff --git a/pkg/tss/internal/lagrange/lagrange_test.go b/pkg/tss/internal/lagrange/lagrange_test.go index a9d2dfd5f..52e98b20b 100644 --- a/pkg/tss/internal/lagrange/lagrange_test.go +++ b/pkg/tss/internal/lagrange/lagrange_test.go @@ -4,8 +4,9 @@ import ( "math/big" "testing" - "github.com/bandprotocol/chain/v2/pkg/tss/internal/lagrange" "github.com/stretchr/testify/assert" + + "github.com/bandprotocol/chain/v2/pkg/tss/internal/lagrange" ) func TestComputeCoefficient(t *testing.T) { diff --git a/pkg/tss/internal/schnorr/signature.go b/pkg/tss/internal/schnorr/signature.go index 41ed22aec..4017d9bb0 100644 --- a/pkg/tss/internal/schnorr/signature.go +++ b/pkg/tss/internal/schnorr/signature.go @@ -16,20 +16,18 @@ const ( SignatureSize = 65 ) -var ( - // rfc6979ExtraDataV0 is the extra data to feed to RFC6979 when generating - // the deterministic nonce for the EC-Schnorr-DCRv0 scheme. This ensures - // the same nonce is not generated for the same message and key as for other - // signing algorithms such as ECDSA. - // - // It is equal to BLAKE-256([]byte("EC-Schnorr-DCRv0")). - RFC6979ExtraDataV0 = [32]byte{ - 0x0b, 0x75, 0xf9, 0x7b, 0x60, 0xe8, 0xa5, 0x76, - 0x28, 0x76, 0xc0, 0x04, 0x82, 0x9e, 0xe9, 0xb9, - 0x26, 0xfa, 0x6f, 0x0d, 0x2e, 0xea, 0xec, 0x3a, - 0x4f, 0xd1, 0x44, 0x6a, 0x76, 0x83, 0x31, 0xcb, - } -) +// RFC6979ExtraDataV0 is the extra data to feed to RFC6979 when generating +// the deterministic nonce for the EC-Schnorr-DCRv0 scheme. This ensures +// the same nonce is not generated for the same message and key as for other +// signing algorithms such as ECDSA. +// +// It is equal to BLAKE-256([]byte("EC-Schnorr-DCRv0")). +var RFC6979ExtraDataV0 = [32]byte{ + 0x0b, 0x75, 0xf9, 0x7b, 0x60, 0xe8, 0xa5, 0x76, + 0x28, 0x76, 0xc0, 0x04, 0x82, 0x9e, 0xe9, 0xb9, + 0x26, 0xfa, 0x6f, 0x0d, 0x2e, 0xea, 0xec, 0x3a, + 0x4f, 0xd1, 0x44, 0x6a, 0x76, 0x83, 0x31, 0xcb, +} // Signature is a type representing a Schnorr signature. type Signature struct { diff --git a/pkg/tss/operation_bench_test.go b/pkg/tss/operation_bench_test.go index 256c05a95..c2ea5963b 100644 --- a/pkg/tss/operation_bench_test.go +++ b/pkg/tss/operation_bench_test.go @@ -1,7 +1,7 @@ package tss_test import ( - "math/rand" + "crypto/rand" "testing" "github.com/bandprotocol/chain/v2/pkg/tss" @@ -40,12 +40,12 @@ func BenchmarkSumScalars(b *testing.B) { for _, test := range tests { b.Run(test.name, func(b *testing.B) { - rand.Seed(0) - var scalars tss.Scalars for i := 0; i < test.numOfScalars; i++ { scalar := make([]byte, 32) - rand.Read(scalar) + if _, err := rand.Read(scalar); err != nil { + b.Fatal(err) + } scalars = append(scalars, scalar) } @@ -91,8 +91,6 @@ func BenchmarkSumPoints(b *testing.B) { for _, test := range tests { b.Run(test.name, func(b *testing.B) { - rand.Seed(0) - var points tss.Points for i := 0; i < test.numOfPoints; i++ { _, point, _ := tss.GenerateDKGNonce() @@ -102,7 +100,7 @@ func BenchmarkSumPoints(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - tss.SumPoints(points...) + _, _ = tss.SumPoints(points...) } }) } @@ -141,14 +139,17 @@ func BenchmarkSolveScalarPolynomial(b *testing.B) { for _, test := range tests { b.Run(test.name, func(b *testing.B) { - rand.Seed(0) x := make([]byte, 32) - rand.Read(x) + if _, err := rand.Read(x); err != nil { + b.Fatal(err) + } var coeffs tss.Scalars for i := 0; i < test.numOfCoefficients; i++ { coeff := make([]byte, 32) - rand.Read(coeff) + if _, err := rand.Read(coeff); err != nil { + b.Fatal(err) + } coeffs = append(coeffs, coeff) } @@ -194,9 +195,10 @@ func BenchmarkSolvePointPolynomial(b *testing.B) { for _, test := range tests { b.Run(test.name, func(b *testing.B) { - rand.Seed(0) x := make([]byte, 32) - rand.Read(x) + if _, err := rand.Read(x); err != nil { + b.Fatal(err) + } var coeffs tss.Points for i := 0; i < test.numOfCoefficients; i++ { @@ -207,7 +209,9 @@ func BenchmarkSolvePointPolynomial(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - tss.SolvePointPolynomial(coeffs, x) + if _, err := tss.SolvePointPolynomial(coeffs, x); err != nil { + b.Fatal(err) + } } }) } diff --git a/pkg/tss/operation_test.go b/pkg/tss/operation_test.go index 5e91425ee..34d5e4afd 100644 --- a/pkg/tss/operation_test.go +++ b/pkg/tss/operation_test.go @@ -227,7 +227,8 @@ func (suite *TSSTestSuite) TestSolvePointPolynomial() { testutil.HexDecode("000000000000000000000000000000000000000000000000000000000000000a"), testutil.HexDecode("0202f33c93bad4c720b2ac925e90273bd0bcc3cba7855839265cd6b2722512a5ab"), nil, - }} + }, + } for _, t := range tests { suite.Run(t.name, func() { result, err := tss.SolvePointPolynomial(t.coefficients, t.x) diff --git a/pkg/tss/round1.go b/pkg/tss/round1.go index cb446f23e..1f26df958 100644 --- a/pkg/tss/round1.go +++ b/pkg/tss/round1.go @@ -44,8 +44,8 @@ func GenerateRound1Info( var coefficientCommits Points var coefficients Scalars for i := 1; i < len(kps); i++ { - coefficientCommits = append(coefficientCommits, Point(kps[i].PubKey)) - coefficients = append(coefficients, Scalar(kps[i].PrivKey)) + coefficientCommits = append(coefficientCommits, kps[i].PubKey) + coefficients = append(coefficients, kps[i].PrivKey) } return &Round1Info{ diff --git a/pkg/tss/round3.go b/pkg/tss/round3.go index 8d254e2e5..9f698393f 100644 --- a/pkg/tss/round3.go +++ b/pkg/tss/round3.go @@ -183,7 +183,7 @@ func SignComplaint( return nil, nil, NewError(err, "compute nonce sym") } - challenge, err = HashRound3Complain(pubNonce, Point(nonceSym), oneTimePubI, oneTimePubJ, keySym) + challenge, err = HashRound3Complain(pubNonce, nonceSym, oneTimePubI, oneTimePubJ, keySym) if err == nil { break } @@ -253,5 +253,5 @@ func VerifyComplaintSignature( return NewError(err, "verify") } - return Verify(complaintSignature.A2(), complaintSignature.Z(), challenge, keySym, Point(oneTimePubJ), nil) + return Verify(complaintSignature.A2(), complaintSignature.Z(), challenge, keySym, oneTimePubJ, nil) } diff --git a/pkg/tss/round3_test.go b/pkg/tss/round3_test.go index 56ac41ba7..a51747c81 100644 --- a/pkg/tss/round3_test.go +++ b/pkg/tss/round3_test.go @@ -71,7 +71,7 @@ func (suite *TSSTestSuite) TestComputeSecretShareCommit() { suite.Require().NoError(err) expSecretCommit := memberI.SecretShares[testutil.GetSlot(memberI.ID, memberJ.ID)].Point() - suite.Require().Equal(tss.Point(expSecretCommit), secretCommit) + suite.Require().Equal(expSecretCommit, secretCommit) }, ) } diff --git a/pkg/tss/schnorr.go b/pkg/tss/schnorr.go index f6d5d12d4..ed061631b 100644 --- a/pkg/tss/schnorr.go +++ b/pkg/tss/schnorr.go @@ -1,8 +1,9 @@ package tss import ( - "github.com/bandprotocol/chain/v2/pkg/tss/internal/schnorr" "github.com/decred/dcrd/dcrec/secp256k1/v4" + + "github.com/bandprotocol/chain/v2/pkg/tss/internal/schnorr" ) // Sign generates a schnorr signature for the given private key, challenge, and nonce. diff --git a/pkg/tss/schnorr_bench_test.go b/pkg/tss/schnorr_bench_test.go index 2b56c2c3b..95a2b2714 100644 --- a/pkg/tss/schnorr_bench_test.go +++ b/pkg/tss/schnorr_bench_test.go @@ -14,7 +14,9 @@ func BenchmarkSign(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - tss.Sign(suite.privKey, suite.challenge, suite.nonce, nil) + if _, err := tss.Sign(suite.privKey, suite.challenge, suite.nonce, nil); err != nil { + b.Fatal(err) + } } } @@ -29,7 +31,9 @@ func BenchmarkVerify(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - tss.Verify(signatureR, signatureS, suite.challenge, suite.pubKey, nil, nil) + if err := tss.Verify(signatureR, signatureS, suite.challenge, suite.pubKey, nil, nil); err != nil { + b.Fatal(err) + } } } @@ -47,7 +51,9 @@ func BenchmarkVerifyWithCustomGenerator(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - tss.Verify(tss.Point(nonceSym), signatureS, suite.challenge, keySym, tss.Point(generator), nil) + if err := tss.Verify(nonceSym, signatureS, suite.challenge, keySym, generator, nil); err != nil { + b.Fatal(err) + } } } @@ -63,6 +69,8 @@ func BenchmarkVerifyWithCustomLagrange(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - tss.Verify(signatureR, signatureS, suite.challenge, suite.pubKey, nil, lagrange) + if err := tss.Verify(signatureR, signatureS, suite.challenge, suite.pubKey, nil, lagrange); err != nil { + b.Fatal(err) + } } } diff --git a/pkg/tss/schnorr_test.go b/pkg/tss/schnorr_test.go index b40630d64..6487bf3f5 100644 --- a/pkg/tss/schnorr_test.go +++ b/pkg/tss/schnorr_test.go @@ -39,7 +39,7 @@ func (suite *TSSTestSuite) TestSignAndVerifyWithCustomGenerator() { func(tc testutil.TestCase, memberI testutil.Member, memberJ testutil.Member) { // Prepare generator := []byte(memberJ.OneTimePubKey()) - fakeGenerator := []byte(testutil.FalsePubKey) + fakeGenerator := testutil.FalsePubKey // Sign signature, err := tss.Sign(memberI.OneTimePrivKey, suite.challenge, suite.nonce, nil) @@ -52,19 +52,19 @@ func (suite *TSSTestSuite) TestSignAndVerifyWithCustomGenerator() { suite.Require().NoError(err) // Success case - err = tss.Verify(tss.Point(nonceSym), signature.S(), suite.challenge, keySym, generator, nil) + err = tss.Verify(nonceSym, signature.S(), suite.challenge, keySym, generator, nil) suite.Require().NoError(err) // Wrong msg case - err = tss.Verify(tss.Point(nonceSym), signature.S(), testutil.FalseChallenge, keySym, generator, nil) + err = tss.Verify(nonceSym, signature.S(), testutil.FalseChallenge, keySym, generator, nil) suite.Require().ErrorIs(err, tss.ErrInvalidSignature) // Wrong key sym case - err = tss.Verify(tss.Point(nonceSym), signature.S(), suite.challenge, testutil.FalsePubKey, generator, nil) + err = tss.Verify(nonceSym, signature.S(), suite.challenge, testutil.FalsePubKey, generator, nil) suite.Require().ErrorIs(err, tss.ErrInvalidSignature) // Wrong generator case - err = tss.Verify(tss.Point(nonceSym), signature.S(), suite.challenge, keySym, fakeGenerator, nil) + err = tss.Verify(nonceSym, signature.S(), suite.challenge, keySym, fakeGenerator, nil) suite.Require().ErrorIs(err, tss.ErrInvalidSignature) // Wrong nonce sym case @@ -162,7 +162,7 @@ func (suite *TSSTestSuite) TestSignAndVerifyRandomly() { randByte := rng.Intn(len(badMsg)) randBit := rng.Intn(7) badMsg[randByte] ^= 1 << randBit - if err := tss.Verify(signature.R(), signature.S(), badMsg[:], pubKey, nil, nil); err == nil { + if err := tss.Verify(signature.R(), signature.S(), badMsg, pubKey, nil, nil); err == nil { suite.T(). Fatalf("verified signature for bad hash\nsignature: %x\nhash: %x\n"+"pubkey: %x", signature, badMsg, pubKey) } diff --git a/pkg/tss/signing.go b/pkg/tss/signing.go index cff9fe4f4..6082707f7 100644 --- a/pkg/tss/signing.go +++ b/pkg/tss/signing.go @@ -3,10 +3,11 @@ package tss import ( "errors" - "github.com/bandprotocol/chain/v2/pkg/tss/internal/lagrange" - "github.com/bandprotocol/chain/v2/pkg/tss/internal/schnorr" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/decred/dcrd/dcrec/secp256k1/v4" + + "github.com/bandprotocol/chain/v2/pkg/tss/internal/lagrange" + "github.com/bandprotocol/chain/v2/pkg/tss/internal/schnorr" ) // checkLagrangeInput checks if a given MemberID (mid) is present in the provided memberList @@ -194,7 +195,7 @@ func SignSigning( return nil, err } - return Sign(ownPrivKey, challenge, Scalar(ownPrivNonce), rawLagrange) + return Sign(ownPrivKey, challenge, ownPrivNonce, rawLagrange) } // VerifySigning verifies the signing using the group public nonce, group public key, data, Lagrange coefficient, diff --git a/pkg/tss/testutil/suite.go b/pkg/tss/testutil/suite.go index 0506c20d4..14025d4b9 100644 --- a/pkg/tss/testutil/suite.go +++ b/pkg/tss/testutil/suite.go @@ -3,8 +3,9 @@ package testutil import ( "fmt" - "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/stretchr/testify/suite" + + "github.com/bandprotocol/chain/v2/pkg/tss" ) type Suite struct { diff --git a/pkg/tss/tss_test.go b/pkg/tss/tss_test.go index 031b470ff..4fcb60c51 100644 --- a/pkg/tss/tss_test.go +++ b/pkg/tss/tss_test.go @@ -3,9 +3,10 @@ package tss_test import ( "testing" + "github.com/stretchr/testify/suite" + "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" - "github.com/stretchr/testify/suite" ) type TSSTestSuite struct { diff --git a/pkg/tss/types.go b/pkg/tss/types.go index 52bbb6894..abe85f14c 100644 --- a/pkg/tss/types.go +++ b/pkg/tss/types.go @@ -8,8 +8,9 @@ import ( "strconv" "strings" - "github.com/bandprotocol/chain/v2/pkg/tss/internal/schnorr" "github.com/decred/dcrd/dcrec/secp256k1/v4" + + "github.com/bandprotocol/chain/v2/pkg/tss/internal/schnorr" ) // GroupID represents the ID of a group. diff --git a/pkg/tss/types_test.go b/pkg/tss/types_test.go index 5c0f6d16a..a80f2fa1e 100644 --- a/pkg/tss/types_test.go +++ b/pkg/tss/types_test.go @@ -3,9 +3,10 @@ package tss_test import ( "fmt" + "github.com/decred/dcrd/dcrec/secp256k1/v4" + "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" - "github.com/decred/dcrd/dcrec/secp256k1/v4" ) func (suite *TSSTestSuite) TestParseScalar() { diff --git a/testing/chain.go b/testing/chain.go index d63614c0f..8da1c5f0a 100644 --- a/testing/chain.go +++ b/testing/chain.go @@ -37,9 +37,7 @@ import ( "github.com/bandprotocol/chain/v2/x/oracle/types" ) -var ( - valSize uint64 = 2 -) +var valSize uint64 = 2 // TestChain is a testing struct that wraps a TestingApp with the last TM Header, the current ABCI // header and the validators of the TestChain. It also contains a field called ChainID. This @@ -112,7 +110,8 @@ func NewTestChain(t *testing.T, coord *Coordinator, chainID string) *TestChain { app := testapp.SetupWithGenesisValSet(t, valSet, genesisAccount, chainID, balances...) vals := app.StakingKeeper.GetAllValidators(app.DeliverContext) for _, v := range vals { - app.OracleKeeper.Activate(app.DeliverContext, v.GetOperator()) + err := app.OracleKeeper.Activate(app.DeliverContext, v.GetOperator()) + require.NoError(t, err) } // create current header and call begin block @@ -273,7 +272,8 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { chain.NextBlock() // increment sequence for successful transaction execution - chain.SenderAccount.SetSequence(chain.SenderAccount.GetSequence() + 1) + err = chain.SenderAccount.SetSequence(chain.SenderAccount.GetSequence() + 1) + require.NoError(chain.t, err) chain.Coordinator.IncrementTime() @@ -312,7 +312,8 @@ func (chain *TestChain) SendReport( chain.NextBlock() // increment sequence for successful transaction execution - senderAccount.SetSequence(senderAccount.GetSequence() + 1) + err = senderAccount.SetSequence(senderAccount.GetSequence() + 1) + require.NoError(chain.t, err) chain.Coordinator.IncrementTime() @@ -492,7 +493,7 @@ func (chain *TestChain) CreateTMClientHeader( Commit: commit.ToProto(), } - if tmValSet != nil { + if tmValSet != nil { //nolint:staticcheck valSet, err = tmValSet.ToProto() if err != nil { panic(err) @@ -531,8 +532,12 @@ func MakeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) tmtypes.Bl // (including voting power). It returns a signer array of PrivValidators that matches the // sorting of ValidatorSet. // The sorting is first by .VotingPower (descending), with secondary index of .Address (ascending). -func CreateSortedSignerArray(altPrivVal, suitePrivVal tmtypes.PrivValidator, - altVal, suiteVal *tmtypes.Validator) []tmtypes.PrivValidator { +func CreateSortedSignerArray( + altPrivVal, + suitePrivVal tmtypes.PrivValidator, + altVal, + suiteVal *tmtypes.Validator, +) []tmtypes.PrivValidator { switch { case altVal.VotingPower > suiteVal.VotingPower: return []tmtypes.PrivValidator{altPrivVal, suitePrivVal} diff --git a/testing/coordinator.go b/testing/coordinator.go index 29d2b5ba2..704b57853 100644 --- a/testing/coordinator.go +++ b/testing/coordinator.go @@ -118,7 +118,8 @@ func (coord *Coordinator) CreateConnections(path *Path) { require.NoError(coord.t, err) // ensure counterparty is up to date - path.EndpointA.UpdateClient() + err = path.EndpointA.UpdateClient() + require.NoError(coord.t, err) } // CreateMockChannels constructs and executes channel handshake messages to create OPEN @@ -159,7 +160,8 @@ func (coord *Coordinator) CreateChannels(path *Path) { require.NoError(coord.t, err) // ensure counterparty is up to date - path.EndpointA.UpdateClient() + err = path.EndpointA.UpdateClient() + require.NoError(coord.t, err) } // GetChain returns the TestChain using the given chainID and returns an error if it does diff --git a/testing/endpoint.go b/testing/endpoint.go index 8ce9726a3..b0eb8413e 100644 --- a/testing/endpoint.go +++ b/testing/endpoint.go @@ -136,9 +136,7 @@ func (endpoint *Endpoint) UpdateClient() (err error) { // ensure counterparty has committed state endpoint.Chain.Coordinator.CommitBlock(endpoint.Counterparty.Chain) - var ( - header *ibctmtypes.Header - ) + var header *ibctmtypes.Header switch endpoint.ClientConfig.GetClientType() { case exported.Tendermint: @@ -182,7 +180,8 @@ func (endpoint *Endpoint) ConnOpenInit() error { // ConnOpenTry will construct and execute a MsgConnectionOpenTry on the associated endpoint. func (endpoint *Endpoint) ConnOpenTry() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) counterpartyClient, proofClient, proofConsensus, consensusHeight, proofInit, proofHeight := endpoint.QueryConnectionHandshakeProof() @@ -216,7 +215,8 @@ func (endpoint *Endpoint) ConnOpenTry() error { // ConnOpenAck will construct and execute a MsgConnectionOpenAck on the associated endpoint. func (endpoint *Endpoint) ConnOpenAck() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) counterpartyClient, proofClient, proofConsensus, consensusHeight, proofTry, proofHeight := endpoint.QueryConnectionHandshakeProof() @@ -237,7 +237,8 @@ func (endpoint *Endpoint) ConnOpenAck() error { // ConnOpenConfirm will construct and execute a MsgConnectionOpenConfirm on the associated endpoint. func (endpoint *Endpoint) ConnOpenConfirm() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) connectionKey := host.ConnectionKey(endpoint.Counterparty.ConnectionID) proof, height := endpoint.Counterparty.Chain.QueryProof(connectionKey) @@ -300,7 +301,8 @@ func (endpoint *Endpoint) ChanOpenInit() error { // ChanOpenTry will construct and execute a MsgChannelOpenTry on the associated endpoint. func (endpoint *Endpoint) ChanOpenTry() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) @@ -332,7 +334,8 @@ func (endpoint *Endpoint) ChanOpenTry() error { // ChanOpenAck will construct and execute a MsgChannelOpenAck on the associated endpoint. func (endpoint *Endpoint) ChanOpenAck() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) @@ -351,7 +354,8 @@ func (endpoint *Endpoint) ChanOpenAck() error { // ChanOpenConfirm will construct and execute a MsgChannelOpenConfirm on the associated endpoint. func (endpoint *Endpoint) ChanOpenConfirm() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) diff --git a/testing/events.go b/testing/events.go index ac1fdd719..7d3a54e96 100644 --- a/testing/events.go +++ b/testing/events.go @@ -5,11 +5,10 @@ import ( "strconv" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" connectiontypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types" channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" + "github.com/stretchr/testify/suite" ) type EventsMap map[string]map[string]string diff --git a/testing/testapp/setup.go b/testing/testapp/setup.go index 6029cc554..10d5055fc 100644 --- a/testing/testapp/setup.go +++ b/testing/testapp/setup.go @@ -57,7 +57,6 @@ type Account struct { ValAddress sdk.ValAddress } -// nolint var ( Owner Account Treasury Account @@ -71,7 +70,6 @@ var ( OwasmVM *owasm.Vm ) -// nolint var ( EmptyCoins = sdk.Coins(nil) Coins1uband = sdk.NewCoins(sdk.NewInt64Coin("uband", 1)) @@ -341,10 +339,14 @@ func NewTestApp(chainID string, logger log.Logger) *TestingApp { {Address: Validators[0].Address.String(), Coins: Coins100000000uband}, {Address: Validators[1].Address.String(), Coins: Coins100000000uband}, {Address: Validators[2].Address.String(), Coins: Coins100000000uband}, - {Address: authtypes.NewModuleAddress(tsstypes.ModuleName).String(), - Coins: Coins100000000uband}, - {Address: authtypes.NewModuleAddress(tsstypes.ModuleName).String(), - Coins: Coins100000000token}, + { + Address: authtypes.NewModuleAddress(tsstypes.ModuleName).String(), + Coins: Coins100000000uband, + }, + { + Address: authtypes.NewModuleAddress(tsstypes.ModuleName).String(), + Coins: Coins100000000token, + }, } totalSupply := sdk.NewCoins() for idx := 0; idx < len(balances)-len(validators); idx++ { @@ -398,31 +400,31 @@ func CreateTestInput(autoActivate bool) (*TestingApp, sdk.Context, keeper.Keeper ctx := app.NewContext(false, tmproto.Header{Height: app.LastBlockHeight()}) if autoActivate { // active oracle status - app.OracleKeeper.Activate(ctx, Validators[0].ValAddress) - app.OracleKeeper.Activate(ctx, Validators[1].ValAddress) - app.OracleKeeper.Activate(ctx, Validators[2].ValAddress) + _ = app.OracleKeeper.Activate(ctx, Validators[0].ValAddress) + _ = app.OracleKeeper.Activate(ctx, Validators[1].ValAddress) + _ = app.OracleKeeper.Activate(ctx, Validators[2].ValAddress) // active tss status - app.TSSKeeper.HandleSetDEs(ctx, Validators[0].Address, []tsstypes.DE{ + _ = app.TSSKeeper.HandleSetDEs(ctx, Validators[0].Address, []tsstypes.DE{ { PubD: testutil.HexDecode("dddd"), PubE: testutil.HexDecode("eeee"), }, }) - app.TSSKeeper.HandleSetDEs(ctx, Validators[1].Address, []tsstypes.DE{ + _ = app.TSSKeeper.HandleSetDEs(ctx, Validators[1].Address, []tsstypes.DE{ { PubD: testutil.HexDecode("dddd"), PubE: testutil.HexDecode("eeee"), }, }) - app.TSSKeeper.HandleSetDEs(ctx, Validators[2].Address, []tsstypes.DE{ + _ = app.TSSKeeper.HandleSetDEs(ctx, Validators[2].Address, []tsstypes.DE{ { PubD: testutil.HexDecode("dddd"), PubE: testutil.HexDecode("eeee"), }, }) - app.TSSKeeper.SetActiveStatus(ctx, Validators[0].Address) - app.TSSKeeper.SetActiveStatus(ctx, Validators[1].Address) - app.TSSKeeper.SetActiveStatus(ctx, Validators[2].Address) + _ = app.TSSKeeper.SetActiveStatus(ctx, Validators[0].Address) + _ = app.TSSKeeper.SetActiveStatus(ctx, Validators[1].Address) + _ = app.TSSKeeper.SetActiveStatus(ctx, Validators[2].Address) } return app, ctx, app.OracleKeeper } diff --git a/testing/testapp/wasm_1_simple.go b/testing/testapp/wasm_1_simple.go index c7e822917..e5347441f 100644 --- a/testing/testapp/wasm_1_simple.go +++ b/testing/testapp/wasm_1_simple.go @@ -1,6 +1,6 @@ package testapp -// A simple Owasm script with the following specification: +// Wasm1 is a simple Owasm script with the following specification: // // PREPARE: // CALL ask_external_data with EID 1 DID 1 CALLDATA "beeb" @@ -8,7 +8,7 @@ package testapp // CALL ask_external_data with EID 3 DID 3 CALLDATA "beeb" // EXECUTE: // CALL set_return_date with RETDATE "beeb" -var Wasm1 []byte = wat2wasm([]byte(` +var Wasm1 = wat2wasm([]byte(` (module (type $t0 (func)) (type $t1 (func (param i64 i64 i64 i64))) diff --git a/testing/testapp/wasm_2_return_in_prepare.go b/testing/testapp/wasm_2_return_in_prepare.go index 96f736e51..a94048635 100644 --- a/testing/testapp/wasm_2_return_in_prepare.go +++ b/testing/testapp/wasm_2_return_in_prepare.go @@ -1,6 +1,6 @@ package testapp -// A bad Owasm script with the following specification: +// Wasm2 is a bad Owasm script with the following specification: // // PREPARE: // CALL set_return_data with RETDATA "beeb" -- Not allowed during prepare diff --git a/testing/testapp/wasm_3_do_nothing.go b/testing/testapp/wasm_3_do_nothing.go index 43f9ca30f..f94d4dfc8 100644 --- a/testing/testapp/wasm_3_do_nothing.go +++ b/testing/testapp/wasm_3_do_nothing.go @@ -1,6 +1,6 @@ package testapp -// A silly oracle script, primarily to test that you must make at least one raw request: +// Wasm3 is a silly oracle script, primarily to test that you must make at least one raw request: // // PREPARE: // DO NOTHING diff --git a/testing/testapp/wasm_4_complex.go b/testing/testapp/wasm_4_complex.go index 8320036e1..29d653926 100644 --- a/testing/testapp/wasm_4_complex.go +++ b/testing/testapp/wasm_4_complex.go @@ -4,7 +4,7 @@ import ( "encoding/hex" ) -// An oracle script for testing complex interactions. +// Wasm4 is an oracle script for testing complex interactions. // // PREPARE: // Call into the given data source ids with the given calldata. diff --git a/testing/testapp/wasm_extras.go b/testing/testapp/wasm_extras.go index 7de803843..3f2c0551e 100644 --- a/testing/testapp/wasm_extras.go +++ b/testing/testapp/wasm_extras.go @@ -5,7 +5,7 @@ import ( "encoding/hex" ) -// An extra Owasm code to test creating or editing oracle scripts. +// WasmExtra1 is an extra Owasm code to test creating or editing oracle scripts. var WasmExtra1 []byte = wat2wasm([]byte(` (module (type $t0 (func)) @@ -17,7 +17,7 @@ var WasmExtra1 []byte = wat2wasm([]byte(` `)) -// Another extra Owasm code to test creating or editing oracle scripts. +// WasmExtra2 is another extra Owasm code to test creating or editing oracle scripts. var WasmExtra2 []byte = wat2wasm([]byte(` (module (type $t0 (func)) @@ -30,8 +30,10 @@ var WasmExtra2 []byte = wat2wasm([]byte(` (memory $memory (export "memory") 17)) `)) -var WasmExtra1FileName string -var WasmExtra2FileName string +var ( + WasmExtra1FileName string + WasmExtra2FileName string +) func init() { wasm1CompiledHash := sha256.Sum256(compile(WasmExtra1)) diff --git a/testing/testapp/wasm_util.go b/testing/testapp/wasm_util.go index f894b967d..1ab6e078e 100644 --- a/testing/testapp/wasm_util.go +++ b/testing/testapp/wasm_util.go @@ -12,6 +12,7 @@ func compile(code []byte) []byte { if err != nil { panic(err) } + return compiled } @@ -21,20 +22,25 @@ func wat2wasm(wat []byte) []byte { panic(err) } defer os.Remove(inputFile.Name()) + outputFile, err := os.CreateTemp("", "output") if err != nil { panic(err) } defer os.Remove(outputFile.Name()) + if _, err := inputFile.Write(wat); err != nil { panic(err) } - if err := exec.Command("wat2wasm", inputFile.Name(), "-o", outputFile.Name()).Run(); err != nil { + + if err := exec.Command("wat2wasm", inputFile.Name(), "-o", outputFile.Name()).Run(); err != nil { //nolint:gosec panic(err) } + output, err := os.ReadFile(outputFile.Name()) if err != nil { panic(err) } + return output } diff --git a/testing/value.go b/testing/value.go index e9eba50ef..e11da44ba 100644 --- a/testing/value.go +++ b/testing/value.go @@ -9,7 +9,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" connectiontypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types" - commitmenttypes "github.com/cosmos/ibc-go/v7/modules/core/23-commitment/types" ibctmtypes "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint" "github.com/cosmos/ibc-go/v7/testing/mock" @@ -55,5 +54,5 @@ var ( // MockFailPacketData = []byte("mock failed packet data") // MockCanaryCapabilityName = []byte("mock async packet data") - prefix = commitmenttypes.NewMerklePrefix([]byte("ibc")) + // prefix = commitmenttypes.NewMerklePrefix([]byte("ibc")) ) diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index d37e6c4a2..aa479555a 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/cometbft/cometbft/libs/log" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -71,7 +70,11 @@ func (k WrappedBankKeeper) BurnCoins(ctx sdk.Context, moduleName string, amt sdk } // Instead of burning coins, we send them to the community pool. - k.SendCoinsFromModuleToModule(ctx, moduleName, distrtypes.ModuleName, amt) + err := k.SendCoinsFromModuleToModule(ctx, moduleName, distrtypes.ModuleName, amt) + if err != nil { + return err + } + feePool := k.distrKeeper.GetFeePool(ctx) feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amt...)...) k.distrKeeper.SetFeePool(ctx, feePool) diff --git a/x/globalfee/feechecker/feechecker_test.go b/x/globalfee/feechecker/feechecker_test.go index ed863a740..6aa15ba62 100644 --- a/x/globalfee/feechecker/feechecker_test.go +++ b/x/globalfee/feechecker/feechecker_test.go @@ -40,6 +40,7 @@ func (st *StubTx) ValidateBasic() error { func (st *StubTx) GetGas() uint64 { return 1000000 } + func (st *StubTx) GetFee() sdk.Coins { fees := make(sdk.Coins, len(st.GasPrices)) @@ -57,7 +58,7 @@ type FeeCheckerTestSuite struct { suite.Suite FeeChecker feechecker.FeeChecker ctx sdk.Context - requestId oracletypes.RequestID + requestID oracletypes.RequestID } func (suite *FeeCheckerTestSuite) SetupTest() { @@ -66,10 +67,11 @@ func (suite *FeeCheckerTestSuite) SetupTest() { WithIsCheckTx(true). WithMinGasPrices(sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(1, 4)}}) - oracleKeeper.GrantReporter(suite.ctx, testapp.Validators[0].ValAddress, testapp.Alice.Address) + err := oracleKeeper.GrantReporter(suite.ctx, testapp.Validators[0].ValAddress, testapp.Alice.Address) + suite.Require().NoError(err) expiration := ctx.BlockTime().Add(1000 * time.Hour) - app.AuthzKeeper.SaveGrant( + err = app.AuthzKeeper.SaveGrant( ctx, testapp.Alice.Address, testapp.Validators[0].Address, @@ -78,6 +80,7 @@ func (suite *FeeCheckerTestSuite) SetupTest() { ), &expiration, ) + suite.Require().NoError(err) req := oracletypes.NewRequest( 1, @@ -95,7 +98,7 @@ func (suite *FeeCheckerTestSuite) SetupTest() { testapp.FeePayer.Address.String(), testapp.Coins100000000uband, ) - suite.requestId = oracleKeeper.AddRequest(suite.ctx, req) + suite.requestID = oracleKeeper.AddRequest(suite.ctx, req) suite.FeeChecker = feechecker.NewFeeChecker( &app.AuthzKeeper, @@ -121,11 +124,12 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri return &StubTx{ Msgs: []sdk.Msg{ oracletypes.NewMsgReportData( - suite.requestId, + suite.requestID, []oracletypes.RawReport{}, testapp.Validators[0].ValAddress, ), - }} + }, + } }, expIsBypassMinFeeTx: true, expErr: nil, @@ -242,7 +246,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri stubTx: func() *StubTx { msgExec := authz.NewMsgExec(testapp.Alice.Address, []sdk.Msg{ oracletypes.NewMsgReportData( - suite.requestId, + suite.requestID, []oracletypes.RawReport{}, testapp.Validators[0].ValAddress, ), @@ -278,7 +282,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri stubTx: func() *StubTx { msgExec := authz.NewMsgExec(testapp.Alice.Address, []sdk.Msg{ oracletypes.NewMsgReportData( - suite.requestId+1, + suite.requestID+1, []oracletypes.RawReport{}, testapp.Validators[0].ValAddress, ), @@ -300,7 +304,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri stubTx: func() *StubTx { msgExec := authz.NewMsgExec(testapp.Bob.Address, []sdk.Msg{ oracletypes.NewMsgReportData( - suite.requestId, + suite.requestID, []oracletypes.RawReport{}, testapp.Validators[0].ValAddress, ), @@ -363,7 +367,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri name: "valid MsgRequestData and valid MsgReport in valid MsgExec with enough fee", stubTx: func() *StubTx { msgReportData := oracletypes.NewMsgReportData( - suite.requestId, + suite.requestID, []oracletypes.RawReport{}, testapp.Validators[0].ValAddress, ) @@ -399,7 +403,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri name: "valid MsgRequestData and valid MsgReport with enough fee", stubTx: func() *StubTx { msgReportData := oracletypes.NewMsgReportData( - suite.requestId, + suite.requestID, []oracletypes.RawReport{}, testapp.Validators[0].ValAddress, ) diff --git a/x/globalfee/keeper/genesis.go b/x/globalfee/keeper/genesis.go index 330402d92..f7188ca17 100644 --- a/x/globalfee/keeper/genesis.go +++ b/x/globalfee/keeper/genesis.go @@ -7,14 +7,14 @@ import ( ) // InitGenesis new globalfee genesis -func (keeper Keeper) InitGenesis(ctx sdk.Context, data *types.GenesisState) { - if err := keeper.SetParams(ctx, data.Params); err != nil { +func (k Keeper) InitGenesis(ctx sdk.Context, data *types.GenesisState) { + if err := k.SetParams(ctx, data.Params); err != nil { panic(err) } } // ExportGenesis returns a GenesisState for a given context. -func (keeper Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { - params := keeper.GetParams(ctx) +func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { + params := k.GetParams(ctx) return types.NewGenesisState(params) } diff --git a/x/globalfee/keeper/genesis_test.go b/x/globalfee/keeper/genesis_test.go index c24285b1d..57c2cfc8b 100644 --- a/x/globalfee/keeper/genesis_test.go +++ b/x/globalfee/keeper/genesis_test.go @@ -68,14 +68,14 @@ func (s *GenesisTestSuite) TestImportExportGenesis() { } for name, spec := range specs { s.Run(name, func() { - genesisState := &spec.exp - s.keeper.InitGenesis(s.sdkCtx, genesisState) + genesisState := spec.exp + s.keeper.InitGenesis(s.sdkCtx, &genesisState) params := s.keeper.GetParams(s.sdkCtx) s.Require().Equal(genesisState.Params, params) genesisState2 := s.keeper.ExportGenesis(s.sdkCtx) - s.Require().Equal(genesisState, genesisState2) + s.Require().Equal(&genesisState, genesisState2) }) } } diff --git a/x/globalfee/keeper/grpc_query_test.go b/x/globalfee/keeper/grpc_query_test.go index 39aa29be7..e482070eb 100644 --- a/x/globalfee/keeper/grpc_query_test.go +++ b/x/globalfee/keeper/grpc_query_test.go @@ -22,7 +22,7 @@ func TestQueryParams(t *testing.T) { }{ "one coin": { setupStore: func(ctx sdk.Context, k keeper.Keeper) { - k.SetParams(ctx, types.Params{ + _ = k.SetParams(ctx, types.Params{ MinimumGasPrices: sdk.NewDecCoins(sdk.NewDecCoin("ALX", sdk.OneInt())), }) }, @@ -30,18 +30,22 @@ func TestQueryParams(t *testing.T) { }, "multiple coins": { setupStore: func(ctx sdk.Context, k keeper.Keeper) { - k.SetParams(ctx, types.Params{ + if err := k.SetParams(ctx, types.Params{ MinimumGasPrices: sdk.NewDecCoins( sdk.NewDecCoin("ALX", sdk.OneInt()), sdk.NewDecCoin("BLX", sdk.NewInt(2)), ), - }) + }); err != nil { + t.Error(err) + } }, expMin: sdk.NewDecCoins(sdk.NewDecCoin("ALX", sdk.OneInt()), sdk.NewDecCoin("BLX", sdk.NewInt(2))), }, "no min gas price set": { setupStore: func(ctx sdk.Context, k keeper.Keeper) { - k.SetParams(ctx, types.Params{}) + if err := k.SetParams(ctx, types.Params{}); err != nil { + t.Error(err) + } }, }, "no param set": { diff --git a/x/globalfee/keeper/keeper_test.go b/x/globalfee/keeper/keeper_test.go index dd6f3b437..7b161048a 100644 --- a/x/globalfee/keeper/keeper_test.go +++ b/x/globalfee/keeper/keeper_test.go @@ -3,13 +3,12 @@ package keeper_test import ( "testing" - "github.com/stretchr/testify/suite" - "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/stretchr/testify/suite" "github.com/bandprotocol/chain/v2/x/globalfee" "github.com/bandprotocol/chain/v2/x/globalfee/keeper" diff --git a/x/globalfee/module.go b/x/globalfee/module.go index 2d98a852a..7ef025ee7 100644 --- a/x/globalfee/module.go +++ b/x/globalfee/module.go @@ -41,7 +41,7 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { } // RegisterInterfaces registers the module's interface types -func (b AppModuleBasic) RegisterInterfaces(r codectypes.InterfaceRegistry) { +func (a AppModuleBasic) RegisterInterfaces(r codectypes.InterfaceRegistry) { types.RegisterInterfaces(r) } @@ -68,7 +68,9 @@ func (a AppModuleBasic) ValidateGenesis( } func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) + if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { + panic(err) + } } func (a AppModuleBasic) GetTxCmd() *cobra.Command { diff --git a/x/globalfee/types/keys.go b/x/globalfee/types/keys.go index 012e31211..b4cc14221 100644 --- a/x/globalfee/types/keys.go +++ b/x/globalfee/types/keys.go @@ -14,6 +14,4 @@ const ( RouterKey = ModuleName ) -var ( - ParamsKeyPrefix = []byte{0x01} -) +var ParamsKeyPrefix = []byte{0x01} diff --git a/x/oracle/abci_test.go b/x/oracle/abci_test.go index 2bf4eb552..cc224375c 100644 --- a/x/oracle/abci_test.go +++ b/x/oracle/abci_test.go @@ -34,23 +34,29 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { // Set collected fee to 100uband + 70% oracle reward proportion + disable minting inflation. // NOTE: we intentionally keep ctx.BlockHeight = 0, so distr's AllocateTokens doesn't get called. feeCollector := app.AccountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) - app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("uband", 100))) - app.BankKeeper.SendCoinsFromModuleToModule( + err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("uband", 100))) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToModule( ctx, minttypes.ModuleName, authtypes.FeeCollectorName, sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), ) + require.NoError(t, err) + distModule := app.AccountKeeper.GetModuleAccount(ctx, distrtypes.ModuleName) app.AccountKeeper.SetAccount(ctx, feeCollector) mintParams := app.MintKeeper.GetParams(ctx) mintParams.InflationMin = sdk.ZeroDec() mintParams.InflationMax = sdk.ZeroDec() - app.MintKeeper.SetParams(ctx, mintParams) + err = app.MintKeeper.SetParams(ctx, mintParams) + require.NoError(t, err) + params := k.GetParams(ctx) params.OracleRewardPercentage = 70 - k.SetParams(ctx, params) + err = k.SetParams(ctx, params) + require.NoError(t, err) require.Equal( t, sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), @@ -67,7 +73,8 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress()), ) // 1 validator active, begin block should take 70% of the fee. 2% of that goes to comm pool. - k.Activate(ctx, testapp.Validators[1].ValAddress) + err = k.Activate(ctx, testapp.Validators[1].ValAddress) + require.NoError(t, err) app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), LastCommitInfo: abci.CommitInfo{Votes: votes}, @@ -97,7 +104,9 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, ) // 2 validators active now. 70% of the remaining fee pool will be split 3 ways (comm pool + val1 + val2). - k.Activate(ctx, testapp.Validators[0].ValAddress) + err = k.Activate(ctx, testapp.Validators[0].ValAddress) + require.NoError(t, err) + app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), LastCommitInfo: abci.CommitInfo{Votes: votes}, @@ -181,21 +190,25 @@ func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { distModule := app.AccountKeeper.GetModuleAccount(ctx, distrtypes.ModuleName) // Set collected fee to 100uband + 70% oracle reward proportion + disable minting inflation. - app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("uband", 50))) - app.BankKeeper.SendCoinsFromModuleToModule( + err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("uband", 50))) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToModule( ctx, minttypes.ModuleName, authtypes.FeeCollectorName, sdk.NewCoins(sdk.NewInt64Coin("uband", 50)), ) + require.NoError(t, err) app.AccountKeeper.SetAccount(ctx, feeCollector) mintParams := app.MintKeeper.GetParams(ctx) mintParams.InflationMin = sdk.ZeroDec() mintParams.InflationMax = sdk.ZeroDec() - app.MintKeeper.SetParams(ctx, mintParams) + err = app.MintKeeper.SetParams(ctx, mintParams) + require.NoError(t, err) params := k.GetParams(ctx) params.OracleRewardPercentage = 70 - k.SetParams(ctx, params) + err = k.SetParams(ctx, params) + require.NoError(t, err) // Set block proposer to Validators[1], who will receive 5% bonus. app.DistrKeeper.SetPreviousProposerConsAddr(ctx, testapp.Validators[1].Address.Bytes()) require.Equal( @@ -217,7 +230,8 @@ func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { // Community pool: 0.7 + 0.3 = 1 // Validators[0]: 34.3 + 8.715 = 43.015 // Validators[1]: 2.25 + 3.735 = 5.985 - k.Activate(ctx, testapp.Validators[0].ValAddress) + err = k.Activate(ctx, testapp.Validators[0].ValAddress) + require.NoError(t, err) app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), LastCommitInfo: abci.CommitInfo{Votes: votes}, diff --git a/x/oracle/app_test.go b/x/oracle/app_test.go index 2a0387f0a..df8faba75 100644 --- a/x/oracle/app_test.go +++ b/x/oracle/app_test.go @@ -110,7 +110,7 @@ func TestSuccessRequestOracleData(t *testing.T) { expectRequest.ClientID, types.RequestID(1), 2, - int64(expectRequest.RequestTime), + expectRequest.RequestTime, 1581589795, types.RESOLVE_STATUS_SUCCESS, []byte("beeb"), @@ -192,7 +192,7 @@ func TestExpiredRequestOracleData(t *testing.T) { expectRequest.ClientID, types.RequestID(1), 0, - int64(expectRequest.RequestTime), + expectRequest.RequestTime, ctx.BlockTime().Unix(), types.RESOLVE_STATUS_EXPIRED, []byte{}, diff --git a/x/oracle/genesis.go b/x/oracle/genesis.go index 0aa539dcb..e625a02cb 100644 --- a/x/oracle/genesis.go +++ b/x/oracle/genesis.go @@ -3,6 +3,7 @@ package oracle import ( "fmt" + errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bandprotocol/chain/v2/x/oracle/keeper" @@ -11,7 +12,10 @@ import ( // InitGenesis performs genesis initialization for the oracle module. func InitGenesis(ctx sdk.Context, k keeper.Keeper, data *types.GenesisState) { - k.SetParams(ctx, data.Params) + if err := k.SetParams(ctx, data.Params); err != nil { + panic(errorsmod.Wrapf(err, "set params")) + } + k.SetDataSourceCount(ctx, 0) k.SetOracleScriptCount(ctx, 0) k.SetRequestCount(ctx, 0) diff --git a/x/oracle/handler_test.go b/x/oracle/handler_test.go index 9022fde9c..e3999f2ca 100644 --- a/x/oracle/handler_test.go +++ b/x/oracle/handler_test.go @@ -55,7 +55,7 @@ func TestCreateDataSourceSuccess(t *testing.T) { {Key: types.AttributeKeyID, Value: fmt.Sprintf("%d", dsCount+1)}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestCreateGzippedExecutableDataSourceFail(t *testing.T) { @@ -67,7 +67,8 @@ func TestCreateGzippedExecutableDataSourceFail(t *testing.T) { executable := []byte("executable") var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(executable) + _, err := zw.Write(executable) + require.NoError(t, err) zw.Close() sender := testapp.Alice.Address msg := types.NewMsgCreateDataSource( @@ -121,7 +122,7 @@ func TestEditDataSourceSuccess(t *testing.T) { Type: types.EventTypeEditDataSource, Attributes: []abci.EventAttribute{{Key: types.AttributeKeyID, Value: "1"}}, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestEditDataSourceFail(t *testing.T) { @@ -160,7 +161,8 @@ func TestEditDataSourceFail(t *testing.T) { // Bad Gzip var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(newExecutable) + _, err = zw.Write(newExecutable) + require.NoError(t, err) zw.Close() msg = types.NewMsgEditDataSource( 1, @@ -210,7 +212,7 @@ func TestCreateOracleScriptSuccess(t *testing.T) { {Key: types.AttributeKeyID, Value: fmt.Sprintf("%d", osCount+1)}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestCreateGzippedOracleScriptSuccess(t *testing.T) { @@ -222,7 +224,8 @@ func TestCreateGzippedOracleScriptSuccess(t *testing.T) { url := "url" var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(testapp.WasmExtra1) + _, err := zw.Write(testapp.WasmExtra1) + require.NoError(t, err) zw.Close() msg := types.NewMsgCreateOracleScript( name, @@ -249,7 +252,7 @@ func TestCreateGzippedOracleScriptSuccess(t *testing.T) { {Key: types.AttributeKeyID, Value: fmt.Sprintf("%d", osCount+1)}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestCreateOracleScriptFail(t *testing.T) { @@ -274,7 +277,8 @@ func TestCreateOracleScriptFail(t *testing.T) { // Bad Gzip var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(testapp.WasmExtra1) + _, err = zw.Write(testapp.WasmExtra1) + require.NoError(t, err) zw.Close() msg = types.NewMsgCreateOracleScript( name, @@ -328,7 +332,7 @@ func TestEditOracleScriptSuccess(t *testing.T) { Type: types.EventTypeEditOracleScript, Attributes: []abci.EventAttribute{{Key: types.AttributeKeyID, Value: "1"}}, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestEditOracleScriptFail(t *testing.T) { @@ -383,7 +387,8 @@ func TestEditOracleScriptFail(t *testing.T) { // Bad Gzip var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(testapp.WasmExtra2) + _, err = zw.Write(testapp.WasmExtra2) + require.NoError(t, err) zw.Close() msg = types.NewMsgEditOracleScript( 1, @@ -432,7 +437,7 @@ func TestRequestDataSuccess(t *testing.T) { types.NewRawRequest(3, 3, []byte("beeb")), }, nil, - uint64(testapp.TestDefaultExecuteGas), + testapp.TestDefaultExecuteGas, 0, 0, testapp.FeePayer.Address.String(), @@ -445,9 +450,9 @@ func TestRequestDataSuccess(t *testing.T) { {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) - require.Equal(t, abci.Event(event), res.Events[4]) - require.Equal(t, abci.Event(event), res.Events[8]) + require.Equal(t, event, res.Events[0]) + require.Equal(t, event, res.Events[4]) + require.Equal(t, event, res.Events[8]) event = abci.Event{ Type: authtypes.EventTypeCoinReceived, Attributes: []abci.EventAttribute{ @@ -455,9 +460,9 @@ func TestRequestDataSuccess(t *testing.T) { {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[1]) - require.Equal(t, abci.Event(event), res.Events[5]) - require.Equal(t, abci.Event(event), res.Events[9]) + require.Equal(t, event, res.Events[1]) + require.Equal(t, event, res.Events[5]) + require.Equal(t, event, res.Events[9]) event = abci.Event{ Type: authtypes.EventTypeTransfer, Attributes: []abci.EventAttribute{ @@ -466,18 +471,18 @@ func TestRequestDataSuccess(t *testing.T) { {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[2]) - require.Equal(t, abci.Event(event), res.Events[6]) - require.Equal(t, abci.Event(event), res.Events[10]) + require.Equal(t, event, res.Events[2]) + require.Equal(t, event, res.Events[6]) + require.Equal(t, event, res.Events[10]) event = abci.Event{ Type: sdk.EventTypeMessage, Attributes: []abci.EventAttribute{ {Key: authtypes.AttributeKeySender, Value: testapp.FeePayer.Address.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[3]) - require.Equal(t, abci.Event(event), res.Events[7]) - require.Equal(t, abci.Event(event), res.Events[11]) + require.Equal(t, event, res.Events[3]) + require.Equal(t, event, res.Events[7]) + require.Equal(t, event, res.Events[11]) event = abci.Event{ Type: types.EventTypeRequest, @@ -495,7 +500,7 @@ func TestRequestDataSuccess(t *testing.T) { {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[12]) + require.Equal(t, event, res.Events[12]) event = abci.Event{ Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ @@ -506,7 +511,7 @@ func TestRequestDataSuccess(t *testing.T) { {Key: types.AttributeKeyFee, Value: "1000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[13]) + require.Equal(t, event, res.Events[13]) event = abci.Event{ Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ @@ -517,7 +522,7 @@ func TestRequestDataSuccess(t *testing.T) { {Key: types.AttributeKeyFee, Value: "1000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[14]) + require.Equal(t, event, res.Events[14]) event = abci.Event{ Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ @@ -528,7 +533,7 @@ func TestRequestDataSuccess(t *testing.T) { {Key: types.AttributeKeyFee, Value: "1000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[15]) + require.Equal(t, event, res.Events[15]) } func TestRequestDataFail(t *testing.T) { @@ -554,8 +559,10 @@ func TestRequestDataFail(t *testing.T) { ) testapp.CheckErrorf(t, err, types.ErrInsufficientValidators, "0 < 2") require.Nil(t, res) - k.Activate(ctx, testapp.Validators[0].ValAddress) - k.Activate(ctx, testapp.Validators[1].ValAddress) + err = k.Activate(ctx, testapp.Validators[0].ValAddress) + require.NoError(t, err) + err = k.Activate(ctx, testapp.Validators[1].ValAddress) + require.NoError(t, err) // Too large calldata res, err = oracle.NewHandler( k, @@ -681,7 +688,7 @@ func TestReportSuccess(t *testing.T) { {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) // Validators[1] reports data. Now the request should move to pending resolve. res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Validators[1].ValAddress)) require.NoError(t, err) @@ -693,7 +700,7 @@ func TestReportSuccess(t *testing.T) { {Key: types.AttributeKeyValidator, Value: testapp.Validators[1].ValAddress.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) // Even if we resolve the request, Validators[2] should still be able to report. k.SetPendingResolveList(ctx, []types.RequestID{}) k.ResolveSuccess( @@ -715,7 +722,7 @@ func TestReportSuccess(t *testing.T) { {Key: types.AttributeKeyValidator, Value: testapp.Validators[2].ValAddress.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) // Check the reports of this request. We should see 3 reports, with report from Validators[2] comes after resolve. finalReport := k.GetReports(ctx, 42) require.Contains(t, finalReport, types.NewReport(testapp.Validators[0].ValAddress, true, reports)) @@ -834,7 +841,7 @@ func TestActivateSuccess(t *testing.T) { {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestActivateFail(t *testing.T) { @@ -882,7 +889,7 @@ func TestUpdateParamsSuccess(t *testing.T) { {Key: types.AttributeKeyParams, Value: expectedParams.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) expectedParams = types.Params{ MaxRawRequestCount: 2, @@ -907,7 +914,7 @@ func TestUpdateParamsSuccess(t *testing.T) { {Key: types.AttributeKeyParams, Value: expectedParams.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestUpdateParamsFail(t *testing.T) { diff --git a/x/oracle/ibc_test.go b/x/oracle/ibc_test.go index ce4a204ed..9aba6bdf4 100644 --- a/x/oracle/ibc_test.go +++ b/x/oracle/ibc_test.go @@ -102,7 +102,7 @@ func (suite *OracleTestSuite) TestHandleIBCRequestSuccess() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - suite.chainB.SendReport(1, raws1, testapp.Validators[0]) + _, err = suite.chainB.SendReport(1, raws1, testapp.Validators[0]) suite.Require().NoError(err) raws2 := []types.RawReport{ @@ -110,7 +110,7 @@ func (suite *OracleTestSuite) TestHandleIBCRequestSuccess() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - suite.chainB.SendReport(1, raws2, testapp.Validators[1]) + _, err = suite.chainB.SendReport(1, raws2, testapp.Validators[1]) suite.Require().NoError(err) oracleResponsePacket := types.NewOracleResponsePacketData( @@ -268,17 +268,19 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestNotEnoughFund() { // Use Carol as a relayer carol := testapp.Carol carolExpectedBalance := sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2492500))) - suite.chainB.SendMsgs(banktypes.NewMsgSend( + _, err := suite.chainB.SendMsgs(banktypes.NewMsgSend( suite.chainB.SenderAccount.GetAddress(), carol.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2500000))), )) + suite.Require().NoError(err) + suite.chainB.SenderPrivKey = carol.PrivKey suite.chainB.SenderAccount = suite.chainB.App.AccountKeeper.GetAccount(suite.chainB.GetContext(), carol.Address) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) - err := path.RelayPacket(packet) + err = path.RelayPacket(packet) suite.Require().NoError(err) // relay committed carolBalance := suite.chainB.App.BankKeeper.GetAllBalances(suite.chainB.GetContext(), carol.Address) @@ -400,7 +402,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestBaseOwasmFeePanic() { params := suite.chainB.App.OracleKeeper.GetParams(suite.chainB.GetContext()) params.BaseOwasmGas = 100000000 params.PerValidatorRequestGas = 0 - suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + err := suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + suite.Require().NoError(err) // send request from A to B timeoutHeight := clienttypes.NewHeight(0, 110) @@ -418,7 +421,7 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestBaseOwasmFeePanic() { packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) // ConsumeGas panics due to insufficient gas, so ErrAcknowledgement is not created. - err := path.RelayPacket(packet) + err = path.RelayPacket(packet) suite.Require().Contains(err.Error(), "BASE_OWASM_FEE; gasWanted: 1000000") } @@ -427,7 +430,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestPerValidatorRequestFeePanic() params := suite.chainB.App.OracleKeeper.GetParams(suite.chainB.GetContext()) params.PerValidatorRequestGas = 100000000 - suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + err := suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + suite.Require().NoError(err) // send request from A to B timeoutHeight := clienttypes.NewHeight(0, 110) @@ -445,7 +449,7 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestPerValidatorRequestFeePanic() packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) // ConsumeGas panics due to insufficient gas, so ErrAcknowledgement is not created. - err := path.RelayPacket(packet) + err = path.RelayPacket(packet) suite.Require().Contains(err.Error(), "PER_VALIDATOR_REQUEST_FEE; gasWanted: 1000000") } @@ -542,7 +546,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidDataSourceCount() { params := suite.chainB.App.OracleKeeper.GetParams(suite.chainB.GetContext()) params.MaxRawRequestCount = 3 - suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + err := suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + suite.Require().NoError(err) // send request from A to B timeoutHeight := clienttypes.NewHeight(0, 110) @@ -562,7 +567,7 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidDataSourceCount() { ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) - err := path.RelayPacket(packet) + err = path.RelayPacket(packet) suite.Require().NoError(err) // relay committed } @@ -638,7 +643,8 @@ func (suite *OracleTestSuite) TestIBCResolveRequestOutOfGas() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err = suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -695,10 +701,12 @@ func (suite *OracleTestSuite) TestIBCResolveReadNilExternalData() { suite.checkChainBSenderBalances(sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(5970000)))) raws1 := []types.RawReport{types.NewRawReport(0, 0, nil), types.NewRawReport(1, 0, []byte("beebd2v1"))} - suite.chainB.SendReport(1, raws1, testapp.Validators[0]) + _, err = suite.chainB.SendReport(1, raws1, testapp.Validators[0]) + suite.Require().NoError(err) raws2 := []types.RawReport{types.NewRawReport(0, 0, []byte("beebd1v2")), types.NewRawReport(1, 0, nil)} - suite.chainB.SendReport(1, raws2, testapp.Validators[1]) + _, err = suite.chainB.SendReport(1, raws2, testapp.Validators[1]) + suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -756,7 +764,8 @@ func (suite *OracleTestSuite) TestIBCResolveRequestNoReturnData() { )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err := suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -814,7 +823,8 @@ func (suite *OracleTestSuite) TestIBCResolveRequestWasmFailure() { )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err := suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -872,7 +882,8 @@ func (suite *OracleTestSuite) TestIBCResolveRequestCallReturnDataSeveralTimes() )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err := suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), diff --git a/x/oracle/keeper/grpc_query.go b/x/oracle/keeper/grpc_query.go index 20a5c503c..d5cf80728 100644 --- a/x/oracle/keeper/grpc_query.go +++ b/x/oracle/keeper/grpc_query.go @@ -29,10 +29,10 @@ var _ types.QueryServer = Querier{} func (k Querier) Counts(c context.Context, req *types.QueryCountsRequest) (*types.QueryCountsResponse, error) { ctx := sdk.UnwrapSDKContext(c) return &types.QueryCountsResponse{ - DataSourceCount: k.GetDataSourceCount(ctx), - OracleScriptCount: k.GetOracleScriptCount(ctx), - RequestCount: k.GetRequestCount(ctx)}, - nil + DataSourceCount: k.GetDataSourceCount(ctx), + OracleScriptCount: k.GetOracleScriptCount(ctx), + RequestCount: k.GetRequestCount(ctx), + }, nil } // Data queries the data source or oracle script script for given file hash. @@ -372,7 +372,7 @@ func (k Querier) RequestVerification( if err != nil || len(pk) != secp256k1.PubKeySize { return nil, status.Error(codes.InvalidArgument, "unable to get reporter's public key") } - reporterPubKey := secp256k1.PubKey(pk[:]) + reporterPubKey := secp256k1.PubKey(pk) requestVerificationContent := types.NewRequestVerification( req.ChainId, @@ -429,14 +429,14 @@ func (k Querier) RequestVerification( } // Provided external ID should be required by the request determined by oracle script - var dataSourceID *types.DataSourceID + dataSourceID := types.DataSourceID(0) for _, rawRequest := range request.RawRequests { if rawRequest.ExternalID == types.ExternalID(req.ExternalId) { - dataSourceID = &rawRequest.DataSourceID + dataSourceID = rawRequest.DataSourceID break } } - if dataSourceID == nil { + if dataSourceID == 0 { return nil, status.Error( codes.InvalidArgument, fmt.Sprintf( @@ -446,7 +446,7 @@ func (k Querier) RequestVerification( ), ) } - if *dataSourceID != types.DataSourceID(req.DataSourceId) { + if dataSourceID != types.DataSourceID(req.DataSourceId) { return nil, status.Error( codes.InvalidArgument, fmt.Sprintf( @@ -487,7 +487,7 @@ func (k Querier) RequestVerification( Validator: req.Validator, RequestId: req.RequestId, ExternalId: req.ExternalId, - DataSourceId: uint64(*dataSourceID), + DataSourceId: uint64(dataSourceID), IsDelay: false, }, nil } diff --git a/x/oracle/keeper/grpc_query_test.go b/x/oracle/keeper/grpc_query_test.go index d210687db..207f22d6c 100644 --- a/x/oracle/keeper/grpc_query_test.go +++ b/x/oracle/keeper/grpc_query_test.go @@ -67,8 +67,10 @@ func (suite *RequestVerificationTestSuite) SetupTest() { k.SetRequest(ctx, types.RequestID(1), suite.request) k.SetRequestCount(ctx, 1) err := k.GrantReporter(ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + suite.assert.NoError(err) + expiration := ctx.BlockTime().Add(10 * time.Minute) - app.AuthzKeeper.SaveGrant(ctx, suite.granteeAddr, sdk.AccAddress(testapp.Validators[0].ValAddress), + err = app.AuthzKeeper.SaveGrant(ctx, suite.granteeAddr, sdk.AccAddress(testapp.Validators[0].ValAddress), authz.NewGenericAuthorization("some url"), &expiration, ) suite.assert.NoError(err) @@ -551,7 +553,8 @@ func (suite *RequestVerificationTestSuite) TestIsNotReporter() { } func (suite *RequestVerificationTestSuite) TestRevokeReporters() { - suite.querier.Keeper.RevokeReporter(suite.ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + err := suite.querier.Keeper.RevokeReporter(suite.ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + suite.assert.NoError(err) req := &types.QueryReportersRequest{ ValidatorAddress: testapp.Validators[0].ValAddress.String(), } diff --git a/x/oracle/keeper/oracle_script_test.go b/x/oracle/keeper/oracle_script_test.go index 80bdeaa0d..87bebbe66 100644 --- a/x/oracle/keeper/oracle_script_test.go +++ b/x/oracle/keeper/oracle_script_test.go @@ -121,7 +121,7 @@ func TestAddOracleScriptMustReturnCorrectID(t *testing.T) { )) require.Equal(t, types.OracleScriptID(genesisCount+2), id2) // Finally we expect the oracle script to increase as well. - require.Equal(t, uint64(genesisCount+2), k.GetOracleScriptCount(ctx)) + require.Equal(t, genesisCount+2, k.GetOracleScriptCount(ctx)) } func TestEditNonExistentOracleScript(t *testing.T) { diff --git a/x/oracle/keeper/owasm.go b/x/oracle/keeper/owasm.go index 11b8d85d3..6ca521dc0 100644 --- a/x/oracle/keeper/owasm.go +++ b/x/oracle/keeper/owasm.go @@ -16,7 +16,7 @@ import ( const gasConversionFactor = 20_000_000 func ConvertToOwasmGas(cosmos uint64) uint64 { - return uint64(cosmos * gasConversionFactor) + return cosmos * gasConversionFactor } func ConvertToGas(owasm uint64) uint64 { diff --git a/x/oracle/keeper/owasm_test.go b/x/oracle/keeper/owasm_test.go index c2888b21b..ebb0da277 100644 --- a/x/oracle/keeper/owasm_test.go +++ b/x/oracle/keeper/owasm_test.go @@ -95,8 +95,10 @@ func TestGetRandomValidatorsWithActivate(t *testing.T) { _, err := k.GetRandomValidators(ctx, 1, 1) require.ErrorIs(t, err, types.ErrInsufficientValidators) // If we activate 2 validators, we should be able to get at most 2 from the function. - k.Activate(ctx, testapp.Validators[0].ValAddress) - k.Activate(ctx, testapp.Validators[1].ValAddress) + err = k.Activate(ctx, testapp.Validators[0].ValAddress) + require.NoError(t, err) + err = k.Activate(ctx, testapp.Validators[1].ValAddress) + require.NoError(t, err) vals, err := k.GetRandomValidators(ctx, 1, 1) require.NoError(t, err) require.Equal(t, []sdk.ValAddress{testapp.Validators[0].ValAddress}, vals) @@ -408,7 +410,8 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { _, ctx, k := testapp.CreateTestInput(true) params := k.GetParams(ctx) params.MaxAskCount = 5 - k.SetParams(ctx, params) + err := k.SetParams(ctx, params) + require.NoError(t, err) wrappedGasMeter := testapp.NewGasMeterWrapper(ctx.GasMeter()) ctx = ctx.WithGasMeter(wrappedGasMeter) @@ -426,7 +429,7 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { 0, 0, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrInvalidAskCount) require.Equal(t, 0, wrappedGasMeter.CountDescriptor("BASE_OWASM_FEE")) @@ -479,7 +482,8 @@ func TestPrepareRequestBaseOwasmFeePanic(t *testing.T) { params := k.GetParams(ctx) params.BaseOwasmGas = 100000 params.PerValidatorRequestGas = 0 - k.SetParams(ctx, params) + err := k.SetParams(ctx, params) + require.NoError(t, err) m := types.NewMsgRequestData( 1, BasicCalldata, @@ -497,7 +501,7 @@ func TestPrepareRequestBaseOwasmFeePanic(t *testing.T) { require.PanicsWithValue( t, sdk.ErrorOutOfGas{Descriptor: "BASE_OWASM_FEE"}, - func() { k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, + func() { _, _ = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, ) ctx = ctx.WithGasMeter(sdk.NewGasMeter(1000000)) id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) @@ -510,7 +514,8 @@ func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { params := k.GetParams(ctx) params.BaseOwasmGas = 100000 params.PerValidatorRequestGas = 50000 - k.SetParams(ctx, params) + err := k.SetParams(ctx, params) + require.NoError(t, err) m := types.NewMsgRequestData( 1, BasicCalldata, @@ -528,7 +533,7 @@ func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { require.PanicsWithValue( t, sdk.ErrorOutOfGas{Descriptor: "PER_VALIDATOR_REQUEST_FEE"}, - func() { k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, + func() { _, _ = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, ) m = types.NewMsgRequestData( 1, @@ -639,12 +644,13 @@ func TestPrepareRequestInvalidDataSourceCount(t *testing.T) { _, ctx, k := testapp.CreateTestInput(true) params := k.GetParams(ctx) params.MaxRawRequestCount = 3 - k.SetParams(ctx, params) + err := k.SetParams(ctx, params) + require.NoError(t, err) m := types.NewMsgRequestData(4, obi.MustEncode(testapp.Wasm4Input{ IDs: []int64{1, 2, 3, 4}, Calldata: "beeb", }), 1, 1, BasicClientID, testapp.Coins100000000uband, testapp.TestDefaultPrepareGas, testapp.TestDefaultExecuteGas, testapp.Alice.Address, 0, 0) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrBadWasmExecution) m = types.NewMsgRequestData(4, obi.MustEncode(testapp.Wasm4Input{ IDs: []int64{1, 2, 3}, @@ -1147,15 +1153,17 @@ func TestCollectFeeWithWithManyUnitSuccess(t *testing.T) { testapp.EmptyCoins, }) - app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(2000000)))) + err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(2000000)))) + require.NoError(t, err) // Carol have not enough uband but have enough uabc - app.BankKeeper.SendCoinsFromModuleToAccount( + err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, testapp.FeePayer.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(2000000))), ) + require.NoError(t, err) coins, err := k.CollectFee( ctx, @@ -1208,35 +1216,42 @@ func TestCollectFeeWithWithManyUnitFail(t *testing.T) { testapp.EmptyCoins, }) - app.BankKeeper.MintCoins( + err := app.BankKeeper.MintCoins( ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(10000000)), sdk.NewCoin("uabc", sdk.NewInt(2000000))), ) + require.NoError(t, err) + // Alice have no enough uband and don't have uabc so don't top up // Bob have enough uband and have some but not enough uabc so add some - app.BankKeeper.SendCoinsFromModuleToAccount( + err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, testapp.Bob.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), ) - app.BankKeeper.SendCoinsFromModuleToAccount( + require.NoError(t, err) + + err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, testapp.Bob.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(1))), ) + require.NoError(t, err) + // Carol have not enough uband but have enough uabc - app.BankKeeper.SendCoinsFromModuleToAccount( + err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, testapp.Carol.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(1000000))), ) + require.NoError(t, err) // Alice - _, err := k.CollectFee( + _, err = k.CollectFee( ctx, testapp.Alice.Address, testapp.MustGetBalances(ctx, app.BankKeeper, testapp.Alice.Address), diff --git a/x/oracle/keeper/params_test.go b/x/oracle/keeper/params_test.go index 9b94a8473..58fdb502a 100644 --- a/x/oracle/keeper/params_test.go +++ b/x/oracle/keeper/params_test.go @@ -25,7 +25,8 @@ func TestGetSetParams(t *testing.T) { InactivePenaltyDuration: 1000, IBCRequestEnabled: true, } - k.SetParams(ctx, expectedParams) + err := k.SetParams(ctx, expectedParams) + require.NoError(t, err) require.Equal(t, expectedParams, k.GetParams(ctx)) expectedParams = types.Params{ @@ -41,7 +42,8 @@ func TestGetSetParams(t *testing.T) { InactivePenaltyDuration: 10000, IBCRequestEnabled: false, } - k.SetParams(ctx, expectedParams) + err = k.SetParams(ctx, expectedParams) + require.NoError(t, err) require.Equal(t, expectedParams, k.GetParams(ctx)) expectedParams = types.Params{ @@ -57,7 +59,8 @@ func TestGetSetParams(t *testing.T) { InactivePenaltyDuration: 0, IBCRequestEnabled: false, } - k.SetParams(ctx, expectedParams) + err = k.SetParams(ctx, expectedParams) + require.NoError(t, err) require.Equal(t, expectedParams, k.GetParams(ctx)) expectedParams = types.Params{ @@ -73,6 +76,6 @@ func TestGetSetParams(t *testing.T) { InactivePenaltyDuration: 10000, IBCRequestEnabled: false, } - err := k.SetParams(ctx, expectedParams) + err = k.SetParams(ctx, expectedParams) require.EqualError(t, fmt.Errorf("max raw request count must be positive: 0"), err.Error()) } diff --git a/x/oracle/keeper/request.go b/x/oracle/keeper/request.go index 1629afa10..f293289c0 100644 --- a/x/oracle/keeper/request.go +++ b/x/oracle/keeper/request.go @@ -76,7 +76,7 @@ func (k Keeper) ProcessExpiredRequests(ctx sdk.Context) { for _, val := range req.RequestedValidators { v, _ := sdk.ValAddressFromBech32(val) if !k.HasReport(ctx, currentReqID, v) { - k.MissReport(ctx, v, time.Unix(int64(req.RequestTime), 0)) + k.MissReport(ctx, v, time.Unix(req.RequestTime, 0)) } } diff --git a/x/oracle/keeper/request_test.go b/x/oracle/keeper/request_test.go index 3dd6831a9..3ad5df372 100644 --- a/x/oracle/keeper/request_test.go +++ b/x/oracle/keeper/request_test.go @@ -230,7 +230,8 @@ func TestProcessExpiredRequests(t *testing.T) { _, ctx, k := testapp.CreateTestInput(true) params := k.GetParams(ctx) params.ExpirationBlockCount = 3 - k.SetParams(ctx, params) + err := k.SetParams(ctx, params) + require.NoError(t, err) // Set some initial requests. All requests are asked to validators 1 & 2. req1 := defaultRequest() @@ -252,13 +253,20 @@ func TestProcessExpiredRequests(t *testing.T) { // Validator 1 reports all requests. Validator 2 misses request#3. rawReports := []types.RawReport{types.NewRawReport(42, 0, BasicReport), types.NewRawReport(43, 0, BasicReport)} - k.AddReport(ctx, 1, testapp.Validators[0].ValAddress, false, rawReports) - k.AddReport(ctx, 2, testapp.Validators[0].ValAddress, true, rawReports) - k.AddReport(ctx, 3, testapp.Validators[0].ValAddress, false, rawReports) - k.AddReport(ctx, 4, testapp.Validators[0].ValAddress, true, rawReports) - k.AddReport(ctx, 1, testapp.Validators[1].ValAddress, true, rawReports) - k.AddReport(ctx, 2, testapp.Validators[1].ValAddress, true, rawReports) - k.AddReport(ctx, 4, testapp.Validators[1].ValAddress, true, rawReports) + err = k.AddReport(ctx, 1, testapp.Validators[0].ValAddress, false, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 2, testapp.Validators[0].ValAddress, true, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 3, testapp.Validators[0].ValAddress, false, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 4, testapp.Validators[0].ValAddress, true, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 1, testapp.Validators[1].ValAddress, true, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 2, testapp.Validators[1].ValAddress, true, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 4, testapp.Validators[1].ValAddress, true, rawReports) + require.NoError(t, err) // Request 1, 2 and 4 gets resolved. Request 3 does not. k.ResolveSuccess(ctx, 1, defaultRequest().Requester, defaultRequest().FeeLimit, BasicResult, 1234, 0, 0) @@ -307,7 +315,7 @@ func TestProcessExpiredRequests(t *testing.T) { require.False(t, k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress).IsActive) require.Equal(t, types.NewResult( BasicClientID, req3.OracleScriptID, req3.Calldata, uint64(len(req3.RequestedValidators)), req3.MinCount, - 3, 1, int64(req3.RequestTime), testapp.ParseTime(9000).Unix(), + 3, 1, req3.RequestTime, testapp.ParseTime(9000).Unix(), types.RESOLVE_STATUS_EXPIRED, nil, ), k.MustGetResult(ctx, 3)) testRequest(t, k, ctx, types.RequestID(1), types.RESOLVE_STATUS_SUCCESS, 0, false) diff --git a/x/oracle/keeper/result.go b/x/oracle/keeper/result.go index b7d579ca0..e344d13b7 100644 --- a/x/oracle/keeper/result.go +++ b/x/oracle/keeper/result.go @@ -153,7 +153,7 @@ func (k Keeper) SaveResult( r.MinCount, // MinCount id, // RequestID reportCount, // AnsCount - int64(r.RequestTime), // RequestTime + r.RequestTime, // RequestTime ctx.BlockTime().Unix(), // ResolveTime status, // ResolveStatus result, // Result @@ -173,7 +173,7 @@ func (k Keeper) SaveResult( } packetData := types.NewOracleResponsePacketData( - r.ClientID, id, reportCount, int64(r.RequestTime), ctx.BlockTime().Unix(), status, result, + r.ClientID, id, reportCount, r.RequestTime, ctx.BlockTime().Unix(), status, result, ) if _, err := k.channelKeeper.SendPacket( diff --git a/x/oracle/keeper/validator_status_test.go b/x/oracle/keeper/validator_status_test.go index 94dbac3f9..8baa5e122 100644 --- a/x/oracle/keeper/validator_status_test.go +++ b/x/oracle/keeper/validator_status_test.go @@ -41,8 +41,8 @@ func defaultVotes() []abci.VoteInfo { func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper) authtypes.ModuleAccountI { // Set collected fee to 1000000uband and 70% oracle reward proportion. feeCollector := app.AccountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) - app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, Coins1000000uband) - app.BankKeeper.SendCoinsFromModuleToModule( + _ = app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, Coins1000000uband) + _ = app.BankKeeper.SendCoinsFromModuleToModule( ctx, minttypes.ModuleName, authtypes.FeeCollectorName, @@ -52,7 +52,7 @@ func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper params := k.GetParams(ctx) params.OracleRewardPercentage = 70 - k.SetParams(ctx, params) + _ = k.SetParams(ctx, params) return feeCollector } @@ -76,7 +76,8 @@ func TestAllocateTokensOneActive(t *testing.T) { require.Equal(t, Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // From 70% of fee, 2% should go to community pool, the rest goes to the only active validator. - k.Activate(ctx, testapp.Validators[1].ValAddress) + err := k.Activate(ctx, testapp.Validators[1].ValAddress) + require.NoError(t, err) k.AllocateTokens(ctx, defaultVotes()) distAccount := app.AccountKeeper.GetModuleAccount(ctx, disttypes.ModuleName) diff --git a/x/oracle/module.go b/x/oracle/module.go index 439ccc599..c7bd3fca6 100644 --- a/x/oracle/module.go +++ b/x/oracle/module.go @@ -5,9 +5,6 @@ import ( "encoding/json" "fmt" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -15,6 +12,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "github.com/bandprotocol/chain/v2/hooks/common" "github.com/bandprotocol/chain/v2/x/oracle/client/cli" @@ -67,7 +66,9 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the oracle module. func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) + if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { + panic(err) + } } // GetTxCmd returns cobra CLI command to send txs for this module (SDK AppModuleBasic interface). diff --git a/x/oracle/types/channel.go b/x/oracle/types/channel.go index 33aa45b30..38fb48171 100644 --- a/x/oracle/types/channel.go +++ b/x/oracle/types/channel.go @@ -1,9 +1,9 @@ package types // NewIBCChannel creates a new IBCChannel instance. -func NewIBCChannel(portId, channelId string) IBCChannel { +func NewIBCChannel(portID, channelID string) IBCChannel { return IBCChannel{ - PortId: portId, - ChannelId: channelId, + PortId: portID, + ChannelId: channelID, } } diff --git a/x/oracle/types/codec.go b/x/oracle/types/codec.go index 533f7d7d2..97a05a621 100644 --- a/x/oracle/types/codec.go +++ b/x/oracle/types/codec.go @@ -6,9 +6,9 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" ) // RegisterLegacyAminoCodec registers the necessary x/oracle interfaces and concrete types diff --git a/x/oracle/types/constants.go b/x/oracle/types/constants.go index 2a0d17688..3a87650be 100644 --- a/x/oracle/types/constants.go +++ b/x/oracle/types/constants.go @@ -1,6 +1,5 @@ package types -// nolint const ( DoNotModify = "[do-not-modify]" @@ -17,7 +16,4 @@ const ( MaximumOwasmGas = 8000000 ) -// nolint -var ( - DoNotModifyBytes = []byte(DoNotModify) -) +var DoNotModifyBytes = []byte(DoNotModify) diff --git a/x/oracle/types/events.go b/x/oracle/types/events.go index cb1b7e8f6..e2de62b56 100644 --- a/x/oracle/types/events.go +++ b/x/oracle/types/events.go @@ -1,6 +1,5 @@ package types -// nolint const ( EventTypeCreateDataSource = "create_data_source" EventTypeEditDataSource = "edit_data_source" diff --git a/x/oracle/types/exec_env.go b/x/oracle/types/exec_env.go index 33a2ce122..a25b736c5 100644 --- a/x/oracle/types/exec_env.go +++ b/x/oracle/types/exec_env.go @@ -44,7 +44,7 @@ func (env *BaseEnv) GetMinCount() int64 { // GetPrepareTime implements Owasm ExecEnv interface. func (env *BaseEnv) GetPrepareTime() int64 { - return int64(env.request.RequestTime) + return env.request.RequestTime } // GetExecuteTime implements Owasm ExecEnv interface. diff --git a/x/oracle/types/exec_env_test.go b/x/oracle/types/exec_env_test.go index dfb785ec8..bc1fdff68 100644 --- a/x/oracle/types/exec_env_test.go +++ b/x/oracle/types/exec_env_test.go @@ -4,11 +4,10 @@ import ( "testing" "time" + "github.com/bandprotocol/go-owasm/api" "github.com/cometbft/cometbft/crypto/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - - "github.com/bandprotocol/go-owasm/api" ) var ( @@ -90,9 +89,9 @@ func mockFreshPrepareEnv() *PrepareEnv { func mockAlreadyPreparedEnv() *PrepareEnv { env := mockFreshPrepareEnv() - env.AskExternalData(1, 1, []byte("CALLDATA1")) - env.AskExternalData(2, 2, []byte("CALLDATA2")) - env.AskExternalData(3, 3, []byte("CALLDATA3")) + _ = env.AskExternalData(1, 1, []byte("CALLDATA1")) + _ = env.AskExternalData(2, 2, []byte("CALLDATA2")) + _ = env.AskExternalData(3, 3, []byte("CALLDATA3")) return env } @@ -114,9 +113,11 @@ func TestSetReturnData(t *testing.T) { require.Equal(t, api.ErrWrongPeriodAction, err) eenv := mockExecEnv() - eenv.SetReturnData(result) + err = eenv.SetReturnData(result) + require.NoError(t, err) require.Equal(t, result, eenv.Retdata) } + func TestGetAskCount(t *testing.T) { // Can call on both environment penv := mockFreshPrepareEnv() @@ -212,9 +213,12 @@ func TestFailedGetExternalData(t *testing.T) { func TestAskExternalData(t *testing.T) { env := mockFreshPrepareEnv() - env.AskExternalData(1, 1, []byte("CALLDATA1")) - env.AskExternalData(42, 2, []byte("CALLDATA2")) - env.AskExternalData(3, 4, []byte("CALLDATA3")) + err := env.AskExternalData(1, 1, []byte("CALLDATA1")) + require.NoError(t, err) + err = env.AskExternalData(42, 2, []byte("CALLDATA2")) + require.NoError(t, err) + err = env.AskExternalData(3, 4, []byte("CALLDATA3")) + require.NoError(t, err) rawReq := env.GetRawRequests() expectRawReq := []RawRequest{ @@ -232,6 +236,7 @@ func TestAskExternalDataOnTooSmallSpan(t *testing.T) { require.Equal(t, api.ErrSpanTooSmall, err) require.Equal(t, []RawRequest(nil), penv.GetRawRequests()) } + func TestAskTooManyExternalData(t *testing.T) { penv := mockFreshPrepareEnv() diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go index 209e09540..0ad180c2d 100644 --- a/x/oracle/types/msgs.go +++ b/x/oracle/types/msgs.go @@ -63,57 +63,57 @@ func NewMsgRequestData( } // Route returns the route of MsgRequestData - "oracle" (sdk.Msg interface). -func (msg MsgRequestData) Route() string { return RouterKey } +func (m MsgRequestData) Route() string { return RouterKey } // Type returns the message type of MsgRequestData (sdk.Msg interface). -func (msg MsgRequestData) Type() string { return TypeMsgRequestData } +func (m MsgRequestData) Type() string { return TypeMsgRequestData } // ValidateBasic checks whether the given MsgRequestData instance (sdk.Msg interface). -func (msg MsgRequestData) ValidateBasic() error { - sender, err := sdk.AccAddressFromBech32(msg.Sender) +func (m MsgRequestData) ValidateBasic() error { + sender, err := sdk.AccAddressFromBech32(m.Sender) if err != nil { return err } if err := sdk.VerifyAddressFormat(sender); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("sender: %s", msg.Sender) + return sdkerrors.ErrInvalidAddress.Wrapf("sender: %s", m.Sender) } - if msg.MinCount <= 0 { - return ErrInvalidMinCount.Wrapf("got: %d", msg.MinCount) + if m.MinCount <= 0 { + return ErrInvalidMinCount.Wrapf("got: %d", m.MinCount) } - if msg.AskCount < msg.MinCount { - return ErrInvalidAskCount.Wrapf("got: %d, min count: %d", msg.AskCount, msg.MinCount) + if m.AskCount < m.MinCount { + return ErrInvalidAskCount.Wrapf("got: %d, min count: %d", m.AskCount, m.MinCount) } - if len(msg.ClientID) > MaxClientIDLength { - return WrapMaxError(ErrTooLongClientID, len(msg.ClientID), MaxClientIDLength) + if len(m.ClientID) > MaxClientIDLength { + return WrapMaxError(ErrTooLongClientID, len(m.ClientID), MaxClientIDLength) } - if msg.PrepareGas <= 0 { - return ErrInvalidOwasmGas.Wrapf("invalid prepare gas: %d", msg.PrepareGas) + if m.PrepareGas <= 0 { + return ErrInvalidOwasmGas.Wrapf("invalid prepare gas: %d", m.PrepareGas) } - if msg.ExecuteGas <= 0 { - return ErrInvalidOwasmGas.Wrapf("invalid execute gas: %d", msg.ExecuteGas) + if m.ExecuteGas <= 0 { + return ErrInvalidOwasmGas.Wrapf("invalid execute gas: %d", m.ExecuteGas) } - if msg.PrepareGas+msg.ExecuteGas > MaximumOwasmGas { + if m.PrepareGas+m.ExecuteGas > MaximumOwasmGas { return ErrInvalidOwasmGas.Wrapf( "sum of prepare gas and execute gas (%d) exceed %d", - msg.PrepareGas+msg.ExecuteGas, + m.PrepareGas+m.ExecuteGas, MaximumOwasmGas, ) } - if !msg.FeeLimit.IsValid() { - return sdkerrors.ErrInvalidCoins.Wrap(msg.FeeLimit.String()) + if !m.FeeLimit.IsValid() { + return sdkerrors.ErrInvalidCoins.Wrap(m.FeeLimit.String()) } return nil } // GetSigners returns the required signers for the given MsgRequestData (sdk.Msg interface). -func (msg MsgRequestData) GetSigners() []sdk.AccAddress { - sender, _ := sdk.AccAddressFromBech32(msg.Sender) +func (m MsgRequestData) GetSigners() []sdk.AccAddress { + sender, _ := sdk.AccAddressFromBech32(m.Sender) return []sdk.AccAddress{sender} } // GetSignBytes returns raw JSON bytes to be signed by the signers (sdk.Msg interface). -func (msg MsgRequestData) GetSignBytes() []byte { - return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg)) +func (m MsgRequestData) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&m)) } // NewMsgReportData creates a new MsgReportData instance @@ -126,25 +126,25 @@ func NewMsgReportData(requestID RequestID, rawReports []RawReport, validator sdk } // Route returns the route of MsgReportData - "oracle" (sdk.Msg interface). -func (msg MsgReportData) Route() string { return RouterKey } +func (m MsgReportData) Route() string { return RouterKey } // Type returns the message type of MsgReportData (sdk.Msg interface). -func (msg MsgReportData) Type() string { return TypeMsgReportData } +func (m MsgReportData) Type() string { return TypeMsgReportData } // ValidateBasic checks whether the given MsgReportData instance (sdk.Msg interface). -func (msg MsgReportData) ValidateBasic() error { - valAddr, err := sdk.ValAddressFromBech32(msg.Validator) +func (m MsgReportData) ValidateBasic() error { + valAddr, err := sdk.ValAddressFromBech32(m.Validator) if err != nil { return err } if err := sdk.VerifyAddressFormat(valAddr); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("validator: %s", msg.Validator) + return sdkerrors.ErrInvalidAddress.Wrapf("validator: %s", m.Validator) } - if len(msg.RawReports) == 0 { + if len(m.RawReports) == 0 { return ErrEmptyReport } uniqueMap := make(map[ExternalID]bool) - for _, r := range msg.RawReports { + for _, r := range m.RawReports { if _, found := uniqueMap[r.ExternalID]; found { return ErrDuplicateExternalID.Wrapf("external id: %d", r.ExternalID) } @@ -154,14 +154,14 @@ func (msg MsgReportData) ValidateBasic() error { } // GetSigners returns the required signers for the given MsgReportData (sdk.Msg interface). -func (msg MsgReportData) GetSigners() []sdk.AccAddress { - validator, _ := sdk.ValAddressFromBech32(msg.Validator) +func (m MsgReportData) GetSigners() []sdk.AccAddress { + validator, _ := sdk.ValAddressFromBech32(m.Validator) return []sdk.AccAddress{sdk.AccAddress(validator)} } // GetSignBytes returns raw JSON bytes to be signed by the signers (sdk.Msg interface). -func (msg MsgReportData) GetSignBytes() []byte { - return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg)) +func (m MsgReportData) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&m)) } // NewMsgCreateDataSource creates a new MsgCreateDataSource instance @@ -180,64 +180,64 @@ func NewMsgCreateDataSource( } // Route returns the route of MsgCreateDataSource - "oracle" (sdk.Msg interface). -func (msg MsgCreateDataSource) Route() string { return RouterKey } +func (m MsgCreateDataSource) Route() string { return RouterKey } // Type returns the message type of MsgCreateDataSource (sdk.Msg interface). -func (msg MsgCreateDataSource) Type() string { return TypeMsgCreateDataSource } +func (m MsgCreateDataSource) Type() string { return TypeMsgCreateDataSource } // ValidateBasic checks whether the given MsgCreateDataSource instance (sdk.Msg interface). -func (msg MsgCreateDataSource) ValidateBasic() error { - treasury, err := sdk.AccAddressFromBech32(msg.Treasury) +func (m MsgCreateDataSource) ValidateBasic() error { + treasury, err := sdk.AccAddressFromBech32(m.Treasury) if err != nil { return err } - owner, err := sdk.AccAddressFromBech32(msg.Owner) + owner, err := sdk.AccAddressFromBech32(m.Owner) if err != nil { return err } - sender, err := sdk.AccAddressFromBech32(msg.Sender) + sender, err := sdk.AccAddressFromBech32(m.Sender) if err != nil { return err } if err := sdk.VerifyAddressFormat(treasury); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("treasury: %s", msg.Treasury) + return sdkerrors.ErrInvalidAddress.Wrapf("treasury: %s", m.Treasury) } if err := sdk.VerifyAddressFormat(owner); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("owner: %s", msg.Owner) + return sdkerrors.ErrInvalidAddress.Wrapf("owner: %s", m.Owner) } if err := sdk.VerifyAddressFormat(sender); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("sender: %s", msg.Sender) + return sdkerrors.ErrInvalidAddress.Wrapf("sender: %s", m.Sender) } - if len(msg.Name) > MaxNameLength { - return WrapMaxError(ErrTooLongName, len(msg.Name), MaxNameLength) + if len(m.Name) > MaxNameLength { + return WrapMaxError(ErrTooLongName, len(m.Name), MaxNameLength) } - if len(msg.Description) > MaxDescriptionLength { - return WrapMaxError(ErrTooLongDescription, len(msg.Description), MaxDescriptionLength) + if len(m.Description) > MaxDescriptionLength { + return WrapMaxError(ErrTooLongDescription, len(m.Description), MaxDescriptionLength) } - if !msg.Fee.IsValid() { - return sdkerrors.ErrInvalidCoins.Wrap(msg.Fee.String()) + if !m.Fee.IsValid() { + return sdkerrors.ErrInvalidCoins.Wrap(m.Fee.String()) } - if len(msg.Executable) == 0 { + if len(m.Executable) == 0 { return ErrEmptyExecutable } - if len(msg.Executable) > MaxExecutableSize { - return WrapMaxError(ErrTooLargeExecutable, len(msg.Executable), MaxExecutableSize) + if len(m.Executable) > MaxExecutableSize { + return WrapMaxError(ErrTooLargeExecutable, len(m.Executable), MaxExecutableSize) } - if bytes.Equal(msg.Executable, DoNotModifyBytes) { + if bytes.Equal(m.Executable, DoNotModifyBytes) { return ErrCreateWithDoNotModify } return nil } // GetSigners returns the required signers for the given MsgCreateDataSource (sdk.Msg interface). -func (msg MsgCreateDataSource) GetSigners() []sdk.AccAddress { - sender, _ := sdk.AccAddressFromBech32(msg.Sender) +func (m MsgCreateDataSource) GetSigners() []sdk.AccAddress { + sender, _ := sdk.AccAddressFromBech32(m.Sender) return []sdk.AccAddress{sender} } // GetSignBytes returns raw JSON bytes to be signed by the signers (sdk.Msg interface). -func (msg MsgCreateDataSource) GetSignBytes() []byte { - return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg)) +func (m MsgCreateDataSource) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&m)) } // NewMsgEditDataSource creates a new MsgEditDataSource instance @@ -262,61 +262,61 @@ func NewMsgEditDataSource( } // Route returns the route of MsgEditDataSource - "oracle" (sdk.Msg interface). -func (msg MsgEditDataSource) Route() string { return RouterKey } +func (m MsgEditDataSource) Route() string { return RouterKey } // Type returns the message type of MsgEditDataSource (sdk.Msg interface). -func (msg MsgEditDataSource) Type() string { return TypeMsgEditDataSource } +func (m MsgEditDataSource) Type() string { return TypeMsgEditDataSource } // ValidateBasic checks whether the given MsgEditDataSource instance (sdk.Msg interface). -func (msg MsgEditDataSource) ValidateBasic() error { - treasury, err := sdk.AccAddressFromBech32(msg.Treasury) +func (m MsgEditDataSource) ValidateBasic() error { + treasury, err := sdk.AccAddressFromBech32(m.Treasury) if err != nil { return err } - owner, err := sdk.AccAddressFromBech32(msg.Owner) + owner, err := sdk.AccAddressFromBech32(m.Owner) if err != nil { return err } - sender, err := sdk.AccAddressFromBech32(msg.Sender) + sender, err := sdk.AccAddressFromBech32(m.Sender) if err != nil { return err } if err := sdk.VerifyAddressFormat(treasury); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("treasury: %s", msg.Treasury) + return sdkerrors.ErrInvalidAddress.Wrapf("treasury: %s", m.Treasury) } if err := sdk.VerifyAddressFormat(owner); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("owner: %s", msg.Owner) + return sdkerrors.ErrInvalidAddress.Wrapf("owner: %s", m.Owner) } if err := sdk.VerifyAddressFormat(sender); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("sender: %s", msg.Sender) + return sdkerrors.ErrInvalidAddress.Wrapf("sender: %s", m.Sender) } - if len(msg.Name) > MaxNameLength { - return WrapMaxError(ErrTooLongName, len(msg.Name), MaxNameLength) + if len(m.Name) > MaxNameLength { + return WrapMaxError(ErrTooLongName, len(m.Name), MaxNameLength) } - if len(msg.Description) > MaxDescriptionLength { - return WrapMaxError(ErrTooLongDescription, len(msg.Description), MaxDescriptionLength) + if len(m.Description) > MaxDescriptionLength { + return WrapMaxError(ErrTooLongDescription, len(m.Description), MaxDescriptionLength) } - if !msg.Fee.IsValid() { - return sdkerrors.ErrInvalidCoins.Wrap(msg.Fee.String()) + if !m.Fee.IsValid() { + return sdkerrors.ErrInvalidCoins.Wrap(m.Fee.String()) } - if len(msg.Executable) == 0 { + if len(m.Executable) == 0 { return ErrEmptyExecutable } - if len(msg.Executable) > MaxExecutableSize { - return WrapMaxError(ErrTooLargeExecutable, len(msg.Executable), MaxExecutableSize) + if len(m.Executable) > MaxExecutableSize { + return WrapMaxError(ErrTooLargeExecutable, len(m.Executable), MaxExecutableSize) } return nil } // GetSigners returns the required signers for the given MsgEditDataSource (sdk.Msg interface). -func (msg MsgEditDataSource) GetSigners() []sdk.AccAddress { - sender, _ := sdk.AccAddressFromBech32(msg.Sender) +func (m MsgEditDataSource) GetSigners() []sdk.AccAddress { + sender, _ := sdk.AccAddressFromBech32(m.Sender) return []sdk.AccAddress{sender} } // GetSignBytes returns raw JSON bytes to be signed by the signers (sdk.Msg interface). -func (msg MsgEditDataSource) GetSignBytes() []byte { - return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg)) +func (m MsgEditDataSource) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&m)) } // NewMsgCreateOracleScript creates a new MsgCreateOracleScript instance @@ -335,60 +335,60 @@ func NewMsgCreateOracleScript( } // Route returns the route of MsgCreateOracleScript - "oracle" (sdk.Msg interface). -func (msg MsgCreateOracleScript) Route() string { return RouterKey } +func (m MsgCreateOracleScript) Route() string { return RouterKey } // Type returns the message type of MsgCreateOracleScript (sdk.Msg interface). -func (msg MsgCreateOracleScript) Type() string { return TypeMsgCreateOracleScript } +func (m MsgCreateOracleScript) Type() string { return TypeMsgCreateOracleScript } // ValidateBasic checks whether the given MsgCreateOracleScript instance (sdk.Msg interface). -func (msg MsgCreateOracleScript) ValidateBasic() error { - owner, err := sdk.AccAddressFromBech32(msg.Owner) +func (m MsgCreateOracleScript) ValidateBasic() error { + owner, err := sdk.AccAddressFromBech32(m.Owner) if err != nil { return err } - sender, err := sdk.AccAddressFromBech32(msg.Sender) + sender, err := sdk.AccAddressFromBech32(m.Sender) if err != nil { return err } if err := sdk.VerifyAddressFormat(owner); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("owner: %s", msg.Owner) + return sdkerrors.ErrInvalidAddress.Wrapf("owner: %s", m.Owner) } if err := sdk.VerifyAddressFormat(sender); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("sender: %s", msg.Sender) + return sdkerrors.ErrInvalidAddress.Wrapf("sender: %s", m.Sender) } - if len(msg.Name) > MaxNameLength { - return WrapMaxError(ErrTooLongName, len(msg.Name), MaxNameLength) + if len(m.Name) > MaxNameLength { + return WrapMaxError(ErrTooLongName, len(m.Name), MaxNameLength) } - if len(msg.Description) > MaxDescriptionLength { - return WrapMaxError(ErrTooLongDescription, len(msg.Description), MaxDescriptionLength) + if len(m.Description) > MaxDescriptionLength { + return WrapMaxError(ErrTooLongDescription, len(m.Description), MaxDescriptionLength) } - if len(msg.Schema) > MaxSchemaLength { - return WrapMaxError(ErrTooLongSchema, len(msg.Schema), MaxSchemaLength) + if len(m.Schema) > MaxSchemaLength { + return WrapMaxError(ErrTooLongSchema, len(m.Schema), MaxSchemaLength) } - if len(msg.SourceCodeURL) > MaxURLLength { - return WrapMaxError(ErrTooLongURL, len(msg.SourceCodeURL), MaxURLLength) + if len(m.SourceCodeURL) > MaxURLLength { + return WrapMaxError(ErrTooLongURL, len(m.SourceCodeURL), MaxURLLength) } - if len(msg.Code) == 0 { + if len(m.Code) == 0 { return ErrEmptyWasmCode } - if len(msg.Code) > MaxWasmCodeSize { - return WrapMaxError(ErrTooLargeWasmCode, len(msg.Code), MaxWasmCodeSize) + if len(m.Code) > MaxWasmCodeSize { + return WrapMaxError(ErrTooLargeWasmCode, len(m.Code), MaxWasmCodeSize) } - if bytes.Equal(msg.Code, DoNotModifyBytes) { + if bytes.Equal(m.Code, DoNotModifyBytes) { return ErrCreateWithDoNotModify } return nil } // GetSigners returns the required signers for the given MsgCreateOracleScript (sdk.Msg interface). -func (msg MsgCreateOracleScript) GetSigners() []sdk.AccAddress { - sender, _ := sdk.AccAddressFromBech32(msg.Sender) +func (m MsgCreateOracleScript) GetSigners() []sdk.AccAddress { + sender, _ := sdk.AccAddressFromBech32(m.Sender) return []sdk.AccAddress{sender} } // GetSignBytes returns raw JSON bytes to be signed by the signers (sdk.Msg interface). -func (msg MsgCreateOracleScript) GetSignBytes() []byte { - return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg)) +func (m MsgCreateOracleScript) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&m)) } // NewMsgEditOracleScript creates a new MsgEditOracleScript instance @@ -411,57 +411,57 @@ func NewMsgEditOracleScript( } // Route returns the route of MsgEditOracleScript - "oracle" (sdk.Msg interface). -func (msg MsgEditOracleScript) Route() string { return RouterKey } +func (m MsgEditOracleScript) Route() string { return RouterKey } // Type returns the message type of MsgEditOracleScript (sdk.Msg interface). -func (msg MsgEditOracleScript) Type() string { return TypeMsgEditOracleScript } +func (m MsgEditOracleScript) Type() string { return TypeMsgEditOracleScript } // ValidateBasic checks whether the given MsgEditOracleScript instance (sdk.Msg interface). -func (msg MsgEditOracleScript) ValidateBasic() error { - owner, err := sdk.AccAddressFromBech32(msg.Owner) +func (m MsgEditOracleScript) ValidateBasic() error { + owner, err := sdk.AccAddressFromBech32(m.Owner) if err != nil { return err } - sender, err := sdk.AccAddressFromBech32(msg.Sender) + sender, err := sdk.AccAddressFromBech32(m.Sender) if err != nil { return err } if err := sdk.VerifyAddressFormat(owner); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("owner: %s", msg.Owner) + return sdkerrors.ErrInvalidAddress.Wrapf("owner: %s", m.Owner) } if err := sdk.VerifyAddressFormat(sender); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("sender: %s", msg.Sender) + return sdkerrors.ErrInvalidAddress.Wrapf("sender: %s", m.Sender) } - if len(msg.Name) > MaxNameLength { - return WrapMaxError(ErrTooLongName, len(msg.Name), MaxNameLength) + if len(m.Name) > MaxNameLength { + return WrapMaxError(ErrTooLongName, len(m.Name), MaxNameLength) } - if len(msg.Description) > MaxDescriptionLength { - return WrapMaxError(ErrTooLongDescription, len(msg.Description), MaxDescriptionLength) + if len(m.Description) > MaxDescriptionLength { + return WrapMaxError(ErrTooLongDescription, len(m.Description), MaxDescriptionLength) } - if len(msg.Schema) > MaxSchemaLength { - return WrapMaxError(ErrTooLongSchema, len(msg.Schema), MaxSchemaLength) + if len(m.Schema) > MaxSchemaLength { + return WrapMaxError(ErrTooLongSchema, len(m.Schema), MaxSchemaLength) } - if len(msg.SourceCodeURL) > MaxURLLength { - return WrapMaxError(ErrTooLongURL, len(msg.SourceCodeURL), MaxURLLength) + if len(m.SourceCodeURL) > MaxURLLength { + return WrapMaxError(ErrTooLongURL, len(m.SourceCodeURL), MaxURLLength) } - if len(msg.Code) == 0 { + if len(m.Code) == 0 { return ErrEmptyWasmCode } - if len(msg.Code) > MaxWasmCodeSize { - return WrapMaxError(ErrTooLargeWasmCode, len(msg.Code), MaxWasmCodeSize) + if len(m.Code) > MaxWasmCodeSize { + return WrapMaxError(ErrTooLargeWasmCode, len(m.Code), MaxWasmCodeSize) } return nil } // GetSigners returns the required signers for the given MsgEditOracleScript (sdk.Msg interface). -func (msg MsgEditOracleScript) GetSigners() []sdk.AccAddress { - sender, _ := sdk.AccAddressFromBech32(msg.Sender) +func (m MsgEditOracleScript) GetSigners() []sdk.AccAddress { + sender, _ := sdk.AccAddressFromBech32(m.Sender) return []sdk.AccAddress{sender} } // GetSignBytes returns raw JSON bytes to be signed by the signers (sdk.Msg interface). -func (msg MsgEditOracleScript) GetSignBytes() []byte { - return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg)) +func (m MsgEditOracleScript) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&m)) } // NewMsgActivate creates a new MsgActivate instance @@ -472,32 +472,32 @@ func NewMsgActivate(validator sdk.ValAddress) *MsgActivate { } // Route returns the route of MsgActivate - "oracle" (sdk.Msg interface). -func (msg MsgActivate) Route() string { return RouterKey } +func (m MsgActivate) Route() string { return RouterKey } // Type returns the message type of MsgActivate (sdk.Msg interface). -func (msg MsgActivate) Type() string { return TypeMsgActivate } +func (m MsgActivate) Type() string { return TypeMsgActivate } // ValidateBasic checks whether the given MsgActivate instance (sdk.Msg interface). -func (msg MsgActivate) ValidateBasic() error { - val, err := sdk.ValAddressFromBech32(msg.Validator) +func (m MsgActivate) ValidateBasic() error { + val, err := sdk.ValAddressFromBech32(m.Validator) if err != nil { return err } if err := sdk.VerifyAddressFormat(val); err != nil { - return sdkerrors.ErrInvalidAddress.Wrapf("validator: %s", msg.Validator) + return sdkerrors.ErrInvalidAddress.Wrapf("validator: %s", m.Validator) } return nil } // GetSigners returns the required signers for the given MsgActivate (sdk.Msg interface). -func (msg MsgActivate) GetSigners() []sdk.AccAddress { - val, _ := sdk.ValAddressFromBech32(msg.Validator) +func (m MsgActivate) GetSigners() []sdk.AccAddress { + val, _ := sdk.ValAddressFromBech32(m.Validator) return []sdk.AccAddress{sdk.AccAddress(val)} } // GetSignBytes returns raw JSON bytes to be signed by the signers (sdk.Msg interface). -func (msg MsgActivate) GetSignBytes() []byte { - return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg)) +func (m MsgActivate) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&m)) } // NewMsgActivate creates a new MsgActivate instance @@ -533,7 +533,7 @@ func (m *MsgUpdateParams) ValidateBasic() error { } // Route returns the route of MsgUpdateParams - "oracle" (sdk.Msg interface). -func (msg MsgUpdateParams) Route() string { return RouterKey } +func (m MsgUpdateParams) Route() string { return RouterKey } // Type returns the message type of MsgUpdateParams (sdk.Msg interface). -func (msg MsgUpdateParams) Type() string { return TypeMsgUpdateParams } +func (m MsgUpdateParams) Type() string { return TypeMsgUpdateParams } diff --git a/x/oracle/types/oracle_script.go b/x/oracle/types/oracle_script.go index 61cd80927..a10d50464 100644 --- a/x/oracle/types/oracle_script.go +++ b/x/oracle/types/oracle_script.go @@ -5,19 +5,19 @@ import ( ) func NewOracleScript( - Owner sdk.AccAddress, - Name string, - Description string, - Filename string, - Schema string, - SourceCodeURL string, + owner sdk.AccAddress, + name string, + description string, + filename string, + schema string, + sourceCodeURL string, ) OracleScript { return OracleScript{ - Owner: Owner.String(), - Name: Name, - Description: Description, - Filename: Filename, - Schema: Schema, - SourceCodeURL: SourceCodeURL, + Owner: owner.String(), + Name: name, + Description: description, + Filename: filename, + Schema: schema, + SourceCodeURL: sourceCodeURL, } } diff --git a/x/oracle/types/params.go b/x/oracle/types/params.go index 1dcbaf5ee..d797df14c 100644 --- a/x/oracle/types/params.go +++ b/x/oracle/types/params.go @@ -7,7 +7,6 @@ import ( "gopkg.in/yaml.v2" ) -// nolint const ( // Each value below is the default value for each parameter when generating the default // genesis file. See comments in types.proto for explanation for each parameter. diff --git a/x/oracle/types/params_legacy.go b/x/oracle/types/params_legacy.go index 3ff56a3c1..a34d45c0c 100644 --- a/x/oracle/types/params_legacy.go +++ b/x/oracle/types/params_legacy.go @@ -9,7 +9,6 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) -// nolint // Parameter store keys var ( // Each value below is the key to store the respective oracle module parameter. See comments diff --git a/x/oracle/types/report.go b/x/oracle/types/report.go index 1bf810e09..f4cc5da8d 100644 --- a/x/oracle/types/report.go +++ b/x/oracle/types/report.go @@ -5,25 +5,25 @@ import ( ) func NewReport( - Validator sdk.ValAddress, - InBeforeResolve bool, - RawReports []RawReport, + validator sdk.ValAddress, + inBeforeResolve bool, + rawReports []RawReport, ) Report { return Report{ - Validator: Validator.String(), - InBeforeResolve: InBeforeResolve, - RawReports: RawReports, + Validator: validator.String(), + InBeforeResolve: inBeforeResolve, + RawReports: rawReports, } } func NewRawReport( - ExternalID ExternalID, - ExitCode uint32, - Data []byte, + externalID ExternalID, + exitCode uint32, + data []byte, ) RawReport { return RawReport{ - ExternalID: ExternalID, - ExitCode: ExitCode, - Data: Data, + ExternalID: externalID, + ExitCode: exitCode, + Data: data, } } diff --git a/x/oracle/types/request.go b/x/oracle/types/request.go index 256b5b6e8..4837acf51 100644 --- a/x/oracle/types/request.go +++ b/x/oracle/types/request.go @@ -28,14 +28,14 @@ type RequestSpec interface { } func NewRawRequest( - ExternalID ExternalID, - DataSourceID DataSourceID, - Calldata []byte, + externalID ExternalID, + dataSourceID DataSourceID, + calldata []byte, ) RawRequest { return RawRequest{ - ExternalID: ExternalID, - DataSourceID: DataSourceID, - Calldata: Calldata, + ExternalID: externalID, + DataSourceID: dataSourceID, + Calldata: calldata, } } diff --git a/x/oracle/types/result.go b/x/oracle/types/result.go index b20868118..4d7d7b8b9 100644 --- a/x/oracle/types/result.go +++ b/x/oracle/types/result.go @@ -40,23 +40,23 @@ var ( // NewResult creates a new Result instance. func NewResult( - clientId string, + clientID string, oid OracleScriptID, calldata []byte, askCount, minCount uint64, - requestId RequestID, + requestID RequestID, ansCount uint64, requestTime, resolveTime int64, resolveStatus ResolveStatus, result []byte, ) Result { return Result{ - ClientID: clientId, + ClientID: clientID, OracleScriptID: oid, Calldata: calldata, AskCount: askCount, MinCount: minCount, - RequestID: requestId, + RequestID: requestID, AnsCount: ansCount, RequestTime: requestTime, ResolveTime: resolveTime, diff --git a/x/oracle/types/validator_status.go b/x/oracle/types/validator_status.go index 7a204fd1c..71fb7db4c 100644 --- a/x/oracle/types/validator_status.go +++ b/x/oracle/types/validator_status.go @@ -3,11 +3,11 @@ package types import "time" func NewValidatorStatus( - IsActive bool, - Since time.Time, + isActive bool, + since time.Time, ) ValidatorStatus { return ValidatorStatus{ - IsActive: IsActive, - Since: Since, + IsActive: isActive, + Since: since, } } diff --git a/x/rollingseed/abci_test.go b/x/rollingseed/abci_test.go index 4621d2404..9cf1f28eb 100644 --- a/x/rollingseed/abci_test.go +++ b/x/rollingseed/abci_test.go @@ -4,9 +4,10 @@ import ( "encoding/hex" "testing" - "github.com/bandprotocol/chain/v2/testing/testapp" abci "github.com/cometbft/cometbft/abci/types" "github.com/stretchr/testify/require" + + "github.com/bandprotocol/chain/v2/testing/testapp" ) func fromHex(hexStr string) []byte { diff --git a/x/rollingseed/module.go b/x/rollingseed/module.go index 3e44b23b7..cd0f84ac3 100644 --- a/x/rollingseed/module.go +++ b/x/rollingseed/module.go @@ -45,7 +45,7 @@ func (AppModuleBasic) GetQueryCmd() *cobra.Command { } // GetTxCmd returns the transaction commands for the rollingseed module. -func (b AppModuleBasic) GetTxCmd() *cobra.Command { +func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } @@ -53,7 +53,7 @@ func (b AppModuleBasic) GetTxCmd() *cobra.Command { func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) {} // RegisterInterfaces registers the rollingseed module's interface types -func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) {} +func (AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) {} // RegisterLegacyAminoCodec registers the rollingseed module's types for the given codec. func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} diff --git a/x/tss/client/cli/tx.go b/x/tss/client/cli/tx.go index f73c15743..66abb51ca 100644 --- a/x/tss/client/cli/tx.go +++ b/x/tss/client/cli/tx.go @@ -457,8 +457,8 @@ func GetTxCmdRequestSignature() *cobra.Command { cmd.PersistentFlags().String(flagFeeLimit, "", "The maximum tokens that will be paid for this request") cmd.PersistentFlags().Uint64(flagGroupID, 0, "The group that is requested to sign the result") - cmd.MarkPersistentFlagRequired(flagGroupID) - cmd.MarkPersistentFlagRequired(flagFeeLimit) + _ = cmd.MarkPersistentFlagRequired(flagFeeLimit) + _ = cmd.MarkPersistentFlagRequired(flagGroupID) return cmd } diff --git a/x/tss/genesis.go b/x/tss/genesis.go index 83801a460..f28e18b87 100644 --- a/x/tss/genesis.go +++ b/x/tss/genesis.go @@ -9,7 +9,9 @@ import ( // InitGenesis performs genesis initialization for the tss module. func InitGenesis(ctx sdk.Context, k *keeper.Keeper, data *types.GenesisState) { - k.SetParams(ctx, data.Params) + if err := k.SetParams(ctx, data.Params); err != nil { + panic(err) + } k.SetGroupCount(ctx, data.GroupCount) for _, group := range data.Groups { diff --git a/x/tss/keeper/de_test.go b/x/tss/keeper/de_test.go index 7d4b3e88d..55c58f83d 100644 --- a/x/tss/keeper/de_test.go +++ b/x/tss/keeper/de_test.go @@ -168,7 +168,8 @@ func (s *KeeperTestSuite) TestHandleSetDEs() { } // Handle setting DEs - k.HandleSetDEs(ctx, address, des) + err := k.HandleSetDEs(ctx, address, des) + s.Require().NoError(err) // Get DEQueue deQueue := k.GetDEQueue(ctx, address) @@ -194,7 +195,8 @@ func (s *KeeperTestSuite) TestPollDE() { index := uint64(1) // Set DE and DEQueue - k.HandleSetDEs(ctx, address, des) + err := k.HandleSetDEs(ctx, address, des) + s.Require().NoError(err) // Poll DE polledDE, err := k.PollDE(ctx, address) @@ -240,7 +242,8 @@ func (s *KeeperTestSuite) TestHandlePollDEForAssignedMembers() { for _, m := range members { accM := sdk.MustAccAddressFromBech32(m.Address) - k.HandleSetDEs(ctx, accM, des) + err := k.HandleSetDEs(ctx, accM, des) + s.Require().NoError(err) } assignedMembers, err := k.HandleAssignedMembersPollDE(ctx, members) diff --git a/x/tss/keeper/grpc_query.go b/x/tss/keeper/grpc_query.go index dabc82181..1d6aa911e 100644 --- a/x/tss/keeper/grpc_query.go +++ b/x/tss/keeper/grpc_query.go @@ -380,7 +380,6 @@ func (q queryServer) Replacements( }, func() *types.Replacement { return &types.Replacement{} }) - if err != nil { return nil, status.Error(codes.Internal, err.Error()) } diff --git a/x/tss/keeper/grpc_query_test.go b/x/tss/keeper/grpc_query_test.go index 504c7f67a..86bec13cf 100644 --- a/x/tss/keeper/grpc_query_test.go +++ b/x/tss/keeper/grpc_query_test.go @@ -5,11 +5,12 @@ import ( "fmt" "time" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/authz" + "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" "github.com/bandprotocol/chain/v2/x/tss/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/authz" ) func (s *KeeperTestSuite) TestGRPCQueryCounts() { @@ -36,13 +37,16 @@ func (s *KeeperTestSuite) TestGRPCQueryGroup() { for _, m := range members { address := sdk.MustAccAddressFromBech32(m) - k.SetActiveStatus(ctx, sdk.MustAccAddressFromBech32(m)) - k.HandleSetDEs(ctx, address, []types.DE{ + err := k.SetActiveStatus(ctx, sdk.MustAccAddressFromBech32(m)) + s.Require().NoError(err) + + err = k.HandleSetDEs(ctx, address, []types.DE{ { PubD: testutil.HexDecode("dddd"), PubE: testutil.HexDecode("eeee"), }, }) + s.Require().NoError(err) } round1Info1 := types.Round1Info{ @@ -118,11 +122,12 @@ func (s *KeeperTestSuite) TestGRPCQueryGroup() { OwnPubKeySig: []byte("own_pub_key_sig"), } - msgSrvr.CreateGroup(ctx, &types.MsgCreateGroup{ + _, err := msgSrvr.CreateGroup(ctx, &types.MsgCreateGroup{ Members: members, Threshold: 3, Authority: s.authority.String(), }) + s.Require().NoError(err) // Add round 1 infos k.AddRound1Info(ctx, groupID, round1Info1) @@ -359,7 +364,8 @@ func (s *KeeperTestSuite) TestGRPCQueryIsGrantee() { // Save grant msgs to grantee for _, m := range types.GetTSSGrantMsgTypes() { - authzKeeper.SaveGrant(s.ctx, grantee, granter, authz.NewGenericAuthorization(m), &expTime) + err := authzKeeper.SaveGrant(s.ctx, grantee, granter, authz.NewGenericAuthorization(m), &expTime) + s.Require().NoError(err) } var req types.QueryIsGranteeRequest diff --git a/x/tss/keeper/keeper.go b/x/tss/keeper/keeper.go index 2c8bf67ae..4b4a4d320 100644 --- a/x/tss/keeper/keeper.go +++ b/x/tss/keeper/keeper.go @@ -629,8 +629,8 @@ func (k Keeper) InsertReplacementQueue(ctx sdk.Context, replacementID uint64, en } // RemoveFromReplacementQueue removes a replacementID from the replacement queue. -func (keeper Keeper) RemoveFromReplacementQueue(ctx sdk.Context, replacementID uint64, endTime time.Time) { - ctx.KVStore(keeper.storeKey).Delete(types.ReplacementQueueKey(replacementID, endTime)) +func (k Keeper) RemoveFromReplacementQueue(ctx sdk.Context, replacementID uint64, endTime time.Time) { + ctx.KVStore(k.storeKey).Delete(types.ReplacementQueueKey(replacementID, endTime)) } // IterateReplacementQueue iterates over the replacements in the active proposal replacement group queue. diff --git a/x/tss/keeper/keeper_test.go b/x/tss/keeper/keeper_test.go index b871d24c8..420991633 100644 --- a/x/tss/keeper/keeper_test.go +++ b/x/tss/keeper/keeper_test.go @@ -219,7 +219,8 @@ func (s *KeeperTestSuite) TestIsGrantee() { // Save grant msgs to grantee for _, m := range types.GetTSSGrantMsgTypes() { - s.app.AuthzKeeper.SaveGrant(ctx, grantee, granter, authz.NewGenericAuthorization(m), &expTime) + err := s.app.AuthzKeeper.SaveGrant(ctx, grantee, granter, authz.NewGenericAuthorization(m), &expTime) + s.Require().NoError(err) } isGrantee := k.CheckIsGrantee(ctx, granter, grantee) diff --git a/x/tss/keeper/msg_server_test.go b/x/tss/keeper/msg_server_test.go index c75071a23..44606977c 100644 --- a/x/tss/keeper/msg_server_test.go +++ b/x/tss/keeper/msg_server_test.go @@ -33,10 +33,12 @@ func (s *KeeperTestSuite) TestCreateGroupReq() { } for _, m := range members { - msgSrvr.Activate(ctx, &types.MsgActivate{ + _, err := msgSrvr.Activate(ctx, &types.MsgActivate{ Address: m, }) - msgSrvr.SubmitDEs(ctx, &types.MsgSubmitDEs{ + s.Require().NoError(err) + + _, err = msgSrvr.SubmitDEs(ctx, &types.MsgSubmitDEs{ DEs: []types.DE{ { PubD: testutil.HexDecode("dddd"), @@ -45,6 +47,7 @@ func (s *KeeperTestSuite) TestCreateGroupReq() { }, Address: m, }) + s.Require().NoError(err) } s.Run("create group", func() { diff --git a/x/tss/keeper/params.go b/x/tss/keeper/params.go index 65d1ad82a..5d9ed991a 100644 --- a/x/tss/keeper/params.go +++ b/x/tss/keeper/params.go @@ -1,8 +1,9 @@ package keeper import ( - "github.com/bandprotocol/chain/v2/x/tss/types" sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/tss/types" ) // GetParams returns the current x/council module parameters. diff --git a/x/tss/keeper/params_test.go b/x/tss/keeper/params_test.go index 81b91dbe4..72a1098dc 100644 --- a/x/tss/keeper/params_test.go +++ b/x/tss/keeper/params_test.go @@ -8,7 +8,8 @@ func (s *KeeperTestSuite) TestGetSetParams() { ctx, k := s.ctx, s.app.TSSKeeper params := types.DefaultParams() - k.SetParams(ctx, params) + err := k.SetParams(ctx, params) + s.Require().NoError(err) s.Require().Equal(params, k.GetParams(ctx)) } diff --git a/x/tss/keeper/signing_test.go b/x/tss/keeper/signing_test.go index b768d88b0..9a1f9d859 100644 --- a/x/tss/keeper/signing_test.go +++ b/x/tss/keeper/signing_test.go @@ -1,11 +1,12 @@ package keeper_test import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" "github.com/bandprotocol/chain/v2/testing/testapp" "github.com/bandprotocol/chain/v2/x/tss/types" - sdk "github.com/cosmos/cosmos-sdk/types" ) func (s *KeeperTestSuite) TestGetSetSigningCount() { diff --git a/x/tss/keeper/validator_test.go b/x/tss/keeper/validator_test.go index 8ade686e3..84e847bab 100644 --- a/x/tss/keeper/validator_test.go +++ b/x/tss/keeper/validator_test.go @@ -37,28 +37,36 @@ func defaultVotes() []abci.VoteInfo { }} } -func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper) authtypes.ModuleAccountI { +func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper) (authtypes.ModuleAccountI, error) { // Set collected fee to 1000000uband and 50% tss reward proportion. feeCollector := app.AccountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) - app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, Coins1000000uband) - app.BankKeeper.SendCoinsFromModuleToModule( + if err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, Coins1000000uband); err != nil { + return nil, err + } + + if err := app.BankKeeper.SendCoinsFromModuleToModule( ctx, minttypes.ModuleName, authtypes.FeeCollectorName, Coins1000000uband, - ) + ); err != nil { + return nil, err + } app.AccountKeeper.SetAccount(ctx, feeCollector) params := k.GetParams(ctx) params.RewardPercentage = 50 - k.SetParams(ctx, params) + if err := k.SetParams(ctx, params); err != nil { + return nil, err + } - return feeCollector + return feeCollector, nil } func (s *KeeperTestSuite) TestAllocateTokenNoActiveValidators() { app, ctx, k := testapp.CreateTestInput(false) - feeCollector := SetupFeeCollector(app, ctx, app.TSSKeeper) + feeCollector, err := SetupFeeCollector(app, ctx, app.TSSKeeper) + s.Require().NoError(err) s.Require().Equal(Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // No active tss validators so nothing should happen. @@ -72,17 +80,22 @@ func (s *KeeperTestSuite) TestAllocateTokenNoActiveValidators() { func (s *KeeperTestSuite) TestAllocateTokensOneActive() { app, ctx, _ := testapp.CreateTestInput(false) k := app.TSSKeeper - feeCollector := SetupFeeCollector(app, ctx, app.TSSKeeper) + feeCollector, err := SetupFeeCollector(app, ctx, app.TSSKeeper) + s.Require().NoError(err) s.Require().Equal(Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // From 50% of fee, 1% should go to community pool, the rest goes to the only active validator. - k.HandleSetDEs(ctx, testapp.Validators[1].Address, []types.DE{ + err = k.HandleSetDEs(ctx, testapp.Validators[1].Address, []types.DE{ { PubD: testutil.HexDecode("dddd"), PubE: testutil.HexDecode("eeee"), }, }) - k.SetActiveStatus(ctx, testapp.Validators[1].Address) + s.Require().NoError(err) + + err = k.SetActiveStatus(ctx, testapp.Validators[1].Address) + s.Require().NoError(err) + k.AllocateTokens(ctx, defaultVotes()) distAccount := app.AccountKeeper.GetModuleAccount(ctx, disttypes.ModuleName) @@ -108,7 +121,8 @@ func (s *KeeperTestSuite) TestAllocateTokensOneActive() { func (s *KeeperTestSuite) TestAllocateTokensAllActive() { ctx, app, k := s.ctx, s.app, s.app.TSSKeeper - feeCollector := SetupFeeCollector(app, ctx, k) + feeCollector, err := SetupFeeCollector(app, ctx, k) + s.Require().NoError(err) s.Require().Equal(Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // From 50% of fee, 1% should go to community pool, the rest get split to validators. diff --git a/x/tss/module.go b/x/tss/module.go index 6d1a13462..815497bb5 100644 --- a/x/tss/module.go +++ b/x/tss/module.go @@ -73,11 +73,13 @@ func getSignatureOrderCLIHandlers(handlers []tssclient.SignatureOrderHandler) [] // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the tss module. func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) + if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { + panic(err) + } } // RegisterInterfaces registers the tss module's interface types -func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { +func (AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { types.RegisterInterfaces(reg) } diff --git a/x/tss/types/helpers_test.go b/x/tss/types/helpers_test.go index 6ba5cc63c..b94cb24b7 100644 --- a/x/tss/types/helpers_test.go +++ b/x/tss/types/helpers_test.go @@ -3,8 +3,9 @@ package types_test import ( "testing" - "github.com/bandprotocol/chain/v2/x/tss/types" "github.com/stretchr/testify/require" + + "github.com/bandprotocol/chain/v2/x/tss/types" ) func TestDuplicateInArray(t *testing.T) { diff --git a/x/tss/types/keys.go b/x/tss/types/keys.go index 0932b47ba..b9fa5c880 100644 --- a/x/tss/types/keys.go +++ b/x/tss/types/keys.go @@ -27,10 +27,9 @@ const ( ) var ( + // ReplaceGroupMsgPrefix is the prefix for replace group msg. ReplaceGroupMsgPrefix = tss.Hash([]byte(ReplaceGroupPath))[:4] -) -var ( // GlobalStoreKeyPrefix is the prefix for global primitive state variables. GlobalStoreKeyPrefix = []byte{0x00} @@ -245,7 +244,7 @@ func ReplacementQueueByTimeKey(endTime time.Time) []byte { } func ReplacementQueueKey(replacementID uint64, endTime time.Time) []byte { - return append(ReplacementQueueByTimeKey(endTime), sdk.Uint64ToBigEndian(uint64(replacementID))...) + return append(ReplacementQueueByTimeKey(endTime), sdk.Uint64ToBigEndian(replacementID)...) } func SplitReplacementQueueKey(key []byte) (replacementID uint64, endTime time.Time) { diff --git a/x/tss/types/router.go b/x/tss/types/router.go index 3abb525bf..f9a775716 100644 --- a/x/tss/types/router.go +++ b/x/tss/types/router.go @@ -4,8 +4,9 @@ import ( "fmt" "cosmossdk.io/errors" - tsslib "github.com/bandprotocol/chain/v2/pkg/tss" sdk "github.com/cosmos/cosmos-sdk/types" + + tsslib "github.com/bandprotocol/chain/v2/pkg/tss" ) type Router struct { diff --git a/yoda/execute.go b/yoda/execute.go index b1c953e6e..9f753c714 100644 --- a/yoda/execute.go +++ b/yoda/execute.go @@ -21,10 +21,8 @@ import ( "github.com/bandprotocol/chain/v2/x/oracle/types" ) -var ( - // Proto codec for encoding/decoding proto message - cdc = band.MakeEncodingConfig().Marshaler -) +// Proto codec for encoding/decoding proto message +var cdc = band.MakeEncodingConfig().Marshaler func signAndBroadcast( c *Context, key *keyring.Record, msgs []sdk.Msg, gasLimit uint64, memo string, diff --git a/yoda/executor/docker.go b/yoda/executor/docker.go index fdd65961b..5704b8632 100644 --- a/yoda/executor/docker.go +++ b/yoda/executor/docker.go @@ -30,7 +30,7 @@ func (e *DockerExec) Exec(code []byte, arg string, env interface{}) (ExecResult, return ExecResult{}, err } defer os.RemoveAll(dir) - err = os.WriteFile(filepath.Join(dir, "exec"), code, 0777) + err = os.WriteFile(filepath.Join(dir, "exec"), code, 0o600) if err != nil { return ExecResult{}, err } @@ -54,7 +54,7 @@ func (e *DockerExec) Exec(code []byte, arg string, env interface{}) (ExecResult, cmd.Stderr = &buf err = cmd.Run() if ctx.Err() == context.DeadlineExceeded { - exec.Command("docker", "kill", name).Start() + _ = exec.Command("docker", "kill", name).Start() return ExecResult{}, ErrExecutionimeout } exitCode := uint32(0) diff --git a/yoda/executor/executor.go b/yoda/executor/executor.go index 1eddaa24b..e4a7df03f 100644 --- a/yoda/executor/executor.go +++ b/yoda/executor/executor.go @@ -54,7 +54,6 @@ func NewExecutor(executor string) (exec Executor, err error) { "BAND_REPORTER": "test-reporter", "BAND_SIGNATURE": "test-signature", }) - if err != nil { return nil, fmt.Errorf("failed to run test program: %s", err.Error()) } @@ -64,6 +63,7 @@ func NewExecutor(executor string) (exec Executor, err error) { if string(res.Output) != "TEST_ARG test-chain-id\n" { return nil, fmt.Errorf("test program returned wrong output: %s", res.Output) } + return exec, nil } diff --git a/yoda/executor/rest.go b/yoda/executor/rest.go index 5e01bdb1d..1c3892792 100644 --- a/yoda/executor/rest.go +++ b/yoda/executor/rest.go @@ -41,7 +41,6 @@ func (e *RestExec) Exec(code []byte, arg string, env interface{}) (ExecResult, e RequestTimeout: e.timeout, }, ) - if err != nil { urlErr, ok := err.(*url.Error) if !ok || !urlErr.Timeout() { @@ -57,7 +56,6 @@ func (e *RestExec) Exec(code []byte, arg string, env interface{}) (ExecResult, e r := externalExecutionResponse{} err = resp.JSON(&r) - if err != nil { return ExecResult{}, err } diff --git a/yoda/executor/rest_test.go b/yoda/executor/rest_test.go index 2be616afa..f50fad80f 100644 --- a/yoda/executor/rest_test.go +++ b/yoda/executor/rest_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" ) -func creatDefaultServer() *httptest.Server { +func createDefaultServer() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(200) ret := externalExecutionResponse{ @@ -18,24 +18,24 @@ func creatDefaultServer() *httptest.Server { Stdout: "BEEB", Stderr: "Stderr", } - json.NewEncoder(res).Encode(ret) + _ = json.NewEncoder(res).Encode(ret) })) } -func createResponseNotOkSenarioServer() *httptest.Server { +func createResponseNotOkScenarioServer() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(500) })) } -func createCannotDecodeJsonSenarioServer() *httptest.Server { +func createCannotDecodeJSONScenarioServer() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(200) - res.Write([]byte("invalid bytes")) + _, _ = res.Write([]byte("invalid bytes")) })) } -func creatExecuteFailSenarioServer() *httptest.Server { +func createExecuteFailScenarioServer() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(200) ret := externalExecutionResponse{ @@ -43,12 +43,12 @@ func creatExecuteFailSenarioServer() *httptest.Server { Stdout: "BEEB", Stderr: "Stderr", } - json.NewEncoder(res).Encode(ret) + _ = json.NewEncoder(res).Encode(ret) })) } func TestExecuteSuccess(t *testing.T) { - testServer := creatDefaultServer() + testServer := createDefaultServer() defer func() { testServer.Close() }() executor := NewRestExec(testServer.URL, 1*time.Second) @@ -59,7 +59,7 @@ func TestExecuteSuccess(t *testing.T) { } func TestExecuteBadUrlFail(t *testing.T) { - testServer := creatDefaultServer() + testServer := createDefaultServer() defer func() { testServer.Close() }() executor := NewRestExec("www.beeb.com", 1*time.Second) // bad url @@ -68,7 +68,7 @@ func TestExecuteBadUrlFail(t *testing.T) { } func TestExecuteDecodeStructFail(t *testing.T) { - testServer := createCannotDecodeJsonSenarioServer() + testServer := createCannotDecodeJSONScenarioServer() defer func() { testServer.Close() }() executor := NewRestExec(testServer.URL, 1*time.Second) @@ -77,7 +77,7 @@ func TestExecuteDecodeStructFail(t *testing.T) { } func TestExecuteResponseNotOk(t *testing.T) { - testServer := createResponseNotOkSenarioServer() + testServer := createResponseNotOkScenarioServer() defer func() { testServer.Close() }() executor := NewRestExec(testServer.URL, 1*time.Second) @@ -86,7 +86,7 @@ func TestExecuteResponseNotOk(t *testing.T) { } func TestExecuteFail(t *testing.T) { - testServer := creatExecuteFailSenarioServer() + testServer := createExecuteFailScenarioServer() defer func() { testServer.Close() }() executor := NewRestExec(testServer.URL, 1*time.Second) diff --git a/yoda/gas.go b/yoda/gas.go index fbcbcb429..0b4591fcb 100644 --- a/yoda/gas.go +++ b/yoda/gas.go @@ -107,7 +107,7 @@ func estimateReportHandlerGas(msg *types.MsgReportData, f FeeEstimationData) uin } func estimateAuthAnteHandlerGas(c *Context, msgs []sdk.Msg) uint64 { - gas := uint64(baseAuthAnteGas) + gas := baseAuthAnteGas txByteLength := getTxByteLength(msgs) gas += txCostPerByte * txByteLength diff --git a/yoda/handler.go b/yoda/handler.go index 7a72cbc54..6e0182e42 100644 --- a/yoda/handler.go +++ b/yoda/handler.go @@ -112,7 +112,7 @@ func handleRequest(c *Context, l *Logger, id types.RequestID) { reports, execVersions := handleRawRequests(c, l, id, rawRequests, key) c.pendingMsgs <- ReportMsgWithKey{ - msg: types.NewMsgReportData(types.RequestID(id), reports, c.validator), + msg: types.NewMsgReportData(id, reports, c.validator), execVersion: execVersions, keyIndex: keyIndex, feeEstimationData: FeeEstimationData{ @@ -139,7 +139,7 @@ func handleRawRequests( l.With("did", req.dataSourceID, "eid", req.externalID), req, key, - types.RequestID(id), + id, resultsChan, ) } diff --git a/yoda/keys.go b/yoda/keys.go index 958f6892a..b202426c2 100644 --- a/yoda/keys.go +++ b/yoda/keys.go @@ -186,7 +186,7 @@ func keysListCmd(c *Context) *cobra.Command { }, } cmd.Flags().BoolP(flagAddress, "a", false, "Output the address only") - viper.BindPFlag(flagAddress, cmd.Flags().Lookup(flagAddress)) + _ = viper.BindPFlag(flagAddress, cmd.Flags().Lookup(flagAddress)) flags.AddQueryFlagsToCmd(cmd) diff --git a/yoda/metrics.go b/yoda/metrics.go index 5d054f475..0f38118c4 100644 --- a/yoda/metrics.go +++ b/yoda/metrics.go @@ -3,6 +3,7 @@ package yoda import ( "net/http" "sync/atomic" + "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" @@ -60,5 +61,13 @@ func metricsListen(listenAddr string, c *Context) { collector := NewYodaCollector(c) prometheus.MustRegister(collector) http.Handle("/metrics", promhttp.Handler()) - panic(http.ListenAndServe(listenAddr, nil)) + + server := &http.Server{ + Addr: listenAddr, + ReadHeaderTimeout: 10 * time.Second, + } + + if err := server.ListenAndServe(); err != nil { + panic(err) + } } diff --git a/yoda/run.go b/yoda/run.go index e21d52f49..2325543a5 100644 --- a/yoda/run.go +++ b/yoda/run.go @@ -31,7 +31,7 @@ func runImpl(c *Context, l *Logger) error { if err != nil { return err } - defer c.client.Stop() + defer c.client.Stop() //nolint:errcheck ctx, cxl := context.WithTimeout(context.Background(), 5*time.Second) defer cxl() @@ -170,15 +170,16 @@ func runCmd(c *Context) *cobra.Command { cmd.Flags().String(flagRPCPollInterval, "1s", "The duration of rpc poll interval") cmd.Flags().Uint64(flagMaxTry, 5, "The maximum number of tries to submit a report transaction") cmd.Flags().Uint64(flagMaxReport, 10, "The maximum number of reports in one transaction") - viper.BindPFlag(flags.FlagChainID, cmd.Flags().Lookup(flags.FlagChainID)) - viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode)) - viper.BindPFlag(flagValidator, cmd.Flags().Lookup(flagValidator)) - viper.BindPFlag(flags.FlagGasPrices, cmd.Flags().Lookup(flags.FlagGasPrices)) - viper.BindPFlag(flagLogLevel, cmd.Flags().Lookup(flagLogLevel)) - viper.BindPFlag(flagExecutor, cmd.Flags().Lookup(flagExecutor)) - viper.BindPFlag(flagBroadcastTimeout, cmd.Flags().Lookup(flagBroadcastTimeout)) - viper.BindPFlag(flagRPCPollInterval, cmd.Flags().Lookup(flagRPCPollInterval)) - viper.BindPFlag(flagMaxTry, cmd.Flags().Lookup(flagMaxTry)) - viper.BindPFlag(flagMaxReport, cmd.Flags().Lookup(flagMaxReport)) + _ = viper.BindPFlag(flags.FlagChainID, cmd.Flags().Lookup(flags.FlagChainID)) + _ = viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode)) + _ = viper.BindPFlag(flagValidator, cmd.Flags().Lookup(flagValidator)) + _ = viper.BindPFlag(flags.FlagGasPrices, cmd.Flags().Lookup(flags.FlagGasPrices)) + _ = viper.BindPFlag(flagLogLevel, cmd.Flags().Lookup(flagLogLevel)) + _ = viper.BindPFlag(flagExecutor, cmd.Flags().Lookup(flagExecutor)) + _ = viper.BindPFlag(flagBroadcastTimeout, cmd.Flags().Lookup(flagBroadcastTimeout)) + _ = viper.BindPFlag(flagRPCPollInterval, cmd.Flags().Lookup(flagRPCPollInterval)) + _ = viper.BindPFlag(flagMaxTry, cmd.Flags().Lookup(flagMaxTry)) + _ = viper.BindPFlag(flagMaxReport, cmd.Flags().Lookup(flagMaxReport)) + return cmd } From 84ff4abcbd11f60a20a2da8b7058a585c2b634f8 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 23 Apr 2024 15:26:46 +0700 Subject: [PATCH 032/132] fix grpc_query test --- x/bandtss/keeper/grpc_query_test.go | 9 +++++++-- x/bandtss/keeper/keeper_test.go | 5 +++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/x/bandtss/keeper/grpc_query_test.go b/x/bandtss/keeper/grpc_query_test.go index 0a2567a80..33ab6ca7b 100644 --- a/x/bandtss/keeper/grpc_query_test.go +++ b/x/bandtss/keeper/grpc_query_test.go @@ -4,11 +4,14 @@ import ( "fmt" "github.com/bandprotocol/chain/v2/x/bandtss/types" + tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) func (s *KeeperTestSuite) TestGRPCQueryMembers() { ctx, q := s.ctx, s.queryClient + s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) + var req types.QueryMembersRequest testCases := []struct { msg string @@ -19,13 +22,15 @@ func (s *KeeperTestSuite) TestGRPCQueryMembers() { { "success", func() { - req = types.QueryMembersRequest{} + req = types.QueryMembersRequest{ + IsActive: true, + } }, true, func(res *types.QueryMembersResponse, err error) { s.Require().NoError(err) s.Require().NotNil(res) - s.Require().Len(res.Members, 3) + s.Require().Len(res.Members, 2) }, }, } diff --git a/x/bandtss/keeper/keeper_test.go b/x/bandtss/keeper/keeper_test.go index abc9f650b..df9d4e0bb 100644 --- a/x/bandtss/keeper/keeper_test.go +++ b/x/bandtss/keeper/keeper_test.go @@ -1,6 +1,7 @@ package keeper_test import ( + "testing" "time" abci "github.com/cometbft/cometbft/abci/types" @@ -231,3 +232,7 @@ func (s *KeeperTestSuite) TestParams() { }) } } + +func TestKeeperTestSuite(t *testing.T) { + suite.Run(t, new(KeeperTestSuite)) +} From 5461758ca0027f09d49d89028deeb81e04d80157 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 23 Apr 2024 15:27:38 +0700 Subject: [PATCH 033/132] fix hook_test --- x/bandtss/keeper/hooks_test.go | 60 +++++++++++++++++++++++++--------- 1 file changed, 45 insertions(+), 15 deletions(-) diff --git a/x/bandtss/keeper/hooks_test.go b/x/bandtss/keeper/hooks_test.go index 4bd049a64..1e282178b 100644 --- a/x/bandtss/keeper/hooks_test.go +++ b/x/bandtss/keeper/hooks_test.go @@ -4,7 +4,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bandprotocol/chain/v2/testing/testapp" - "github.com/bandprotocol/chain/v2/x/tss/types" + "github.com/bandprotocol/chain/v2/x/bandtss/types" + tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) func (s *KeeperTestSuite) TestAfterSigningFailed() { @@ -12,59 +13,88 @@ func (s *KeeperTestSuite) TestAfterSigningFailed() { hook := k.Hooks() testCases := []struct { - name string - signing types.Signing - expCoins sdk.Coins + name string + signing tsstypes.Signing + bandtssSignign types.Signing + expCoins sdk.Coins }{ { "10uband with 2 members", - types.Signing{ + tsstypes.Signing{ ID: 1, GroupID: 1, - AssignedMembers: []types.AssignedMember{ + AssignedMembers: []tsstypes.AssignedMember{ {MemberID: 1}, {MemberID: 2}, }, }, + types.Signing{ + ID: 1, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + CurrentGroupSigningID: 1, + Requester: testapp.FeePayer.Address.String(), + }, sdk.NewCoins(sdk.NewInt64Coin("uband", 20)), }, { "10uband,15token with 2 members", - types.Signing{ - ID: 1, + tsstypes.Signing{ + ID: 2, GroupID: 1, - AssignedMembers: []types.AssignedMember{ + AssignedMembers: []tsstypes.AssignedMember{ {MemberID: 1}, {MemberID: 2}, }, }, + types.Signing{ + ID: 2, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10), sdk.NewInt64Coin("token", 15)), + CurrentGroupSigningID: 2, + Requester: testapp.FeePayer.Address.String(), + }, sdk.NewCoins(sdk.NewInt64Coin("uband", 20), sdk.NewInt64Coin("token", 30)), }, { "0uband with 2 members", - types.Signing{ - ID: 2, + tsstypes.Signing{ + ID: 3, GroupID: 1, - AssignedMembers: []types.AssignedMember{ + AssignedMembers: []tsstypes.AssignedMember{ {MemberID: 1}, {MemberID: 2}, }, }, + types.Signing{ + ID: 3, + Fee: sdk.NewCoins(), + CurrentGroupSigningID: 3, + Requester: testapp.FeePayer.Address.String(), + }, sdk.NewCoins(), }, { "10uband with 0 member", - types.Signing{ - ID: 3, + tsstypes.Signing{ + ID: 4, GroupID: 1, - AssignedMembers: []types.AssignedMember{}, + AssignedMembers: []tsstypes.AssignedMember{}, + }, + types.Signing{ + ID: 4, + Fee: sdk.NewCoins(), + CurrentGroupSigningID: 4, + Requester: testapp.FeePayer.Address.String(), }, sdk.NewCoins(), }, } + s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) for _, tc := range testCases { s.Run(tc.name, func() { + k.SetSigning(ctx, tc.bandtssSignign) + k.SetSigningIDMapping(ctx, tc.signing.ID, tc.bandtssSignign.ID) + balancesBefore := s.app.BankKeeper.GetAllBalances(ctx, testapp.FeePayer.Address) balancesModuleBefore := s.app.BankKeeper.GetAllBalances(ctx, k.GetBandtssAccount(ctx).GetAddress()) From 630dc4e6e43f728c8b1709d75b2b5412aa0ff5f4 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 23 Apr 2024 15:29:18 +0700 Subject: [PATCH 034/132] fix member_test --- x/bandtss/keeper/member_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/bandtss/keeper/member_test.go b/x/bandtss/keeper/member_test.go index 019c83d5e..92f688be3 100644 --- a/x/bandtss/keeper/member_test.go +++ b/x/bandtss/keeper/member_test.go @@ -8,7 +8,7 @@ import ( tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) -func (s *KeeperTestSuite) TestSetInActive() { +func (s *KeeperTestSuite) TestDeactivateMember() { ctx, k, tssKeeper := s.ctx, s.app.BandtssKeeper, s.app.TSSKeeper s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) address := sdk.AccAddress(testutil.TestCases[0].Group.Members[0].PubKey()) From fb82a9232af29769e17320334f9f7783d6f0d1a0 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 23 Apr 2024 15:39:39 +0700 Subject: [PATCH 035/132] remove groupID from signingRequest --- benchmark/app_test.go | 5 ++--- benchmark/helper_test.go | 3 +-- benchmark/tss_bench_test.go | 3 +-- scripts/bandtss/request_signature_oracle.sh | 1 - scripts/bandtss/request_signature_text.sh | 1 - x/bandtss/client/cli/tx.go | 11 ++--------- x/bandtss/keeper/msg_server_test.go | 4 ---- x/bandtss/types/msgs.go | 1 - x/oracle/client/cli/tx.go | 9 ++------- x/tss/keeper/msg_server_test.go | 1 - 10 files changed, 8 insertions(+), 31 deletions(-) diff --git a/benchmark/app_test.go b/benchmark/app_test.go index 385415d9d..23646fe00 100644 --- a/benchmark/app_test.go +++ b/benchmark/app_test.go @@ -321,7 +321,7 @@ func (ba *BenchmarkApp) HandleGenPendingSignTxs( return txs } - ba.RequestSignature(ba.Sender, gid, content, feeLimit) + ba.RequestSignature(ba.Sender, content, feeLimit) ba.AddDEs(ba.Gid) return ba.GetPendingSignTxs(gid, tcs) @@ -329,13 +329,12 @@ func (ba *BenchmarkApp) HandleGenPendingSignTxs( func (ba *BenchmarkApp) RequestSignature( sender *Account, - gid tss.GroupID, content tsstypes.Content, feeLimit sdk.Coins, ) { ctx, msgSrvr := ba.Ctx, ba.BandtssMsgSrvr - msg, err := bandtsstypes.NewMsgRequestSignature(gid, content, feeLimit, sender.Address) + msg, err := bandtsstypes.NewMsgRequestSignature(content, feeLimit, sender.Address) require.NoError(ba.TB, err) _, err = msgSrvr.RequestSignature(ctx, msg) diff --git a/benchmark/helper_test.go b/benchmark/helper_test.go index e9c48f60c..e9a236080 100644 --- a/benchmark/helper_test.go +++ b/benchmark/helper_test.go @@ -135,11 +135,10 @@ func MockByte(n int) []byte { func GenMsgRequestSignature( sender *Account, - gid tss.GroupID, content tsstypes.Content, feeLimit sdk.Coins, ) []sdk.Msg { - msg, err := bandtsstypes.NewMsgRequestSignature(gid, content, feeLimit, sender.Address) + msg, err := bandtsstypes.NewMsgRequestSignature(content, feeLimit, sender.Address) if err != nil { panic(err) } diff --git a/benchmark/tss_bench_test.go b/benchmark/tss_bench_test.go index a3ef0346d..7da9056a3 100644 --- a/benchmark/tss_bench_test.go +++ b/benchmark/tss_bench_test.go @@ -41,7 +41,6 @@ func BenchmarkRequestSignatureDeliver(b *testing.B) { ba.TxConfig, GenMsgRequestSignature( ba.Sender, - ba.Gid, tsstypes.NewTextSignatureOrder(msg), tc.feeLimit, ), @@ -137,7 +136,7 @@ func BenchmarkEndBlockHandleProcessSigning(b *testing.B) { ba.CallBeginBlock() // generate tx - ba.RequestSignature(ba.Sender, ba.Gid, tsstypes.NewTextSignatureOrder(msg), tc.feeLimit) + ba.RequestSignature(ba.Sender, tsstypes.NewTextSignatureOrder(msg), tc.feeLimit) // everyone submit signature txs := ba.GetPendingSignTxs(ba.Gid, testutil.TestCases) diff --git a/scripts/bandtss/request_signature_oracle.sh b/scripts/bandtss/request_signature_oracle.sh index 57a1a3d0e..b372f4276 100755 --- a/scripts/bandtss/request_signature_oracle.sh +++ b/scripts/bandtss/request_signature_oracle.sh @@ -6,7 +6,6 @@ export GROUP_ID=1 export ENCODE_TYPE=1 bandd tx bandtss request-signature oracle-result $REQUEST_ID $ENCODE_TYPE \ - --group-id $GROUP_ID \ --from requester --keyring-backend test \ --gas-prices 0.0025uband --fee-limit 100uband \ -b sync -y diff --git a/scripts/bandtss/request_signature_text.sh b/scripts/bandtss/request_signature_text.sh index 446d09c00..f9800d61a 100755 --- a/scripts/bandtss/request_signature_text.sh +++ b/scripts/bandtss/request_signature_text.sh @@ -5,7 +5,6 @@ export TEXT=62616e6470726f746f636f6c export GROUP_ID=1 bandd tx bandtss request-signature text $TEXT \ - --group-id $GROUP_ID \ --from requester --keyring-backend test \ --gas-prices 0.0025uband --fee-limit 100uband \ -b sync -y diff --git a/x/bandtss/client/cli/tx.go b/x/bandtss/client/cli/tx.go index c429cf413..3f2c8a856 100644 --- a/x/bandtss/client/cli/tx.go +++ b/x/bandtss/client/cli/tx.go @@ -14,7 +14,6 @@ import ( "github.com/spf13/cobra" "github.com/bandprotocol/chain/v2/pkg/grant" - "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/x/bandtss/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) @@ -83,9 +82,9 @@ func GetTxCmdTextRequestSignature() *cobra.Command { return &cobra.Command{ Use: "text [message]", Args: cobra.ExactArgs(1), - Short: "request signature of the message from the group", + Short: "request signature of the message from the current group", Example: fmt.Sprintf( - `%s tx bandtss request-signature text [message] --group-id 1 --fee-limit 10uband`, + `%s tx bandtss request-signature text [message] --fee-limit 10uband`, version.AppName, ), RunE: func(cmd *cobra.Command, args []string) error { @@ -94,11 +93,6 @@ func GetTxCmdTextRequestSignature() *cobra.Command { return err } - gid, err := cmd.Flags().GetUint64(flagGroupID) - if err != nil { - return err - } - data, err := hex.DecodeString(args[0]) if err != nil { return err @@ -117,7 +111,6 @@ func GetTxCmdTextRequestSignature() *cobra.Command { } msg, err := types.NewMsgRequestSignature( - tss.GroupID(gid), content, feeLimit, clientCtx.GetFromAddress(), diff --git a/x/bandtss/keeper/msg_server_test.go b/x/bandtss/keeper/msg_server_test.go index 0a1f28e59..8d114728f 100644 --- a/x/bandtss/keeper/msg_server_test.go +++ b/x/bandtss/keeper/msg_server_test.go @@ -148,7 +148,6 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { "failure with invalid groupID", func() { req, err = types.NewMsgRequestSignature( - tss.GroupID(999), // non-existent groupID tsstypes.NewTextSignatureOrder([]byte("msg")), sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), testapp.FeePayer.Address, @@ -170,7 +169,6 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { } k.SetGroup(ctx, inactiveGroup) req, err = types.NewMsgRequestSignature( - tss.GroupID(2), // inactive groupID tsstypes.NewTextSignatureOrder([]byte("msg")), sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), testapp.FeePayer.Address, @@ -184,7 +182,6 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { "failure with not enough fee", func() { req, err = types.NewMsgRequestSignature( - tss.GroupID(1), tsstypes.NewTextSignatureOrder([]byte("msg")), sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), testapp.FeePayer.Address, @@ -239,7 +236,6 @@ func (s *KeeperTestSuite) TestSuccessRequestSignatureReq() { ) msg, err := types.NewMsgRequestSignature( - tc.Group.ID, tsstypes.NewTextSignatureOrder(signing.Data), sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), testapp.FeePayer.Address, diff --git a/x/bandtss/types/msgs.go b/x/bandtss/types/msgs.go index 7b3a629de..de40163d3 100644 --- a/x/bandtss/types/msgs.go +++ b/x/bandtss/types/msgs.go @@ -127,7 +127,6 @@ func (m MsgReplaceGroup) ValidateBasic() error { // NewMsgRequestSignature creates a new MsgRequestSignature. func NewMsgRequestSignature( - gid tss.GroupID, content tsstypes.Content, feeLimit sdk.Coins, sender sdk.AccAddress, diff --git a/x/oracle/client/cli/tx.go b/x/oracle/client/cli/tx.go index da7521007..7ebbd332e 100644 --- a/x/oracle/client/cli/tx.go +++ b/x/oracle/client/cli/tx.go @@ -705,7 +705,7 @@ func GetCmdRequestSignature() *cobra.Command { Long: strings.TrimSpace( fmt.Sprintf(`Request signature from request id. Example: -$ %s tx tss request-signature oracle-result 1 --group-id 1 --fee-limit 10uband +$ %s tx tss request-signature oracle-result 1 --fee-limit 10uband `, version.AppName, ), @@ -716,11 +716,6 @@ $ %s tx tss request-signature oracle-result 1 --group-id 1 --fee-limit 10uband return err } - gid, err := cmd.Flags().GetUint64(flagGroupID) - if err != nil { - return err - } - rid, err := strconv.ParseUint(args[0], 10, 64) if err != nil { return err @@ -744,7 +739,7 @@ $ %s tx tss request-signature oracle-result 1 --group-id 1 --fee-limit 10uband from := clientCtx.GetFromAddress() content := types.NewOracleResultSignatureOrder(types.RequestID(rid), types.EncodeType(encodeType)) - msg, err := bandtsstypes.NewMsgRequestSignature(tss.GroupID(gid), content, feeLimit, from) + msg, err := bandtsstypes.NewMsgRequestSignature(content, feeLimit, from) if err != nil { return err } diff --git a/x/tss/keeper/msg_server_test.go b/x/tss/keeper/msg_server_test.go index 28e4c15ac..a49f77514 100644 --- a/x/tss/keeper/msg_server_test.go +++ b/x/tss/keeper/msg_server_test.go @@ -565,7 +565,6 @@ func (s *KeeperTestSuite) TestSuccessSubmitSignatureReq() { // Request signature for the first member in the group msg, err := bandtsstypes.NewMsgRequestSignature( - tc.Group.ID, types.NewTextSignatureOrder([]byte("msg")), sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), testapp.FeePayer.Address, From 87c7ab73ce76967bd36d641fcc97237256ab453b Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 23 Apr 2024 16:39:31 +0700 Subject: [PATCH 036/132] fix msg_server_test --- x/bandtss/keeper/msg_server_test.go | 121 ++++++++++++++++------------ x/bandtss/keeper/signing.go | 4 + x/bandtss/types/errors.go | 11 +-- 3 files changed, 78 insertions(+), 58 deletions(-) diff --git a/x/bandtss/keeper/msg_server_test.go b/x/bandtss/keeper/msg_server_test.go index 8d114728f..6335b20d5 100644 --- a/x/bandtss/keeper/msg_server_test.go +++ b/x/bandtss/keeper/msg_server_test.go @@ -12,7 +12,6 @@ import ( "github.com/bandprotocol/chain/v2/pkg/tss/testutil" "github.com/bandprotocol/chain/v2/testing/testapp" "github.com/bandprotocol/chain/v2/x/bandtss/types" - tsskeeper "github.com/bandprotocol/chain/v2/x/tss/keeper" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) @@ -23,43 +22,8 @@ type TestCase struct { ExpectedErr error } -func (s *KeeperTestSuite) TestCreateGroupReq() { - ctx, msgSrvr := s.ctx, s.msgSrvr - tssMsgSrvr := tsskeeper.NewMsgServerImpl(s.app.TSSKeeper) - - members := []string{ - "band18gtd9xgw6z5fma06fxnhet7z2ctrqjm3z4k7ad", - "band1s743ydr36t6p29jsmrxm064guklgthsn3t90ym", - "band1p08slm6sv2vqy4j48hddkd6hpj8yp6vlw3pf8p", - "band12jf07lcaj67mthsnklngv93qkeuphhmxst9mh8", - } - - for _, m := range members { - _, err := msgSrvr.Activate(ctx, &types.MsgActivate{ - Address: m, - }) - s.Require().NoError(err) - - _, err = tssMsgSrvr.SubmitDEs(ctx, &tsstypes.MsgSubmitDEs{ - DEs: []tsstypes.DE{ - { - PubD: testutil.HexDecode("dddd"), - PubE: testutil.HexDecode("eeee"), - }, - }, - Address: m, - }) - s.Require().NoError(err) - } - - s.Run("create group", func() { - _, err := msgSrvr.CreateGroup(ctx, &types.MsgCreateGroup{ - Members: members, - Threshold: 3, - Authority: s.authority.String(), - }) - s.Require().NoError(err) - }) +func (s *KeeperTestSuite) TestCreateGroup() { + s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) } func (s *KeeperTestSuite) TestFailedReplaceGroup() { @@ -70,7 +34,8 @@ func (s *KeeperTestSuite) TestFailedReplaceGroup() { var req types.MsgReplaceGroup s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) - group := k.MustGetGroup(ctx, newGroupID) + currentGroupID := s.app.BandtssKeeper.GetCurrentGroupID(ctx) + currentGroup := k.MustGetGroup(ctx, currentGroupID) tcs := []TestCase{ { @@ -94,12 +59,12 @@ func (s *KeeperTestSuite) TestFailedReplaceGroup() { NewGroupID: newGroupID, ExecTime: time.Now().UTC(), } - group.Status = tsstypes.GROUP_STATUS_FALLEN - k.SetGroup(ctx, group) + currentGroup.Status = tsstypes.GROUP_STATUS_FALLEN + k.SetGroup(ctx, currentGroup) }, func() { - group.Status = tsstypes.GROUP_STATUS_ACTIVE - k.SetGroup(ctx, group) + currentGroup.Status = tsstypes.GROUP_STATUS_ACTIVE + k.SetGroup(ctx, currentGroup) }, tsstypes.ErrGroupIsNotActive, }, @@ -145,8 +110,9 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { tcs := []TestCase{ { - "failure with invalid groupID", + "failure with no groupID", func() { + s.app.BandtssKeeper.SetCurrentGroupID(ctx, 0) req, err = types.NewMsgRequestSignature( tsstypes.NewTextSignatureOrder([]byte("msg")), sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), @@ -154,8 +120,10 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { ) s.Require().NoError(err) }, - func() {}, - tsstypes.ErrGroupNotFound, + func() { + s.app.BandtssKeeper.SetCurrentGroupID(ctx, 1) + }, + types.ErrNoActiveGroup, }, { "failure with inactive group", @@ -168,6 +136,8 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { Status: tsstypes.GROUP_STATUS_FALLEN, } k.SetGroup(ctx, inactiveGroup) + s.app.BandtssKeeper.SetCurrentGroupID(ctx, 2) + req, err = types.NewMsgRequestSignature( tsstypes.NewTextSignatureOrder([]byte("msg")), sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), @@ -175,7 +145,9 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { ) s.Require().NoError(err) }, - func() {}, + func() { + s.app.BandtssKeeper.SetCurrentGroupID(ctx, 1) + }, tsstypes.ErrGroupIsNotActive, }, { @@ -212,8 +184,8 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { ) // Check if the balances of payer and module account doesn't change - s.Require().Equal(balancesAfter, balancesBefore) - s.Require().Equal(balancesModuleAfter, balancesModuleBefore) + s.Require().Equal(balancesBefore, balancesAfter) + s.Require().Equal(balancesModuleBefore, balancesModuleAfter) tc.PostTest() }) @@ -221,7 +193,7 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { } func (s *KeeperTestSuite) TestSuccessRequestSignatureReq() { - ctx, msgSrvr := s.ctx, s.msgSrvr + ctx, msgSrvr, k := s.ctx, s.msgSrvr, s.app.BandtssKeeper s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) @@ -229,6 +201,8 @@ func (s *KeeperTestSuite) TestSuccessRequestSignatureReq() { // Request signature for each member in the group s.Run(fmt.Sprintf("success %s", tc.Name), func() { for _, signing := range tc.Signings { + k.SetCurrentGroupID(ctx, tc.Group.ID) + balancesBefore := s.app.BankKeeper.GetAllBalances(ctx, testapp.FeePayer.Address) balancesModuleBefore := s.app.BankKeeper.GetAllBalances( ctx, @@ -252,7 +226,7 @@ func (s *KeeperTestSuite) TestSuccessRequestSignatureReq() { s.app.BandtssKeeper.GetBandtssAccount(ctx).GetAddress(), ) - diff := sdk.NewCoins(sdk.NewInt64Coin("uband", int64(10*len(signing.AssignedMembers)))) + diff := k.GetParams(ctx).Fee.MulInt(sdk.NewInt(int64(len(signing.AssignedMembers)))) s.Require().Equal(diff, balancesBefore.Sub(balancesAfter...)) s.Require().Equal(diff, balancesModuleAfter.Sub(balancesModuleBefore...)) } @@ -266,12 +240,45 @@ func (s *KeeperTestSuite) TestActivateReq() { for _, tc := range testutil.TestCases { s.Run(fmt.Sprintf("success %s", tc.Name), func() { + s.app.BandtssKeeper.SetCurrentGroupID(ctx, tc.Group.ID) + + for _, m := range tc.Group.Members { + addr := sdk.AccAddress(m.PubKey()) + existed := s.app.BandtssKeeper.HasMember(ctx, addr) + if !existed { + err := s.app.BandtssKeeper.AddNewMember(ctx, addr) + s.Require().NoError(err) + } + + existedMember, err := s.app.BandtssKeeper.GetMember(ctx, addr) + s.Require().NoError(err) + if existedMember.IsActive { + err := s.app.BandtssKeeper.DeactivateMember(ctx, addr) + s.Require().NoError(err) + } + } + + // skip time frame. + activeDuration := s.app.BandtssKeeper.GetParams(ctx).ActiveDuration + ctx = ctx.WithBlockTime(ctx.BlockTime().Add(activeDuration)) + for _, m := range tc.Group.Members { - _, err := msgSrvr.Activate(ctx, &types.MsgActivate{ + member, err := s.app.BandtssKeeper.GetMember(ctx, sdk.AccAddress(m.PubKey())) + s.Require().NoError(err) + // There are some test cases in which the members are using the same private key. + if member.IsActive { + continue + } + + _, err = msgSrvr.Activate(ctx, &types.MsgActivate{ Address: sdk.AccAddress(m.PubKey()).String(), }) s.Require().NoError(err) } + + for _, m := range tc.Group.Members { + s.app.BandtssKeeper.DeleteMember(ctx, sdk.AccAddress(m.PubKey())) + } }) } } @@ -282,7 +289,15 @@ func (s *KeeperTestSuite) TestHealthCheckReq() { for _, tc := range testutil.TestCases { s.Run(fmt.Sprintf("success %s", tc.Name), func() { + s.app.BandtssKeeper.SetCurrentGroupID(ctx, tc.Group.ID) for _, m := range tc.Group.Members { + addr := sdk.AccAddress(m.PubKey()) + existed := s.app.BandtssKeeper.HasMember(ctx, addr) + if !existed { + err := s.app.BandtssKeeper.AddNewMember(ctx, addr) + s.Require().NoError(err) + } + _, err := msgSrvr.HealthCheck(ctx, &types.MsgHealthCheck{ Address: sdk.AccAddress(m.PubKey()).String(), }) @@ -317,7 +332,7 @@ func (s *KeeperTestSuite) TestUpdateParams() { ActiveDuration: types.DefaultActiveDuration, RewardPercentage: types.DefaultRewardPercentage, InactivePenaltyDuration: types.DefaultInactivePenaltyDuration, - JailPenaltyDuration: types.DefaultJailPenaltyDuration, + Fee: types.DefaultFee, }, }, expectErr: false, diff --git a/x/bandtss/keeper/signing.go b/x/bandtss/keeper/signing.go index ba80f892c..d4c9115ff 100644 --- a/x/bandtss/keeper/signing.go +++ b/x/bandtss/keeper/signing.go @@ -137,6 +137,10 @@ func (k Keeper) HandleCreateSigning( } currentGroupID := k.GetCurrentGroupID(ctx) + if currentGroupID == 0 { + return 0, types.ErrNoActiveGroup + } + replacement := k.GetReplacement(ctx) currentGroup, err := k.tssKeeper.GetGroup(ctx, currentGroupID) diff --git a/x/bandtss/types/errors.go b/x/bandtss/types/errors.go index babe3928e..6f03afe32 100644 --- a/x/bandtss/types/errors.go +++ b/x/bandtss/types/errors.go @@ -9,9 +9,10 @@ var ( ErrTooSoonToActivate = errors.Register(ModuleName, 4, "too soon to activate") ErrNotEnoughFee = errors.Register(ModuleName, 5, "not enough fee") ErrInvalidGroupID = errors.Register(ModuleName, 6, "invalid groupID") - ErrReplacementInProgress = errors.Register(ModuleName, 7, "group replacement is in progress") - ErrSigningNotFound = errors.Register(ModuleName, 8, "signing not found") - ErrMemberNotFound = errors.Register(ModuleName, 9, "member not found") - ErrMemberAlreadyExists = errors.Register(ModuleName, 10, "member already exists") - ErrMemberAlreadyActive = errors.Register(ModuleName, 11, "member already active") + ErrNoActiveGroup = errors.Register(ModuleName, 7, "no active group") + ErrReplacementInProgress = errors.Register(ModuleName, 8, "group replacement is in progress") + ErrSigningNotFound = errors.Register(ModuleName, 9, "signing not found") + ErrMemberNotFound = errors.Register(ModuleName, 10, "member not found") + ErrMemberAlreadyExists = errors.Register(ModuleName, 11, "member already exists") + ErrMemberAlreadyActive = errors.Register(ModuleName, 12, "member already active") ) From 69b373cee740edafd4a8713af2e72b527fdcab71 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 23 Apr 2024 16:44:30 +0700 Subject: [PATCH 037/132] fix member_test --- x/bandtss/keeper/member_test.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/x/bandtss/keeper/member_test.go b/x/bandtss/keeper/member_test.go index 92f688be3..1bb296c0d 100644 --- a/x/bandtss/keeper/member_test.go +++ b/x/bandtss/keeper/member_test.go @@ -8,7 +8,7 @@ import ( tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) -func (s *KeeperTestSuite) TestDeactivateMember() { +func (s *KeeperTestSuite) TestSetInActive() { ctx, k, tssKeeper := s.ctx, s.app.BandtssKeeper, s.app.TSSKeeper s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) address := sdk.AccAddress(testutil.TestCases[0].Group.Members[0].PubKey()) @@ -31,7 +31,11 @@ func (s *KeeperTestSuite) TestActivateMember() { address := sdk.AccAddress(testutil.TestCases[0].Group.Members[0].PubKey()) // Success case - err := k.ActivateMember(ctx, address) + err := k.DeactivateMember(ctx, address) + s.Require().NoError(err) + ctx = ctx.WithBlockTime(ctx.BlockTime().Add(k.GetParams(ctx).ActiveDuration)) + + err = k.ActivateMember(ctx, address) s.Require().NoError(err) member, err := k.GetMember(ctx, address) From 9a2b580d767a0791f7208ca2c1956606fd7e0de7 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 23 Apr 2024 16:47:57 +0700 Subject: [PATCH 038/132] fix update params --- x/bandtss/keeper/msg_server_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/x/bandtss/keeper/msg_server_test.go b/x/bandtss/keeper/msg_server_test.go index 6335b20d5..a39e421bb 100644 --- a/x/bandtss/keeper/msg_server_test.go +++ b/x/bandtss/keeper/msg_server_test.go @@ -332,6 +332,7 @@ func (s *KeeperTestSuite) TestUpdateParams() { ActiveDuration: types.DefaultActiveDuration, RewardPercentage: types.DefaultRewardPercentage, InactivePenaltyDuration: types.DefaultInactivePenaltyDuration, + JailPenaltyDuration: types.DefaultJailPenaltyDuration, Fee: types.DefaultFee, }, }, From 916f42fd233dc56252e488989626dab9ce38581a Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 23 Apr 2024 17:16:41 +0700 Subject: [PATCH 039/132] fix validator_test --- x/bandtss/keeper/validator_test.go | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/x/bandtss/keeper/validator_test.go b/x/bandtss/keeper/validator_test.go index e967554a2..aff9356a8 100644 --- a/x/bandtss/keeper/validator_test.go +++ b/x/bandtss/keeper/validator_test.go @@ -96,8 +96,9 @@ func (s *KeeperTestSuite) TestAllocateTokensOneActive() { }) s.Require().NoError(err) - err = k.ActivateMember(ctx, testapp.Validators[1].Address) - s.Require().NoError(err) + for _, validator := range testapp.Validators { + k.AddNewMember(ctx, validator.Address) + } k.AllocateTokens(ctx, defaultVotes()) @@ -127,8 +128,14 @@ func (s *KeeperTestSuite) TestAllocateTokensAllActive() { feeCollector, err := SetupFeeCollector(app, ctx, *k) s.Require().NoError(err) - s.Require().Equal(Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) + + for _, validator := range testapp.Validators { + k.AddNewMember(ctx, validator.Address) + deCount := s.app.TSSKeeper.GetDECount(ctx, validator.Address) + s.Require().Greater(deCount, uint64(0)) + } + // From 50% of fee, 1% should go to community pool, the rest get split to validators. k.AllocateTokens(ctx, defaultVotes()) @@ -171,6 +178,12 @@ func (s *KeeperTestSuite) TestHandleInactiveValidators() { LastActive: time.Time{}, } k.SetMember(ctx, member) + s.app.TSSKeeper.SetMember(ctx, tsstypes.Member{ + ID: 1, + GroupID: 1, + Address: address.String(), + IsActive: true, + }) ctx = ctx.WithBlockTime(time.Now()) k.HandleInactiveValidators(ctx) From 74ddb34226a83743652492686c8e4fa52db46db3 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 23 Apr 2024 17:17:09 +0700 Subject: [PATCH 040/132] change payment logic order --- x/bandtss/keeper/signing.go | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/x/bandtss/keeper/signing.go b/x/bandtss/keeper/signing.go index d4c9115ff..e530b980a 100644 --- a/x/bandtss/keeper/signing.go +++ b/x/bandtss/keeper/signing.go @@ -150,9 +150,10 @@ func (k Keeper) HandleCreateSigning( // charged fee if necessary; If found any coins that exceed limit then return error feePerSigner := sdk.NewCoins() + totalFee := sdk.NewCoins() if sender.String() != k.authority { feePerSigner = k.GetParams(ctx).Fee - totalFee := feePerSigner.MulInt(sdk.NewInt(int64(currentGroup.Threshold))) + totalFee = feePerSigner.MulInt(sdk.NewInt(int64(currentGroup.Threshold))) for _, fc := range totalFee { limitAmt := feeLimit.AmountOf(fc.Denom) if fc.Amount.GT(limitAmt) { @@ -164,14 +165,6 @@ func (k Keeper) HandleCreateSigning( ) } } - - // transfer fee to module account. - if !totalFee.IsZero() { - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, totalFee) - if err != nil { - return 0, err - } - } } currentGroupSigning, err := k.tssKeeper.CreateSigning(ctx, currentGroup, msg) @@ -194,6 +187,14 @@ func (k Keeper) HandleCreateSigning( replacingGroupSigningID = replacingGroupSigning.ID } + // transfer fee to module account. + if !totalFee.IsZero() { + err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, totalFee) + if err != nil { + return 0, err + } + } + // save signingInfo bandtssSigningID := k.AddSigning(ctx, types.Signing{ Fee: feePerSigner, From 9e6605fb1ac714193731a4f9c20df072acce56b2 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Wed, 24 Apr 2024 00:16:47 +0700 Subject: [PATCH 041/132] fix replace group test --- .gitignore | 2 + x/bandtss/keeper/group.go | 8 + x/bandtss/keeper/group_test.go | 310 +++++++++++++++++++++++++++++++++ x/bandtss/types/errors.go | 9 +- 4 files changed, 325 insertions(+), 4 deletions(-) create mode 100644 x/bandtss/keeper/group_test.go diff --git a/.gitignore b/.gitignore index da9dffbc2..8d0d6eca6 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,5 @@ vendor **/target/ /pkg/owasm/res/*.wasm /docker-config/genesis.json + +coverage.out diff --git a/x/bandtss/keeper/group.go b/x/bandtss/keeper/group.go index 7b99ae30b..3a3f5d314 100644 --- a/x/bandtss/keeper/group.go +++ b/x/bandtss/keeper/group.go @@ -16,7 +16,15 @@ func (k Keeper) CreateGroupReplacement( newGroupID tss.GroupID, execTime time.Time, ) (tss.SigningID, error) { + if execTime.Before(ctx.BlockTime()) { + return 0, types.ErrInvalidExecTime + } + currentGroupID := k.GetCurrentGroupID(ctx) + if currentGroupID == 0 { + return 0, types.ErrNoActiveGroup + } + currentGroup, err := k.tssKeeper.GetGroup(ctx, currentGroupID) if err != nil { return 0, err diff --git a/x/bandtss/keeper/group_test.go b/x/bandtss/keeper/group_test.go new file mode 100644 index 000000000..a44b6d4eb --- /dev/null +++ b/x/bandtss/keeper/group_test.go @@ -0,0 +1,310 @@ +package keeper_test + +import ( + "time" + + "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/bandprotocol/chain/v2/x/bandtss/types" + tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" +) + +func (s *KeeperTestSuite) TestSuccessCreateGroupReplacement() { + ctx, k := s.ctx, s.app.BandtssKeeper + s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) + + currentGroupID := s.app.BandtssKeeper.GetCurrentGroupID(ctx) + newGroupID := tss.GroupID(2) + currentGroup := s.app.TSSKeeper.MustGetGroup(ctx, currentGroupID) + newGroup := s.app.TSSKeeper.MustGetGroup(ctx, newGroupID) + execTime := time.Now().UTC().Add(10 * time.Minute) + + signingID, err := k.CreateGroupReplacement(ctx, newGroupID, execTime) + s.Require().NoError(err) + + expectedReplacement := types.Replacement{ + SigningID: signingID, + CurrentGroupID: currentGroupID, + NewGroupID: newGroupID, + CurrentPubKey: currentGroup.PubKey, + NewPubKey: newGroup.PubKey, + Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + ExecTime: execTime, + } + + resp, err := s.queryClient.Replacement(ctx, &types.QueryReplacementRequest{}) + s.Require().NoError(err) + s.Require().Equal(expectedReplacement, resp.Replacement) +} + +func (s *KeeperTestSuite) TestFailCreateGroupReplacement() { + ctx, k := s.ctx, s.app.BandtssKeeper + ctx = ctx.WithBlockTime(time.Now().UTC()) + + s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) + currentGroupID := s.app.BandtssKeeper.GetCurrentGroupID(ctx) + + type input struct { + groupID tss.GroupID + execTime time.Time + } + testcases := []struct { + name string + preProcess func() + input input + expectErr error + postProcess func() + }{ + { + name: "replacement in progress - waiting signing", + preProcess: func() { + k.SetReplacement(ctx, types.Replacement{ + Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + }) + }, + input: input{ + groupID: tss.GroupID(2), + execTime: time.Now().UTC().Add(10 * time.Minute), + }, + expectErr: types.ErrReplacementInProgress, + postProcess: func() { + k.SetReplacement(ctx, types.Replacement{}) + }, + }, + { + name: "replacement in progress - waiting replace", + preProcess: func() { + k.SetReplacement(ctx, types.Replacement{ + Status: types.REPLACEMENT_STATUS_WAITING_REPLACE, + }) + }, + input: input{ + groupID: tss.GroupID(2), + execTime: time.Now().UTC().Add(10 * time.Minute), + }, + expectErr: types.ErrReplacementInProgress, + postProcess: func() { + k.SetReplacement(ctx, types.Replacement{}) + }, + }, + { + name: "replacement exec time is in the past", + preProcess: func() {}, + input: input{ + groupID: tss.GroupID(2), + execTime: time.Now().UTC().Add(time.Duration(-10) * time.Hour), + }, + expectErr: types.ErrInvalidExecTime, + postProcess: func() {}, + }, + { + name: "no current group", + preProcess: func() { + k.SetCurrentGroupID(ctx, 0) + }, + input: input{ + groupID: tss.GroupID(2), + execTime: time.Now().UTC().Add(10 * time.Minute), + }, + expectErr: types.ErrNoActiveGroup, + postProcess: func() { + k.SetCurrentGroupID(ctx, currentGroupID) + }, + }, + } + + for _, tc := range testcases { + s.Run(tc.name, func() { + tc.preProcess() + _, err := k.CreateGroupReplacement(ctx, tc.input.groupID, tc.input.execTime) + s.Require().ErrorIs(err, tc.expectErr) + tc.postProcess() + }) + } +} + +func (s *KeeperTestSuite) TestHandleReplaceGroup() { + ctx, k := s.ctx, s.app.BandtssKeeper + ctx = ctx.WithBlockTime(time.Now().UTC()) + + s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) + currentGroupID := tss.GroupID(1) + + type expectOut struct { + replacementStatus types.ReplacementStatus + currentGroupID tss.GroupID + } + + testcases := []struct { + name string + preProcess func() + expectOut expectOut + postProcess func() + }{ + { + name: "no replacement setup", + preProcess: func() {}, + expectOut: expectOut{ + replacementStatus: types.REPLACEMENT_STATUS_UNSPECIFIED, + currentGroupID: currentGroupID, + }, + postProcess: func() {}, + }, + { + name: "have replacement but not signed", + preProcess: func() { + k.SetReplacement(ctx, types.Replacement{ + SigningID: tss.SigningID(1), + Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + ExecTime: time.Now().UTC().Add(10 * time.Minute), + }) + s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + ID: tss.SigningID(1), + Status: tsstypes.SIGNING_STATUS_WAITING, + }) + }, + expectOut: expectOut{ + replacementStatus: types.REPLACEMENT_STATUS_WAITING_SIGNING, + currentGroupID: currentGroupID, + }, + postProcess: func() {}, + }, + { + name: "have replacement and signed but not meet exec time", + preProcess: func() { + k.SetReplacement(ctx, types.Replacement{ + SigningID: tss.SigningID(1), + Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + ExecTime: time.Now().UTC().Add(10 * time.Minute), + }) + s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + ID: tss.SigningID(1), + Status: tsstypes.SIGNING_STATUS_SUCCESS, + }) + }, + expectOut: expectOut{ + replacementStatus: types.REPLACEMENT_STATUS_WAITING_REPLACE, + currentGroupID: currentGroupID, + }, + postProcess: func() {}, + }, + { + name: "have replacement and signing failed", + preProcess: func() { + k.SetReplacement(ctx, types.Replacement{ + SigningID: tss.SigningID(1), + Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + ExecTime: time.Now().UTC().Add(10 * time.Minute), + }) + s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + ID: tss.SigningID(1), + Status: tsstypes.SIGNING_STATUS_FALLEN, + }) + }, + expectOut: expectOut{ + replacementStatus: types.REPLACEMENT_STATUS_FALLEN, + currentGroupID: currentGroupID, + }, + postProcess: func() {}, + }, + { + name: "have replacement and signing expired", + preProcess: func() { + k.SetReplacement(ctx, types.Replacement{ + SigningID: tss.SigningID(1), + Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + ExecTime: time.Now().UTC().Add(10 * time.Minute), + }) + s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + ID: tss.SigningID(1), + Status: tsstypes.SIGNING_STATUS_EXPIRED, + }) + }, + expectOut: expectOut{ + replacementStatus: types.REPLACEMENT_STATUS_FALLEN, + currentGroupID: currentGroupID, + }, + postProcess: func() {}, + }, + { + name: "have replacement and signing is waiting but exec time is passed", + preProcess: func() { + k.SetReplacement(ctx, types.Replacement{ + SigningID: tss.SigningID(1), + Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + ExecTime: time.Now().UTC().Add(10 * time.Minute), + }) + s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + ID: tss.SigningID(1), + Status: tsstypes.SIGNING_STATUS_WAITING, + }) + ctx = ctx.WithBlockTime(time.Now().UTC().Add(11 * time.Minute)) + }, + expectOut: expectOut{ + replacementStatus: types.REPLACEMENT_STATUS_FALLEN, + currentGroupID: currentGroupID, + }, + postProcess: func() { + ctx = ctx.WithBlockTime(time.Now().UTC()) + }, + }, + // TODO: remove this after fix test_case 2 (group 2; same user) + // { + // name: "have replacement and signing is ready and passed exec time", + // preProcess: func() { + // k.SetReplacement(ctx, types.Replacement{ + // SigningID: tss.SigningID(1), + // Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + // ExecTime: time.Now().UTC().Add(10 * time.Minute), + // CurrentGroupID: currentGroupID, + // NewGroupID: tss.GroupID(2), + // }) + // s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + // ID: tss.SigningID(1), + // Status: tsstypes.SIGNING_STATUS_SUCCESS, + // }) + // ctx = ctx.WithBlockTime(time.Now().UTC().Add(11 * time.Minute)) + // }, + // expectOut: expectOut{ + // replacementStatus: types.REPLACEMENT_STATUS_SUCCESS, + // currentGroupID: tss.GroupID(2), + // }, + // postProcess: func() { + // ctx = ctx.WithBlockTime(time.Now().UTC()) + // }, + // }, + { + name: "have replacement and only waiting to replace but not meet exec time", + preProcess: func() { + k.SetReplacement(ctx, types.Replacement{ + SigningID: tss.SigningID(1), + Status: types.REPLACEMENT_STATUS_WAITING_REPLACE, + ExecTime: time.Now().UTC().Add(10 * time.Minute), + }) + s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + ID: tss.SigningID(1), + Status: tsstypes.SIGNING_STATUS_SUCCESS, + }) + }, + expectOut: expectOut{ + replacementStatus: types.REPLACEMENT_STATUS_WAITING_REPLACE, + currentGroupID: currentGroupID, + }, + postProcess: func() {}, + }, + } + + for _, tc := range testcases { + s.Run(tc.name, func() { + s.Require().Equal(currentGroupID, k.GetCurrentGroupID(ctx)) + tc.preProcess() + + err := k.HandleReplaceGroup(ctx, ctx.BlockTime()) + s.Require().NoError(err) + + // s.Require().Equal(tc.expectOut.replacementStatus, k.GetReplacement(ctx).Status) + s.Require().Equal(tc.expectOut.currentGroupID, k.GetCurrentGroupID(ctx)) + + tc.postProcess() + }) + } +} diff --git a/x/bandtss/types/errors.go b/x/bandtss/types/errors.go index 6f03afe32..86e9745de 100644 --- a/x/bandtss/types/errors.go +++ b/x/bandtss/types/errors.go @@ -11,8 +11,9 @@ var ( ErrInvalidGroupID = errors.Register(ModuleName, 6, "invalid groupID") ErrNoActiveGroup = errors.Register(ModuleName, 7, "no active group") ErrReplacementInProgress = errors.Register(ModuleName, 8, "group replacement is in progress") - ErrSigningNotFound = errors.Register(ModuleName, 9, "signing not found") - ErrMemberNotFound = errors.Register(ModuleName, 10, "member not found") - ErrMemberAlreadyExists = errors.Register(ModuleName, 11, "member already exists") - ErrMemberAlreadyActive = errors.Register(ModuleName, 12, "member already active") + ErrInvalidExecTime = errors.Register(ModuleName, 9, "invalid exec time") + ErrSigningNotFound = errors.Register(ModuleName, 10, "signing not found") + ErrMemberNotFound = errors.Register(ModuleName, 11, "member not found") + ErrMemberAlreadyExists = errors.Register(ModuleName, 12, "member already exists") + ErrMemberAlreadyActive = errors.Register(ModuleName, 13, "member already active") ) From ac38039eee60684c70b2ef36be04955e223f94be Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Wed, 24 Apr 2024 13:22:32 +0700 Subject: [PATCH 042/132] fix script --- scripts/bandtss/start_cylinder.sh | 5 ----- 1 file changed, 5 deletions(-) diff --git a/scripts/bandtss/start_cylinder.sh b/scripts/bandtss/start_cylinder.sh index fc587738d..d83598075 100755 --- a/scripts/bandtss/start_cylinder.sh +++ b/scripts/bandtss/start_cylinder.sh @@ -48,11 +48,6 @@ cylinder config random-secret "$(openssl rand -hex 32)" --home $HOME_PATH # setup random-secret to cylinder config cylinder config active-period "12h" --home $HOME_PATH -bandd tx bandtss activate --from $KEY --gas-prices 0.0025uband --keyring-backend test --chain-id bandchain -b sync -y - -# wait for activiting status transaction success -sleep 4 - for i in $(eval echo {1..2}) do # add signer key From 0464feca2f1b8685836a0d98aa39324f97d25f4a Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 25 Apr 2024 09:29:01 +0700 Subject: [PATCH 043/132] use gomock --- go.mod | 1 + go.sum | 2 + x/bandtss/keeper/group.go | 3 + x/bandtss/keeper/group_test.go | 229 +++++--- x/bandtss/keeper/grpc_query_test.go | 109 +++- x/bandtss/testutil/mock_expected_keepers.go | 569 ++++++++++++++++++++ x/bandtss/testutil/mock_keeper.go | 74 +++ 7 files changed, 877 insertions(+), 110 deletions(-) create mode 100644 x/bandtss/testutil/mock_expected_keepers.go create mode 100644 x/bandtss/testutil/mock_keeper.go diff --git a/go.mod b/go.mod index 68d876915..3551d9e5f 100644 --- a/go.mod +++ b/go.mod @@ -34,6 +34,7 @@ require ( github.com/spf13/cobra v1.7.0 github.com/spf13/viper v1.16.0 github.com/stretchr/testify v1.8.4 + go.uber.org/mock v0.4.0 golang.org/x/crypto v0.16.0 golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb google.golang.org/genproto/googleapis/api v0.0.0-20231212172506-995d672761c0 diff --git a/go.sum b/go.sum index cdeeea016..53828a3a1 100644 --- a/go.sum +++ b/go.sum @@ -1060,6 +1060,8 @@ go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqe go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU= +go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= diff --git a/x/bandtss/keeper/group.go b/x/bandtss/keeper/group.go index 3a3f5d314..1c4c0302c 100644 --- a/x/bandtss/keeper/group.go +++ b/x/bandtss/keeper/group.go @@ -41,6 +41,9 @@ func (k Keeper) CreateGroupReplacement( if err != nil { return 0, err } + if newGroup.Status != tsstypes.GROUP_STATUS_ACTIVE { + return 0, tsstypes.ErrGroupIsNotActive + } // Execute the handler to process the replacement request. msg, err := k.tssKeeper.HandleSigningContent(ctx, types.NewReplaceGroupSignatureOrder(newGroup.PubKey)) diff --git a/x/bandtss/keeper/group_test.go b/x/bandtss/keeper/group_test.go index a44b6d4eb..4a2701861 100644 --- a/x/bandtss/keeper/group_test.go +++ b/x/bandtss/keeper/group_test.go @@ -1,28 +1,50 @@ package keeper_test import ( + "testing" "time" "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/stretchr/testify/require" + + "github.com/bandprotocol/chain/v2/x/bandtss/testutil" "github.com/bandprotocol/chain/v2/x/bandtss/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) -func (s *KeeperTestSuite) TestSuccessCreateGroupReplacement() { - ctx, k := s.ctx, s.app.BandtssKeeper - s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) +func TestSuccessCreateGroupReplacement(t *testing.T) { + s := testutil.NewTestSuite(t) + ctx, k := s.Ctx, s.Keeper - currentGroupID := s.app.BandtssKeeper.GetCurrentGroupID(ctx) + currentGroupID := tss.GroupID(1) newGroupID := tss.GroupID(2) - currentGroup := s.app.TSSKeeper.MustGetGroup(ctx, currentGroupID) - newGroup := s.app.TSSKeeper.MustGetGroup(ctx, newGroupID) execTime := time.Now().UTC().Add(10 * time.Minute) + currentGroup := tsstypes.Group{ + ID: currentGroupID, + PubKey: []byte("test-pubkey-group1"), + } + newGroup := tsstypes.Group{ + ID: newGroupID, + PubKey: []byte("test-pubkey-group2"), + Status: tsstypes.GROUP_STATUS_ACTIVE, + } + expectSigning := &tsstypes.Signing{ + ID: tss.SigningID(1), + } + + k.SetCurrentGroupID(ctx, currentGroupID) + s.MockTSSKeeper.EXPECT().GetGroup(ctx, currentGroupID).Return(currentGroup, nil).AnyTimes() + s.MockTSSKeeper.EXPECT().GetGroup(ctx, newGroupID).Return(newGroup, nil).AnyTimes() + s.MockTSSKeeper.EXPECT().HandleSigningContent(ctx, types.NewReplaceGroupSignatureOrder(newGroup.PubKey)).Return([]byte("test-msg"), nil) + s.MockTSSKeeper.EXPECT().CreateSigning(ctx, currentGroup, []byte("test-msg")).Return(expectSigning, nil) + signingID, err := k.CreateGroupReplacement(ctx, newGroupID, execTime) - s.Require().NoError(err) + require.NoError(t, err) + require.Equal(t, expectSigning.ID, signingID) - expectedReplacement := types.Replacement{ - SigningID: signingID, + expectReplacement := types.Replacement{ + SigningID: expectSigning.ID, CurrentGroupID: currentGroupID, NewGroupID: newGroupID, CurrentPubKey: currentGroup.PubKey, @@ -30,24 +52,29 @@ func (s *KeeperTestSuite) TestSuccessCreateGroupReplacement() { Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, ExecTime: execTime, } - - resp, err := s.queryClient.Replacement(ctx, &types.QueryReplacementRequest{}) - s.Require().NoError(err) - s.Require().Equal(expectedReplacement, resp.Replacement) + actualReplacement := k.GetReplacement(ctx) + require.Equal(t, expectReplacement, actualReplacement) } -func (s *KeeperTestSuite) TestFailCreateGroupReplacement() { - ctx, k := s.ctx, s.app.BandtssKeeper - ctx = ctx.WithBlockTime(time.Now().UTC()) +func TestFailCreateGroupReplacement(t *testing.T) { + s := testutil.NewTestSuite(t) + ctx, k := s.Ctx, s.Keeper + + currentGroupID := tss.GroupID(1) + newGroupID := tss.GroupID(2) + currentGroup := tsstypes.Group{ + ID: currentGroupID, + PubKey: []byte("test-pubkey-group1"), + } - s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) - currentGroupID := s.app.BandtssKeeper.GetCurrentGroupID(ctx) + k.SetCurrentGroupID(ctx, currentGroupID) + s.MockTSSKeeper.EXPECT().GetGroup(ctx, currentGroupID).Return(currentGroup, nil).AnyTimes() type input struct { groupID tss.GroupID execTime time.Time } - testcases := []struct { + testCases := []struct { name string preProcess func() input input @@ -62,8 +89,8 @@ func (s *KeeperTestSuite) TestFailCreateGroupReplacement() { }) }, input: input{ - groupID: tss.GroupID(2), - execTime: time.Now().UTC().Add(10 * time.Minute), + groupID: newGroupID, + execTime: ctx.BlockTime().Add(10 * time.Minute), }, expectErr: types.ErrReplacementInProgress, postProcess: func() { @@ -78,8 +105,8 @@ func (s *KeeperTestSuite) TestFailCreateGroupReplacement() { }) }, input: input{ - groupID: tss.GroupID(2), - execTime: time.Now().UTC().Add(10 * time.Minute), + groupID: newGroupID, + execTime: ctx.BlockTime().Add(10 * time.Minute), }, expectErr: types.ErrReplacementInProgress, postProcess: func() { @@ -90,7 +117,7 @@ func (s *KeeperTestSuite) TestFailCreateGroupReplacement() { name: "replacement exec time is in the past", preProcess: func() {}, input: input{ - groupID: tss.GroupID(2), + groupID: newGroupID, execTime: time.Now().UTC().Add(time.Duration(-10) * time.Hour), }, expectErr: types.ErrInvalidExecTime, @@ -102,7 +129,7 @@ func (s *KeeperTestSuite) TestFailCreateGroupReplacement() { k.SetCurrentGroupID(ctx, 0) }, input: input{ - groupID: tss.GroupID(2), + groupID: newGroupID, execTime: time.Now().UTC().Add(10 * time.Minute), }, expectErr: types.ErrNoActiveGroup, @@ -110,35 +137,54 @@ func (s *KeeperTestSuite) TestFailCreateGroupReplacement() { k.SetCurrentGroupID(ctx, currentGroupID) }, }, + { + name: "replacing group is inactive", + preProcess: func() { + s.MockTSSKeeper.EXPECT().GetGroup(ctx, newGroupID).Return(tsstypes.Group{ + ID: newGroupID, + PubKey: []byte("test-pubkey-group2"), + Status: tsstypes.GROUP_STATUS_FALLEN, + }, nil) + }, + input: input{ + groupID: newGroupID, + execTime: time.Now().UTC().Add(10 * time.Minute), + }, + expectErr: tsstypes.ErrGroupIsNotActive, + postProcess: func() {}, + }, } - for _, tc := range testcases { - s.Run(tc.name, func() { + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { tc.preProcess() _, err := k.CreateGroupReplacement(ctx, tc.input.groupID, tc.input.execTime) - s.Require().ErrorIs(err, tc.expectErr) + require.ErrorIs(t, err, tc.expectErr) tc.postProcess() }) } + } -func (s *KeeperTestSuite) TestHandleReplaceGroup() { - ctx, k := s.ctx, s.app.BandtssKeeper - ctx = ctx.WithBlockTime(time.Now().UTC()) +func TestHandleReplaceGroup2(t *testing.T) { + s := testutil.NewTestSuite(t) + ctx, k := s.Ctx, s.Keeper - s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) currentGroupID := tss.GroupID(1) + k.SetCurrentGroupID(ctx, currentGroupID) + type expectOut struct { replacementStatus types.ReplacementStatus currentGroupID tss.GroupID } - testcases := []struct { + testCases := []struct { name string preProcess func() expectOut expectOut postProcess func() + postCheck func(t *testing.T) }{ { name: "no replacement setup", @@ -155,12 +201,12 @@ func (s *KeeperTestSuite) TestHandleReplaceGroup() { k.SetReplacement(ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - ExecTime: time.Now().UTC().Add(10 * time.Minute), + ExecTime: ctx.BlockTime().Add(10 * time.Minute), }) - s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ ID: tss.SigningID(1), Status: tsstypes.SIGNING_STATUS_WAITING, - }) + }, nil) }, expectOut: expectOut{ replacementStatus: types.REPLACEMENT_STATUS_WAITING_SIGNING, @@ -174,12 +220,12 @@ func (s *KeeperTestSuite) TestHandleReplaceGroup() { k.SetReplacement(ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - ExecTime: time.Now().UTC().Add(10 * time.Minute), + ExecTime: ctx.BlockTime().Add(10 * time.Minute), }) - s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ ID: tss.SigningID(1), Status: tsstypes.SIGNING_STATUS_SUCCESS, - }) + }, nil) }, expectOut: expectOut{ replacementStatus: types.REPLACEMENT_STATUS_WAITING_REPLACE, @@ -193,12 +239,12 @@ func (s *KeeperTestSuite) TestHandleReplaceGroup() { k.SetReplacement(ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - ExecTime: time.Now().UTC().Add(10 * time.Minute), + ExecTime: ctx.BlockTime().Add(10 * time.Minute), }) - s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ ID: tss.SigningID(1), Status: tsstypes.SIGNING_STATUS_FALLEN, - }) + }, nil) }, expectOut: expectOut{ replacementStatus: types.REPLACEMENT_STATUS_FALLEN, @@ -212,12 +258,12 @@ func (s *KeeperTestSuite) TestHandleReplaceGroup() { k.SetReplacement(ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - ExecTime: time.Now().UTC().Add(10 * time.Minute), + ExecTime: ctx.BlockTime().Add(10 * time.Minute), }) - s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ ID: tss.SigningID(1), Status: tsstypes.SIGNING_STATUS_EXPIRED, - }) + }, nil) }, expectOut: expectOut{ replacementStatus: types.REPLACEMENT_STATUS_FALLEN, @@ -231,58 +277,65 @@ func (s *KeeperTestSuite) TestHandleReplaceGroup() { k.SetReplacement(ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - ExecTime: time.Now().UTC().Add(10 * time.Minute), + ExecTime: ctx.BlockTime().Add(10 * time.Minute), }) - s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ + + ctx = ctx.WithBlockTime(ctx.BlockTime().Add(11 * time.Minute)) + s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ ID: tss.SigningID(1), Status: tsstypes.SIGNING_STATUS_WAITING, - }) - ctx = ctx.WithBlockTime(time.Now().UTC().Add(11 * time.Minute)) + }, nil) }, expectOut: expectOut{ replacementStatus: types.REPLACEMENT_STATUS_FALLEN, currentGroupID: currentGroupID, }, + postProcess: func() {}, + }, + { + name: "have replacement and signing is ready and passed exec time", + preProcess: func() { + k.SetReplacement(ctx, types.Replacement{ + SigningID: tss.SigningID(1), + Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + ExecTime: ctx.BlockTime().Add(10 * time.Minute), + CurrentGroupID: currentGroupID, + NewGroupID: tss.GroupID(2), + }) + ctx = ctx.WithBlockTime(ctx.BlockTime().Add(11 * time.Minute)) + + s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ + ID: tss.SigningID(1), + Status: tsstypes.SIGNING_STATUS_SUCCESS, + }, nil) + s.MockTSSKeeper.EXPECT().MustGetMembers(ctx, tss.GroupID(1)).Return([]tsstypes.Member{ + {ID: 1, Address: "band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs"}, + }) + s.MockTSSKeeper.EXPECT().MustGetMembers(ctx, tss.GroupID(2)).Return([]tsstypes.Member{ + {ID: 1, Address: "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun"}, + }) + + }, + expectOut: expectOut{ + replacementStatus: types.REPLACEMENT_STATUS_SUCCESS, + currentGroupID: tss.GroupID(2), + }, + postCheck: func(t *testing.T) { + members := k.GetMembers(ctx) + require.Len(t, members, 1) + require.Equal(t, "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun", members[0].Address) + }, postProcess: func() { - ctx = ctx.WithBlockTime(time.Now().UTC()) + k.SetCurrentGroupID(ctx, tss.GroupID(1)) }, }, - // TODO: remove this after fix test_case 2 (group 2; same user) - // { - // name: "have replacement and signing is ready and passed exec time", - // preProcess: func() { - // k.SetReplacement(ctx, types.Replacement{ - // SigningID: tss.SigningID(1), - // Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - // ExecTime: time.Now().UTC().Add(10 * time.Minute), - // CurrentGroupID: currentGroupID, - // NewGroupID: tss.GroupID(2), - // }) - // s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ - // ID: tss.SigningID(1), - // Status: tsstypes.SIGNING_STATUS_SUCCESS, - // }) - // ctx = ctx.WithBlockTime(time.Now().UTC().Add(11 * time.Minute)) - // }, - // expectOut: expectOut{ - // replacementStatus: types.REPLACEMENT_STATUS_SUCCESS, - // currentGroupID: tss.GroupID(2), - // }, - // postProcess: func() { - // ctx = ctx.WithBlockTime(time.Now().UTC()) - // }, - // }, { name: "have replacement and only waiting to replace but not meet exec time", preProcess: func() { k.SetReplacement(ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_REPLACE, - ExecTime: time.Now().UTC().Add(10 * time.Minute), - }) - s.app.TSSKeeper.SetSigning(ctx, tsstypes.Signing{ - ID: tss.SigningID(1), - Status: tsstypes.SIGNING_STATUS_SUCCESS, + ExecTime: ctx.BlockTime().Add(10 * time.Minute), }) }, expectOut: expectOut{ @@ -293,16 +346,20 @@ func (s *KeeperTestSuite) TestHandleReplaceGroup() { }, } - for _, tc := range testcases { - s.Run(tc.name, func() { - s.Require().Equal(currentGroupID, k.GetCurrentGroupID(ctx)) + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, currentGroupID, k.GetCurrentGroupID(ctx)) tc.preProcess() err := k.HandleReplaceGroup(ctx, ctx.BlockTime()) - s.Require().NoError(err) + require.NoError(t, err) + + require.Equal(t, tc.expectOut.replacementStatus, k.GetReplacement(ctx).Status) + require.Equal(t, tc.expectOut.currentGroupID, k.GetCurrentGroupID(ctx)) - // s.Require().Equal(tc.expectOut.replacementStatus, k.GetReplacement(ctx).Status) - s.Require().Equal(tc.expectOut.currentGroupID, k.GetCurrentGroupID(ctx)) + if tc.postCheck != nil { + tc.postCheck(t) + } tc.postProcess() }) diff --git a/x/bandtss/keeper/grpc_query_test.go b/x/bandtss/keeper/grpc_query_test.go index 33ab6ca7b..0ff31c3e1 100644 --- a/x/bandtss/keeper/grpc_query_test.go +++ b/x/bandtss/keeper/grpc_query_test.go @@ -3,6 +3,9 @@ package keeper_test import ( "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" + querytypes "github.com/cosmos/cosmos-sdk/types/query" + "github.com/bandprotocol/chain/v2/x/bandtss/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) @@ -12,41 +15,99 @@ func (s *KeeperTestSuite) TestGRPCQueryMembers() { s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) - var req types.QueryMembersRequest + result, err := s.queryClient.Members(ctx, &types.QueryMembersRequest{IsActive: true}) + s.Require().NoError(err) + s.Require().Len(result.Members, 2) + members := result.Members + + type expectOut struct { + members []*types.Member + } + testCases := []struct { - msg string - malleate func() - expPass bool - postTest func(res *types.QueryMembersResponse, err error) + name string + preProcess func() + input types.QueryMembersRequest + expectOut expectOut + postProcess func() }{ { - "success", - func() { - req = types.QueryMembersRequest{ - IsActive: true, - } - }, - true, - func(res *types.QueryMembersResponse, err error) { + name: "get 2 active members", + preProcess: func() {}, + input: types.QueryMembersRequest{ + IsActive: true, + }, + expectOut: expectOut{members: members}, + postProcess: func() {}, + }, + { + name: "get 1 active members; limit 1 offset 0", + preProcess: func() {}, + input: types.QueryMembersRequest{ + IsActive: true, + Pagination: &querytypes.PageRequest{Limit: 1, Offset: 0}, + }, + expectOut: expectOut{members: members[:1]}, + postProcess: func() {}, + }, + { + name: "get 1 active members limit 1 offset 1", + preProcess: func() {}, + input: types.QueryMembersRequest{ + IsActive: true, + Pagination: &querytypes.PageRequest{Limit: 1, Offset: 1}, + }, + expectOut: expectOut{members: members[1:]}, + postProcess: func() {}, + }, + { + name: "get 0 active members; out of pages limit 1 offset 5", + preProcess: func() {}, + input: types.QueryMembersRequest{ + IsActive: true, + Pagination: &querytypes.PageRequest{Limit: 1, Offset: 5}, + }, + expectOut: expectOut{members: nil}, + postProcess: func() {}, + }, + { + name: "get no active members", + preProcess: func() {}, + input: types.QueryMembersRequest{ + IsActive: false, + }, + expectOut: expectOut{members: nil}, + postProcess: func() {}, + }, + { + name: "get inactive members", + preProcess: func() { + err := s.app.BandtssKeeper.DeactivateMember(ctx, sdk.MustAccAddressFromBech32(members[0].Address)) + s.Require().NoError(err) + }, + input: types.QueryMembersRequest{ + IsActive: false, + }, + expectOut: expectOut{members: []*types.Member{ + {Address: members[0].Address, IsActive: false, Since: members[0].Since, LastActive: members[0].LastActive}, + }}, + postProcess: func() { + ctx = ctx.WithBlockTime(ctx.BlockTime().Add(types.DefaultInactivePenaltyDuration)) + err := s.app.BandtssKeeper.ActivateMember(ctx, sdk.MustAccAddressFromBech32(members[0].Address)) s.Require().NoError(err) - s.Require().NotNil(res) - s.Require().Len(res.Members, 2) }, }, } for _, tc := range testCases { - s.Run(fmt.Sprintf("Case %s", tc.msg), func() { - tc.malleate() + s.Run(fmt.Sprintf("Case %s", tc.name), func() { + tc.preProcess() - res, err := q.Members(ctx, &req) - if tc.expPass { - s.Require().NoError(err) - } else { - s.Require().Error(err) - } + res, err := q.Members(ctx, &tc.input) + s.Require().NoError(err) + s.Require().Equal(tc.expectOut.members, res.Members) - tc.postTest(res, err) + tc.postProcess() }) } } diff --git a/x/bandtss/testutil/mock_expected_keepers.go b/x/bandtss/testutil/mock_expected_keepers.go new file mode 100644 index 000000000..3d807c60f --- /dev/null +++ b/x/bandtss/testutil/mock_expected_keepers.go @@ -0,0 +1,569 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: x/bandtss/types/expected_keepers.go +// +// Generated by this command: +// +// mockgen --destination x/bandtss/testutil/expected_keepers_mock.go --source x/bandtss/types/expected_keepers.go --package testutil +// + +// Package testutil is a generated GoMock package. +package testutil + +import ( + reflect "reflect" + + tss "github.com/bandprotocol/chain/v2/pkg/tss" + types "github.com/bandprotocol/chain/v2/x/tss/types" + types0 "github.com/cosmos/cosmos-sdk/types" + types1 "github.com/cosmos/cosmos-sdk/x/auth/types" + types2 "github.com/cosmos/cosmos-sdk/x/distribution/types" + types3 "github.com/cosmos/cosmos-sdk/x/staking/types" + gomock "go.uber.org/mock/gomock" +) + +// MockAccountKeeper is a mock of AccountKeeper interface. +type MockAccountKeeper struct { + ctrl *gomock.Controller + recorder *MockAccountKeeperMockRecorder +} + +// MockAccountKeeperMockRecorder is the mock recorder for MockAccountKeeper. +type MockAccountKeeperMockRecorder struct { + mock *MockAccountKeeper +} + +// NewMockAccountKeeper creates a new mock instance. +func NewMockAccountKeeper(ctrl *gomock.Controller) *MockAccountKeeper { + mock := &MockAccountKeeper{ctrl: ctrl} + mock.recorder = &MockAccountKeeperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { + return m.recorder +} + +// GetAccount mocks base method. +func (m *MockAccountKeeper) GetAccount(ctx types0.Context, addr types0.AccAddress) types1.AccountI { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAccount", ctx, addr) + ret0, _ := ret[0].(types1.AccountI) + return ret0 +} + +// GetAccount indicates an expected call of GetAccount. +func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccount", reflect.TypeOf((*MockAccountKeeper)(nil).GetAccount), ctx, addr) +} + +// GetModuleAccount mocks base method. +func (m *MockAccountKeeper) GetModuleAccount(ctx types0.Context, name string) types1.ModuleAccountI { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetModuleAccount", ctx, name) + ret0, _ := ret[0].(types1.ModuleAccountI) + return ret0 +} + +// GetModuleAccount indicates an expected call of GetModuleAccount. +func (mr *MockAccountKeeperMockRecorder) GetModuleAccount(ctx, name any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAccount", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAccount), ctx, name) +} + +// GetModuleAddress mocks base method. +func (m *MockAccountKeeper) GetModuleAddress(name string) types0.AccAddress { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetModuleAddress", name) + ret0, _ := ret[0].(types0.AccAddress) + return ret0 +} + +// GetModuleAddress indicates an expected call of GetModuleAddress. +func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(name any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModuleAddress", reflect.TypeOf((*MockAccountKeeper)(nil).GetModuleAddress), name) +} + +// MockBankKeeper is a mock of BankKeeper interface. +type MockBankKeeper struct { + ctrl *gomock.Controller + recorder *MockBankKeeperMockRecorder +} + +// MockBankKeeperMockRecorder is the mock recorder for MockBankKeeper. +type MockBankKeeperMockRecorder struct { + mock *MockBankKeeper +} + +// NewMockBankKeeper creates a new mock instance. +func NewMockBankKeeper(ctrl *gomock.Controller) *MockBankKeeper { + mock := &MockBankKeeper{ctrl: ctrl} + mock.recorder = &MockBankKeeperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockBankKeeper) EXPECT() *MockBankKeeperMockRecorder { + return m.recorder +} + +// GetAllBalances mocks base method. +func (m *MockBankKeeper) GetAllBalances(ctx types0.Context, addr types0.AccAddress) types0.Coins { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAllBalances", ctx, addr) + ret0, _ := ret[0].(types0.Coins) + return ret0 +} + +// GetAllBalances indicates an expected call of GetAllBalances. +func (mr *MockBankKeeperMockRecorder) GetAllBalances(ctx, addr any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllBalances", reflect.TypeOf((*MockBankKeeper)(nil).GetAllBalances), ctx, addr) +} + +// GetBalance mocks base method. +func (m *MockBankKeeper) GetBalance(ctx types0.Context, addr types0.AccAddress, denom string) types0.Coin { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetBalance", ctx, addr, denom) + ret0, _ := ret[0].(types0.Coin) + return ret0 +} + +// GetBalance indicates an expected call of GetBalance. +func (mr *MockBankKeeperMockRecorder) GetBalance(ctx, addr, denom any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBalance", reflect.TypeOf((*MockBankKeeper)(nil).GetBalance), ctx, addr, denom) +} + +// SendCoinsFromAccountToModule mocks base method. +func (m *MockBankKeeper) SendCoinsFromAccountToModule(ctx types0.Context, senderAddr types0.AccAddress, recipientModule string, amt types0.Coins) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendCoinsFromAccountToModule", ctx, senderAddr, recipientModule, amt) + ret0, _ := ret[0].(error) + return ret0 +} + +// SendCoinsFromAccountToModule indicates an expected call of SendCoinsFromAccountToModule. +func (mr *MockBankKeeperMockRecorder) SendCoinsFromAccountToModule(ctx, senderAddr, recipientModule, amt any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendCoinsFromAccountToModule", reflect.TypeOf((*MockBankKeeper)(nil).SendCoinsFromAccountToModule), ctx, senderAddr, recipientModule, amt) +} + +// SendCoinsFromModuleToAccount mocks base method. +func (m *MockBankKeeper) SendCoinsFromModuleToAccount(ctx types0.Context, senderModule string, recipientAddr types0.AccAddress, amt types0.Coins) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendCoinsFromModuleToAccount", ctx, senderModule, recipientAddr, amt) + ret0, _ := ret[0].(error) + return ret0 +} + +// SendCoinsFromModuleToAccount indicates an expected call of SendCoinsFromModuleToAccount. +func (mr *MockBankKeeperMockRecorder) SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, amt any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendCoinsFromModuleToAccount", reflect.TypeOf((*MockBankKeeper)(nil).SendCoinsFromModuleToAccount), ctx, senderModule, recipientAddr, amt) +} + +// SendCoinsFromModuleToModule mocks base method. +func (m *MockBankKeeper) SendCoinsFromModuleToModule(ctx types0.Context, senderModule, recipientModule string, amt types0.Coins) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendCoinsFromModuleToModule", ctx, senderModule, recipientModule, amt) + ret0, _ := ret[0].(error) + return ret0 +} + +// SendCoinsFromModuleToModule indicates an expected call of SendCoinsFromModuleToModule. +func (mr *MockBankKeeperMockRecorder) SendCoinsFromModuleToModule(ctx, senderModule, recipientModule, amt any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendCoinsFromModuleToModule", reflect.TypeOf((*MockBankKeeper)(nil).SendCoinsFromModuleToModule), ctx, senderModule, recipientModule, amt) +} + +// MockDistrKeeper is a mock of DistrKeeper interface. +type MockDistrKeeper struct { + ctrl *gomock.Controller + recorder *MockDistrKeeperMockRecorder +} + +// MockDistrKeeperMockRecorder is the mock recorder for MockDistrKeeper. +type MockDistrKeeperMockRecorder struct { + mock *MockDistrKeeper +} + +// NewMockDistrKeeper creates a new mock instance. +func NewMockDistrKeeper(ctrl *gomock.Controller) *MockDistrKeeper { + mock := &MockDistrKeeper{ctrl: ctrl} + mock.recorder = &MockDistrKeeperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockDistrKeeper) EXPECT() *MockDistrKeeperMockRecorder { + return m.recorder +} + +// AllocateTokensToValidator mocks base method. +func (m *MockDistrKeeper) AllocateTokensToValidator(ctx types0.Context, val types3.ValidatorI, tokens types0.DecCoins) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AllocateTokensToValidator", ctx, val, tokens) +} + +// AllocateTokensToValidator indicates an expected call of AllocateTokensToValidator. +func (mr *MockDistrKeeperMockRecorder) AllocateTokensToValidator(ctx, val, tokens any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AllocateTokensToValidator", reflect.TypeOf((*MockDistrKeeper)(nil).AllocateTokensToValidator), ctx, val, tokens) +} + +// GetCommunityTax mocks base method. +func (m *MockDistrKeeper) GetCommunityTax(ctx types0.Context) types0.Dec { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCommunityTax", ctx) + ret0, _ := ret[0].(types0.Dec) + return ret0 +} + +// GetCommunityTax indicates an expected call of GetCommunityTax. +func (mr *MockDistrKeeperMockRecorder) GetCommunityTax(ctx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCommunityTax", reflect.TypeOf((*MockDistrKeeper)(nil).GetCommunityTax), ctx) +} + +// GetFeePool mocks base method. +func (m *MockDistrKeeper) GetFeePool(ctx types0.Context) types2.FeePool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetFeePool", ctx) + ret0, _ := ret[0].(types2.FeePool) + return ret0 +} + +// GetFeePool indicates an expected call of GetFeePool. +func (mr *MockDistrKeeperMockRecorder) GetFeePool(ctx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFeePool", reflect.TypeOf((*MockDistrKeeper)(nil).GetFeePool), ctx) +} + +// SetFeePool mocks base method. +func (m *MockDistrKeeper) SetFeePool(ctx types0.Context, feePool types2.FeePool) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetFeePool", ctx, feePool) +} + +// SetFeePool indicates an expected call of SetFeePool. +func (mr *MockDistrKeeperMockRecorder) SetFeePool(ctx, feePool any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFeePool", reflect.TypeOf((*MockDistrKeeper)(nil).SetFeePool), ctx, feePool) +} + +// MockRollingseedKeeper is a mock of RollingseedKeeper interface. +type MockRollingseedKeeper struct { + ctrl *gomock.Controller + recorder *MockRollingseedKeeperMockRecorder +} + +// MockRollingseedKeeperMockRecorder is the mock recorder for MockRollingseedKeeper. +type MockRollingseedKeeperMockRecorder struct { + mock *MockRollingseedKeeper +} + +// NewMockRollingseedKeeper creates a new mock instance. +func NewMockRollingseedKeeper(ctrl *gomock.Controller) *MockRollingseedKeeper { + mock := &MockRollingseedKeeper{ctrl: ctrl} + mock.recorder = &MockRollingseedKeeperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockRollingseedKeeper) EXPECT() *MockRollingseedKeeperMockRecorder { + return m.recorder +} + +// GetRollingSeed mocks base method. +func (m *MockRollingseedKeeper) GetRollingSeed(ctx types0.Context) []byte { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRollingSeed", ctx) + ret0, _ := ret[0].([]byte) + return ret0 +} + +// GetRollingSeed indicates an expected call of GetRollingSeed. +func (mr *MockRollingseedKeeperMockRecorder) GetRollingSeed(ctx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRollingSeed", reflect.TypeOf((*MockRollingseedKeeper)(nil).GetRollingSeed), ctx) +} + +// MockStakingKeeper is a mock of StakingKeeper interface. +type MockStakingKeeper struct { + ctrl *gomock.Controller + recorder *MockStakingKeeperMockRecorder +} + +// MockStakingKeeperMockRecorder is the mock recorder for MockStakingKeeper. +type MockStakingKeeperMockRecorder struct { + mock *MockStakingKeeper +} + +// NewMockStakingKeeper creates a new mock instance. +func NewMockStakingKeeper(ctrl *gomock.Controller) *MockStakingKeeper { + mock := &MockStakingKeeper{ctrl: ctrl} + mock.recorder = &MockStakingKeeperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockStakingKeeper) EXPECT() *MockStakingKeeperMockRecorder { + return m.recorder +} + +// IterateBondedValidatorsByPower mocks base method. +func (m *MockStakingKeeper) IterateBondedValidatorsByPower(ctx types0.Context, fn func(int64, types3.ValidatorI) bool) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "IterateBondedValidatorsByPower", ctx, fn) +} + +// IterateBondedValidatorsByPower indicates an expected call of IterateBondedValidatorsByPower. +func (mr *MockStakingKeeperMockRecorder) IterateBondedValidatorsByPower(ctx, fn any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IterateBondedValidatorsByPower", reflect.TypeOf((*MockStakingKeeper)(nil).IterateBondedValidatorsByPower), ctx, fn) +} + +// MaxValidators mocks base method. +func (m *MockStakingKeeper) MaxValidators(ctx types0.Context) uint32 { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "MaxValidators", ctx) + ret0, _ := ret[0].(uint32) + return ret0 +} + +// MaxValidators indicates an expected call of MaxValidators. +func (mr *MockStakingKeeperMockRecorder) MaxValidators(ctx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MaxValidators", reflect.TypeOf((*MockStakingKeeper)(nil).MaxValidators), ctx) +} + +// ValidatorByConsAddr mocks base method. +func (m *MockStakingKeeper) ValidatorByConsAddr(arg0 types0.Context, arg1 types0.ConsAddress) types3.ValidatorI { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ValidatorByConsAddr", arg0, arg1) + ret0, _ := ret[0].(types3.ValidatorI) + return ret0 +} + +// ValidatorByConsAddr indicates an expected call of ValidatorByConsAddr. +func (mr *MockStakingKeeperMockRecorder) ValidatorByConsAddr(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidatorByConsAddr", reflect.TypeOf((*MockStakingKeeper)(nil).ValidatorByConsAddr), arg0, arg1) +} + +// MockTSSKeeper is a mock of TSSKeeper interface. +type MockTSSKeeper struct { + ctrl *gomock.Controller + recorder *MockTSSKeeperMockRecorder +} + +// MockTSSKeeperMockRecorder is the mock recorder for MockTSSKeeper. +type MockTSSKeeperMockRecorder struct { + mock *MockTSSKeeper +} + +// NewMockTSSKeeper creates a new mock instance. +func NewMockTSSKeeper(ctrl *gomock.Controller) *MockTSSKeeper { + mock := &MockTSSKeeper{ctrl: ctrl} + mock.recorder = &MockTSSKeeperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockTSSKeeper) EXPECT() *MockTSSKeeperMockRecorder { + return m.recorder +} + +// ActivateMember mocks base method. +func (m *MockTSSKeeper) ActivateMember(ctx types0.Context, groupID tss.GroupID, address types0.AccAddress) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ActivateMember", ctx, groupID, address) + ret0, _ := ret[0].(error) + return ret0 +} + +// ActivateMember indicates an expected call of ActivateMember. +func (mr *MockTSSKeeperMockRecorder) ActivateMember(ctx, groupID, address any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ActivateMember", reflect.TypeOf((*MockTSSKeeper)(nil).ActivateMember), ctx, groupID, address) +} + +// CreateGroup mocks base method. +func (m *MockTSSKeeper) CreateGroup(ctx types0.Context, members []types0.AccAddress, threshold uint64, moduleOwner string) (tss.GroupID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateGroup", ctx, members, threshold, moduleOwner) + ret0, _ := ret[0].(tss.GroupID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateGroup indicates an expected call of CreateGroup. +func (mr *MockTSSKeeperMockRecorder) CreateGroup(ctx, members, threshold, moduleOwner any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateGroup", reflect.TypeOf((*MockTSSKeeper)(nil).CreateGroup), ctx, members, threshold, moduleOwner) +} + +// CreateSigning mocks base method. +func (m *MockTSSKeeper) CreateSigning(ctx types0.Context, group types.Group, message []byte) (*types.Signing, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateSigning", ctx, group, message) + ret0, _ := ret[0].(*types.Signing) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateSigning indicates an expected call of CreateSigning. +func (mr *MockTSSKeeperMockRecorder) CreateSigning(ctx, group, message any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSigning", reflect.TypeOf((*MockTSSKeeper)(nil).CreateSigning), ctx, group, message) +} + +// DeactivateMember mocks base method. +func (m *MockTSSKeeper) DeactivateMember(ctx types0.Context, groupID tss.GroupID, address types0.AccAddress) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeactivateMember", ctx, groupID, address) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeactivateMember indicates an expected call of DeactivateMember. +func (mr *MockTSSKeeperMockRecorder) DeactivateMember(ctx, groupID, address any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeactivateMember", reflect.TypeOf((*MockTSSKeeper)(nil).DeactivateMember), ctx, groupID, address) +} + +// GetDECount mocks base method. +func (m *MockTSSKeeper) GetDECount(ctx types0.Context, address types0.AccAddress) uint64 { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetDECount", ctx, address) + ret0, _ := ret[0].(uint64) + return ret0 +} + +// GetDECount indicates an expected call of GetDECount. +func (mr *MockTSSKeeperMockRecorder) GetDECount(ctx, address any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDECount", reflect.TypeOf((*MockTSSKeeper)(nil).GetDECount), ctx, address) +} + +// GetGroup mocks base method. +func (m *MockTSSKeeper) GetGroup(ctx types0.Context, groupID tss.GroupID) (types.Group, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetGroup", ctx, groupID) + ret0, _ := ret[0].(types.Group) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetGroup indicates an expected call of GetGroup. +func (mr *MockTSSKeeperMockRecorder) GetGroup(ctx, groupID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGroup", reflect.TypeOf((*MockTSSKeeper)(nil).GetGroup), ctx, groupID) +} + +// GetMemberByAddress mocks base method. +func (m *MockTSSKeeper) GetMemberByAddress(ctx types0.Context, groupID tss.GroupID, address string) (types.Member, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetMemberByAddress", ctx, groupID, address) + ret0, _ := ret[0].(types.Member) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetMemberByAddress indicates an expected call of GetMemberByAddress. +func (mr *MockTSSKeeperMockRecorder) GetMemberByAddress(ctx, groupID, address any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMemberByAddress", reflect.TypeOf((*MockTSSKeeper)(nil).GetMemberByAddress), ctx, groupID, address) +} + +// GetPenalizedMembersExpiredGroup mocks base method. +func (m *MockTSSKeeper) GetPenalizedMembersExpiredGroup(ctx types0.Context, group types.Group) ([]types0.AccAddress, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPenalizedMembersExpiredGroup", ctx, group) + ret0, _ := ret[0].([]types0.AccAddress) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPenalizedMembersExpiredGroup indicates an expected call of GetPenalizedMembersExpiredGroup. +func (mr *MockTSSKeeperMockRecorder) GetPenalizedMembersExpiredGroup(ctx, group any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPenalizedMembersExpiredGroup", reflect.TypeOf((*MockTSSKeeper)(nil).GetPenalizedMembersExpiredGroup), ctx, group) +} + +// GetPenalizedMembersExpiredSigning mocks base method. +func (m *MockTSSKeeper) GetPenalizedMembersExpiredSigning(ctx types0.Context, signing types.Signing) ([]types0.AccAddress, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPenalizedMembersExpiredSigning", ctx, signing) + ret0, _ := ret[0].([]types0.AccAddress) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPenalizedMembersExpiredSigning indicates an expected call of GetPenalizedMembersExpiredSigning. +func (mr *MockTSSKeeperMockRecorder) GetPenalizedMembersExpiredSigning(ctx, signing any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPenalizedMembersExpiredSigning", reflect.TypeOf((*MockTSSKeeper)(nil).GetPenalizedMembersExpiredSigning), ctx, signing) +} + +// GetSigning mocks base method. +func (m *MockTSSKeeper) GetSigning(ctx types0.Context, signingID tss.SigningID) (types.Signing, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSigning", ctx, signingID) + ret0, _ := ret[0].(types.Signing) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSigning indicates an expected call of GetSigning. +func (mr *MockTSSKeeperMockRecorder) GetSigning(ctx, signingID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSigning", reflect.TypeOf((*MockTSSKeeper)(nil).GetSigning), ctx, signingID) +} + +// GetSigningResult mocks base method. +func (m *MockTSSKeeper) GetSigningResult(ctx types0.Context, signingID tss.SigningID) (*types.SigningResult, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSigningResult", ctx, signingID) + ret0, _ := ret[0].(*types.SigningResult) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSigningResult indicates an expected call of GetSigningResult. +func (mr *MockTSSKeeperMockRecorder) GetSigningResult(ctx, signingID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSigningResult", reflect.TypeOf((*MockTSSKeeper)(nil).GetSigningResult), ctx, signingID) +} + +// HandleSigningContent mocks base method. +func (m *MockTSSKeeper) HandleSigningContent(ctx types0.Context, content types.Content) ([]byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "HandleSigningContent", ctx, content) + ret0, _ := ret[0].([]byte) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// HandleSigningContent indicates an expected call of HandleSigningContent. +func (mr *MockTSSKeeperMockRecorder) HandleSigningContent(ctx, content any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleSigningContent", reflect.TypeOf((*MockTSSKeeper)(nil).HandleSigningContent), ctx, content) +} + +// MustGetMembers mocks base method. +func (m *MockTSSKeeper) MustGetMembers(ctx types0.Context, groupID tss.GroupID) []types.Member { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "MustGetMembers", ctx, groupID) + ret0, _ := ret[0].([]types.Member) + return ret0 +} + +// MustGetMembers indicates an expected call of MustGetMembers. +func (mr *MockTSSKeeperMockRecorder) MustGetMembers(ctx, groupID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MustGetMembers", reflect.TypeOf((*MockTSSKeeper)(nil).MustGetMembers), ctx, groupID) +} diff --git a/x/bandtss/testutil/mock_keeper.go b/x/bandtss/testutil/mock_keeper.go new file mode 100644 index 000000000..22dd66cb4 --- /dev/null +++ b/x/bandtss/testutil/mock_keeper.go @@ -0,0 +1,74 @@ +package testutil + +import ( + "testing" + "time" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cosmos/cosmos-sdk/codec" + sdktestutil "github.com/cosmos/cosmos-sdk/testutil" + sdk "github.com/cosmos/cosmos-sdk/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + "go.uber.org/mock/gomock" + + "github.com/bandprotocol/chain/v2/x/bandtss" + "github.com/bandprotocol/chain/v2/x/bandtss/keeper" + "github.com/bandprotocol/chain/v2/x/bandtss/types" +) + +// NOTE: cannot put suite.Suite inside this struct, or else the test get timeout. +type TestSuite struct { + Keeper *keeper.Keeper + + MockAccountKeeper *MockAccountKeeper + MockBankKeeper *MockBankKeeper + MockDistrKeeper *MockDistrKeeper + MockStakingKeeper *MockStakingKeeper + MockTSSKeeper *MockTSSKeeper + + Ctx sdk.Context + Authority sdk.AccAddress +} + +func NewTestSuite(t *testing.T) TestSuite { + ctrl := gomock.NewController(t) + key := sdk.NewKVStoreKey(types.StoreKey) + testCtx := sdktestutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) + encCfg := moduletestutil.MakeTestEncodingConfig(bandtss.AppModuleBasic{}) + ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: time.Now().UTC()}) + + accountKeeper := NewMockAccountKeeper(ctrl) + bankKeeper := NewMockBankKeeper(ctrl) + distrKeeper := NewMockDistrKeeper(ctrl) + stakingKeeper := NewMockStakingKeeper(ctrl) + tssKeeper := NewMockTSSKeeper(ctrl) + + authority := authtypes.NewModuleAddress(govtypes.ModuleName) + accountKeeper.EXPECT().GetModuleAddress(types.ModuleName).Return(authority).AnyTimes() + bandtssKeeper := keeper.NewKeeper( + encCfg.Codec.(codec.BinaryCodec), + key, + paramtypes.Subspace{}, + accountKeeper, + bankKeeper, + distrKeeper, + stakingKeeper, + tssKeeper, + authority.String(), + authtypes.FeeCollectorName, + ) + + return TestSuite{ + Keeper: bandtssKeeper, + MockAccountKeeper: accountKeeper, + MockBankKeeper: bankKeeper, + MockDistrKeeper: distrKeeper, + MockStakingKeeper: stakingKeeper, + MockTSSKeeper: tssKeeper, + Ctx: ctx, + Authority: authority, + } +} From db478e9d4002bcfd6317cfa214e9c74af37fc6d6 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 25 Apr 2024 09:29:21 +0700 Subject: [PATCH 044/132] fix tss test_case --- pkg/tss/round2_test.go | 64 ++++++--- pkg/tss/testutil/test_case.go | 197 ++++++++++++++++++++-------- x/bandtss/keeper/group_test.go | 4 +- x/bandtss/keeper/grpc_query_test.go | 16 +-- x/bandtss/keeper/msg_server_test.go | 158 +++++++++++++++++++++- x/bandtss/keeper/validator_test.go | 6 +- x/tss/keeper/msg_server_test.go | 2 +- 7 files changed, 356 insertions(+), 91 deletions(-) diff --git a/pkg/tss/round2_test.go b/pkg/tss/round2_test.go index 2715a4dfa..b6cab4dfb 100644 --- a/pkg/tss/round2_test.go +++ b/pkg/tss/round2_test.go @@ -12,34 +12,58 @@ func (suite *TSSTestSuite) TestComputeEncryptedSecretShares() { pubKeys = append(pubKeys, m.OneTimePubKey()) } - encSecretShares, err := tss.ComputeEncryptedSecretShares( - member.ID, - member.OneTimePrivKey, - pubKeys, - member.Coefficients, - testutil.MockNonce16Generator{ - MockGenerateFunc: func() ([]byte, error) { - return member.EncSecretShares[0].Nonce(), nil + var encSecretShares tss.EncSecretShares + + counter := 0 + for idx := range pubKeys { + if idx+1 == int(member.ID) { + continue + } + encSecretShare, err := tss.ComputeEncryptedSecretShares( + member.ID, + member.OneTimePrivKey, + pubKeys, + member.Coefficients, + testutil.MockNonce16Generator{ + MockGenerateFunc: func() ([]byte, error) { + return member.EncSecretShares[counter].Nonce(), nil + }, }, - }, - ) - suite.Require().NoError(err) + ) + suite.Require().NoError(err) + + encSecretShares = append(encSecretShares, encSecretShare[counter]) + counter++ + } + suite.Require().Equal(member.EncSecretShares, encSecretShares) }) } func (suite *TSSTestSuite) TestEncryptSecretShares() { suite.RunOnMember(suite.testCases, func(tc testutil.TestCase, member testutil.Member) { - encSecretShares, err := tss.EncryptSecretShares( - member.SecretShares, - member.KeySyms, - testutil.MockNonce16Generator{ - MockGenerateFunc: func() ([]byte, error) { - return member.EncSecretShares[0].Nonce(), nil + var encSecretShares tss.EncSecretShares + counter := 0 + for idx := range tc.Group.Members { + if idx+1 == int(member.ID) { + continue + } + + encSecretShare, err := tss.EncryptSecretShares( + member.SecretShares, + member.KeySyms, + testutil.MockNonce16Generator{ + MockGenerateFunc: func() ([]byte, error) { + return member.EncSecretShares[counter].Nonce(), nil + }, }, - }, - ) - suite.Require().NoError(err) + ) + suite.Require().NoError(err) + + encSecretShares = append(encSecretShares, encSecretShare[counter]) + counter++ + } + suite.Require().Equal(member.EncSecretShares, encSecretShares) }) } diff --git a/pkg/tss/testutil/test_case.go b/pkg/tss/testutil/test_case.go index 4db2c51b9..66fa50b51 100644 --- a/pkg/tss/testutil/test_case.go +++ b/pkg/tss/testutil/test_case.go @@ -237,154 +237,239 @@ var ( }, }, { - "Group: 2 (Threshold: 1, Size: 2)", + "Group: 2 (Threshold: 2, Size: 3)", Group{ ID: 2, DKGContext: HexDecode("a1cdd234702bbdbd8a4fa9fc17f2a83d569f553ae4bd1755985e5039532d108c"), - Threshold: 1, - PubKey: HexDecode("02a37461c1621d12f2c436b98ffe95d6ff0fedc102e8b5b35a08c96b889cb448fd"), + Threshold: 2, + PubKey: HexDecode("0251d3a86d64f1a578f4e2cdca2cc2374578c5b5c450dc61c4edc24e89d94017ac"), Members: []Member{ { ID: 1, - OneTimePrivKey: HexDecode("b688151a692b3742303d15a820f48df74f169e1f335c0eec32a9062485fcec11"), + OneTimePrivKey: HexDecode("cd956cec2a3e763d8635581452b86f4a21f59656f1c6b59a6b0114a29c01c367"), OneTimeSignature: HexDecode( - "026905d1d2af2fa42f7118b1c5d3ddf65e562485aa4bced9ef16ddb41dab4962520b1a37f255e033ecf2b499b80fe603da131f225e2c514c1facfcd60151f6ab62", + "0256826ba9c85c45d275737fecb4ccd8645902815edd7db48a0e8bc87e4c479bb01f767cb4bf77d09de015b754153350ae0324657463858f4ad560a06959c85d54", ), - A0PrivKey: HexDecode("75455ebc9f9f6aa3471da39a85a1283df7451d4e9b3c5c807bb10dd0c14bb051"), + A0PrivKey: HexDecode("32ad23c573d211b2266cd5e710351abe00ead1cd55563bf863ed606174d0fde1"), A0Signature: HexDecode( - "02cc374c42e50675c8942de9dd6644a0920f78c9bde40f9020337f42d8db918eacc5e5ab6fc039404098c2e12998ecfedb3d7fa8c5949f1409114a096ec347f957", + "0210d598daa4e9874d1323a199c9b60bc063ff9fecf9d76cb2d5b33feb04d8f77fe315e7b20f4957d9ca57fac0144ba4266e28743f8a312ca7c7ee300b52d82e17", ), Coefficients: tss.Scalars{ - HexDecode("75455ebc9f9f6aa3471da39a85a1283df7451d4e9b3c5c807bb10dd0c14bb051"), + HexDecode("32ad23c573d211b2266cd5e710351abe00ead1cd55563bf863ed606174d0fde1"), + HexDecode("a8bb0d73bb89203897fcbf1607045025e5d1f09ead256684b41c38313da23cd8"), }, CoefficientCommits: tss.Points{ - HexDecode("0262f4888feb37b89c9744444093f6c00b0e196087c7c28671bb8247a32eef704f"), + HexDecode("03e90ce3454b707e6e8334428c4da865e912658dba71d5f501fb72b866d0eb8690"), + HexDecode("0229c799e84406b43408a35849e301aa54ad995e0132312127cd1138cc7d761d2c"), }, KeySyms: tss.Points{ - HexDecode("036f9072ece9b94f22a5547acd536e25c609fb065f276104444df535ea78288198"), + HexDecode("0218ba7f417710821dc5d4e86ba046cc083181971cde692ff7909be1499fcd03de"), + HexDecode("0283a20dc326b4cc1a5c6c5d140019ebb88f4970557a8128b6165e1979c5581a9b"), }, SecretShares: tss.Scalars{ - HexDecode("75455ebc9f9f6aa3471da39a85a1283df7451d4e9b3c5c807bb10dd0c14bb051"), + HexDecode("84233eaceae45223566654131e3dbb0b11dfd624005868c60c5372371fdf3650"), + HexDecode("2cde4c20a66d725bee63132925420b323d02e9dbfe352f0f009d4bdb8d4b31e7"), }, EncSecretShares: tss.EncSecretShares{ - HexDecode( - "fa00ec78f1dd3a82b12abebaa084251bde4879e295cab318ae9dcef42cd54c953f3d151aef2e69037c729a8c490a38bb", - ), + HexDecode("5a623a2e84efa588797d7a4fad1765f65ea41559264755de920c55322838eff028ecfd8c84cc823f90b0aa2b0dbea504"), + HexDecode("364f4dbd7f9099dfabfacba14a1b71788b52decc479ef6bdb960eabfa01293058817e8b044549dd6ef6e749fe2757316"), }, - PrivKey: HexDecode("97f0af1189e626c1bb22a0611c8947567b6fb5c29a543669a8e877168b806cbb"), + PrivKey: HexDecode("e4b3fd82472bfd8d1d6d8eebb19ef7ec4b5c7b783305fceb4f8b98b7a58b8157"), PubKeySignature: HexDecode( - "0398ba0bae0d08502c7112f12d153e3044779ea1c7b4be2931655c906f2e515c4b65904c694643fa9ebe18b28c0852dce2aca58712477a1631651096fefe4ef2a3", + "03cda14c12880e5eee98aa652ca80033539bffbc4e2eca8e7d05b5b04c73dbee19fc1977817df73ebc703119a0310ae63958065d10cbce45d92c5cfcbf5d762f59", ), ComplaintSignatures: tss.ComplaintSignatures{ - HexDecode( - "03f8d441370179701150e6c87c4e12b9549e8501b6bee9456ed20001a292f495e1034b8a8f569c8a1a3b0a25c963a85d526dafe4c01ce71a7d15db445098a21fdb7bff5bb38f970fd3d6f33161a1eec7056e3b5e9bbebc9f8b617750ce545ee0173b", - ), + HexDecode("0372cbbcaec0d2ec31c3d894c23b3c7497f4383de756835fea963a5c2b5be0c7ed0356b1e3345ed7d7c5039cca70c8c8207fabe09ed51b82d8f8057f0580a43c0f7d1f2926ef027fc226b559ddefead6d3a3da851d369836e766c56885ab7677376e"), + HexDecode("032eec8eb3e5be690a4c92260b1c95e31b2ea57f9d06ef3a5c3cbe95d01571a4ee02ae8bdd5e57282ecb88b391ad8c645de71e96509cc32bbe21c63df58d5d955bde400abb72b277199a33a400f6f5c5bc75265fdf7cfaaf11705ad9816df2f09088"), }, }, { ID: 2, - OneTimePrivKey: HexDecode("f11005581a9438273cddb8c00cab5e137b530d30ec874593050d194a328c3152"), + OneTimePrivKey: HexDecode("c6b8e5314e8dfd9b0c4880374d27f42ba50fe753c178eb42f735ae78b6b2d68f"), OneTimeSignature: HexDecode( - "025a6024eb03400c5bb2758170194b561ec888dc90b0f343cfb193088877d4a6e8f7b1927258296bf023b2cda5b1443fc6b902cd371f3d0484b01211eb09b5968b", + "0380c5e12b16b2200b72ebdd950f30cd266266e424bc28511ef81aa37c6a15ca0f76a1e06f75508b700fc85fe9244ba126002280acac3f437e81a9ddeed042638e", ), - A0PrivKey: HexDecode("22ab5054ea46bc1e7404fcc696e81f18842a9873ff17d9e92d376945ca34bc6a"), + A0PrivKey: HexDecode("1895756c29647ca1b14e87096ca67b14ac983559f23c535402f58e0d69aef88b"), A0Signature: HexDecode( - "039a483f79423309cae3c4b05b03327c6921411579647cdc2a80a6079ec375dc0b41142f756b007b087faf736609ac670e710003264fbce2b8b2cccc0ba35609f0", + "02a381f467a0e84caae5e40d32e162c378c9adb625d583f596421060c6b3bb981146f84a558e8809b4980239e4f78b99fcbe68834d621cb084140e8849ba48d630", ), Coefficients: tss.Scalars{ - HexDecode("22ab5054ea46bc1e7404fcc696e81f18842a9873ff17d9e92d376945ca34bc6a"), + HexDecode("1895756c29647ca1b14e87096ca67b14ac983559f23c535402f58e0d69aef88b"), + HexDecode("de5839a83e4e110d7d0746f254e74d60e769b6e4ed6fa4fa13e96bbe417afaf3"), }, CoefficientCommits: tss.Points{ - HexDecode("0369f21b7c2841750b8ba29e8559147643f8f49c41b54be2f4f7c453c84b0bc929"), + HexDecode("03f19598161ea1aa499f565bab580b9e65a130bc46e08dcca7535308a5c6663d53"), + HexDecode("02f115e4f31816720ab285f3eaf08dbd0fa875f4c3ad4395b6f710ed1a21bb5664"), }, KeySyms: tss.Points{ - HexDecode("036f9072ece9b94f22a5547acd536e25c609fb065f276104444df535ea78288198"), + HexDecode("0218ba7f417710821dc5d4e86ba046cc083181971cde692ff7909be1499fcd03de"), + HexDecode("03e3943bba202780275763d4a765435884d9b0afd078485c759baf89bac3ba9963"), }, SecretShares: tss.Scalars{ - HexDecode("22ab5054ea46bc1e7404fcc696e81f18842a9873ff17d9e92d376945ca34bc6a"), + HexDecode("f6edaf1467b28daf2e55cdfbc18dc8759401ec3edfabf84e16def9cbab29f37e"), + HexDecode("b39e2264e44eafca28645be06b5c6339ed77a03b5bfa01cabf0d142e8db366e2"), }, EncSecretShares: tss.EncSecretShares{ - HexDecode( - "57e9ea849d1a4efba136a950eda2d0119b753a89a42e98b71d0de49249baa137c1e4d34f382090758f29da4c0a52173f", - ), + HexDecode("efa2c5ee920d6b4c704354fbb94c96812fa8d956383a9e93b3e63923fe26365a1c223188ffa46a00ffd912db5ef3f2e1"), + HexDecode("487d0f7dfadd7fbcd8cf5b81ba8de0781f72fd4484ebca069d5fbab273216346e29da6d2a55a6df3c4635082d8780f81"), }, - PrivKey: HexDecode("97f0af1189e626c1bb22a0611c8947567b6fb5c29a543669a8e877168b806cbb"), + PrivKey: HexDecode("ffbc3899b67ac41b3222d444a0a2c75e2d2d55a2aa71ed064e9be772c055af55"), PubKeySignature: HexDecode( - "02aac6b21e1e05461544f933a2c4b5bc3e37380462f855ebaf62cb3e867514a9df098c3ac9c120d7a4c1f2ce1e0cdc109da41792122440c0a2669d084d96c90441", + "0329bece4c42bf6c0bf9b4e6f987a6ef05d16fc0cd557a362da4b2e6909c4905a6a31d4670bdd2b37ba2cd36b58e323c8286984a5cb3d4a6d5ebcafef48c6d703f", ), ComplaintSignatures: tss.ComplaintSignatures{ - HexDecode( - "021ab11f3eae2807ead59d5e8cc65d0841cb324de5988be2768ea38116ac130af50399487cefdecbcf378edb1533d41c2640fa35f9e8e98f862ec7108d135e243aea0f1bf8672686f3c8972de0eaeeb989558c1fd01bea58e7c6cfeaa1f143513b55", - ), + HexDecode("03a27d33b3021365d1eab97bf6adef79b511cc278498113e927c891642d81f902002ac71d05629f60219d90cb67b1adfb729407092475094530a97f4939c9b0437e3a70a0e9d3cf044f3aa1ad88b91ce2796bc9a3f3d2de94177f67d7486e38e73f1"), + HexDecode("020d6276ada49e605d00700ea66e9ef76e90de8c44094b9fa2dfa92e744277b441028b452cdaaf8c6c59b6ee5b02b89394bfe72b414bcabbedefe859c840872e5f7c98b3063beb346e658278a9ffff4b93d395b562ab5cfb349bf3d6ab2a0fbd0823"), + }, + }, + { + ID: 3, + OneTimePrivKey: HexDecode("72e9945e6ccdee9a164574a213de49f6f2532b428234fb67c974ad8244f8fca7"), + OneTimeSignature: HexDecode( + "02f12cd884d2f0359266caab11ecbe5e7d9726804254e7e65368fdb2e8ae338190f6fd1a81882f87ae43e8bba511116871b7e8b0812d6a571e96f4f8904408af43", + ), + A0PrivKey: HexDecode("7e6929393aa6a8ab30fceca245bf92a7bc089a2674077d83e9985b8dac415ced"), + A0Signature: HexDecode( + "03740b8ebea15764d9c9648049a40457732637accf05cb9dc5b76e769e2082d7b803f715b0687d6a5a7ffcb6c7180f25d2853af270a55aa7e153bda8f91bd52bf3", + ), + Coefficients: tss.Scalars{ + HexDecode("7e6929393aa6a8ab30fceca245bf92a7bc089a2674077d83e9985b8dac415ced"), + HexDecode("93f4f3fb75779547ffb13f50931831e889f2ec743b682513b6af67e53c1978b5"), + }, + CoefficientCommits: tss.Points{ + HexDecode("0396ab224ca0dbd7cc3b303f7100a71ac930c20e49dd7308d421b6f72831fdd856"), + HexDecode("034a458d016c2841b5d5d39ad9c27bc9569c8ee72e9d2744f221bed5cb7200cf77"), + }, + KeySyms: tss.Points{ + HexDecode("0283a20dc326b4cc1a5c6c5d140019ebb88f4970557a8128b6165e1979c5581a9b"), + HexDecode("03e3943bba202780275763d4a765435884d9b0afd078485c759baf89bac3ba9963"), + }, + SecretShares: tss.Scalars{ + HexDecode("125e1d34b01e3df330ae2bf2d8d7c4918b4ca9b40027025be07564e618249461"), + HexDecode("a65311302595d33b305f6b436beff67a153f96283b8f276f9724cccb543e0d16"), + }, + EncSecretShares: tss.EncSecretShares{ + HexDecode("3d1dab73ed4bdef79f6fbef372dcc8a747cb1fd8448a405c0dfa8d6971941241cca9f02d758784aa74e86147acf3df39"), + HexDecode("4bfd9fd3e644275397009b8486011e2701e26e47aa6616e5012ff5d0c407114b4b4dd72ea5301637829c1a900bc96b57"), + }, + PrivKey: HexDecode("1ac473b125c98aa946d8199d8fa696d1544f52e672953ce58dd9d7a10ae99c12"), + PubKeySignature: HexDecode( + "02b4c20e7025a241153ed11bf609ca56158ec00ee4659aba5a03ae462b84167a440e771e2ac285e26d0e5d225f0b5d741c4dd74b94c3754a8db49e5aeeefa9dd68", + ), + ComplaintSignatures: tss.ComplaintSignatures{ + HexDecode("02d0de565cc13dd0fb199920f4d4ad29a4b20b1d23f4b0197fb5f4e70ea1e3e19f039eefb2bc14b2020d4ae8d36484123da3ba8e6ea380d35f934e6c637dd40a919257228ff64901de13157fb80f8b87e211f2ebab8e189c46d3a2fee6ededda84dc"), + HexDecode("035ba017738a2c38d1966791bab75ea3330efbac7e6a5e7cadc5a502003c7f7b9c03e8385e4825101ed8b597ace877ee73aed5c3a9b777a21aa5554157fff3698d62feca03f2d8cf15896b6af43e2e10976ee082a965d7cc627d968e34554066ff5d"), }, }, }, }, []Signing{ { - ID: 3, + ID: 1, Data: []byte("data"), - PubNonce: HexDecode("024a00a111b8231ee0b4995f1f97280a3b22f2db298bbc31b1ef07adfd286bf955"), + PubNonce: HexDecode("027f0906568a068e3dba900e407b086fcc078284e44d50b877a0589b3354c18789"), Commitment: HexDecode( - "000000000000000102a1233c2d1ef055f8ff047518d35e64f2b1b938b37ba3093599f5fe41ce18080402228a0cece369591d357e6c89f29eb779b755912418fd389f94b9060b17ca49d2", + "000000000000000202c3e8303ff3ab6162e9937b974d783a71d7c99866d7389b16849b1b31988c034102da5ee04fc506dfdc4dc587efda8a71b9a8633678417a6239bff3561ed62b3bfc0000000000000003030dd45952da828c4c0870858506a325b5de0b1195fbed6ec50c1121c9c13eb04c029f8afbedab3986071f2848db288d87b733da52cbedc27d7ce3b6f7e1a4e01c05", ), Signature: HexDecode( - "024a00a111b8231ee0b4995f1f97280a3b22f2db298bbc31b1ef07adfd286bf9551c5000d5b8811a82eb25e139727d3bbbc04affcc36a88178b7cba24db58647d4", + "027f0906568a068e3dba900e407b086fcc078284e44d50b877a0589b3354c1878953564beae1470af077ef8bf1da1a94402ef144d3b19deb3c4b01cf01896bc2a6", ), AssignedMembers: []AssignedMember{ { - ID: 1, + ID: 2, + PrivD: HexDecode( + "b6f6e21b4090c9e74be0ea9ce6e0efc2eef8ec6a07a11c21a51ce2e90acc3f75", + ), + PrivE: HexDecode( + "d4637d5788ce7fd6549a7f9e71fc67fe900482da9c634630e2820c2e32f6dc93", + ), + BindingFactor: HexDecode( + "6370f893c2c6a690167a7bd6a68e5dba820bdda6bf9918a268d9803f93a4475a", + ), + PrivNonce: HexDecode( + "02c503f09190581e520a288425306c6500c0618f2b6fe56257d4a3b1025139b0", + ), + Lagrange: HexDecode( + "0000000000000000000000000000000000000000000000000000000000000003", + ), + Signature: HexDecode( + "036907a0d92d5b26e53cedcaf82159a32f40847f70babe112aeb91a2c9a459dba9274ba98cb462610a3b975e15b941f2c6df42e5aab085ee18bdab24769bbfdb6f", + ), + }, + { + ID: 3, PrivD: HexDecode( - "ff92bb0c646c6aa0bfeda96b76d92a3636fa3481ea8acde486def423a76bf7ff", + "f24cc73fab7b57357fdee9a63bc847cc8b0c46d480e97e2a298fd3e2df4f7540", ), PrivE: HexDecode( - "ab1ccde9bfa9dfba4a6b07549c9e6ed67703675d3593f7ff93e34a8c48a9ad56", + "1f6cf5d526d40e5d8febf625433bd9f4e5c359c4be0602096cd98f67525a34a3", ), BindingFactor: HexDecode( - "c2209639bb4beb23c553e593174a22c90806d81ba710077a8f78607a40923bf1", + "cd5974caff745ea0e0c0188234a8ee2ac44ae70a4041c453ef8d4de84f38f2fa", ), PrivNonce: HexDecode( - "41eafa30986f64ef8b7f842916cfd832ee6fda2bd5a54a588f9233d6274e80d7", + "84db3e9d273ef4d72b7e4b9617f785d26fa340880226f6f803aacc4d3a9a61f0", ), Lagrange: HexDecode( - "0000000000000000000000000000000000000000000000000000000000000001", + "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413f", ), Signature: HexDecode( - "024a00a111b8231ee0b4995f1f97280a3b22f2db298bbc31b1ef07adfd286bf9551c5000d5b8811a82eb25e139727d3bbbc04affcc36a88178b7cba24db58647d4", + "032526c7d602c2973436b3e7497fd2edbc4353a90628af64c34f71dc6cd010ee712c0aa25e2ce4a9e63c582ddc20d8a1794fae5f290117fd238d56aa8aedabe737", ), }, }, }, { - ID: 4, + ID: 2, Data: []byte("data"), - PubNonce: HexDecode("036b790561a9c631033a9f8a18e2e200f713394be93ff51131d47f43755a181a2e"), + PubNonce: HexDecode("0375462a5782139d93592a51e26e36d99c8d2bbc51787f165afcfbdf81ca5f3667"), Commitment: HexDecode( - "0000000000000002023533bf77c50242fe743daba7292644f9a71c34ae9b9d7b8a22526af45828d5f4034df4a62cf3d8e0267dc2392651ca7b544e70abdcfc770b07d1fcb1ededef34bc", + "000000000000000202f4e2de38c0f3c190d99772eeee9b91c032ac83ef4e9ad8110be1f922394577b203ef2b2b3d4a0ebdb9b11168bf5b38cdd1ef1e550dad2ec93081926cae9e187b16000000000000000302ff74d305d77671b8ab63a761c6b56215a3c7335161a57b507bbab244700e0fa102ca62e66708596612e44b2044523261cb2e0f52b43475b3b439692eb356289742", ), Signature: HexDecode( - "036b790561a9c631033a9f8a18e2e200f713394be93ff51131d47f43755a181a2e8d0b88adbbe74eb40af9f00f2d9a43853f82334c30b7bfc2e13e951612292439", + "0375462a5782139d93592a51e26e36d99c8d2bbc51787f165afcfbdf81ca5f366757220b7a95335cce51623cd25c71aa432a54a24869249da404b1cc1a0c192ade", ), AssignedMembers: []AssignedMember{ { ID: 2, PrivD: HexDecode( - "43cb56ddf0a36b601480ae041d4aca6f504215993191a605a70645110f64f975", + "5b30c4aa92e343416f4b8c83f446a79496cb0fe65c46972ae0b0b6d947ab97e3", + ), + PrivE: HexDecode( + "939b931782c40dfb161cb15a26467cd845f3179984929323f33dd7b225142244", + ), + BindingFactor: HexDecode( + "b081adee5d407dab4e5a768223822ef1b60105a526a7d9be13b08025757e6c6d", + ), + PrivNonce: HexDecode( + "e614528b09b432974fefc98a7167235f6cf439b34d8b07e4728d70e7e8c291bd", + ), + Lagrange: HexDecode( + "0000000000000000000000000000000000000000000000000000000000000003", + ), + Signature: HexDecode( + "024e0e0836e38da513d044d9ac6ccdbbbec24749296b652b82b203f6d69b3537b24f816d040ffee0e74757ea0cb15d15ade67f279719966895400318f5159c273e", + ), + }, + { + ID: 3, + PrivD: HexDecode( + "4bf931569bd7db77cae4c7040a90aac9a8ebfec3f4dc4d84afa01d411d1f632f", ), PrivE: HexDecode( - "097bbd65bb9b82f138eb99c569714e692fe1d18fe256cf37cec83a969892ec27", + "55c339819a78d531530afc8c93f4b53c0dd74b90e2fb930859554c68fd951994", ), BindingFactor: HexDecode( - "218c8a95e82d00d970f919d99fca9ebaf0833e0fd592533336b1568530c841f7", + "f38a9a43ce8ed9f27db69f329ffa257eeba1474edcce58199e776928cd7d25a6", ), PrivNonce: HexDecode( - "afb2c697eef9fa1f0efd479ec9b56b79d050dfee71b8fb7ccbeb7b4d87d9de3a", + "0b6a860495e88e1b68dc03d471320c3dad91ba2c40369614dc6bb9a67bdf2f7b", ), Lagrange: HexDecode( - "0000000000000000000000000000000000000000000000000000000000000001", + "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413f", ), Signature: HexDecode( - "036b790561a9c631033a9f8a18e2e200f713394be93ff51131d47f43755a181a2e8d0b88adbbe74eb40af9f00f2d9a43853f82334c30b7bfc2e13e951612292439", + "033ab01cfd5f0884b3a8d2e2feead62ae11d97f12b108ef5fdfcd2b008405055fb07a09e7685347be70a0a52c5ab14949543d57ab14f8e350ec4aeb324f67d03a0", ), }, }, diff --git a/x/bandtss/keeper/group_test.go b/x/bandtss/keeper/group_test.go index 4a2701861..224429ddb 100644 --- a/x/bandtss/keeper/group_test.go +++ b/x/bandtss/keeper/group_test.go @@ -4,9 +4,9 @@ import ( "testing" "time" - "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/stretchr/testify/require" + "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/x/bandtss/testutil" "github.com/bandprotocol/chain/v2/x/bandtss/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" @@ -163,7 +163,6 @@ func TestFailCreateGroupReplacement(t *testing.T) { tc.postProcess() }) } - } func TestHandleReplaceGroup2(t *testing.T) { @@ -314,7 +313,6 @@ func TestHandleReplaceGroup2(t *testing.T) { s.MockTSSKeeper.EXPECT().MustGetMembers(ctx, tss.GroupID(2)).Return([]tsstypes.Member{ {ID: 1, Address: "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun"}, }) - }, expectOut: expectOut{ replacementStatus: types.REPLACEMENT_STATUS_SUCCESS, diff --git a/x/bandtss/keeper/grpc_query_test.go b/x/bandtss/keeper/grpc_query_test.go index 0ff31c3e1..a6d9a1839 100644 --- a/x/bandtss/keeper/grpc_query_test.go +++ b/x/bandtss/keeper/grpc_query_test.go @@ -27,14 +27,14 @@ func (s *KeeperTestSuite) TestGRPCQueryMembers() { testCases := []struct { name string preProcess func() - input types.QueryMembersRequest + input *types.QueryMembersRequest expectOut expectOut postProcess func() }{ { name: "get 2 active members", preProcess: func() {}, - input: types.QueryMembersRequest{ + input: &types.QueryMembersRequest{ IsActive: true, }, expectOut: expectOut{members: members}, @@ -43,7 +43,7 @@ func (s *KeeperTestSuite) TestGRPCQueryMembers() { { name: "get 1 active members; limit 1 offset 0", preProcess: func() {}, - input: types.QueryMembersRequest{ + input: &types.QueryMembersRequest{ IsActive: true, Pagination: &querytypes.PageRequest{Limit: 1, Offset: 0}, }, @@ -53,7 +53,7 @@ func (s *KeeperTestSuite) TestGRPCQueryMembers() { { name: "get 1 active members limit 1 offset 1", preProcess: func() {}, - input: types.QueryMembersRequest{ + input: &types.QueryMembersRequest{ IsActive: true, Pagination: &querytypes.PageRequest{Limit: 1, Offset: 1}, }, @@ -63,7 +63,7 @@ func (s *KeeperTestSuite) TestGRPCQueryMembers() { { name: "get 0 active members; out of pages limit 1 offset 5", preProcess: func() {}, - input: types.QueryMembersRequest{ + input: &types.QueryMembersRequest{ IsActive: true, Pagination: &querytypes.PageRequest{Limit: 1, Offset: 5}, }, @@ -73,7 +73,7 @@ func (s *KeeperTestSuite) TestGRPCQueryMembers() { { name: "get no active members", preProcess: func() {}, - input: types.QueryMembersRequest{ + input: &types.QueryMembersRequest{ IsActive: false, }, expectOut: expectOut{members: nil}, @@ -85,7 +85,7 @@ func (s *KeeperTestSuite) TestGRPCQueryMembers() { err := s.app.BandtssKeeper.DeactivateMember(ctx, sdk.MustAccAddressFromBech32(members[0].Address)) s.Require().NoError(err) }, - input: types.QueryMembersRequest{ + input: &types.QueryMembersRequest{ IsActive: false, }, expectOut: expectOut{members: []*types.Member{ @@ -103,7 +103,7 @@ func (s *KeeperTestSuite) TestGRPCQueryMembers() { s.Run(fmt.Sprintf("Case %s", tc.name), func() { tc.preProcess() - res, err := q.Members(ctx, &tc.input) + res, err := q.Members(ctx, tc.input) s.Require().NoError(err) s.Require().Equal(tc.expectOut.members, res.Members) diff --git a/x/bandtss/keeper/msg_server_test.go b/x/bandtss/keeper/msg_server_test.go index a39e421bb..04306ba06 100644 --- a/x/bandtss/keeper/msg_server_test.go +++ b/x/bandtss/keeper/msg_server_test.go @@ -22,10 +22,166 @@ type TestCase struct { ExpectedErr error } -func (s *KeeperTestSuite) TestCreateGroup() { +func (s *KeeperTestSuite) TestFlowCreatingGroup() { s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) } +func (s *KeeperTestSuite) TestSuccessCreateGroup() { + ctx, k := s.ctx, s.app.BandtssKeeper + + _, err := s.msgSrvr.CreateGroup(ctx, &types.MsgCreateGroup{ + Members: []string{"band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs"}, + Threshold: 1, + Authority: s.authority.String(), + }) + + s.Require().NoError(err) + + // Check if the group is created but not set as active. + s.Require().Equal(tss.GroupID(0), k.GetCurrentGroupID(ctx)) + + group, err := s.app.TSSKeeper.GetGroup(ctx, tss.GroupID(1)) + s.Require().NoError(err) + s.Require().Equal(tsstypes.GROUP_STATUS_ROUND_1, group.Status) + s.Require().Equal(types.ModuleName, group.ModuleOwner) + s.Require().Equal(uint64(1), group.Threshold) + s.Require().Equal(uint64(1), group.Size_) + + // check if the member is added into the group. + actualMembers, err := s.app.TSSKeeper.GetGroupMembers(ctx, tss.GroupID(1)) + s.Require().NoError(err) + s.Require().Equal(1, len(actualMembers)) + s.Require().Equal("band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", actualMembers[0].Address) +} + +func (s *KeeperTestSuite) TestSuccessCreateNewGroupAfterHavingCurrentGroup() { + ctx, k := s.ctx, s.app.BandtssKeeper + + // provided that group is already created + s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) + + s.Require().Equal(tss.GroupID(1), s.app.BandtssKeeper.GetCurrentGroupID(s.ctx)) + + members, err := s.app.TSSKeeper.GetGroupMembers(ctx, tss.GroupID(1)) + s.Require().NoError(err) + + // even member in current group is deactivated, it should not affect the new group. + err = k.DeactivateMember(ctx, sdk.MustAccAddressFromBech32(members[0].Address)) + s.Require().NoError(err) + + expectedGroupID := tss.GroupID(s.app.TSSKeeper.GetGroupCount(ctx) + 1) + + _, err = s.msgSrvr.CreateGroup(ctx, &types.MsgCreateGroup{ + Members: []string{sdk.MustAccAddressFromBech32(members[0].Address).String()}, + Threshold: 1, + Authority: s.authority.String(), + }) + s.Require().NoError(err) + + s.Require().Equal(uint64(expectedGroupID), s.app.TSSKeeper.GetGroupCount(ctx)) + + // Check if the group is created but not impact current group ID in bandtss. + s.Require().Equal(tss.GroupID(1), k.GetCurrentGroupID(ctx)) + + group, err := s.app.TSSKeeper.GetGroup(ctx, expectedGroupID) + s.Require().NoError(err) + s.Require().Equal(tsstypes.GROUP_STATUS_ROUND_1, group.Status) + s.Require().Equal(types.ModuleName, group.ModuleOwner) + s.Require().Equal(uint64(1), group.Threshold) + s.Require().Equal(uint64(1), group.Size_) + + // check if the member is added into the group. + actualMembers, err := s.app.TSSKeeper.GetGroupMembers(ctx, expectedGroupID) + s.Require().NoError(err) + s.Require().Equal(1, len(actualMembers)) + s.Require().Equal(members[0].Address, actualMembers[0].Address) +} + +func (s *KeeperTestSuite) TestFailCreateGroup() { + ctx := s.ctx + tssParams := s.app.TSSKeeper.GetParams(ctx) + + testCases := []struct { + name string + input *types.MsgCreateGroup + preProcess func() + expectErr error + postProcess func() + }{ + { + name: "invalid authority", + input: &types.MsgCreateGroup{ + Members: []string{"band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs"}, + Threshold: 1, + Authority: "band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", + }, + preProcess: func() {}, + postProcess: func() {}, + expectErr: govtypes.ErrInvalidSigner, + }, + { + name: "over max group size", + input: &types.MsgCreateGroup{ + Members: []string{"band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", testapp.Alice.Address.String()}, + Threshold: 1, + Authority: s.authority.String(), + }, + preProcess: func() { + err := s.app.TSSKeeper.SetParams(ctx, tsstypes.Params{ + MaxGroupSize: 1, + MaxDESize: tssParams.MaxDESize, + CreatingPeriod: tssParams.CreatingPeriod, + SigningPeriod: tssParams.SigningPeriod, + }) + s.Require().NoError(err) + }, + postProcess: func() { + err := s.app.TSSKeeper.SetParams(ctx, tssParams) + s.Require().NoError(err) + }, + expectErr: tsstypes.ErrGroupSizeTooLarge, + }, + { + name: "duplicate members", + input: &types.MsgCreateGroup{ + Members: []string{"band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", "band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", "band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs"}, + Threshold: 1, + Authority: s.authority.String(), + }, + preProcess: func() {}, + postProcess: func() {}, + expectErr: fmt.Errorf("members can not duplicate"), + }, + { + name: "threshold more than members length", + input: &types.MsgCreateGroup{ + Members: []string{"band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs"}, + Threshold: 10, + Authority: s.authority.String(), + }, + preProcess: func() {}, + postProcess: func() {}, + expectErr: fmt.Errorf("threshold must be less than or equal to the members but more than zero"), + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + tc.preProcess() + + err := tc.input.ValidateBasic() + if err != nil { + s.Require().ErrorContains(err, tc.expectErr.Error()) + } else { + _, err := s.msgSrvr.CreateGroup(ctx, tc.input) + s.Require().ErrorIs(err, tc.expectErr) + } + + tc.postProcess() + }) + } +} + func (s *KeeperTestSuite) TestFailedReplaceGroup() { ctx, msgSrvr, k := s.ctx, s.msgSrvr, s.app.TSSKeeper authority := authtypes.NewModuleAddress(govtypes.ModuleName) diff --git a/x/bandtss/keeper/validator_test.go b/x/bandtss/keeper/validator_test.go index aff9356a8..9019b7a58 100644 --- a/x/bandtss/keeper/validator_test.go +++ b/x/bandtss/keeper/validator_test.go @@ -97,7 +97,8 @@ func (s *KeeperTestSuite) TestAllocateTokensOneActive() { s.Require().NoError(err) for _, validator := range testapp.Validators { - k.AddNewMember(ctx, validator.Address) + err := k.AddNewMember(ctx, validator.Address) + s.Require().NoError(err) } k.AllocateTokens(ctx, defaultVotes()) @@ -131,7 +132,8 @@ func (s *KeeperTestSuite) TestAllocateTokensAllActive() { s.Require().Equal(Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) for _, validator := range testapp.Validators { - k.AddNewMember(ctx, validator.Address) + err := k.AddNewMember(ctx, validator.Address) + s.Require().NoError(err) deCount := s.app.TSSKeeper.GetDECount(ctx, validator.Address) s.Require().Greater(deCount, uint64(0)) } diff --git a/x/tss/keeper/msg_server_test.go b/x/tss/keeper/msg_server_test.go index a49f77514..378a497c1 100644 --- a/x/tss/keeper/msg_server_test.go +++ b/x/tss/keeper/msg_server_test.go @@ -363,7 +363,7 @@ func (s *KeeperTestSuite) TestSuccessComplainReq() { Signature: signature, }, }, - Address: sdk.AccAddress(tc.Group.Members[0].PubKey()).String(), + Address: sdk.AccAddress(m.PubKey()).String(), }) s.Require().NoError(err) } From dfac12069973e1c35b58f99593f4e3002fe2da20 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 25 Apr 2024 15:11:29 +0700 Subject: [PATCH 045/132] test handleCreateSigning --- x/bandtss/keeper/msg_server_test.go | 4 +- x/bandtss/keeper/signing.go | 2 +- x/bandtss/keeper/signing_test.go | 305 ++++++++++++++++++++++++++++ x/bandtss/types/errors.go | 2 +- 4 files changed, 309 insertions(+), 4 deletions(-) create mode 100644 x/bandtss/keeper/signing_test.go diff --git a/x/bandtss/keeper/msg_server_test.go b/x/bandtss/keeper/msg_server_test.go index 04306ba06..d13a3bf0d 100644 --- a/x/bandtss/keeper/msg_server_test.go +++ b/x/bandtss/keeper/msg_server_test.go @@ -307,7 +307,7 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { tsstypes.ErrGroupIsNotActive, }, { - "failure with not enough fee", + "failure with fee is more than user's limit", func() { req, err = types.NewMsgRequestSignature( tsstypes.NewTextSignatureOrder([]byte("msg")), @@ -316,7 +316,7 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { ) }, func() {}, - types.ErrNotEnoughFee, + types.ErrFeeExceedsLimit, }, } diff --git a/x/bandtss/keeper/signing.go b/x/bandtss/keeper/signing.go index e530b980a..ccc268239 100644 --- a/x/bandtss/keeper/signing.go +++ b/x/bandtss/keeper/signing.go @@ -157,7 +157,7 @@ func (k Keeper) HandleCreateSigning( for _, fc := range totalFee { limitAmt := feeLimit.AmountOf(fc.Denom) if fc.Amount.GT(limitAmt) { - return 0, types.ErrNotEnoughFee.Wrapf( + return 0, types.ErrFeeExceedsLimit.Wrapf( "require: %s, limit: %s%s", fc.String(), limitAmt.String(), diff --git a/x/bandtss/keeper/signing_test.go b/x/bandtss/keeper/signing_test.go new file mode 100644 index 000000000..253d3a328 --- /dev/null +++ b/x/bandtss/keeper/signing_test.go @@ -0,0 +1,305 @@ +package keeper_test + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + + "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/bandprotocol/chain/v2/testing/testapp" + "github.com/bandprotocol/chain/v2/x/bandtss/testutil" + "github.com/bandprotocol/chain/v2/x/bandtss/types" + tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" +) + +func TestHandleCreateSigning(t *testing.T) { + s := testutil.NewTestSuite(t) + ctx, k := s.Ctx, s.Keeper + + currentGroupID := tss.GroupID(1) + currentGroup := tsstypes.Group{ + ID: currentGroupID, + Status: tsstypes.GROUP_STATUS_ACTIVE, + Size_: 3, + Threshold: 2, + } + content := &tsstypes.TextSignatureOrder{Message: []byte("test")} + params := types.DefaultParams() + params.Fee = sdk.NewCoins(sdk.NewInt64Coin("uband", 10)) + + k.SetCurrentGroupID(ctx, currentGroupID) + err := k.SetParams(ctx, params) + require.NoError(t, err) + + s.MockTSSKeeper.EXPECT().HandleSigningContent(ctx, content).Return([]byte("test"), nil).AnyTimes() + s.MockTSSKeeper.EXPECT().GetGroup(ctx, currentGroupID).Return(currentGroup, nil).AnyTimes() + + type input struct { + sender sdk.AccAddress + feeLimit sdk.Coins + } + + testCases := []struct { + name string + preProcess func() + input input + expectErr error + postProcess func() + postCheck func() + }{ + { + name: "test success with only current group", + preProcess: func() { + expectCurrentGroupSigning := &tsstypes.Signing{ + ID: tss.SigningID(1), + GroupID: currentGroupID, + Status: tsstypes.SIGNING_STATUS_WAITING, + } + s.MockTSSKeeper.EXPECT().CreateSigning( + ctx, + currentGroup, + []byte("test"), + ).Return(expectCurrentGroupSigning, nil) + s.MockBankKeeper.EXPECT().SendCoinsFromAccountToModule( + ctx, + testapp.Alice.Address, + types.ModuleName, + sdk.NewCoins(sdk.NewInt64Coin("uband", 20)), + ).Return(nil) + }, + postCheck: func() { + // check mapping of tss signingID -> bandtss signingID + actualMappedSigningID := k.GetSigningIDMapping(ctx, tss.SigningID(1)) + require.Equal(t, types.SigningID(1), actualMappedSigningID) + + // check bandtssSigning + bandtssSigning, err := k.GetSigning(ctx, types.SigningID(1)) + require.NoError(t, err) + require.Equal(t, types.Signing{ + ID: types.SigningID(1), + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: testapp.Alice.Address.String(), + CurrentGroupSigningID: tss.SigningID(1), + ReplacingGroupSigningID: tss.SigningID(0), + }, bandtssSigning) + }, + input: input{sender: testapp.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, + postProcess: func() { + k.SetSigningCount(ctx, 0) + k.DeleteSigningIDMapping(ctx, tss.SigningID(1)) + }, + expectErr: nil, + }, + { + name: "test success with creator is authority", + preProcess: func() { + expectCurrentGroupSigning := &tsstypes.Signing{ + ID: tss.SigningID(1), + GroupID: currentGroupID, + Status: tsstypes.SIGNING_STATUS_WAITING, + } + s.MockTSSKeeper.EXPECT().CreateSigning( + ctx, + currentGroup, + []byte("test"), + ).Return(expectCurrentGroupSigning, nil) + }, + postCheck: func() { + // check mapping of tss signingID -> bandtss signingID + actualMappedSigningID := k.GetSigningIDMapping(ctx, tss.SigningID(1)) + require.Equal(t, types.SigningID(1), actualMappedSigningID) + + // check bandtssSigning + bandtssSigning, err := k.GetSigning(ctx, types.SigningID(1)) + require.NoError(t, err) + require.Equal(t, types.Signing{ + ID: types.SigningID(1), + Fee: nil, + Requester: s.Authority.String(), + CurrentGroupSigningID: tss.SigningID(1), + ReplacingGroupSigningID: tss.SigningID(0), + }, bandtssSigning) + }, + input: input{sender: s.Authority, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, + expectErr: nil, + postProcess: func() { + k.SetSigningCount(ctx, 0) + k.DeleteSigningIDMapping(ctx, tss.SigningID(1)) + }, + }, + { + name: "test success with both current and replacing group", + preProcess: func() { + replaceGroupID := tss.GroupID(2) + replaceGroup := tsstypes.Group{ + ID: currentGroupID, + Status: tsstypes.GROUP_STATUS_ACTIVE, + Size_: 3, + Threshold: 3, + } + replacement := types.Replacement{ + SigningID: tss.SigningID(1), + Status: types.REPLACEMENT_STATUS_WAITING_REPLACE, + CurrentGroupID: currentGroupID, + NewGroupID: replaceGroupID, + } + expectCurrentGroupSigning := &tsstypes.Signing{ + ID: tss.SigningID(2), + GroupID: currentGroupID, + Status: tsstypes.SIGNING_STATUS_WAITING, + } + expectReplaceGroupSigning := &tsstypes.Signing{ + ID: tss.SigningID(3), + GroupID: currentGroupID, + Status: tsstypes.SIGNING_STATUS_WAITING, + } + k.SetReplacement(ctx, replacement) + + s.MockTSSKeeper.EXPECT().GetGroup( + ctx, + replaceGroupID, + ).Return(replaceGroup, nil) + s.MockTSSKeeper.EXPECT().CreateSigning( + ctx, + currentGroup, + []byte("test"), + ).Return(expectCurrentGroupSigning, nil) + s.MockTSSKeeper.EXPECT().CreateSigning( + ctx, + replaceGroup, + []byte("test"), + ).Return(expectReplaceGroupSigning, nil) + s.MockBankKeeper.EXPECT().SendCoinsFromAccountToModule( + ctx, + testapp.Alice.Address, + types.ModuleName, + sdk.NewCoins(sdk.NewInt64Coin("uband", 20)), + ).Return(nil) + }, + postCheck: func() { + // check mapping of tss signingID -> bandtss signingID + bandtssSignignID := k.GetSigningIDMapping(ctx, tss.SigningID(2)) + require.Equal(t, types.SigningID(1), bandtssSignignID) + bandtssSignignID = k.GetSigningIDMapping(ctx, tss.SigningID(3)) + require.Equal(t, types.SigningID(1), bandtssSignignID) + + // check bandtssSigning + bandtssSigning, err := k.GetSigning(ctx, types.SigningID(1)) + require.NoError(t, err) + require.Equal(t, types.Signing{ + ID: types.SigningID(1), + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: testapp.Alice.Address.String(), + CurrentGroupSigningID: tss.SigningID(2), + ReplacingGroupSigningID: tss.SigningID(3), + }, bandtssSigning) + }, + input: input{sender: testapp.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, + postProcess: func() { + k.SetReplacement(ctx, types.Replacement{}) + k.SetSigningCount(ctx, 0) + k.DeleteSigningIDMapping(ctx, tss.SigningID(1)) + }, + expectErr: nil, + }, + { + name: "test success with current group. Replacing group request is not signed", + preProcess: func() { + replaceGroupID := tss.GroupID(2) + replacement := types.Replacement{ + SigningID: tss.SigningID(1), + Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + CurrentGroupID: currentGroupID, + NewGroupID: replaceGroupID, + } + expectCurrentGroupSigning := &tsstypes.Signing{ + ID: tss.SigningID(4), + GroupID: currentGroupID, + Status: tsstypes.SIGNING_STATUS_WAITING, + } + k.SetReplacement(ctx, replacement) + + s.MockTSSKeeper.EXPECT().CreateSigning( + ctx, + currentGroup, + []byte("test"), + ).Return(expectCurrentGroupSigning, nil) + s.MockBankKeeper.EXPECT().SendCoinsFromAccountToModule( + ctx, + testapp.Alice.Address, + types.ModuleName, + sdk.NewCoins(sdk.NewInt64Coin("uband", 20)), + ).Return(nil) + }, + postCheck: func() { + // check mapping of tss signingID -> bandtss signingID + bandtssSignignID := k.GetSigningIDMapping(ctx, tss.SigningID(4)) + require.Equal(t, types.SigningID(1), bandtssSignignID) + + // check bandtssSigning + bandtssSigning, err := k.GetSigning(ctx, types.SigningID(1)) + require.NoError(t, err) + require.Equal(t, types.Signing{ + ID: types.SigningID(1), + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: testapp.Alice.Address.String(), + CurrentGroupSigningID: tss.SigningID(4), + ReplacingGroupSigningID: tss.SigningID(0), + }, bandtssSigning) + }, + input: input{sender: testapp.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, + postProcess: func() { + k.SetReplacement(ctx, types.Replacement{}) + k.SetSigningCount(ctx, 0) + k.DeleteSigningIDMapping(ctx, tss.SigningID(1)) + }, + expectErr: nil, + }, + { + name: "error no active group", + preProcess: func() { k.SetCurrentGroupID(ctx, 0) }, + postProcess: func() { k.SetCurrentGroupID(ctx, currentGroupID) }, + input: input{sender: testapp.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, + expectErr: types.ErrNoActiveGroup, + }, + { + name: "fee more than limit", + preProcess: func() { + params.Fee = sdk.NewCoins(sdk.NewInt64Coin("uband", 100)) + err := k.SetParams(ctx, params) + require.NoError(t, err) + }, + postProcess: func() { + params.Fee = sdk.NewCoins(sdk.NewInt64Coin("uband", 10)) + err := k.SetParams(ctx, params) + require.NoError(t, err) + }, + input: input{sender: testapp.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, + expectErr: types.ErrFeeExceedsLimit, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + if tc.preProcess != nil { + tc.preProcess() + } + + _, err := k.HandleCreateSigning(ctx, content, tc.input.sender, tc.input.feeLimit) + if tc.expectErr != nil { + require.ErrorIs(t, err, tc.expectErr) + } else { + require.NoError(t, err) + } + + if tc.postCheck != nil { + tc.postCheck() + } + + if tc.postProcess != nil { + tc.postProcess() + } + }) + } +} diff --git a/x/bandtss/types/errors.go b/x/bandtss/types/errors.go index 86e9745de..20c680966 100644 --- a/x/bandtss/types/errors.go +++ b/x/bandtss/types/errors.go @@ -7,7 +7,7 @@ var ( ErrInvalidStatus = errors.Register(ModuleName, 2, "invalid status") ErrStatusIsNotActive = errors.Register(ModuleName, 3, "status is not active") ErrTooSoonToActivate = errors.Register(ModuleName, 4, "too soon to activate") - ErrNotEnoughFee = errors.Register(ModuleName, 5, "not enough fee") + ErrFeeExceedsLimit = errors.Register(ModuleName, 5, "fee exceeds limit") ErrInvalidGroupID = errors.Register(ModuleName, 6, "invalid groupID") ErrNoActiveGroup = errors.Register(ModuleName, 7, "no active group") ErrReplacementInProgress = errors.Register(ModuleName, 8, "group replacement is in progress") From 0c005d514c9a43cc450b0d47ff4efc0dbe4577fc Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 25 Apr 2024 15:33:33 +0700 Subject: [PATCH 046/132] fix testcases --- x/bandtss/genesis_test.go | 43 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 x/bandtss/genesis_test.go diff --git a/x/bandtss/genesis_test.go b/x/bandtss/genesis_test.go new file mode 100644 index 000000000..361d281cb --- /dev/null +++ b/x/bandtss/genesis_test.go @@ -0,0 +1,43 @@ +package bandtss_test + +import ( + "testing" + + "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/bandprotocol/chain/v2/testing/testapp" + "github.com/bandprotocol/chain/v2/x/bandtss" + "github.com/bandprotocol/chain/v2/x/bandtss/testutil" + "github.com/bandprotocol/chain/v2/x/bandtss/types" + "github.com/stretchr/testify/require" +) + +func TestExportGenesis(t *testing.T) { + s := testutil.NewTestSuite(t) + ctx, k := s.Ctx, s.Keeper + + data := types.GenesisState{ + Params: types.DefaultParams(), + Members: []types.Member{ + {Address: testapp.Alice.Address.String(), Since: ctx.BlockTime(), IsActive: true, LastActive: ctx.BlockTime()}, + }, + CurrentGroupID: tss.GroupID(1), + SigningCount: 1, + Signings: []types.Signing{ + {ID: types.SigningID(1), Requester: testapp.Alice.Address.String(), CurrentGroupSigningID: tss.SigningID(3)}, + }, + SigningIDMappings: []types.SigningIDMappingGenesis{ + {SigningID: tss.SigningID(1), BandtssSigningID: types.SigningID(3)}, + }, + Replacement: types.Replacement{ + SigningID: tss.SigningID(1), + CurrentGroupID: tss.GroupID(1), + NewGroupID: tss.GroupID(2), + Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + }, + } + + bandtss.InitGenesis(ctx, k, &data) + + exported := bandtss.ExportGenesis(ctx, k) + require.Equal(t, data.Params, exported.Params) +} From 28158d97ae68a5dbb1110592e195a4e55e0bc420 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 25 Apr 2024 16:32:55 +0700 Subject: [PATCH 047/132] rename --- x/bandtss/keeper/group_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/bandtss/keeper/group_test.go b/x/bandtss/keeper/group_test.go index 224429ddb..364f3910c 100644 --- a/x/bandtss/keeper/group_test.go +++ b/x/bandtss/keeper/group_test.go @@ -165,7 +165,7 @@ func TestFailCreateGroupReplacement(t *testing.T) { } } -func TestHandleReplaceGroup2(t *testing.T) { +func TestHandleReplaceGroup(t *testing.T) { s := testutil.NewTestSuite(t) ctx, k := s.Ctx, s.Keeper From aeb042aeff437d04b3bef9c1b8593cda1a23dcbc Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Fri, 26 Apr 2024 02:58:10 +0700 Subject: [PATCH 048/132] add currentGroup query --- proto/bandtss/v1beta1/query.proto | 14 +- x/bandtss/keeper/grpc_query.go | 16 +- x/bandtss/types/query.pb.go | 303 +++++++++++++++++++++++------- 3 files changed, 262 insertions(+), 71 deletions(-) diff --git a/proto/bandtss/v1beta1/query.proto b/proto/bandtss/v1beta1/query.proto index 50a000b00..80577156b 100644 --- a/proto/bandtss/v1beta1/query.proto +++ b/proto/bandtss/v1beta1/query.proto @@ -86,8 +86,18 @@ message QueryCurrentGroupRequest {} // QueryCurrentGroupResponse is the response type for the Query/CurrentGroup RPC method. message QueryCurrentGroupResponse { - // TODO: add more field later when add election flow. - uint64 group_id = 1 [(gogoproto.customname) = "GroupID"]; + // group_id is the ID of the current group. + uint64 group_id = 1 [ + (gogoproto.customname) = "GroupID", + (gogoproto.casttype) = "github.com/bandprotocol/chain/v2/pkg/tss.GroupID" + ];// size is the number of members in the group. + uint64 size = 2; + // threshold is the minimum number of members needed to generate a valid signature. + uint64 threshold = 3; + // pub_key is the public key generated by the group. + bytes pub_key = 4 [(gogoproto.casttype) = "github.com/bandprotocol/chain/v2/pkg/tss.Point"]; + // status is the status of the current group. + .tss.v1beta1.GroupStatus status = 5; } // QuerySingingRequest is the request type for the Query/Signing RPC method. diff --git a/x/bandtss/keeper/grpc_query.go b/x/bandtss/keeper/grpc_query.go index ea1a1967f..79404a2aa 100644 --- a/x/bandtss/keeper/grpc_query.go +++ b/x/bandtss/keeper/grpc_query.go @@ -78,7 +78,6 @@ func (q queryServer) Members( } // CurrentGroup function handles the request to get the current group information. -// TODO: update current group response later when add election flow. func (q queryServer) CurrentGroup( goCtx context.Context, req *types.QueryCurrentGroupRequest, @@ -86,8 +85,21 @@ func (q queryServer) CurrentGroup( ctx := sdk.UnwrapSDKContext(goCtx) groupID := q.k.GetCurrentGroupID(ctx) + if groupID == 0 { + return nil, types.ErrNoActiveGroup + } + + group, err := q.k.tssKeeper.GetGroup(ctx, groupID) + if err != nil { + return nil, err + } + return &types.QueryCurrentGroupResponse{ - GroupID: uint64(groupID), + GroupID: groupID, + Size_: group.Size_, + Threshold: group.Threshold, + PubKey: group.PubKey, + Status: group.Status, }, nil } diff --git a/x/bandtss/types/query.pb.go b/x/bandtss/types/query.pb.go index 94cb57575..0e9fce342 100644 --- a/x/bandtss/types/query.pb.go +++ b/x/bandtss/types/query.pb.go @@ -6,9 +6,10 @@ package types import ( context "context" fmt "fmt" - types1 "github.com/bandprotocol/chain/v2/x/tss/types" + github_com_bandprotocol_chain_v2_pkg_tss "github.com/bandprotocol/chain/v2/pkg/tss" + types "github.com/bandprotocol/chain/v2/x/tss/types" github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" + types1 "github.com/cosmos/cosmos-sdk/types" query "github.com/cosmos/cosmos-sdk/types/query" _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" @@ -357,8 +358,15 @@ var xxx_messageInfo_QueryCurrentGroupRequest proto.InternalMessageInfo // QueryCurrentGroupResponse is the response type for the Query/CurrentGroup RPC method. type QueryCurrentGroupResponse struct { - // TODO: add more field later when add election flow. - GroupID uint64 `protobuf:"varint,1,opt,name=group_id,json=groupId,proto3" json:"group_id,omitempty"` + // group_id is the ID of the current group. + GroupID github_com_bandprotocol_chain_v2_pkg_tss.GroupID `protobuf:"varint,1,opt,name=group_id,json=groupId,proto3,casttype=github.com/bandprotocol/chain/v2/pkg/tss.GroupID" json:"group_id,omitempty"` + Size_ uint64 `protobuf:"varint,2,opt,name=size,proto3" json:"size,omitempty"` + // threshold is the minimum number of members needed to generate a valid signature. + Threshold uint64 `protobuf:"varint,3,opt,name=threshold,proto3" json:"threshold,omitempty"` + // pub_key is the public key generated by the group. + PubKey github_com_bandprotocol_chain_v2_pkg_tss.Point `protobuf:"bytes,4,opt,name=pub_key,json=pubKey,proto3,casttype=github.com/bandprotocol/chain/v2/pkg/tss.Point" json:"pub_key,omitempty"` + // status is the status of the current group. + Status types.GroupStatus `protobuf:"varint,5,opt,name=status,proto3,enum=tss.v1beta1.GroupStatus" json:"status,omitempty"` } func (m *QueryCurrentGroupResponse) Reset() { *m = QueryCurrentGroupResponse{} } @@ -394,13 +402,41 @@ func (m *QueryCurrentGroupResponse) XXX_DiscardUnknown() { var xxx_messageInfo_QueryCurrentGroupResponse proto.InternalMessageInfo -func (m *QueryCurrentGroupResponse) GetGroupID() uint64 { +func (m *QueryCurrentGroupResponse) GetGroupID() github_com_bandprotocol_chain_v2_pkg_tss.GroupID { if m != nil { return m.GroupID } return 0 } +func (m *QueryCurrentGroupResponse) GetSize_() uint64 { + if m != nil { + return m.Size_ + } + return 0 +} + +func (m *QueryCurrentGroupResponse) GetThreshold() uint64 { + if m != nil { + return m.Threshold + } + return 0 +} + +func (m *QueryCurrentGroupResponse) GetPubKey() github_com_bandprotocol_chain_v2_pkg_tss.Point { + if m != nil { + return m.PubKey + } + return nil +} + +func (m *QueryCurrentGroupResponse) GetStatus() types.GroupStatus { + if m != nil { + return m.Status + } + return types.GROUP_STATUS_UNSPECIFIED +} + // QuerySingingRequest is the request type for the Query/Signing RPC method. type QuerySigningRequest struct { // signing_id is the ID of the signing request. @@ -454,9 +490,9 @@ type QuerySigningResponse struct { // requester is the address of requester who paid for the Bandtss signing. Requester string `protobuf:"bytes,2,opt,name=requester,proto3" json:"requester,omitempty"` // current_group_signing_result is the signing result from the current group. - CurrentGroupSigningResult *types1.SigningResult `protobuf:"bytes,3,opt,name=current_group_signing_result,json=currentGroupSigningResult,proto3" json:"current_group_signing_result,omitempty"` + CurrentGroupSigningResult *types.SigningResult `protobuf:"bytes,3,opt,name=current_group_signing_result,json=currentGroupSigningResult,proto3" json:"current_group_signing_result,omitempty"` // replacing_group_signing_result is the signing result from the replacing group. - ReplacingGroupSigningResult *types1.SigningResult `protobuf:"bytes,4,opt,name=replacing_group_signing_result,json=replacingGroupSigningResult,proto3" json:"replacing_group_signing_result,omitempty"` + ReplacingGroupSigningResult *types.SigningResult `protobuf:"bytes,4,opt,name=replacing_group_signing_result,json=replacingGroupSigningResult,proto3" json:"replacing_group_signing_result,omitempty"` } func (m *QuerySigningResponse) Reset() { *m = QuerySigningResponse{} } @@ -506,14 +542,14 @@ func (m *QuerySigningResponse) GetRequester() string { return "" } -func (m *QuerySigningResponse) GetCurrentGroupSigningResult() *types1.SigningResult { +func (m *QuerySigningResponse) GetCurrentGroupSigningResult() *types.SigningResult { if m != nil { return m.CurrentGroupSigningResult } return nil } -func (m *QuerySigningResponse) GetReplacingGroupSigningResult() *types1.SigningResult { +func (m *QuerySigningResponse) GetReplacingGroupSigningResult() *types.SigningResult { if m != nil { return m.ReplacingGroupSigningResult } @@ -621,60 +657,67 @@ func init() { func init() { proto.RegisterFile("bandtss/v1beta1/query.proto", fileDescriptor_85d3a287ab772b87) } var fileDescriptor_85d3a287ab772b87 = []byte{ - // 842 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x55, 0xc1, 0x6e, 0xd3, 0x4c, - 0x10, 0x8e, 0xdb, 0xfe, 0x49, 0xb3, 0xf9, 0xa5, 0x5f, 0xda, 0xbf, 0xa8, 0x89, 0x9b, 0x3a, 0x91, - 0x09, 0x21, 0xad, 0x84, 0xdd, 0x16, 0x78, 0x00, 0xd2, 0x8a, 0xaa, 0x08, 0x24, 0x30, 0x37, 0x10, - 0x0a, 0x8e, 0xb3, 0xb8, 0x16, 0x89, 0xd7, 0xf5, 0x3a, 0x55, 0x4b, 0x55, 0x21, 0x71, 0x40, 0x5c, - 0x90, 0x10, 0x5c, 0x79, 0x02, 0x9e, 0xa4, 0xc7, 0x22, 0x2e, 0x9c, 0x0a, 0x4a, 0x79, 0x10, 0xe4, - 0xdd, 0x71, 0x62, 0xc7, 0x49, 0xdb, 0x53, 0xeb, 0x99, 0x6f, 0xe6, 0xfb, 0x66, 0x66, 0x67, 0x82, - 0x96, 0xda, 0xa6, 0xdb, 0x09, 0x18, 0xd3, 0xf7, 0xd7, 0xdb, 0x24, 0x30, 0xd7, 0xf5, 0xbd, 0x3e, - 0xf1, 0x0f, 0x35, 0xcf, 0xa7, 0x01, 0xc5, 0xff, 0x81, 0x53, 0x03, 0xa7, 0xbc, 0x60, 0x53, 0x9b, - 0x72, 0x9f, 0x1e, 0xfe, 0x27, 0x60, 0xf2, 0xaa, 0x45, 0x59, 0x8f, 0x32, 0xbd, 0x6d, 0x32, 0x22, - 0xe2, 0x87, 0xd9, 0x3c, 0xd3, 0x76, 0x5c, 0x33, 0x70, 0xa8, 0x0b, 0x58, 0x25, 0x8e, 0x8d, 0x50, - 0x16, 0x75, 0x22, 0x7f, 0xd9, 0xa6, 0xd4, 0xee, 0x12, 0xdd, 0xf4, 0x1c, 0xdd, 0x74, 0x5d, 0x1a, - 0xf0, 0x60, 0x06, 0xde, 0xe5, 0x71, 0xb5, 0x91, 0xc0, 0x29, 0x6e, 0x9b, 0xb8, 0x84, 0x39, 0x91, - 0xfb, 0x5a, 0xdc, 0x35, 0x8c, 0x52, 0x17, 0x10, 0x7e, 0x12, 0x8a, 0x7e, 0x6c, 0xfa, 0x66, 0x8f, - 0x19, 0x64, 0xaf, 0x4f, 0x58, 0xa0, 0x3e, 0x44, 0xff, 0x27, 0xac, 0xcc, 0xa3, 0x2e, 0x23, 0xf8, - 0x2e, 0xca, 0x7a, 0xdc, 0x52, 0x94, 0xaa, 0x52, 0xa3, 0xb0, 0xb1, 0xa8, 0x8d, 0xf5, 0x48, 0x13, - 0x01, 0xcd, 0xb9, 0x93, 0xb3, 0x4a, 0xc6, 0x00, 0xb0, 0xfa, 0x06, 0xb2, 0x3d, 0x22, 0xbd, 0x36, - 0xf1, 0x23, 0x12, 0xbc, 0x84, 0xf2, 0x0e, 0x6b, 0x99, 0x56, 0xe0, 0xec, 0x13, 0x9e, 0x70, 0xde, - 0x98, 0x77, 0xd8, 0x3d, 0xfe, 0x8d, 0xef, 0x23, 0x34, 0x6a, 0x5f, 0x71, 0x86, 0xd3, 0xd5, 0x35, - 0xd1, 0x3f, 0x2d, 0xec, 0x9f, 0x26, 0x66, 0x35, 0x22, 0xb6, 0x09, 0x24, 0x36, 0x62, 0x91, 0xea, - 0x67, 0x09, 0x2d, 0x24, 0xc9, 0xa1, 0x96, 0x75, 0x94, 0xeb, 0x09, 0x53, 0x51, 0xaa, 0xce, 0x4e, - 0x2c, 0x46, 0x84, 0x18, 0x11, 0x0e, 0x6f, 0x4f, 0xd0, 0x74, 0xf3, 0x52, 0x4d, 0x82, 0x2f, 0x21, - 0x4a, 0x83, 0xa6, 0x03, 0x01, 0xf4, 0xa3, 0x88, 0x72, 0x66, 0xa7, 0xe3, 0x13, 0x26, 0xda, 0x9b, - 0x37, 0xa2, 0xcf, 0xe1, 0x38, 0x22, 0xfc, 0x68, 0x1c, 0x42, 0xda, 0xd4, 0x71, 0x88, 0x80, 0x68, - 0x1c, 0x02, 0xac, 0xca, 0xa8, 0xc8, 0xb3, 0x6d, 0xf6, 0x7d, 0x9f, 0xb8, 0xc1, 0xb6, 0x4f, 0xfb, - 0x5e, 0x34, 0xf8, 0x4d, 0x54, 0x9a, 0xe0, 0x03, 0xbe, 0x3a, 0x9a, 0xb7, 0x43, 0x43, 0xcb, 0xe9, - 0x70, 0xc6, 0xb9, 0x66, 0x61, 0x70, 0x56, 0xc9, 0x71, 0xd0, 0xce, 0x96, 0x91, 0xe3, 0xce, 0x9d, - 0x8e, 0x7a, 0x07, 0xe4, 0x3e, 0x75, 0x6c, 0xd7, 0x71, 0xed, 0xa8, 0xbe, 0x65, 0x84, 0x98, 0xb0, - 0x0c, 0x13, 0x18, 0x79, 0xb0, 0xec, 0x74, 0xd4, 0xef, 0x33, 0x30, 0xa9, 0x61, 0x18, 0xd0, 0xbe, - 0x40, 0xb3, 0xaf, 0x08, 0x81, 0x29, 0x95, 0x12, 0xfd, 0x8e, 0xea, 0xdc, 0xa4, 0x8e, 0xdb, 0x5c, - 0x0b, 0xab, 0xfc, 0xf6, 0xab, 0xd2, 0xb0, 0x9d, 0x60, 0xb7, 0xdf, 0xd6, 0x2c, 0xda, 0xd3, 0x61, - 0xe1, 0xc4, 0x9f, 0x5b, 0xac, 0xf3, 0x5a, 0x0f, 0x0e, 0x3d, 0xc2, 0x78, 0x00, 0x33, 0xc2, 0xbc, - 0xb8, 0x8c, 0xf2, 0xbe, 0x50, 0x48, 0x7c, 0x3e, 0xd4, 0xbc, 0x31, 0x32, 0xe0, 0xe7, 0xa8, 0x6c, - 0x89, 0x5e, 0xb4, 0x44, 0xed, 0x51, 0x09, 0x3e, 0x61, 0xfd, 0x6e, 0x50, 0x9c, 0xe5, 0x9d, 0x97, - 0xb5, 0x78, 0xd7, 0x47, 0x05, 0xf4, 0xbb, 0x81, 0x51, 0xb2, 0x62, 0xbd, 0x4c, 0xb8, 0x70, 0x0b, - 0x29, 0x3e, 0xf1, 0xba, 0xa6, 0x15, 0x26, 0x9c, 0x98, 0x7e, 0xee, 0xd2, 0xf4, 0x4b, 0xc3, 0x0c, - 0x69, 0x02, 0xb5, 0x84, 0x16, 0x79, 0x4b, 0x0d, 0x8e, 0x21, 0x3d, 0xe2, 0x06, 0xd1, 0xa4, 0x5f, - 0xc2, 0x2b, 0x48, 0xb8, 0xa0, 0xe3, 0x5b, 0xa8, 0xe0, 0x8f, 0xcc, 0xf0, 0xba, 0xca, 0xa9, 0xd7, - 0x15, 0x0b, 0x85, 0x27, 0x16, 0x0f, 0xdb, 0xf8, 0x9a, 0x45, 0xff, 0x70, 0x0a, 0x1c, 0xa0, 0xac, - 0x38, 0x0c, 0xf8, 0x7a, 0x2a, 0x49, 0xfa, 0xfa, 0xc8, 0xb5, 0x8b, 0x41, 0x42, 0xa4, 0x5a, 0x79, - 0xf7, 0xe3, 0xcf, 0x97, 0x99, 0x12, 0x5e, 0xd4, 0xc7, 0x0f, 0x9f, 0x38, 0x3b, 0xf8, 0x00, 0xe5, - 0x60, 0xe9, 0xf1, 0x94, 0x8c, 0xc9, 0x83, 0x24, 0xdf, 0xb8, 0x04, 0x05, 0xc4, 0x55, 0x4e, 0x2c, - 0xe3, 0x62, 0x8a, 0x38, 0x3a, 0x14, 0x6f, 0x51, 0x56, 0x04, 0x4d, 0xab, 0x37, 0xb1, 0xf8, 0x72, - 0xed, 0x62, 0x10, 0xd0, 0xae, 0x72, 0xda, 0x1a, 0x56, 0xa7, 0xd1, 0xea, 0x47, 0x70, 0x2f, 0x8e, - 0xf1, 0x47, 0x09, 0xfd, 0x1b, 0x5f, 0x61, 0xbc, 0x32, 0x99, 0x62, 0xc2, 0x09, 0x90, 0x57, 0xaf, - 0x02, 0x05, 0x4d, 0x75, 0xae, 0xa9, 0x8a, 0x95, 0x94, 0xa6, 0xc4, 0xd2, 0xe0, 0xf7, 0x12, 0xca, - 0xc1, 0xcb, 0x9c, 0x36, 0x8b, 0xe4, 0xb1, 0x98, 0x36, 0x8b, 0xb1, 0xdb, 0xa0, 0x6a, 0x5c, 0x40, - 0x03, 0xd7, 0x53, 0x02, 0x60, 0x91, 0x98, 0x7e, 0x34, 0x3a, 0x3a, 0xc7, 0xf8, 0x83, 0x84, 0x0a, - 0xb1, 0x67, 0x8b, 0x1b, 0x93, 0x69, 0xd2, 0xfb, 0x22, 0xaf, 0x5c, 0x01, 0x09, 0xa2, 0x6a, 0x5c, - 0x94, 0x82, 0xcb, 0x29, 0x51, 0xb1, 0xf5, 0x68, 0x3e, 0x38, 0x19, 0x28, 0xd2, 0xe9, 0x40, 0x91, - 0x7e, 0x0f, 0x14, 0xe9, 0xd3, 0xb9, 0x92, 0x39, 0x3d, 0x57, 0x32, 0x3f, 0xcf, 0x95, 0xcc, 0xb3, - 0xb5, 0xd8, 0x01, 0x0b, 0x33, 0xf0, 0x5f, 0x6a, 0x8b, 0x76, 0x75, 0x6b, 0xd7, 0x74, 0x5c, 0x7d, - 0x7f, 0x43, 0x3f, 0x18, 0x66, 0xe6, 0xe7, 0xac, 0x9d, 0xe5, 0x90, 0xdb, 0x7f, 0x03, 0x00, 0x00, - 0xff, 0xff, 0x40, 0x07, 0xf3, 0x27, 0xd1, 0x08, 0x00, 0x00, + // 955 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x55, 0x41, 0x6f, 0xe3, 0x44, + 0x14, 0xae, 0xdb, 0x6c, 0xd2, 0x4c, 0x57, 0x20, 0x0d, 0x45, 0x75, 0xdc, 0xac, 0x13, 0x99, 0x52, + 0xb2, 0x95, 0xb0, 0xdb, 0x00, 0x67, 0x44, 0x76, 0xc5, 0xaa, 0x2c, 0x48, 0x8b, 0x7b, 0x5b, 0x84, + 0x82, 0xe3, 0x0c, 0xee, 0xa8, 0x89, 0xc7, 0xeb, 0x19, 0x57, 0xdb, 0xae, 0x56, 0x48, 0x1c, 0x10, + 0x17, 0x24, 0x04, 0x57, 0x7e, 0x01, 0x47, 0x7e, 0xc5, 0x1e, 0x17, 0x71, 0xe1, 0x14, 0x50, 0xca, + 0xaf, 0xd8, 0x13, 0xf2, 0xcc, 0x73, 0x62, 0xd7, 0xc9, 0xa6, 0xa7, 0xd6, 0xf3, 0xbe, 0xf7, 0xbe, + 0x6f, 0xbe, 0xf7, 0xe6, 0x05, 0xed, 0x0e, 0xbc, 0x70, 0x28, 0x38, 0x77, 0xce, 0x8f, 0x06, 0x44, + 0x78, 0x47, 0xce, 0x93, 0x84, 0xc4, 0x17, 0x76, 0x14, 0x33, 0xc1, 0xf0, 0x9b, 0x10, 0xb4, 0x21, + 0x68, 0x6c, 0x07, 0x2c, 0x60, 0x32, 0xe6, 0xa4, 0xff, 0x29, 0x98, 0x71, 0xe0, 0x33, 0x3e, 0x66, + 0xdc, 0x19, 0x78, 0x9c, 0xa8, 0xfc, 0x59, 0xb5, 0xc8, 0x0b, 0x68, 0xe8, 0x09, 0xca, 0x42, 0xc0, + 0x9a, 0x79, 0x6c, 0x86, 0xf2, 0x19, 0xcd, 0xe2, 0xcd, 0x80, 0xb1, 0x60, 0x44, 0x1c, 0x2f, 0xa2, + 0x8e, 0x17, 0x86, 0x4c, 0xc8, 0x64, 0x0e, 0xd1, 0x3b, 0xd7, 0xd5, 0x66, 0x02, 0x97, 0x84, 0x03, + 0x12, 0x12, 0x4e, 0xb3, 0xf0, 0xdb, 0xf9, 0xd0, 0x2c, 0xcb, 0xda, 0x46, 0xf8, 0xcb, 0x54, 0xf4, + 0x23, 0x2f, 0xf6, 0xc6, 0xdc, 0x25, 0x4f, 0x12, 0xc2, 0x85, 0xf5, 0x39, 0x7a, 0xab, 0x70, 0xca, + 0x23, 0x16, 0x72, 0x82, 0x3f, 0x42, 0xd5, 0x48, 0x9e, 0xe8, 0x5a, 0x5b, 0xeb, 0x6c, 0x75, 0x77, + 0xec, 0x6b, 0x1e, 0xd9, 0x2a, 0xa1, 0x57, 0x79, 0x31, 0x69, 0xad, 0xb9, 0x00, 0xb6, 0x2e, 0xa1, + 0xda, 0x17, 0x64, 0x3c, 0x20, 0x71, 0x46, 0x82, 0x77, 0x51, 0x9d, 0xf2, 0xbe, 0xe7, 0x0b, 0x7a, + 0x4e, 0x64, 0xc1, 0x4d, 0x77, 0x93, 0xf2, 0x4f, 0xe4, 0x37, 0xfe, 0x14, 0xa1, 0xb9, 0x7d, 0xfa, + 0xba, 0xa4, 0xdb, 0xb7, 0x95, 0x7f, 0x76, 0xea, 0x9f, 0xad, 0x7a, 0x35, 0x27, 0x0e, 0x08, 0x14, + 0x76, 0x73, 0x99, 0xd6, 0x2f, 0x1a, 0xda, 0x2e, 0x92, 0xc3, 0x5d, 0x8e, 0x50, 0x6d, 0xac, 0x8e, + 0x74, 0xad, 0xbd, 0xb1, 0xf0, 0x32, 0x2a, 0xc5, 0xcd, 0x70, 0xf8, 0xc1, 0x02, 0x4d, 0xef, 0xad, + 0xd4, 0xa4, 0xf8, 0x0a, 0xa2, 0x6c, 0x30, 0x1d, 0x08, 0xc0, 0x0f, 0x1d, 0xd5, 0xbc, 0xe1, 0x30, + 0x26, 0x5c, 0xd9, 0x5b, 0x77, 0xb3, 0xcf, 0x59, 0x3b, 0x32, 0xfc, 0xbc, 0x1d, 0x4a, 0xda, 0xd2, + 0x76, 0xa8, 0x84, 0xac, 0x1d, 0x0a, 0x6c, 0x19, 0x48, 0x97, 0xd5, 0xee, 0x25, 0x71, 0x4c, 0x42, + 0xf1, 0x20, 0x66, 0x49, 0x94, 0x35, 0xfe, 0x8f, 0x75, 0xd4, 0x58, 0x10, 0x04, 0xc2, 0xc7, 0x68, + 0x33, 0x48, 0x0f, 0xfa, 0x74, 0x28, 0x29, 0x2b, 0xbd, 0x8f, 0xa7, 0x93, 0x56, 0x4d, 0x82, 0x8e, + 0xef, 0xbf, 0x9a, 0xb4, 0x0e, 0x03, 0x2a, 0x4e, 0x93, 0x81, 0xed, 0xb3, 0xb1, 0x9c, 0x4e, 0x39, + 0x63, 0x3e, 0x1b, 0x39, 0xfe, 0xa9, 0x47, 0x43, 0xe7, 0xbc, 0xeb, 0x44, 0x67, 0x81, 0x9c, 0x3e, + 0xc8, 0x71, 0x6b, 0xb2, 0xe0, 0xf1, 0x10, 0x37, 0x51, 0x85, 0xd3, 0x4b, 0x22, 0x6d, 0xad, 0xf4, + 0x36, 0xa7, 0x93, 0x56, 0xe5, 0x84, 0x5e, 0x12, 0x57, 0x9e, 0xe2, 0x26, 0xaa, 0x8b, 0xd3, 0x98, + 0xf0, 0x53, 0x36, 0x1a, 0xea, 0x1b, 0x29, 0xc4, 0x9d, 0x1f, 0xe0, 0x87, 0xa8, 0x16, 0x25, 0x83, + 0xfe, 0x19, 0xb9, 0xd0, 0x2b, 0x6d, 0xad, 0x73, 0xbb, 0xd7, 0x7d, 0x35, 0x69, 0xd9, 0x37, 0xd6, + 0xf2, 0x88, 0xd1, 0x50, 0xb8, 0xd5, 0x28, 0x19, 0x3c, 0x24, 0x17, 0xf8, 0x10, 0x55, 0xb9, 0xf0, + 0x44, 0xc2, 0xf5, 0x5b, 0x6d, 0xad, 0xf3, 0x46, 0x57, 0xb7, 0xf3, 0x8e, 0x4a, 0xdd, 0x27, 0x32, + 0xee, 0x02, 0xce, 0xfa, 0x10, 0xda, 0x73, 0x42, 0x83, 0x90, 0x86, 0x41, 0xd6, 0xcf, 0x3b, 0x08, + 0x71, 0x75, 0x32, 0xf3, 0xcb, 0xad, 0xc3, 0xc9, 0xf1, 0xd0, 0xfa, 0x73, 0x1d, 0x26, 0x73, 0x96, + 0x06, 0x2e, 0x7f, 0x8d, 0x36, 0xbe, 0x25, 0x04, 0xa6, 0xb2, 0x51, 0x98, 0xaf, 0x4c, 0xc5, 0x3d, + 0x46, 0xc3, 0xde, 0x61, 0xda, 0xd5, 0xdf, 0xff, 0x69, 0x75, 0x72, 0x17, 0x85, 0x05, 0xa3, 0xfe, + 0xbc, 0xcf, 0x87, 0x67, 0x8e, 0xb8, 0x88, 0x08, 0x97, 0x09, 0xdc, 0x4d, 0xeb, 0xa6, 0x56, 0xc6, + 0x4a, 0x21, 0x89, 0xa5, 0xdb, 0x75, 0x77, 0x7e, 0x80, 0xbf, 0x42, 0x4d, 0x5f, 0xb5, 0xbe, 0xaf, + 0x5a, 0x9d, 0x5d, 0x21, 0x26, 0x3c, 0x19, 0x09, 0xe9, 0xfd, 0x56, 0xd7, 0x28, 0x78, 0x32, 0xbf, + 0x40, 0x32, 0x12, 0x6e, 0xc3, 0xcf, 0x8d, 0x4e, 0x21, 0x84, 0xfb, 0xc8, 0x8c, 0x49, 0x34, 0xf2, + 0xfc, 0xb4, 0xe0, 0xc2, 0xf2, 0x95, 0x95, 0xe5, 0x77, 0x67, 0x15, 0xca, 0x04, 0x56, 0x03, 0xed, + 0x48, 0x4b, 0x5d, 0x89, 0x21, 0x63, 0x12, 0x8a, 0x6c, 0xb2, 0xbf, 0x81, 0xa9, 0x2f, 0x84, 0xc0, + 0xf1, 0xfb, 0x68, 0x2b, 0x9e, 0x1f, 0xc3, 0x6b, 0x6a, 0x96, 0x5e, 0x53, 0x2e, 0x15, 0x9e, 0x54, + 0x3e, 0xad, 0xfb, 0x5b, 0x15, 0xdd, 0x92, 0x14, 0x58, 0xa0, 0xaa, 0x5a, 0x84, 0xf8, 0x9d, 0x52, + 0x91, 0xf2, 0xb6, 0x35, 0xf6, 0x5e, 0x0f, 0x52, 0x22, 0xad, 0xd6, 0xf7, 0x7f, 0xfd, 0xf7, 0xeb, + 0x7a, 0x03, 0xef, 0x38, 0xd7, 0x17, 0xbd, 0x5a, 0xb3, 0xf8, 0x29, 0xaa, 0xc1, 0x92, 0xc3, 0x4b, + 0x2a, 0x16, 0x17, 0xb0, 0xf1, 0xee, 0x0a, 0x14, 0x10, 0xb7, 0x25, 0xb1, 0x81, 0xf5, 0x12, 0x71, + 0xb6, 0x18, 0xbf, 0x43, 0x55, 0x95, 0xb4, 0xec, 0xbe, 0x85, 0x45, 0x67, 0xec, 0xbd, 0x1e, 0x04, + 0xb4, 0x07, 0x92, 0x76, 0x0f, 0x5b, 0xcb, 0x68, 0x9d, 0x67, 0xb0, 0x1f, 0x9f, 0xe3, 0x9f, 0x34, + 0x74, 0x3b, 0xbf, 0xb1, 0xf0, 0xdd, 0xc5, 0x14, 0x0b, 0x56, 0x9e, 0x71, 0x70, 0x13, 0x28, 0x68, + 0xda, 0x97, 0x9a, 0xda, 0xd8, 0x2c, 0x69, 0x2a, 0x3c, 0x1a, 0xfc, 0x83, 0x86, 0x6a, 0x30, 0x99, + 0xcb, 0x7a, 0x51, 0x5c, 0x16, 0xcb, 0x7a, 0x71, 0x6d, 0x37, 0x58, 0xb6, 0x14, 0xd0, 0xc1, 0xfb, + 0x25, 0x01, 0xf0, 0x90, 0xb8, 0xf3, 0x6c, 0xbe, 0x74, 0x9e, 0xe3, 0x1f, 0x35, 0xb4, 0x95, 0x1b, + 0x5b, 0xdc, 0x59, 0x4c, 0x53, 0x7e, 0x2f, 0xc6, 0xdd, 0x1b, 0x20, 0x41, 0xd4, 0x9e, 0x14, 0x65, + 0xe2, 0x66, 0x49, 0x54, 0xee, 0x79, 0xf4, 0x3e, 0x7b, 0x31, 0x35, 0xb5, 0x97, 0x53, 0x53, 0xfb, + 0x77, 0x6a, 0x6a, 0x3f, 0x5f, 0x99, 0x6b, 0x2f, 0xaf, 0xcc, 0xb5, 0xbf, 0xaf, 0xcc, 0xb5, 0xc7, + 0xab, 0x7f, 0x35, 0x9e, 0xce, 0x2a, 0xcb, 0x75, 0x36, 0xa8, 0x4a, 0xc8, 0x07, 0xff, 0x07, 0x00, + 0x00, 0xff, 0xff, 0xef, 0xa4, 0x6b, 0x2c, 0xc1, 0x09, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -1205,6 +1248,28 @@ func (m *QueryCurrentGroupResponse) MarshalToSizedBuffer(dAtA []byte) (int, erro _ = i var l int _ = l + if m.Status != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Status)) + i-- + dAtA[i] = 0x28 + } + if len(m.PubKey) > 0 { + i -= len(m.PubKey) + copy(dAtA[i:], m.PubKey) + i = encodeVarintQuery(dAtA, i, uint64(len(m.PubKey))) + i-- + dAtA[i] = 0x22 + } + if m.Threshold != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Threshold)) + i-- + dAtA[i] = 0x18 + } + if m.Size_ != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Size_)) + i-- + dAtA[i] = 0x10 + } if m.GroupID != 0 { i = encodeVarintQuery(dAtA, i, uint64(m.GroupID)) i-- @@ -1473,6 +1538,19 @@ func (m *QueryCurrentGroupResponse) Size() (n int) { if m.GroupID != 0 { n += 1 + sovQuery(uint64(m.GroupID)) } + if m.Size_ != 0 { + n += 1 + sovQuery(uint64(m.Size_)) + } + if m.Threshold != 0 { + n += 1 + sovQuery(uint64(m.Threshold)) + } + l = len(m.PubKey) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + if m.Status != 0 { + n += 1 + sovQuery(uint64(m.Status)) + } return n } @@ -2158,7 +2236,98 @@ func (m *QueryCurrentGroupResponse) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.GroupID |= uint64(b&0x7F) << shift + m.GroupID |= github_com_bandprotocol_chain_v2_pkg_tss.GroupID(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Size_", wireType) + } + m.Size_ = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Size_ |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Threshold", wireType) + } + m.Threshold = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Threshold |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PubKey", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PubKey = append(m.PubKey[:0], dAtA[iNdEx:postIndex]...) + if m.PubKey == nil { + m.PubKey = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Status", wireType) + } + m.Status = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Status |= types.GroupStatus(b&0x7F) << shift if b < 0x80 { break } @@ -2311,7 +2480,7 @@ func (m *QuerySigningResponse) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Fee = append(m.Fee, types.Coin{}) + m.Fee = append(m.Fee, types1.Coin{}) if err := m.Fee[len(m.Fee)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } @@ -2378,7 +2547,7 @@ func (m *QuerySigningResponse) Unmarshal(dAtA []byte) error { return io.ErrUnexpectedEOF } if m.CurrentGroupSigningResult == nil { - m.CurrentGroupSigningResult = &types1.SigningResult{} + m.CurrentGroupSigningResult = &types.SigningResult{} } if err := m.CurrentGroupSigningResult.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err @@ -2414,7 +2583,7 @@ func (m *QuerySigningResponse) Unmarshal(dAtA []byte) error { return io.ErrUnexpectedEOF } if m.ReplacingGroupSigningResult == nil { - m.ReplacingGroupSigningResult = &types1.SigningResult{} + m.ReplacingGroupSigningResult = &types.SigningResult{} } if err := m.ReplacingGroupSigningResult.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err From c8ee76f15945fbdbbcaf66f8d59f925c2b1a5980 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Fri, 26 Apr 2024 08:59:55 +0700 Subject: [PATCH 049/132] fix lint --- x/bandtss/genesis_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x/bandtss/genesis_test.go b/x/bandtss/genesis_test.go index 361d281cb..9a4088b2e 100644 --- a/x/bandtss/genesis_test.go +++ b/x/bandtss/genesis_test.go @@ -3,12 +3,13 @@ package bandtss_test import ( "testing" + "github.com/stretchr/testify/require" + "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/testing/testapp" "github.com/bandprotocol/chain/v2/x/bandtss" "github.com/bandprotocol/chain/v2/x/bandtss/testutil" "github.com/bandprotocol/chain/v2/x/bandtss/types" - "github.com/stretchr/testify/require" ) func TestExportGenesis(t *testing.T) { From 8a2bdccab40da9ea330bafe631f7d876d9877820 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Fri, 26 Apr 2024 15:44:44 +0700 Subject: [PATCH 050/132] add events --- x/bandtss/keeper/group.go | 16 ++++++++++++++-- x/bandtss/keeper/hooks.go | 9 +++++++++ x/bandtss/keeper/signing.go | 13 +++++++++++++ x/bandtss/types/events.go | 22 +++++++++++++--------- 4 files changed, 49 insertions(+), 11 deletions(-) diff --git a/x/bandtss/keeper/group.go b/x/bandtss/keeper/group.go index 1c4c0302c..ee3620ea9 100644 --- a/x/bandtss/keeper/group.go +++ b/x/bandtss/keeper/group.go @@ -71,6 +71,7 @@ func (k Keeper) CreateGroupReplacement( sdk.NewAttribute(tsstypes.AttributeKeySigningID, fmt.Sprintf("%d", signing.ID)), sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", currentGroupID)), sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", newGroupID)), + sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_WAITING_SIGNING.String()), ), ) @@ -96,6 +97,15 @@ func (k Keeper) HandleReplaceGroup(ctx sdk.Context, endBlockTime time.Time) erro if signing.Status == tsstypes.SIGNING_STATUS_SUCCESS { replacement.Status = types.REPLACEMENT_STATUS_WAITING_REPLACE k.SetReplacement(ctx, replacement) + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeReplacement, + sdk.NewAttribute(tsstypes.AttributeKeySigningID, fmt.Sprintf("%d", replacement.SigningID)), + sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", replacement.CurrentGroupID)), + sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", replacement.NewGroupID)), + sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_WAITING_REPLACE.String()), + ), + ) } } @@ -112,10 +122,11 @@ func (k Keeper) HandleFailReplacementSigning(ctx sdk.Context, replacement types. ctx.EventManager().EmitEvent( sdk.NewEvent( - types.EventTypeReplacementFailed, + types.EventTypeReplacement, sdk.NewAttribute(tsstypes.AttributeKeySigningID, fmt.Sprintf("%d", replacement.SigningID)), sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", replacement.CurrentGroupID)), sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", replacement.NewGroupID)), + sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_FALLEN.String()), ), ) return nil @@ -142,10 +153,11 @@ func (k Keeper) ReplaceGroup(ctx sdk.Context, replacement types.Replacement) err k.SetReplacement(ctx, replacement) ctx.EventManager().EmitEvent( sdk.NewEvent( - types.EventTypeReplacementSuccess, + types.EventTypeReplacement, sdk.NewAttribute(tsstypes.AttributeKeySigningID, fmt.Sprintf("%d", replacement.SigningID)), sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", replacement.CurrentGroupID)), sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", replacement.NewGroupID)), + sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_SUCCESS.String()), ), ) diff --git a/x/bandtss/keeper/hooks.go b/x/bandtss/keeper/hooks.go index acf63810c..f904c01db 100644 --- a/x/bandtss/keeper/hooks.go +++ b/x/bandtss/keeper/hooks.go @@ -1,6 +1,8 @@ package keeper import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bandprotocol/chain/v2/x/bandtss/types" @@ -35,6 +37,13 @@ func (h Hooks) AfterCreatingGroupCompleted(ctx sdk.Context, group tsstypes.Group } } + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeFirstGroupCreated, + sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", group.ID)), + ), + ) + return nil } diff --git a/x/bandtss/keeper/signing.go b/x/bandtss/keeper/signing.go index ccc268239..83753089f 100644 --- a/x/bandtss/keeper/signing.go +++ b/x/bandtss/keeper/signing.go @@ -1,6 +1,8 @@ package keeper import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/kv" @@ -203,6 +205,17 @@ func (k Keeper) HandleCreateSigning( ReplacingGroupSigningID: replacingGroupSigningID, }) + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeSigningRequestCreated, + sdk.NewAttribute(types.AttributeKeySigningID, fmt.Sprintf("%d", bandtssSigningID)), + sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", currentGroupID)), + sdk.NewAttribute(types.AttributeKeyCurrentGroupSigningID, fmt.Sprintf("%d", currentGroupSigning.ID)), + sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", replacement.NewGroupID)), + sdk.NewAttribute(types.AttributeKeyReplacingGroupSigningID, fmt.Sprintf("%d", replacingGroupSigningID)), + ), + ) + return bandtssSigningID, nil } diff --git a/x/bandtss/types/events.go b/x/bandtss/types/events.go index f4ab90631..e7a1437e3 100644 --- a/x/bandtss/types/events.go +++ b/x/bandtss/types/events.go @@ -1,14 +1,18 @@ package types const ( - EventTypeActivate = "activate" - EventTypeHealthCheck = "health_check" - EventTypeInactiveStatus = "inactive_status" - EventTypeReplacement = "replacement" - EventTypeReplacementSuccess = "replacement_success" - EventTypeReplacementFailed = "replacement_failed" + EventTypeActivate = "activate" + EventTypeHealthCheck = "health_check" + EventTypeInactiveStatus = "inactive_status" + EventTypeFirstGroupCreated = "first_group_created" + EventTypeReplacement = "replacement" + EventTypeSigningRequestCreated = "bandtss_signing_request_created" - AttributeKeyAddress = "address" - AttributeKeyCurrentGroupID = "current_group_id" - AttributeKeyReplacingGroupID = "replacing_group_id" + AttributeKeyAddress = "address" + AttributeKeySigningID = "bandtss_signing_id" + AttributeKeyCurrentGroupID = "current_group_id" + AttributeKeyReplacingGroupID = "replacing_group_id" + AttributeKeyCurrentGroupSigningID = "current_group_signing_id" + AttributeKeyReplacingGroupSigningID = "replacing_group_signing_id" + AttributeKeyReplacementStatus = "replacement_status" ) From 1d5954d4c9d97279d4aa0b4200d3e0bd5a8ea4ce Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Fri, 26 Apr 2024 15:52:40 +0700 Subject: [PATCH 051/132] fix params --- proto/bandtss/v1beta1/genesis.proto | 4 +- x/bandtss/keeper/keeper_test.go | 4 +- x/bandtss/keeper/msg_server_test.go | 1 - x/bandtss/types/genesis.pb.go | 152 +++++++++------------------- x/bandtss/types/params.go | 12 +-- x/bandtss/types/query.pb.go | 122 +++++++++++----------- 6 files changed, 115 insertions(+), 180 deletions(-) diff --git a/proto/bandtss/v1beta1/genesis.proto b/proto/bandtss/v1beta1/genesis.proto index 827b2e3ed..af4ef5b7e 100644 --- a/proto/bandtss/v1beta1/genesis.proto +++ b/proto/bandtss/v1beta1/genesis.proto @@ -40,10 +40,8 @@ message Params { uint64 reward_percentage = 2 [(gogoproto.customname) = "RewardPercentage"]; // inactive_penalty_duration is the duration where a member cannot activate back after inactive. google.protobuf.Duration inactive_penalty_duration = 3 [(gogoproto.stdduration) = true, (gogoproto.nullable) = false]; - // jail_penalty_duration is the duration where a member cannot activate back after jail. - google.protobuf.Duration jail_penalty_duration = 4 [(gogoproto.stdduration) = true, (gogoproto.nullable) = false]; // fee is the tokens that will be paid per signing. - repeated cosmos.base.v1beta1.Coin fee = 5 + repeated cosmos.base.v1beta1.Coin fee = 4 [(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; } diff --git a/x/bandtss/keeper/keeper_test.go b/x/bandtss/keeper/keeper_test.go index df9d4e0bb..226f62de8 100644 --- a/x/bandtss/keeper/keeper_test.go +++ b/x/bandtss/keeper/keeper_test.go @@ -197,8 +197,8 @@ func (s *KeeperTestSuite) TestParams() { input: types.Params{ ActiveDuration: time.Duration(0), InactivePenaltyDuration: time.Duration(0), - JailPenaltyDuration: time.Duration(0), RewardPercentage: 0, + Fee: sdk.NewCoins(), }, expectErr: true, expectErrStr: "must be positive:", @@ -209,7 +209,7 @@ func (s *KeeperTestSuite) TestParams() { ActiveDuration: types.DefaultActiveDuration, RewardPercentage: types.DefaultRewardPercentage, InactivePenaltyDuration: types.DefaultInactivePenaltyDuration, - JailPenaltyDuration: types.DefaultJailPenaltyDuration, + Fee: types.DefaultFee, }, expectErr: false, }, diff --git a/x/bandtss/keeper/msg_server_test.go b/x/bandtss/keeper/msg_server_test.go index d13a3bf0d..a82bfd57c 100644 --- a/x/bandtss/keeper/msg_server_test.go +++ b/x/bandtss/keeper/msg_server_test.go @@ -488,7 +488,6 @@ func (s *KeeperTestSuite) TestUpdateParams() { ActiveDuration: types.DefaultActiveDuration, RewardPercentage: types.DefaultRewardPercentage, InactivePenaltyDuration: types.DefaultInactivePenaltyDuration, - JailPenaltyDuration: types.DefaultJailPenaltyDuration, Fee: types.DefaultFee, }, }, diff --git a/x/bandtss/types/genesis.pb.go b/x/bandtss/types/genesis.pb.go index 401d9012f..54f5b1611 100644 --- a/x/bandtss/types/genesis.pb.go +++ b/x/bandtss/types/genesis.pb.go @@ -140,10 +140,8 @@ type Params struct { RewardPercentage uint64 `protobuf:"varint,2,opt,name=reward_percentage,json=rewardPercentage,proto3" json:"reward_percentage,omitempty"` // inactive_penalty_duration is the duration where a member cannot activate back after inactive. InactivePenaltyDuration time.Duration `protobuf:"bytes,3,opt,name=inactive_penalty_duration,json=inactivePenaltyDuration,proto3,stdduration" json:"inactive_penalty_duration"` - // jail_penalty_duration is the duration where a member cannot activate back after jail. - JailPenaltyDuration time.Duration `protobuf:"bytes,4,opt,name=jail_penalty_duration,json=jailPenaltyDuration,proto3,stdduration" json:"jail_penalty_duration"` // fee is the tokens that will be paid per signing. - Fee github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,5,rep,name=fee,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"fee"` + Fee github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=fee,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"fee"` } func (m *Params) Reset() { *m = Params{} } @@ -200,13 +198,6 @@ func (m *Params) GetInactivePenaltyDuration() time.Duration { return 0 } -func (m *Params) GetJailPenaltyDuration() time.Duration { - if m != nil { - return m.JailPenaltyDuration - } - return 0 -} - func (m *Params) GetFee() github_com_cosmos_cosmos_sdk_types.Coins { if m != nil { return m.Fee @@ -278,50 +269,48 @@ func init() { func init() { proto.RegisterFile("bandtss/v1beta1/genesis.proto", fileDescriptor_521cec35d8e53d42) } var fileDescriptor_521cec35d8e53d42 = []byte{ - // 673 bytes of a gzipped FileDescriptorProto + // 655 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x54, 0x4f, 0x4f, 0xd4, 0x4c, - 0x18, 0xdf, 0xb2, 0xfb, 0x2e, 0x30, 0xf0, 0xc2, 0x32, 0x60, 0xe8, 0x12, 0xdd, 0x22, 0x5e, 0xf6, - 0x62, 0x0b, 0x18, 0x63, 0xe2, 0xcd, 0xee, 0x46, 0x82, 0x91, 0x48, 0xca, 0xc1, 0xc4, 0xc4, 0x34, - 0xd3, 0x76, 0x28, 0x95, 0xed, 0x4c, 0xd3, 0x99, 0x45, 0xf9, 0x0e, 0x1e, 0x3c, 0xfa, 0x19, 0x3c, - 0xfa, 0x29, 0x38, 0x19, 0x8e, 0x9e, 0x8a, 0x29, 0xdf, 0x82, 0x93, 0xe9, 0xcc, 0xb4, 0xbb, 0xee, - 0x4a, 0xe4, 0x04, 0x33, 0xbf, 0x3f, 0xcf, 0x33, 0x7d, 0x7e, 0xcf, 0x82, 0x07, 0x1e, 0x22, 0x01, - 0x67, 0xcc, 0x3a, 0xdb, 0xf1, 0x30, 0x47, 0x3b, 0x56, 0x88, 0x09, 0x66, 0x11, 0x33, 0x93, 0x94, - 0x72, 0x0a, 0x97, 0x15, 0x6c, 0x2a, 0x78, 0x63, 0x2d, 0xa4, 0x21, 0x15, 0x98, 0x55, 0xfc, 0x27, - 0x69, 0x1b, 0x9d, 0x90, 0xd2, 0x70, 0x80, 0x2d, 0x71, 0xf2, 0x86, 0xc7, 0x56, 0x30, 0x4c, 0x11, - 0x8f, 0x28, 0x51, 0xf8, 0x54, 0x95, 0xd2, 0x56, 0xc9, 0x7d, 0xca, 0x62, 0xca, 0x2c, 0x0f, 0x31, - 0x5c, 0x51, 0x7c, 0x1a, 0x95, 0xf2, 0xb6, 0xc4, 0x5d, 0x59, 0x57, 0x1e, 0x24, 0xb4, 0xf5, 0xb9, - 0x01, 0x16, 0xf7, 0x64, 0xcb, 0x47, 0x1c, 0x71, 0x0c, 0x9f, 0x82, 0x66, 0x82, 0x52, 0x14, 0x33, - 0x5d, 0xdb, 0xd4, 0xba, 0x0b, 0xbb, 0xeb, 0xe6, 0xc4, 0x13, 0xcc, 0x43, 0x01, 0xdb, 0x8d, 0x8b, - 0xcc, 0xa8, 0x39, 0x8a, 0x0c, 0x9f, 0x81, 0xd9, 0x18, 0xc7, 0x1e, 0x4e, 0x99, 0x3e, 0xb3, 0x59, - 0xff, 0xab, 0xee, 0x40, 0xe0, 0x4a, 0x57, 0xb2, 0x61, 0x02, 0x5a, 0xfe, 0x30, 0x4d, 0x31, 0xe1, - 0x6e, 0x98, 0xd2, 0x61, 0xe2, 0x46, 0x81, 0x5e, 0xdf, 0xd4, 0xba, 0x0d, 0xfb, 0x65, 0x9e, 0x19, - 0x4b, 0x3d, 0x89, 0xed, 0x15, 0xd0, 0x7e, 0xff, 0x26, 0x33, 0xb6, 0xc3, 0x88, 0x9f, 0x0c, 0x3d, - 0xd3, 0xa7, 0xb1, 0xf8, 0x0a, 0xe2, 0x19, 0x3e, 0x1d, 0x58, 0xfe, 0x09, 0x8a, 0x88, 0x75, 0xb6, - 0x6b, 0x25, 0xa7, 0xa1, 0x55, 0xd4, 0x55, 0x1a, 0x67, 0xc9, 0x1f, 0xf7, 0x08, 0xe0, 0x23, 0xf0, - 0x3f, 0x8b, 0x42, 0x12, 0x91, 0xd0, 0xf5, 0xe9, 0x90, 0x70, 0xbd, 0x51, 0x94, 0x73, 0x16, 0xd5, - 0x65, 0xaf, 0xb8, 0x83, 0xcf, 0xc1, 0x9c, 0x3a, 0x33, 0xfd, 0x3f, 0xf1, 0x20, 0x7d, 0xea, 0x41, - 0x47, 0x92, 0xa0, 0x5e, 0x54, 0xf1, 0x21, 0x03, 0xab, 0x65, 0x81, 0x28, 0x70, 0x63, 0x94, 0x24, - 0xc2, 0xa6, 0x29, 0x6c, 0xba, 0xb7, 0xd9, 0xec, 0xf7, 0x0f, 0x24, 0x53, 0x8d, 0xc3, 0x6e, 0x17, - 0xb6, 0x79, 0x66, 0xac, 0x4c, 0x12, 0x98, 0xb3, 0xa2, 0xfc, 0xf7, 0x83, 0xf2, 0x0a, 0xf6, 0xc1, - 0x42, 0x8a, 0x93, 0x01, 0xf2, 0x71, 0x8c, 0x09, 0xd7, 0x67, 0xc5, 0xf0, 0xee, 0x4f, 0x15, 0x73, - 0x46, 0x1c, 0xd5, 0xf7, 0xb8, 0x6c, 0xeb, 0x7b, 0x1d, 0x34, 0xe5, 0x7c, 0xe1, 0x6b, 0xb0, 0x8c, - 0x7c, 0x1e, 0x9d, 0x61, 0xb7, 0x0c, 0xa3, 0x4a, 0x44, 0xdb, 0x94, 0x69, 0x35, 0xcb, 0xb4, 0x9a, - 0x7d, 0x45, 0xb0, 0xe7, 0x0a, 0xc7, 0xaf, 0x57, 0x86, 0xe6, 0x2c, 0x49, 0x6d, 0x89, 0xc0, 0x17, - 0x60, 0x25, 0xc5, 0x1f, 0x51, 0x1a, 0xb8, 0x09, 0x4e, 0x7d, 0x4c, 0x38, 0x0a, 0xb1, 0x3e, 0x23, - 0xe6, 0xbc, 0x96, 0x67, 0x46, 0xcb, 0x11, 0xe0, 0x61, 0x85, 0x39, 0xad, 0x74, 0xe2, 0x06, 0xba, - 0xa0, 0x1d, 0x11, 0xd5, 0x52, 0x82, 0x09, 0x1a, 0xf0, 0xf3, 0x51, 0x6b, 0xf5, 0xbb, 0xb7, 0xb6, - 0x5e, 0xba, 0x1c, 0x4a, 0x93, 0xaa, 0xc7, 0xb7, 0xe0, 0xde, 0x07, 0x14, 0x0d, 0xa6, 0xcd, 0x1b, - 0x77, 0x37, 0x5f, 0x2d, 0x1c, 0x26, 0x8d, 0xdf, 0x83, 0xfa, 0x31, 0xc6, 0x2a, 0x47, 0x6d, 0x53, - 0x2d, 0x60, 0xb1, 0xad, 0xd5, 0x5c, 0x7a, 0x34, 0x22, 0xf6, 0x76, 0x61, 0xf3, 0xed, 0xca, 0xe8, - 0x8e, 0x65, 0x5c, 0xad, 0xb6, 0xfc, 0xf3, 0x98, 0x05, 0xa7, 0x16, 0x3f, 0x4f, 0x30, 0x13, 0x02, - 0xe6, 0x14, 0xbe, 0x5b, 0x3f, 0x34, 0xb0, 0x7e, 0x4b, 0x88, 0xa0, 0x07, 0xc0, 0x28, 0x8b, 0x62, - 0x80, 0x0d, 0xbb, 0x97, 0x67, 0xc6, 0x7c, 0x25, 0xb8, 0xc9, 0x8c, 0xdd, 0x3b, 0xef, 0x54, 0xa5, - 0x72, 0xe6, 0xab, 0x08, 0xc2, 0x37, 0x00, 0xaa, 0x98, 0xb9, 0x63, 0xb5, 0xe4, 0x70, 0x1f, 0x16, - 0xc3, 0xb5, 0x25, 0x3a, 0x5e, 0x72, 0x54, 0xdf, 0x69, 0x79, 0x7f, 0xc2, 0x81, 0xfd, 0xea, 0x22, - 0xef, 0x68, 0x97, 0x79, 0x47, 0xfb, 0x95, 0x77, 0xb4, 0x2f, 0xd7, 0x9d, 0xda, 0xe5, 0x75, 0xa7, - 0xf6, 0xf3, 0xba, 0x53, 0x7b, 0xf7, 0xef, 0xed, 0xff, 0x54, 0xfe, 0x36, 0xca, 0xef, 0xe4, 0x35, - 0x05, 0xe5, 0xc9, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3e, 0xdf, 0xa7, 0x7b, 0xa9, 0x05, 0x00, - 0x00, + 0x18, 0xdf, 0xb2, 0xfb, 0x2e, 0x30, 0xf0, 0xc2, 0x32, 0x92, 0xd0, 0x25, 0xda, 0x22, 0x5e, 0xf6, + 0x62, 0x0b, 0x18, 0x63, 0xe2, 0xcd, 0xee, 0x46, 0x82, 0x91, 0x48, 0xca, 0xcd, 0xc4, 0x34, 0xd3, + 0x76, 0x28, 0x0d, 0xdb, 0x99, 0xa6, 0x33, 0x45, 0xf9, 0x0e, 0x1e, 0x3c, 0xfa, 0x19, 0xfc, 0x24, + 0x9c, 0x0c, 0x47, 0xbd, 0x14, 0x53, 0xbe, 0x05, 0x27, 0xd3, 0x99, 0x69, 0x77, 0x05, 0x89, 0x9c, + 0x76, 0x67, 0x7e, 0x7f, 0x9e, 0x67, 0xe6, 0xf9, 0x4d, 0xc1, 0x23, 0x1f, 0x91, 0x90, 0x33, 0x66, + 0x9f, 0x6e, 0xfb, 0x98, 0xa3, 0x6d, 0x3b, 0xc2, 0x04, 0xb3, 0x98, 0x59, 0x69, 0x46, 0x39, 0x85, + 0xcb, 0x0a, 0xb6, 0x14, 0xbc, 0xbe, 0x1a, 0xd1, 0x88, 0x0a, 0xcc, 0xae, 0xfe, 0x49, 0xda, 0xba, + 0x11, 0x51, 0x1a, 0x8d, 0xb1, 0x2d, 0x56, 0x7e, 0x7e, 0x64, 0x87, 0x79, 0x86, 0x78, 0x4c, 0x89, + 0xc2, 0x6f, 0x55, 0xa9, 0x6d, 0x95, 0x3c, 0xa0, 0x2c, 0xa1, 0xcc, 0xf6, 0x11, 0xc3, 0x0d, 0x25, + 0xa0, 0x71, 0x2d, 0xef, 0x4b, 0xdc, 0x93, 0x75, 0xe5, 0x42, 0x42, 0x9b, 0x9f, 0x3b, 0x60, 0x71, + 0x57, 0xb6, 0x7c, 0xc8, 0x11, 0xc7, 0xf0, 0x39, 0xe8, 0xa6, 0x28, 0x43, 0x09, 0xd3, 0xb5, 0x0d, + 0x6d, 0xb0, 0xb0, 0xb3, 0x66, 0xdd, 0x38, 0x82, 0x75, 0x20, 0x60, 0xa7, 0x73, 0x5e, 0x98, 0x2d, + 0x57, 0x91, 0xe1, 0x0b, 0x30, 0x9b, 0xe0, 0xc4, 0xc7, 0x19, 0xd3, 0x67, 0x36, 0xda, 0x7f, 0xd5, + 0xed, 0x0b, 0x5c, 0xe9, 0x6a, 0x36, 0x4c, 0x41, 0x2f, 0xc8, 0xb3, 0x0c, 0x13, 0xee, 0x45, 0x19, + 0xcd, 0x53, 0x2f, 0x0e, 0xf5, 0xf6, 0x86, 0x36, 0xe8, 0x38, 0xaf, 0xcb, 0xc2, 0x5c, 0x1a, 0x4a, + 0x6c, 0xb7, 0x82, 0xf6, 0x46, 0xd7, 0x85, 0xb9, 0x15, 0xc5, 0xfc, 0x38, 0xf7, 0xad, 0x80, 0x26, + 0xe2, 0x16, 0xc4, 0x31, 0x02, 0x3a, 0xb6, 0x83, 0x63, 0x14, 0x13, 0xfb, 0x74, 0xc7, 0x4e, 0x4f, + 0x22, 0xbb, 0xaa, 0xab, 0x34, 0xee, 0x52, 0x30, 0xed, 0x11, 0xc2, 0x27, 0xe0, 0x7f, 0x16, 0x47, + 0x24, 0x26, 0x91, 0x17, 0xd0, 0x9c, 0x70, 0xbd, 0x53, 0x95, 0x73, 0x17, 0xd5, 0xe6, 0xb0, 0xda, + 0x83, 0x2f, 0xc1, 0x9c, 0x5a, 0x33, 0xfd, 0x3f, 0x71, 0x20, 0xfd, 0xd6, 0x81, 0x0e, 0x25, 0x41, + 0x9d, 0xa8, 0xe1, 0x43, 0x06, 0x1e, 0xd4, 0x05, 0xe2, 0xd0, 0x4b, 0x50, 0x9a, 0x0a, 0x9b, 0xae, + 0xb0, 0x19, 0xdc, 0x65, 0xb3, 0x37, 0xda, 0x97, 0x4c, 0x35, 0x0e, 0xa7, 0x5f, 0xd9, 0x96, 0x85, + 0xb9, 0x72, 0x93, 0xc0, 0xdc, 0x15, 0xe5, 0xbf, 0x17, 0xd6, 0x5b, 0x70, 0x04, 0x16, 0x32, 0x9c, + 0x8e, 0x51, 0x80, 0x13, 0x4c, 0xb8, 0x3e, 0x2b, 0x86, 0xf7, 0xf0, 0x56, 0x31, 0x77, 0xc2, 0x51, + 0x7d, 0x4f, 0xcb, 0x36, 0x7f, 0xce, 0x80, 0xae, 0x9c, 0x2f, 0x7c, 0x0b, 0x96, 0x51, 0xc0, 0xe3, + 0x53, 0xec, 0xd5, 0x61, 0x54, 0x89, 0xe8, 0x5b, 0x32, 0xad, 0x56, 0x9d, 0x56, 0x6b, 0xa4, 0x08, + 0xce, 0x5c, 0xe5, 0xf8, 0xf5, 0xd2, 0xd4, 0xdc, 0x25, 0xa9, 0xad, 0x11, 0xf8, 0x0a, 0xac, 0x64, + 0xf8, 0x23, 0xca, 0x42, 0x2f, 0xc5, 0x59, 0x80, 0x09, 0x47, 0x11, 0xd6, 0x67, 0xc4, 0x9c, 0x57, + 0xcb, 0xc2, 0xec, 0xb9, 0x02, 0x3c, 0x68, 0x30, 0xb7, 0x97, 0xdd, 0xd8, 0x81, 0x1e, 0xe8, 0xc7, + 0x44, 0xb5, 0x94, 0x62, 0x82, 0xc6, 0xfc, 0x6c, 0xd2, 0x5a, 0xfb, 0xfe, 0xad, 0xad, 0xd5, 0x2e, + 0x07, 0xd2, 0xa4, 0xe9, 0xf1, 0x03, 0x68, 0x1f, 0x61, 0xac, 0x77, 0xc4, 0x9c, 0xfa, 0x96, 0x7a, + 0x27, 0xd5, 0xa3, 0x6a, 0xae, 0x6f, 0x48, 0x63, 0xe2, 0x6c, 0x55, 0x56, 0xdf, 0x2e, 0xcd, 0xc1, + 0x54, 0x14, 0xd5, 0x0b, 0x94, 0x3f, 0x4f, 0x59, 0x78, 0x62, 0xf3, 0xb3, 0x14, 0x33, 0x21, 0x60, + 0x6e, 0xe5, 0xbb, 0xf9, 0x5d, 0x03, 0x6b, 0x77, 0xcc, 0x1a, 0xfa, 0x00, 0x4c, 0x22, 0x23, 0xee, + 0xb9, 0xe3, 0x0c, 0xcb, 0xc2, 0x9c, 0x6f, 0x04, 0xd7, 0x85, 0xb9, 0x73, 0xef, 0xe8, 0x37, 0x2a, + 0x77, 0xbe, 0x49, 0x0a, 0x7c, 0x07, 0xa0, 0x4a, 0x83, 0x37, 0x55, 0x4b, 0xce, 0xe0, 0x71, 0x35, + 0x03, 0x47, 0xa2, 0xd3, 0x25, 0x27, 0xf5, 0xdd, 0x9e, 0xff, 0x27, 0x1c, 0x3a, 0x6f, 0xce, 0x4b, + 0x43, 0xbb, 0x28, 0x0d, 0xed, 0x57, 0x69, 0x68, 0x5f, 0xae, 0x8c, 0xd6, 0xc5, 0x95, 0xd1, 0xfa, + 0x71, 0x65, 0xb4, 0xde, 0xff, 0xfb, 0x91, 0x7e, 0xaa, 0x3f, 0x61, 0xf2, 0x9e, 0xfc, 0xae, 0xa0, + 0x3c, 0xfb, 0x1d, 0x00, 0x00, 0xff, 0xff, 0x95, 0x16, 0xc0, 0xc3, 0x50, 0x05, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { @@ -450,36 +439,28 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x2a + dAtA[i] = 0x22 } } - n3, err3 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.JailPenaltyDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.JailPenaltyDuration):]) + n3, err3 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.InactivePenaltyDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.InactivePenaltyDuration):]) if err3 != nil { return 0, err3 } i -= n3 i = encodeVarintGenesis(dAtA, i, uint64(n3)) i-- - dAtA[i] = 0x22 - n4, err4 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.InactivePenaltyDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.InactivePenaltyDuration):]) - if err4 != nil { - return 0, err4 - } - i -= n4 - i = encodeVarintGenesis(dAtA, i, uint64(n4)) - i-- dAtA[i] = 0x1a if m.RewardPercentage != 0 { i = encodeVarintGenesis(dAtA, i, uint64(m.RewardPercentage)) i-- dAtA[i] = 0x10 } - n5, err5 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.ActiveDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ActiveDuration):]) - if err5 != nil { - return 0, err5 + n4, err4 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.ActiveDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ActiveDuration):]) + if err4 != nil { + return 0, err4 } - i -= n5 - i = encodeVarintGenesis(dAtA, i, uint64(n5)) + i -= n4 + i = encodeVarintGenesis(dAtA, i, uint64(n4)) i-- dAtA[i] = 0xa return len(dAtA) - i, nil @@ -579,8 +560,6 @@ func (m *Params) Size() (n int) { } l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.InactivePenaltyDuration) n += 1 + l + sovGenesis(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.JailPenaltyDuration) - n += 1 + l + sovGenesis(uint64(l)) if len(m.Fee) > 0 { for _, e := range m.Fee { l = e.Size() @@ -982,39 +961,6 @@ func (m *Params) Unmarshal(dAtA []byte) error { } iNdEx = postIndex case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field JailPenaltyDuration", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.JailPenaltyDuration, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Fee", wireType) } diff --git a/x/bandtss/types/params.go b/x/bandtss/types/params.go index a13346e26..a9d39059a 100644 --- a/x/bandtss/types/params.go +++ b/x/bandtss/types/params.go @@ -10,9 +10,8 @@ import ( ) const ( - DefaultActiveDuration time.Duration = time.Hour * 24 // 1 days - DefaultInactivePenaltyDuration time.Duration = time.Minute * 10 // 10 minutes - DefaultJailPenaltyDuration time.Duration = time.Hour * 24 * 30 // 30 days + DefaultActiveDuration time.Duration = time.Hour * 24 // 1 days + DefaultInactivePenaltyDuration time.Duration = time.Minute * 10 // 10 minutes // compute the BandTSS reward following the allocation to Oracle. If the Oracle reward amounts to 40%, // the BandTSS reward will be determined from the remaining 60%. DefaultRewardPercentage = uint64(50) @@ -25,14 +24,12 @@ func NewParams( activeDuration time.Duration, rewardPercentage uint64, inactivePenaltyDuration time.Duration, - jailPenaltyDuration time.Duration, fee sdk.Coins, ) Params { return Params{ ActiveDuration: activeDuration, RewardPercentage: rewardPercentage, InactivePenaltyDuration: inactivePenaltyDuration, - JailPenaltyDuration: jailPenaltyDuration, Fee: fee, } } @@ -43,7 +40,6 @@ func DefaultParams() Params { ActiveDuration: DefaultActiveDuration, RewardPercentage: DefaultRewardPercentage, InactivePenaltyDuration: DefaultInactivePenaltyDuration, - JailPenaltyDuration: DefaultJailPenaltyDuration, Fee: DefaultFee, } } @@ -58,10 +54,6 @@ func (p Params) Validate() error { return err } - if err := validateTimeDuration("jail penalty duration")(p.JailPenaltyDuration); err != nil { - return err - } - if err := validateUint64("reward percentage", false)(p.RewardPercentage); err != nil { return err } diff --git a/x/bandtss/types/query.pb.go b/x/bandtss/types/query.pb.go index 0e9fce342..81ab1f482 100644 --- a/x/bandtss/types/query.pb.go +++ b/x/bandtss/types/query.pb.go @@ -657,67 +657,67 @@ func init() { func init() { proto.RegisterFile("bandtss/v1beta1/query.proto", fileDescriptor_85d3a287ab772b87) } var fileDescriptor_85d3a287ab772b87 = []byte{ - // 955 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x55, 0x41, 0x6f, 0xe3, 0x44, - 0x14, 0xae, 0xdb, 0x6c, 0xd2, 0x4c, 0x57, 0x20, 0x0d, 0x45, 0x75, 0xdc, 0xac, 0x13, 0x99, 0x52, - 0xb2, 0x95, 0xb0, 0xdb, 0x00, 0x67, 0x44, 0x76, 0xc5, 0xaa, 0x2c, 0x48, 0x8b, 0x7b, 0x5b, 0x84, - 0x82, 0xe3, 0x0c, 0xee, 0xa8, 0x89, 0xc7, 0xeb, 0x19, 0x57, 0xdb, 0xae, 0x56, 0x48, 0x1c, 0x10, - 0x17, 0x24, 0x04, 0x57, 0x7e, 0x01, 0x47, 0x7e, 0xc5, 0x1e, 0x17, 0x71, 0xe1, 0x14, 0x50, 0xca, - 0xaf, 0xd8, 0x13, 0xf2, 0xcc, 0x73, 0x62, 0xd7, 0xc9, 0xa6, 0xa7, 0xd6, 0xf3, 0xbe, 0xf7, 0xbe, - 0x6f, 0xbe, 0xf7, 0xe6, 0x05, 0xed, 0x0e, 0xbc, 0x70, 0x28, 0x38, 0x77, 0xce, 0x8f, 0x06, 0x44, - 0x78, 0x47, 0xce, 0x93, 0x84, 0xc4, 0x17, 0x76, 0x14, 0x33, 0xc1, 0xf0, 0x9b, 0x10, 0xb4, 0x21, - 0x68, 0x6c, 0x07, 0x2c, 0x60, 0x32, 0xe6, 0xa4, 0xff, 0x29, 0x98, 0x71, 0xe0, 0x33, 0x3e, 0x66, - 0xdc, 0x19, 0x78, 0x9c, 0xa8, 0xfc, 0x59, 0xb5, 0xc8, 0x0b, 0x68, 0xe8, 0x09, 0xca, 0x42, 0xc0, - 0x9a, 0x79, 0x6c, 0x86, 0xf2, 0x19, 0xcd, 0xe2, 0xcd, 0x80, 0xb1, 0x60, 0x44, 0x1c, 0x2f, 0xa2, - 0x8e, 0x17, 0x86, 0x4c, 0xc8, 0x64, 0x0e, 0xd1, 0x3b, 0xd7, 0xd5, 0x66, 0x02, 0x97, 0x84, 0x03, - 0x12, 0x12, 0x4e, 0xb3, 0xf0, 0xdb, 0xf9, 0xd0, 0x2c, 0xcb, 0xda, 0x46, 0xf8, 0xcb, 0x54, 0xf4, - 0x23, 0x2f, 0xf6, 0xc6, 0xdc, 0x25, 0x4f, 0x12, 0xc2, 0x85, 0xf5, 0x39, 0x7a, 0xab, 0x70, 0xca, - 0x23, 0x16, 0x72, 0x82, 0x3f, 0x42, 0xd5, 0x48, 0x9e, 0xe8, 0x5a, 0x5b, 0xeb, 0x6c, 0x75, 0x77, - 0xec, 0x6b, 0x1e, 0xd9, 0x2a, 0xa1, 0x57, 0x79, 0x31, 0x69, 0xad, 0xb9, 0x00, 0xb6, 0x2e, 0xa1, - 0xda, 0x17, 0x64, 0x3c, 0x20, 0x71, 0x46, 0x82, 0x77, 0x51, 0x9d, 0xf2, 0xbe, 0xe7, 0x0b, 0x7a, - 0x4e, 0x64, 0xc1, 0x4d, 0x77, 0x93, 0xf2, 0x4f, 0xe4, 0x37, 0xfe, 0x14, 0xa1, 0xb9, 0x7d, 0xfa, - 0xba, 0xa4, 0xdb, 0xb7, 0x95, 0x7f, 0x76, 0xea, 0x9f, 0xad, 0x7a, 0x35, 0x27, 0x0e, 0x08, 0x14, - 0x76, 0x73, 0x99, 0xd6, 0x2f, 0x1a, 0xda, 0x2e, 0x92, 0xc3, 0x5d, 0x8e, 0x50, 0x6d, 0xac, 0x8e, - 0x74, 0xad, 0xbd, 0xb1, 0xf0, 0x32, 0x2a, 0xc5, 0xcd, 0x70, 0xf8, 0xc1, 0x02, 0x4d, 0xef, 0xad, - 0xd4, 0xa4, 0xf8, 0x0a, 0xa2, 0x6c, 0x30, 0x1d, 0x08, 0xc0, 0x0f, 0x1d, 0xd5, 0xbc, 0xe1, 0x30, - 0x26, 0x5c, 0xd9, 0x5b, 0x77, 0xb3, 0xcf, 0x59, 0x3b, 0x32, 0xfc, 0xbc, 0x1d, 0x4a, 0xda, 0xd2, - 0x76, 0xa8, 0x84, 0xac, 0x1d, 0x0a, 0x6c, 0x19, 0x48, 0x97, 0xd5, 0xee, 0x25, 0x71, 0x4c, 0x42, - 0xf1, 0x20, 0x66, 0x49, 0x94, 0x35, 0xfe, 0x8f, 0x75, 0xd4, 0x58, 0x10, 0x04, 0xc2, 0xc7, 0x68, - 0x33, 0x48, 0x0f, 0xfa, 0x74, 0x28, 0x29, 0x2b, 0xbd, 0x8f, 0xa7, 0x93, 0x56, 0x4d, 0x82, 0x8e, - 0xef, 0xbf, 0x9a, 0xb4, 0x0e, 0x03, 0x2a, 0x4e, 0x93, 0x81, 0xed, 0xb3, 0xb1, 0x9c, 0x4e, 0x39, - 0x63, 0x3e, 0x1b, 0x39, 0xfe, 0xa9, 0x47, 0x43, 0xe7, 0xbc, 0xeb, 0x44, 0x67, 0x81, 0x9c, 0x3e, - 0xc8, 0x71, 0x6b, 0xb2, 0xe0, 0xf1, 0x10, 0x37, 0x51, 0x85, 0xd3, 0x4b, 0x22, 0x6d, 0xad, 0xf4, - 0x36, 0xa7, 0x93, 0x56, 0xe5, 0x84, 0x5e, 0x12, 0x57, 0x9e, 0xe2, 0x26, 0xaa, 0x8b, 0xd3, 0x98, - 0xf0, 0x53, 0x36, 0x1a, 0xea, 0x1b, 0x29, 0xc4, 0x9d, 0x1f, 0xe0, 0x87, 0xa8, 0x16, 0x25, 0x83, - 0xfe, 0x19, 0xb9, 0xd0, 0x2b, 0x6d, 0xad, 0x73, 0xbb, 0xd7, 0x7d, 0x35, 0x69, 0xd9, 0x37, 0xd6, - 0xf2, 0x88, 0xd1, 0x50, 0xb8, 0xd5, 0x28, 0x19, 0x3c, 0x24, 0x17, 0xf8, 0x10, 0x55, 0xb9, 0xf0, - 0x44, 0xc2, 0xf5, 0x5b, 0x6d, 0xad, 0xf3, 0x46, 0x57, 0xb7, 0xf3, 0x8e, 0x4a, 0xdd, 0x27, 0x32, - 0xee, 0x02, 0xce, 0xfa, 0x10, 0xda, 0x73, 0x42, 0x83, 0x90, 0x86, 0x41, 0xd6, 0xcf, 0x3b, 0x08, - 0x71, 0x75, 0x32, 0xf3, 0xcb, 0xad, 0xc3, 0xc9, 0xf1, 0xd0, 0xfa, 0x73, 0x1d, 0x26, 0x73, 0x96, - 0x06, 0x2e, 0x7f, 0x8d, 0x36, 0xbe, 0x25, 0x04, 0xa6, 0xb2, 0x51, 0x98, 0xaf, 0x4c, 0xc5, 0x3d, - 0x46, 0xc3, 0xde, 0x61, 0xda, 0xd5, 0xdf, 0xff, 0x69, 0x75, 0x72, 0x17, 0x85, 0x05, 0xa3, 0xfe, - 0xbc, 0xcf, 0x87, 0x67, 0x8e, 0xb8, 0x88, 0x08, 0x97, 0x09, 0xdc, 0x4d, 0xeb, 0xa6, 0x56, 0xc6, - 0x4a, 0x21, 0x89, 0xa5, 0xdb, 0x75, 0x77, 0x7e, 0x80, 0xbf, 0x42, 0x4d, 0x5f, 0xb5, 0xbe, 0xaf, - 0x5a, 0x9d, 0x5d, 0x21, 0x26, 0x3c, 0x19, 0x09, 0xe9, 0xfd, 0x56, 0xd7, 0x28, 0x78, 0x32, 0xbf, - 0x40, 0x32, 0x12, 0x6e, 0xc3, 0xcf, 0x8d, 0x4e, 0x21, 0x84, 0xfb, 0xc8, 0x8c, 0x49, 0x34, 0xf2, - 0xfc, 0xb4, 0xe0, 0xc2, 0xf2, 0x95, 0x95, 0xe5, 0x77, 0x67, 0x15, 0xca, 0x04, 0x56, 0x03, 0xed, - 0x48, 0x4b, 0x5d, 0x89, 0x21, 0x63, 0x12, 0x8a, 0x6c, 0xb2, 0xbf, 0x81, 0xa9, 0x2f, 0x84, 0xc0, - 0xf1, 0xfb, 0x68, 0x2b, 0x9e, 0x1f, 0xc3, 0x6b, 0x6a, 0x96, 0x5e, 0x53, 0x2e, 0x15, 0x9e, 0x54, - 0x3e, 0xad, 0xfb, 0x5b, 0x15, 0xdd, 0x92, 0x14, 0x58, 0xa0, 0xaa, 0x5a, 0x84, 0xf8, 0x9d, 0x52, - 0x91, 0xf2, 0xb6, 0x35, 0xf6, 0x5e, 0x0f, 0x52, 0x22, 0xad, 0xd6, 0xf7, 0x7f, 0xfd, 0xf7, 0xeb, - 0x7a, 0x03, 0xef, 0x38, 0xd7, 0x17, 0xbd, 0x5a, 0xb3, 0xf8, 0x29, 0xaa, 0xc1, 0x92, 0xc3, 0x4b, - 0x2a, 0x16, 0x17, 0xb0, 0xf1, 0xee, 0x0a, 0x14, 0x10, 0xb7, 0x25, 0xb1, 0x81, 0xf5, 0x12, 0x71, - 0xb6, 0x18, 0xbf, 0x43, 0x55, 0x95, 0xb4, 0xec, 0xbe, 0x85, 0x45, 0x67, 0xec, 0xbd, 0x1e, 0x04, - 0xb4, 0x07, 0x92, 0x76, 0x0f, 0x5b, 0xcb, 0x68, 0x9d, 0x67, 0xb0, 0x1f, 0x9f, 0xe3, 0x9f, 0x34, - 0x74, 0x3b, 0xbf, 0xb1, 0xf0, 0xdd, 0xc5, 0x14, 0x0b, 0x56, 0x9e, 0x71, 0x70, 0x13, 0x28, 0x68, - 0xda, 0x97, 0x9a, 0xda, 0xd8, 0x2c, 0x69, 0x2a, 0x3c, 0x1a, 0xfc, 0x83, 0x86, 0x6a, 0x30, 0x99, - 0xcb, 0x7a, 0x51, 0x5c, 0x16, 0xcb, 0x7a, 0x71, 0x6d, 0x37, 0x58, 0xb6, 0x14, 0xd0, 0xc1, 0xfb, - 0x25, 0x01, 0xf0, 0x90, 0xb8, 0xf3, 0x6c, 0xbe, 0x74, 0x9e, 0xe3, 0x1f, 0x35, 0xb4, 0x95, 0x1b, - 0x5b, 0xdc, 0x59, 0x4c, 0x53, 0x7e, 0x2f, 0xc6, 0xdd, 0x1b, 0x20, 0x41, 0xd4, 0x9e, 0x14, 0x65, - 0xe2, 0x66, 0x49, 0x54, 0xee, 0x79, 0xf4, 0x3e, 0x7b, 0x31, 0x35, 0xb5, 0x97, 0x53, 0x53, 0xfb, - 0x77, 0x6a, 0x6a, 0x3f, 0x5f, 0x99, 0x6b, 0x2f, 0xaf, 0xcc, 0xb5, 0xbf, 0xaf, 0xcc, 0xb5, 0xc7, - 0xab, 0x7f, 0x35, 0x9e, 0xce, 0x2a, 0xcb, 0x75, 0x36, 0xa8, 0x4a, 0xc8, 0x07, 0xff, 0x07, 0x00, - 0x00, 0xff, 0xff, 0xef, 0xa4, 0x6b, 0x2c, 0xc1, 0x09, 0x00, 0x00, + // 945 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x55, 0x41, 0x6f, 0xdc, 0x44, + 0x14, 0x8e, 0x93, 0xed, 0x6e, 0x76, 0x52, 0x81, 0x34, 0x04, 0xc5, 0xeb, 0x6c, 0xbd, 0x2b, 0x13, + 0xc2, 0x36, 0x12, 0x76, 0xb2, 0xc0, 0x19, 0xb1, 0xad, 0xa8, 0x42, 0x41, 0x2a, 0xee, 0xad, 0x08, + 0x2d, 0x5e, 0x7b, 0x70, 0x46, 0xd9, 0xf5, 0xb8, 0x9e, 0x71, 0xd4, 0xb4, 0xaa, 0x90, 0x38, 0x20, + 0x2e, 0x48, 0x08, 0xae, 0xfc, 0x00, 0xc4, 0x2f, 0xe9, 0xb1, 0x88, 0x0b, 0xa7, 0x80, 0x12, 0x7e, + 0x45, 0x4f, 0xc8, 0x33, 0xcf, 0x6b, 0x3b, 0xde, 0x6d, 0x72, 0xca, 0x7a, 0xde, 0xf7, 0xde, 0xf7, + 0xcd, 0xf7, 0xde, 0xbc, 0xa0, 0xed, 0x89, 0x17, 0x05, 0x82, 0x73, 0xe7, 0xe4, 0x60, 0x42, 0x84, + 0x77, 0xe0, 0x3c, 0x4e, 0x49, 0x72, 0x6a, 0xc7, 0x09, 0x13, 0x0c, 0xbf, 0x09, 0x41, 0x1b, 0x82, + 0xc6, 0x66, 0xc8, 0x42, 0x26, 0x63, 0x4e, 0xf6, 0x4b, 0xc1, 0x8c, 0x3d, 0x9f, 0xf1, 0x19, 0xe3, + 0xce, 0xc4, 0xe3, 0x44, 0xe5, 0xcf, 0xab, 0xc5, 0x5e, 0x48, 0x23, 0x4f, 0x50, 0x16, 0x01, 0xd6, + 0x2c, 0x63, 0x73, 0x94, 0xcf, 0x68, 0x1e, 0xef, 0x86, 0x8c, 0x85, 0x53, 0xe2, 0x78, 0x31, 0x75, + 0xbc, 0x28, 0x62, 0x42, 0x26, 0x73, 0x88, 0xde, 0xba, 0xac, 0x36, 0x17, 0xb8, 0x24, 0x1c, 0x92, + 0x88, 0x70, 0x9a, 0x87, 0xdf, 0x2e, 0x87, 0xe6, 0x59, 0xd6, 0x26, 0xc2, 0x5f, 0x66, 0xa2, 0x1f, + 0x78, 0x89, 0x37, 0xe3, 0x2e, 0x79, 0x9c, 0x12, 0x2e, 0xac, 0xcf, 0xd1, 0x5b, 0x95, 0x53, 0x1e, + 0xb3, 0x88, 0x13, 0xfc, 0x11, 0x6a, 0xc6, 0xf2, 0x44, 0xd7, 0xfa, 0xda, 0x60, 0x63, 0xb8, 0x65, + 0x5f, 0xf2, 0xc8, 0x56, 0x09, 0xa3, 0xc6, 0x8b, 0xb3, 0xde, 0x8a, 0x0b, 0x60, 0xeb, 0x29, 0x54, + 0xfb, 0x82, 0xcc, 0x26, 0x24, 0xc9, 0x49, 0xf0, 0x36, 0x6a, 0x53, 0x3e, 0xf6, 0x7c, 0x41, 0x4f, + 0x88, 0x2c, 0xb8, 0xee, 0xae, 0x53, 0xfe, 0x89, 0xfc, 0xc6, 0x9f, 0x22, 0x54, 0xd8, 0xa7, 0xaf, + 0x4a, 0xba, 0x5d, 0x5b, 0xf9, 0x67, 0x67, 0xfe, 0xd9, 0xaa, 0x57, 0x05, 0x71, 0x48, 0xa0, 0xb0, + 0x5b, 0xca, 0xb4, 0x7e, 0xd1, 0xd0, 0x66, 0x95, 0x1c, 0xee, 0x72, 0x80, 0x5a, 0x33, 0x75, 0xa4, + 0x6b, 0xfd, 0xb5, 0x85, 0x97, 0x51, 0x29, 0x6e, 0x8e, 0xc3, 0xf7, 0x16, 0x68, 0x7a, 0xef, 0x4a, + 0x4d, 0x8a, 0xaf, 0x22, 0xca, 0x06, 0xd3, 0x81, 0x00, 0xfc, 0xd0, 0x51, 0xcb, 0x0b, 0x82, 0x84, + 0x70, 0x65, 0x6f, 0xdb, 0xcd, 0x3f, 0xe7, 0xed, 0xc8, 0xf1, 0x45, 0x3b, 0x94, 0xb4, 0xa5, 0xed, + 0x50, 0x09, 0x79, 0x3b, 0x14, 0xd8, 0x32, 0x90, 0x2e, 0xab, 0xdd, 0x49, 0x93, 0x84, 0x44, 0xe2, + 0x5e, 0xc2, 0xd2, 0x38, 0x6f, 0xfc, 0xef, 0xab, 0xa8, 0xb3, 0x20, 0x08, 0x84, 0x8f, 0xd0, 0x7a, + 0x98, 0x1d, 0x8c, 0x69, 0x20, 0x29, 0x1b, 0xa3, 0x8f, 0xcf, 0xcf, 0x7a, 0x2d, 0x09, 0x3a, 0xbc, + 0xfb, 0xea, 0xac, 0xb7, 0x1f, 0x52, 0x71, 0x94, 0x4e, 0x6c, 0x9f, 0xcd, 0xe4, 0x74, 0xca, 0x19, + 0xf3, 0xd9, 0xd4, 0xf1, 0x8f, 0x3c, 0x1a, 0x39, 0x27, 0x43, 0x27, 0x3e, 0x0e, 0xe5, 0xf4, 0x41, + 0x8e, 0xdb, 0x92, 0x05, 0x0f, 0x03, 0x8c, 0x51, 0x83, 0xd3, 0xa7, 0x44, 0xda, 0xda, 0x70, 0xe5, + 0x6f, 0xdc, 0x45, 0x6d, 0x71, 0x94, 0x10, 0x7e, 0xc4, 0xa6, 0x81, 0xbe, 0x26, 0x03, 0xc5, 0x01, + 0xbe, 0x8f, 0x5a, 0x71, 0x3a, 0x19, 0x1f, 0x93, 0x53, 0xbd, 0xd1, 0xd7, 0x06, 0x37, 0x47, 0xc3, + 0x57, 0x67, 0x3d, 0xfb, 0xda, 0x0a, 0x1e, 0x30, 0x1a, 0x09, 0xb7, 0x19, 0xa7, 0x93, 0xfb, 0xe4, + 0x14, 0xef, 0xa3, 0x26, 0x17, 0x9e, 0x48, 0xb9, 0x7e, 0xa3, 0xaf, 0x0d, 0xde, 0x18, 0xea, 0x76, + 0xd9, 0x47, 0xa9, 0xf6, 0xa1, 0x8c, 0xbb, 0x80, 0xb3, 0x3e, 0x84, 0xa6, 0x3c, 0xa4, 0x61, 0x44, + 0xa3, 0x30, 0xef, 0xe2, 0x2d, 0x84, 0xb8, 0x3a, 0x99, 0xbb, 0xe4, 0xb6, 0xe1, 0xe4, 0x30, 0xb0, + 0xfe, 0x5c, 0x85, 0x79, 0x9c, 0xa7, 0x81, 0xb7, 0x5f, 0xa3, 0xb5, 0x6f, 0x09, 0x81, 0x59, 0xec, + 0x54, 0xa6, 0x2a, 0x57, 0x71, 0x87, 0xd1, 0x68, 0xb4, 0x9f, 0xf5, 0xf2, 0x8f, 0x7f, 0x7a, 0x83, + 0xd2, 0x45, 0x61, 0xad, 0xa8, 0x3f, 0xef, 0xf3, 0xe0, 0xd8, 0x11, 0xa7, 0x31, 0xe1, 0x32, 0x81, + 0xbb, 0x59, 0xdd, 0xcc, 0xca, 0x44, 0x29, 0x24, 0x89, 0xf4, 0xb8, 0xed, 0x16, 0x07, 0xf8, 0x2b, + 0xd4, 0xf5, 0x55, 0xc3, 0xc7, 0xaa, 0xc1, 0xf9, 0x15, 0x12, 0xc2, 0xd3, 0xa9, 0x90, 0xde, 0x6f, + 0x0c, 0x8d, 0x8a, 0x27, 0xc5, 0x05, 0xd2, 0xa9, 0x70, 0x3b, 0x7e, 0x69, 0x60, 0x2a, 0x21, 0x3c, + 0x46, 0x66, 0x42, 0xe2, 0xa9, 0xe7, 0x67, 0x05, 0x17, 0x96, 0x6f, 0x5c, 0x59, 0x7e, 0x7b, 0x5e, + 0xa1, 0x4e, 0x60, 0x75, 0xd0, 0x96, 0xb4, 0xd4, 0x95, 0x18, 0x32, 0x23, 0x91, 0xc8, 0xe7, 0xf9, + 0x1b, 0x98, 0xf5, 0x4a, 0x08, 0x1c, 0xbf, 0x8b, 0x36, 0x92, 0xe2, 0x18, 0xde, 0x50, 0xb7, 0xf6, + 0x86, 0x4a, 0xa9, 0xf0, 0x90, 0xca, 0x69, 0xc3, 0xdf, 0x9a, 0xe8, 0x86, 0xa4, 0xc0, 0x02, 0x35, + 0xd5, 0xfa, 0xc3, 0xef, 0xd4, 0x8a, 0xd4, 0x77, 0xac, 0xb1, 0xf3, 0x7a, 0x90, 0x12, 0x69, 0xf5, + 0xbe, 0xff, 0xeb, 0xbf, 0x5f, 0x57, 0x3b, 0x78, 0xcb, 0xb9, 0xbc, 0xde, 0xd5, 0x72, 0xc5, 0x4f, + 0x50, 0x0b, 0x56, 0x1b, 0x5e, 0x52, 0xb1, 0xba, 0x76, 0x8d, 0x77, 0xaf, 0x40, 0x01, 0x71, 0x5f, + 0x12, 0x1b, 0x58, 0xaf, 0x11, 0xe7, 0xeb, 0xf0, 0x3b, 0xd4, 0x54, 0x49, 0xcb, 0xee, 0x5b, 0x59, + 0x6f, 0xc6, 0xce, 0xeb, 0x41, 0x40, 0xbb, 0x27, 0x69, 0x77, 0xb0, 0xb5, 0x8c, 0xd6, 0x79, 0x06, + 0x5b, 0xf1, 0x39, 0xfe, 0x49, 0x43, 0x37, 0xcb, 0x7b, 0x0a, 0xdf, 0x5e, 0x4c, 0xb1, 0x60, 0xd1, + 0x19, 0x7b, 0xd7, 0x81, 0x82, 0xa6, 0x5d, 0xa9, 0xa9, 0x8f, 0xcd, 0x9a, 0xa6, 0xca, 0xa3, 0xc1, + 0x3f, 0x68, 0xa8, 0x05, 0x93, 0xb9, 0xac, 0x17, 0xd5, 0x65, 0xb1, 0xac, 0x17, 0x97, 0x76, 0x83, + 0x65, 0x4b, 0x01, 0x03, 0xbc, 0x5b, 0x13, 0x00, 0x0f, 0x89, 0x3b, 0xcf, 0x8a, 0xa5, 0xf3, 0x1c, + 0xff, 0xa8, 0xa1, 0x8d, 0xd2, 0xd8, 0xe2, 0xc1, 0x62, 0x9a, 0xfa, 0x7b, 0x31, 0x6e, 0x5f, 0x03, + 0x09, 0xa2, 0x76, 0xa4, 0x28, 0x13, 0x77, 0x6b, 0xa2, 0x4a, 0xcf, 0x63, 0xf4, 0xd9, 0x8b, 0x73, + 0x53, 0x7b, 0x79, 0x6e, 0x6a, 0xff, 0x9e, 0x9b, 0xda, 0xcf, 0x17, 0xe6, 0xca, 0xcb, 0x0b, 0x73, + 0xe5, 0xef, 0x0b, 0x73, 0xe5, 0xd1, 0xd5, 0xff, 0x2b, 0x9e, 0xcc, 0x2b, 0xcb, 0x75, 0x36, 0x69, + 0x4a, 0xc8, 0x07, 0xff, 0x07, 0x00, 0x00, 0xff, 0xff, 0x66, 0x0a, 0x8b, 0xde, 0xb7, 0x09, 0x00, + 0x00, } // Reference imports to suppress errors if they are not otherwise used. From be9738efaf8dd77f830f3933e043e8018dae4355 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Sat, 27 Apr 2024 14:12:37 +0700 Subject: [PATCH 052/132] remove unused flag --- x/bandtss/client/cli/tx.go | 3 --- x/oracle/client/cli/tx.go | 1 - x/tss/client/cli/tx.go | 1 - 3 files changed, 5 deletions(-) diff --git a/x/bandtss/client/cli/tx.go b/x/bandtss/client/cli/tx.go index 3f2c8a856..57980e93e 100644 --- a/x/bandtss/client/cli/tx.go +++ b/x/bandtss/client/cli/tx.go @@ -20,7 +20,6 @@ import ( const ( flagExpiration = "expiration" - flagGroupID = "group-id" flagFeeLimit = "fee-limit" ) @@ -69,10 +68,8 @@ func GetTxCmdRequestSignature() *cobra.Command { } cmd.PersistentFlags().String(flagFeeLimit, "", "The maximum tokens that will be paid for this request") - cmd.PersistentFlags().Uint64(flagGroupID, 0, "The group that is requested to sign the result") _ = cmd.MarkPersistentFlagRequired(flagFeeLimit) - _ = cmd.MarkPersistentFlagRequired(flagGroupID) return cmd } diff --git a/x/oracle/client/cli/tx.go b/x/oracle/client/cli/tx.go index 7ebbd332e..09d5fe40e 100644 --- a/x/oracle/client/cli/tx.go +++ b/x/oracle/client/cli/tx.go @@ -33,7 +33,6 @@ const ( flagExecuteGas = "execute-gas" flagTSSGroupID = "tss-group-id" flagTSSEncodeType = "tss-encode-type" - flagGroupID = "group-id" flagFeeLimit = "fee-limit" flagFee = "fee" flagTreasury = "treasury" diff --git a/x/tss/client/cli/tx.go b/x/tss/client/cli/tx.go index f4d3aa2cf..34a22b410 100644 --- a/x/tss/client/cli/tx.go +++ b/x/tss/client/cli/tx.go @@ -20,7 +20,6 @@ import ( const ( flagExpiration = "expiration" - flagGroupID = "group-id" flagFeeLimit = "fee-limit" ) From 14987254fdd0e13e8109dd5c44072c77785fa4c0 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Sat, 27 Apr 2024 14:12:51 +0700 Subject: [PATCH 053/132] remove unused eventtype --- x/tss/types/events.go | 1 - 1 file changed, 1 deletion(-) diff --git a/x/tss/types/events.go b/x/tss/types/events.go index 1d22dde53..b00c2bd39 100644 --- a/x/tss/types/events.go +++ b/x/tss/types/events.go @@ -2,7 +2,6 @@ package types const ( EventTypeCreateGroup = "create_group" - EventTypeUpdateGroupFee = "update_group_fee" EventTypeExpiredGroup = "expired_group" EventTypeSubmitDKGRound1 = "submit_dkg_round1" EventTypeRound1Success = "round1_success" From d9412b582b256f4f87af867d5591c24ca84344a5 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Sat, 27 Apr 2024 14:13:05 +0700 Subject: [PATCH 054/132] add and fix doc --- x/bandtss/README.md | 423 ++++++++++++++++++++++++++++++++++++++++++++ x/tss/README.md | 194 +++----------------- 2 files changed, 450 insertions(+), 167 deletions(-) create mode 100644 x/bandtss/README.md diff --git a/x/bandtss/README.md b/x/bandtss/README.md new file mode 100644 index 000000000..d212a87a4 --- /dev/null +++ b/x/bandtss/README.md @@ -0,0 +1,423 @@ +# `x/bandtss` + +## Abstract + +Bandtss module facilitates secure message signing within a decentralized network. + +Users can request the module to sign a message, which is then authenticated by members within the module. This ensures the integrity and authenticity of the message, enhancing trust and reliability within the network. + +A fee is charged per request, as specified by the module configuration, and upon successful signing, the fee is transferred to the assigned members. + +This module is used in the BandChain. + +## Contents + +- [`x/bandtss`](#xbandtss) + - [Abstract](#abstract) + - [Contents](#contents) + - [Concepts](#concepts) + - [Current Group](#current-group) + - [Member](#member) + - [Reward](#reward) + - [Block rewards](#block-rewards) + - [Request fee](#request-fee) + - [Signing](#signing) + - [Replacement](#replacement) + - [State](#state) + - [Msg Service](#msg-service) + - [Msg/CreateGroup](#msgcreategroup) + - [Msg/ReplaceGroup](#msgreplacegroup) + - [Msg/RequestSignature](#msgrequestsignature) + - [Msg/Activate](#msgactivate) + - [Msg/HealthCheck](#msghealthcheck) + - [Msg/UpdateParams](#msgupdateparams) + - [Events](#events) + - [EventTypeFirstGroupCreated](#eventtypefirstgroupcreated) + - [EventTypeRequestSignature](#eventtyperequestsignature) + - [EventTypeReplacement](#eventtypereplacement) + - [EventTypeActivate](#eventtypeactivate) + - [EventTypeHealthCheck](#eventtypehealthcheck) + - [EventTypeInactiveStatus](#eventtypeinactivestatus) + - [Parameters](#parameters) + - [Client](#client) + - [CLI](#cli) + - [Query](#query) + - [Group](#group-1) + - [Signing](#signing-1) + - [gRPC](#grpc) + - [Group](#group-2) + - [Signing](#signing-2) + - [REST](#rest) + - [Group](#group-3) + - [Signing](#signing-3) + +## Concepts + +### Current Group + +The signing process mainly happens in the tss module. To handle the signing in bandtss module, a proposal is made to create a tss group for the module. The proposal and bandtss's groups can be created multiple times, but the first one is considered the main group of the module and being used for signing process until a proposal for group replacement is made and approved. Then, the main module group (current group) will be changed. + +### Member + +The members of the module, which are the members of the current group, are nominated in a proposal. Once assigned, these members are responsible for signing messages within the system. Failure to sign messages within the specified timeframe results in deactivation and forfeiture of some block rewards from the module. + +Members who have been deactivated can reactivate themselves by calling [Msg/Activate](#msgactivate) once the penalty duration has been met. + +Additionally, members are required to continuously notify the chain for their active status. This is achieved through the [Msg/HealthCheck](#msghealthcheck). + +Changing the members of the module can be done by [group replacement process](#replacement) + +### Reward + +#### Block rewards + +In each block, active validators serving as members on the bandtss system are rewarded with additional block rewards proportional to their validating power, as recognition for their service. + +The `RewardPercentage` parameter determines the percentage of block rewards allocated to these validators. By default, this parameter is set to 50%. However, it's important to note that this percentage is calculated based on the remaining rewards. For instance, if other modules claim 40% of the rewards, the bandtss module will receive only 30% (50% of the remaining 60%) of the total block rewards. + +#### Request fee + +Users requesting signatures from the bandtss system are required to pay a fee for the service. This fee price is configured in the module's params. Only assigned members of the request will receive this fee as a reward for their service to the group, in addition to block rewards. + +### Signing + +A signing request can be submitted to the module, and the signing process is then forwarded to the TSS module. Subsequently, the bandtss module charges a fee to the requester, which will be transferred later to the assigned members once the message is successfully signed. + +### Replacement + +The replacement process is utilized when updating the members of the module or modifying the module's shared key. The steps involved in the replacement process are as follows: + +1. Initiate a proposal to create a new bandtss signing group. +2. Submit a replacement proposal with a newly created group and the replacement execution time. +3. After the proposal is approved, the current members are responsible for signing the replacement message. +4. At the replacement execution time, the new group becomes the current group, existing members are removed, and new members are activated. + +This process provides users with ample time to update their key before the replacement takes effect. During this transition period, signing requests are sent to both the current group and the group scheduled for replacement. However, signing fees are allocated exclusively to the assigned members of the current group. + +## State + +The `x/bandtss` module keeps the state of the following primary objects: + +1. CurrentGroupID stores main group ID of the module. +2. Members stores members information and their status. +3. Signings stores signing ID of the current group and replacing group, if any. +4. Replacement stores latest replacement information. + +In addition, the `x/bandtss` module still keeps temporary information such as the mapping between signing ID from tss module to bandtss signing ID for using as a mapping when the hooks are called from the tss module. + +Here are the prefixes for each object in the KVStore of the bandtss module. + +```go +var ( + GlobalStoreKeyPrefix = []byte{0x00} + ParamsKeyPrefix = []byte{0x01} + MemberStoreKeyPrefix = []byte{0x02} + SigningStoreKeyPrefix = []byte{0x03} + + SigningCountStoreKey = append(GlobalStoreKeyPrefix, []byte("SigningCount")...) + CurrentGroupIDStoreKey = append(GlobalStoreKeyPrefix, []byte("CurrentGroupID")...) + ReplacementStoreKey = append(GlobalStoreKeyPrefix, []byte("Replacement")...) + + SigningInfoStoreKeyPrefix = append(SigningStoreKeyPrefix, []byte{0x00}...) + SigningIDMappingStoreKeyPrefix = append(SigningStoreKeyPrefix, []byte{0x01}...) +) +``` + +## Msg Service + +### Msg/CreateGroup + +A new group can be created with the `MsgCreateGroup` which needs to open through governance proposal. +This message contains the list of members, the threshold of the group. + +It's expected to fail if: + +- Members are not correct (e.g. wrong address format, duplicates). +- Threshold is more than the number of the members. + +### Msg/ReplaceGroup + +A replacement can be created with the `MsgReplaceGrouup` which needs to open through a governance proposal. +This message contains `new_group_id` , and `exec_time`. + +It's expected to fail if: + +- The status of groups is not active. +- Can't request signing `replacement message` from `current_group_id` + +### Msg/RequestSignature + +Anyone who wants to have a signature from the group can use `MsgRequestSignature` to send their message to the group to request a signature. + +It contains `fee_limit`, and `Content`. `Content` is an interface that any module can implement to have its logic get the specific data from its module so that the module can produce a signature for that data. + +### Msg/Activate + +If members are deactivated due to one of the module's mechanisms, such as a health check or missing signature, they must send `MsgActivate` to rejoin the system. However, there is a punishment period for rejoining the process. + +### Msg/HealthCheck + +This message is used by members in the bandtss system. All active members have to regularly send `MsgHealthCheck` to the chain to show if they are still active. + +The frequency of sending is determined by `ActiveDuration` parameters. + +### Msg/UpdateParams + +When anyone wants to update the parameters of the bandtss module, they will have to open a governance proposal by using the `MsgUpdateParams` of the bandtss module to update those parameters. + +## Events + +The bandtss module emits the following events: + +### EventTypeFirstGroupCreated + +This event ( `first_group_created` ) is emitted when the first bandtss group is created and is set as a current group. + +| Attribute Key | Attribute Value | +| ---------------- | --------------- | +| current_group_id | {groupID} | + +### EventTypeRequestSignature + +This event ( `bandtss_signing_request_created` ) is emitted when the module is requested to sign the data. + +| Attribute Key | Attribute Value | +| -------------------------- | ------------------ | +| bandtss_signing_id | {bandtssSigningID} | +| current_group_id | {groupID} | +| current_group_signing_id | {signingID} | +| replacing_group_id | {groupID} | +| replacing_group_signing_id | {signingID} | + +### EventTypeReplacement + +This event ( `replacement` ) is emitted when replacement is requested via an approved proposal or the replacement changes its status. + +| Attribute Key | Attribute Value | +| ------------------ | ------------------- | +| signingID | {signingID} | +| current_group_id | {groupID} | +| replacing_group_id | {groupID} | +| status | {replacementStatus} | + +### EventTypeActivate + +This event ( `activate` ) is emitted when an account submitted `MsgActivate` to the chain + +| Attribute Key | Attribute Value | +| ------------- | --------------- | +| address | {memberAddress} | + +### EventTypeHealthCheck + +This event ( `healthcheck` ) is emitted when an account submitted `MsgHealthCheck` to the chain + +| Attribute Key | Attribute Value | +| ------------- | --------------- | +| address | {memberAddress} | + +### EventTypeInactiveStatus + +This event ( `inactive_status` ) is emitted when an account is deactivated + +| Attribute Key | Attribute Value | +| ------------- | --------------- | +| address | {memberAddress} | + +## Parameters + +The module contains the following parameters + +```protobuf +type Params struct { + // active_duration is the duration where a member can be active without interaction. + ActiveDuration time.Duration + // reward_percentage is the percentage of block rewards allocated to active TSS validators after being allocated to + // oracle rewards. + RewardPercentage uint64 + // inactive_penalty_duration is the duration where a member cannot activate back after inactive. + InactivePenaltyDuration time.Duration + // fee is the tokens that will be paid per signing. + Fee github_com_cosmos_cosmos_sdk_types.Coins +} +``` + +## Client + +### CLI + +A user can query and interact with the `bandtss` module using the CLI. + +#### Query + +The `query` commands allow users to know other possible queries of the `bandtss` module. + +```bash +bandd query bandtss --help +``` + +##### CurrentGroup + +The `current-group` command allows users to query for current group information. + +```bash +bandd query bandtss current-group +``` + +##### Member + +The `Member` command allows users to query for member information by giving a member address. + +```bash +bandd query bandtss member [address] [flags] +``` + +Example: + +```bash +bandd query bandtss member band1nx0xkpnytk35wvflsg7gszf9smw3vaeauk248q +``` + +##### Replacement + +The `Replacement` command allows users to query for replacement information. + +```bash +bandd query bandtss replacement +``` + +##### Signing + +The `Signing` command allows users to query for bandtss signing information by giving a signing id. + +```bash +bandd query bandtss signing [id] [flags] +``` + +Example: + +```bash +bandd query bandtss signing 1 +``` + +##### Params + +The `Params` command allows users to query for module's configuration. + +```bash +bandd query bandtss params +``` + +### gRPC + +A user can query the `bandtss` module using gRPC endpoints. + +##### CurrentGroup + +The `current-group` command allows users to query for current group information. + +```bash +bandtss.v1beta1.Query/CurrentGroup +``` + +##### Member + +The `Member` command allows users to query for member information by giving a member address. + +```bash +bandtss.v1beta1.Query/Member +``` + +Example: + +```bash +grpcurl -plaintext +-d '{"address":"band1nx0xkpnytk35wvflsg7gszf9smw3vaeauk248q"}' localhost:9090 bandtss.v1beta1.Query/Member +``` + +##### Replacement + +The `Replacement` command allows users to query for replacement information. + +```bash +bandtss.v1beta1.Query/Replacement +``` + +##### Signing + +The `Signing` command allows users to query for bandtss signing information by giving a signing id. + +```bash +bandtss.v1beta1.Query/Signing +``` + +Example: + +```bash +grpcurl -plaintext +-d '{"signing_id":1}' localhost:9090 bandtss.v1beta1.Query/QuerySigningRequest +``` + +##### Params + +The `Params` command allows users to query for module's configuration. + +```bash +bandtss.v1beta1.Query/Params +``` + +### REST + +A user can query the `bandtss` module using REST endpoints. + +##### CurrentGroup + +The `current-group` command allows users to query for current group information. + +```bash +/tss/v1beta1/current_group +``` + +##### Member + +The `Member` command allows users to query for member information by giving a member address. + +```bash +/tss/v1beta1/current_group +``` + +Example: + +```bash +curl localhost:1317/tss/v1beta1/groups/band1nx0xkpnytk35wvflsg7gszf9smw3vaeauk248q +``` + +##### Replacement + +The `Replacement` command allows users to query for replacement information. + +```bash +/tss/v1beta1/replacement +``` + +##### Signing + +The `Signing` command allows users to query for bandtss signing information by giving a signing id. + +```bash +/tss/v1beta1/signing +``` + +Example: + +```bash +curl localhost:1317/tss/v1beta1/signing/1 +``` + +##### Params + +The `Params` command allows users to query for module's configuration. + +```bash +/tss/v1beta1/params +``` diff --git a/x/tss/README.md b/x/tss/README.md index dfdd2a31f..abcce9520 100644 --- a/x/tss/README.md +++ b/x/tss/README.md @@ -2,44 +2,32 @@ ## Abstract -This document specifies the TSS module. +The TSS module centrally manages the threshold signature scheme (TSS) signing process, allowing other system modules to utilize this method for cryptographic signing. -The TSS module acts like a tool that makes signatures for groups of people within the group. +To become a TSS provider, members are simply selected by the caller module. These selected members then submit encrypted secret shares to create a public shared secret of the group, which is subsequently formed and owned by the caller module. -To become a TSS provider, members simply need to show they're ready to join in by activating their status. The group is then formed from these active members. Once the group is all set up, anyone can ask the group to sign something specific. The resulting group signature, which you can check using the group's public key, becomes handy in various situations, making the TSS module quite useful. This way of creating signatures not only makes sure everyone trusts it but also adds an extra layer of security to the system. +Once the group is established, the group's owner can request specific signatures. The resulting group signature, which can be verified using the group's public key, proves useful in various situations, rendering the TSS module quite valuable. This method of creating signatures not only ensures trust among all participants but also adds an extra layer of security to the system. -This module is used in the BandChain. +This module is used in bandtss module in BandChain. ## Contents -* [`x/tss`](#xtss) - + [Abstract](#abstract) - + [Contents](#contents) - + [Concepts](#concepts) - - [Status](#status) - - [Reward](#reward) - - [Block rewards](#block-rewards) - - [Request fee](#request-fee) +- [`x/tss`](#xtss) + - [Abstract](#abstract) + - [Contents](#contents) + - [Concepts](#concepts) - [Group](#group) - [Signing](#signing) - - [Group replacement](#group-replacement) - + [State](#state) - + [Msg Service](#msg-service) - - [Msg/CreateGroup](#msgcreategroup) - - [Msg/ReplaceGroup](#msgreplacegroup) - - [Msg/UpdateGroupFee](#msgupdategroupfee) + - [State](#state) + - [Msg Service](#msg-service) - [Msg/SubmitDKGRound1](#msgsubmitdkground1) - [Msg/SubmitDKGRound2](#msgsubmitdkground2) - [Msg/Complain](#msgcomplain) - [Msg/Confirm](#msgconfirm) - [Msg/SubmitDEs](#msgsubmitdes) - - [Msg/RequestSignature](#msgrequestsignature) - [Msg/SubmitSignature](#msgsubmitsignature) - - [Msg/Activate](#msgactivate) - - [Msg/HealthCheck](#msghealthcheck) - [Msg/UpdateParams](#msgupdateparams) - + [Events](#events) - - [EventTypeCreateGroup](#eventtypecreategroup) + - [Events](#events) - [EventTypeSubmitDKGRound1](#eventtypesubmitdkground1) - [EventTypeRound1Success](#eventtyperound1success) - [EventTypeSubmitDKGRound2](#eventtypesubmitdkground2) @@ -54,68 +42,30 @@ This module is used in the BandChain. - [EventTypeReplaceSuccess](#eventtypereplacesuccess) - [EventTypeSubmitSignature](#eventtypesubmitsignature) - [EventTypeSigningFailed](#eventtypesigningfailed) - - [EventTypeActivate](#eventtypeactivate) - - [EventTypeHealthCheck](#eventtypehealthcheck) - + [Parameters](#parameters) - + [Client](#client) + - [Parameters](#parameters) + - [Client](#client) - [CLI](#cli) - - [Query](#query) - - [Group](#group-1) - - [Signing](#signing-1) + - [Query](#query) + - [Group](#group-1) + - [Signing](#signing-1) - [gRPC](#grpc) - - [Group](#group-2) - - [Signing](#signing-2) + - [Group](#group-2) + - [Signing](#signing-2) - [REST](#rest) - - [Group](#group-3) - - [Signing](#signing-3) + - [Group](#group-3) + - [Signing](#signing-3) ## Concepts -### Status - -There are 4 statuses in the TSS system: -1. Active: This status designates a member who is prepared to engage in the TSS process actively. -2. Paused: Members assume the paused status when their DE (nonce) is run out. -3. Jailed: A member is placed in the jailed status if they fail to respond during the group creation process. -4. Inactive: By default, members are assigned to this status. However, they may be set to inactive status if they fail to respond to a signed request. - -Statuses within the TSS system are account-level indicators. To become a participant in the TSS system, an account must send a message to the chain. Upon activating their status in the TSS module, participants are required to send a health-check message to the chain at regular intervals, typically set as the "ActiveDuration" (defaulting to one day). - -Failure to submit a health-check message or non-participation in assigned actions, such as group creation or signature requests, results in deactivation for a specific duration based on the action. This mechanism is implemented to remove inactive accounts from the TSS system. - -### Reward - -#### Block rewards - -In each block, all active accounts that are validators will receive more block rewards depending on their validating power as a reward for providing service on the TSS system. - -The `RewardPercentage` parameter will be the percent of block rewards that will be assigned to those validators. The default value is 50%. However, this percentage is calculated from the remaining rewards. For example, if somehow other modules took 40% as their rewards. TSS module will receive only 30% (50% of 60%) of the full block rewards. - -#### Request fee - -All users who request signatures on data from the TSS group will have to pay the fee for the TSS service. The fee will depend on the group. Only assigned accounts of the request will receive this fee as a reward for providing service to the group on top of block rewards. - ### Group A group contains multiple members. Each group has its public key that multiple members (at least the threshold of the group) will be able to generate signatures on the message of that public key. -A group will be created through a governance proposal at this phase. At first, when creating a group, each assigned member will have to go through a key generation process to generate a group key together. After that, they will receive their private key that will be used to generate part of the signature of the group. +A group will be created through a call by external module with a set of selected members. At first, when creating a group, each assigned member will have to go through a key generation process to generate a group key together. After that, they will receive their private key that will be used to generate part of the signature of the group. ### Signing -A signing is a request to sign some data from a user to the group. It contains all information of this request such as message, assigned members, and assigned nonce of each member. When a user requests a signing from the group, each member will have to use the key of the group to sign on the message that will combine to generate the final signature of the group. - -### Group replacement - -The process of group replacement is used when we need to change who is in a group and also update the group's key. We can't just swap out individual members because their keys are linked to the group's key. To replace the group, we have to create a new group and then update the old group's information with the new group's details. - -Here are the steps of the replacement process: -1. Create a new group through a proposal -2. Create a group replacement proposal with replacement time -3. After the proposal passed, the old group will be assigned to sign the `changing group` message -4. Once it reaches replacement time, all information from the old group will be replaced by information from the new group. - -This process allows users to have spare time to update their key before it reaches replacement time. Also, users can choose to request from old and new group IDs. +A signing is a request to sign some data from a module to the group. It contains all information of this request such as message, assigned members, and assigned nonce of each member. When a user requests a signing from the group, each member will have to use the key of the group to sign on the message that will combine to generate the final signature of the group. ## State @@ -123,11 +73,9 @@ The `x/tss` module keeps the state of the following primary objects: 1. Groups 2. Signings -3. Statuses -4. Nonces (DEs) -5. Replacements +3. DEs (Nonces being used in a signing process) -In addition, the `x/tss` module still keeps temporary information such as group count, round1Info, round2Info, queue of replacements, groups, and signings. +In addition, the `x/tss` module still keeps temporary information such as group count, round1Info, round2Info, queue of replacements, groups, and partial signings information. Here are the prefixes for each object in the KVStore of the TSS module. @@ -135,14 +83,11 @@ Here are the prefixes for each object in the KVStore of the TSS module. var ( GlobalStoreKeyPrefix = []byte{0x00} GroupCountStoreKey = append(GlobalStoreKeyPrefix, []byte("GroupCount")...) - ReplacementCountStoreKey = append(GlobalStoreKeyPrefix, []byte("ReplacementCount")...) LastExpiredGroupIDStoreKey = append(GlobalStoreKeyPrefix, []byte("LastExpiredGroupID")...) SigningCountStoreKey = append(GlobalStoreKeyPrefix, []byte("SigningCount")...) LastExpiredSigningIDStoreKey = append(GlobalStoreKeyPrefix, []byte("LastExpiredSigningID")...) - RollingSeedStoreKey = append(GlobalStoreKeyPrefix, []byte("RollingSeed")...) PendingProcessGroupsStoreKey = append(GlobalStoreKeyPrefix, []byte("PendingProcessGroups")...) PendingSigningsStoreKey = append(GlobalStoreKeyPrefix, []byte("PendingProcessSignings")...) - PendingReplaceGroupsStoreKey = append(GlobalStoreKeyPrefix, []byte("PendingReplaceGroups")...) GroupStoreKeyPrefix = []byte{0x01} DKGContextStoreKeyPrefix = []byte{0x02} MemberStoreKeyPrefix = []byte{0x03} @@ -159,45 +104,12 @@ var ( SigningStoreKeyPrefix = []byte{0x0e} SigCountStoreKeyPrefix = []byte{0x0f} PartialSignatureStoreKeyPrefix = []byte{0x10} - StatusStoreKeyPrefix = []byte{0x11} - ParamsKeyPrefix = []byte{0x12} - ReplacementKeyPrefix = []byte{0x13} - ReplacementQueuePrefix = []byte{0x14} + ParamsKeyPrefix = []byte{0x11} ) ``` ## Msg Service -### Msg/CreateGroup - -A new group can be created with the `MsgCreateGroup` which needs to open through governance proposal. -This message contains the list of members, the threshold of the group, and the fee for requesting. - -It's expected to fail if: - -* The number of members is greater than the `MaxGroupSize` parameters. -* One of the members has inactive TSS status. -* Members are not correct (e.g. wrong address format, duplicates). - -### Msg/ReplaceGroup - -A replacement can be created with the `MsgReplaceGrouup` which needs to open through a governance proposal. -This message contains `current_group_id` , `new_group_id` , and `exec_time` . - -It's expected to fail if: - -* The status of groups is not active. -* The `current_group_id` is in the replacement process. -* Can't request signing `changing group` message from `current_group_id` - -### Msg/UpdateGroupFee - -A changing fee of the group can be created with the `MsgUpdateGroupFee` which needs to open through the governance proposal. This message contains the ID of the group and the new fee. - -It's expected to fail if: - -* The group doesn't exist. - ### Msg/SubmitDKGRound1 This message is used to send round 1 information in the DKG process of the group. @@ -228,13 +140,7 @@ In the signing process, each member is required to have their nonces (D and E va It's expected to fail if: -* The number of remaining DEs exceeds the maximum size (`MaxDESize`) per user. - -### Msg/RequestSignature - -Anyone who wants to have a signature from the group can use `MsgRequestSignature` to send their message to the group to request a signature. - -It contains `group_id`, `fee_limit`, and `request`. `request` is an interface that any module can implement to have its logic get the specific data from its module so that the TSS module can produce a signature for that data. +- The number of remaining DEs exceeds the maximum size (`MaxDESize`) per user. ### Msg/SubmitSignature @@ -242,18 +148,6 @@ When a user requests a signature from the group, the assigned member of the grou Once all assigned member sends their signature to the chain, the chain will aggregate those signatures to be the final signature of the group for that request. -### Msg/Activate - -An account that wants to participate as a TSS provider (signature provider) has to activate its TSS status through `MsgActivate`. - -If the account is deactivated by one of the TSS mechanisms (such as a health check, or missing signature), they will have to send `MsgActivate` again to rejoin the system. However, there is a punishment period for rejoining depending on the action that the account got deactivated. - -### Msg/HealthCheck - -This message is used by participators in the TSS system. All active TSS accounts have to regularly send `MsgHealthCheck` to the chain to show if they are still active. - -The frequency of sending is determined by `ActiveDuration` parameters. - ### Msg/UpdateParams When anyone wants to update the parameters of the TSS module, they will have to open a governance proposal by using the `MsgUpdateParams` of the TSS module to update those parameters. @@ -271,10 +165,10 @@ This event ( `create_group` ) is emitted when the group is created. | group_id | {groupID} | | size | {groupSize} | | thredhold | {groupThreshold} | -| fee | {groupFee} | | pub_key | "" | | status | {groupStatus} | | dkg_context | {groupDKGContext} | +| module_owner | "" | ### EventTypeSubmitDKGRound1 @@ -398,16 +292,6 @@ This event ( `signing_success` ) is emitted at the end block when all assigned m | group_id | {groupID} | | signature | {signature} | -### EventTypeReplaceSuccess - -This event ( `replace_success` ) is emitted at the end block when it reaches replacement time and replacement is successful. - -| Attribute Key | Attribute Value | -| ---------------- | ---------------- | -| signing_id | {signingID} | -| current_group_id | {currentGroupID} | -| new_group_id | {newGroupID} | - ### EventTypeSubmitSignature This event ( `submit_signature` ) is emitted when an assigned member submits his or her signature on the signing request. @@ -432,22 +316,6 @@ This event ( `signing_failed` ) is emitted at the end block when all assigned me | group_id | {groupID} | | reason | {failedReason} | -### EventTypeActivate - -This event ( `activate` ) is emitted when an account submitted `MsgActivate` to the chain - -| Attribute Key | Attribute Value | -| ------------- | --------------- | -| address | {memberAddress} | - -### EventTypeHealthCheck - -This event ( `healthcheck` ) is emitted when an account submitted `MsgHealthCheck` to the chain - -| Attribute Key | Attribute Value | -| ------------- | --------------- | -| address | {memberAddress} | - ## Parameters The TSS module contains the following parameters @@ -462,14 +330,6 @@ type Params struct { CreatingPeriod uint64 // SigningPeriod is the number of blocks allowed to sign. SigningPeriod uint64 - // ActiveDuration is the duration where a member can be active without interaction. - ActiveDuration time.Duration - // InactivePenaltyDuration is the duration where a member cannot activate back after inactive. - InactivePenaltyDuration time.Duration - // JailPenaltyDuration is the duration where a member cannot activate back after jail. - JailPenaltyDuration time.Duration - // RewardPercentage is the percentage of block rewards allocated to active TSS validators after being allocated to oracle rewards. - RewardPercentage uint64 } ``` From c2c084e4b0995b6920e6caa20666576605390f18 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 29 Apr 2024 09:24:18 +0700 Subject: [PATCH 055/132] Fix doc --- x/bandtss/README.md | 8 ++++---- x/tss/README.md | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/x/bandtss/README.md b/x/bandtss/README.md index d212a87a4..837649349 100644 --- a/x/bandtss/README.md +++ b/x/bandtss/README.md @@ -55,7 +55,7 @@ This module is used in the BandChain. ### Current Group -The signing process mainly happens in the tss module. To handle the signing in bandtss module, a proposal is made to create a tss group for the module. The proposal and bandtss's groups can be created multiple times, but the first one is considered the main group of the module and being used for signing process until a proposal for group replacement is made and approved. Then, the main module group (current group) will be changed. +The signing process mainly happens in the tss module. To handle the signing in bandtss module, a proposal is made to create a tss group for the module and use it as a main group for a signing process. The proposal and bandtss's groups can be created multiple times, in that case, the first one is considered the main group of the module and being used for signing process until a proposal for group replacement is made and approved. ### Member @@ -71,9 +71,9 @@ Changing the members of the module can be done by [group replacement process](#r #### Block rewards -In each block, active validators serving as members on the bandtss system are rewarded with additional block rewards proportional to their validating power, as recognition for their service. +In each block, active validators being served as members on the bandtss system are rewarded with additional block rewards proportional to their validating power, as recognition for their service. -The `RewardPercentage` parameter determines the percentage of block rewards allocated to these validators. By default, this parameter is set to 50%. However, it's important to note that this percentage is calculated based on the remaining rewards. For instance, if other modules claim 40% of the rewards, the bandtss module will receive only 30% (50% of the remaining 60%) of the total block rewards. +The `RewardPercentage` parameter determines the percentage of block rewards allocated to these validators. By default, this parameter is set to 50%. However, please note that this percentage is calculated based on the remaining rewards. For instance, if other modules claim 40% of the rewards, the bandtss module will receive only 30% (50% of the remaining 60%) of the total block rewards. #### Request fee @@ -81,7 +81,7 @@ Users requesting signatures from the bandtss system are required to pay a fee fo ### Signing -A signing request can be submitted to the module, and the signing process is then forwarded to the TSS module. Subsequently, the bandtss module charges a fee to the requester, which will be transferred later to the assigned members once the message is successfully signed. +A signing request can be submitted to the module, and the signing process is then forwarded to the TSS module. Subsequently, the bandtss module charges a fee to the requester, which will be transferred later to the assigned members once the message is successfully signed (as a request fee). ### Replacement diff --git a/x/tss/README.md b/x/tss/README.md index abcce9520..6ed9325bf 100644 --- a/x/tss/README.md +++ b/x/tss/README.md @@ -2,9 +2,9 @@ ## Abstract -The TSS module centrally manages the threshold signature scheme (TSS) signing process, allowing other system modules to utilize this method for cryptographic signing. +The TSS module's main purpose is to manage the threshold signature scheme (TSS) signing process, allowing other system modules to utilize this method for cryptographic signing. -To become a TSS provider, members are simply selected by the caller module. These selected members then submit encrypted secret shares to create a public shared secret of the group, which is subsequently formed and owned by the caller module. +To handle a signing process, the module has to create a group with selected members. These selected members then submit encrypted secret shares to create a public shared secret of the group, which is subsequently formed and owned by the caller module. Once the group is established, the group's owner can request specific signatures. The resulting group signature, which can be verified using the group's public key, proves useful in various situations, rendering the TSS module quite valuable. This method of creating signatures not only ensures trust among all participants but also adds an extra layer of security to the system. @@ -61,11 +61,11 @@ This module is used in bandtss module in BandChain. A group contains multiple members. Each group has its public key that multiple members (at least the threshold of the group) will be able to generate signatures on the message of that public key. -A group will be created through a call by external module with a set of selected members. At first, when creating a group, each assigned member will have to go through a key generation process to generate a group key together. After that, they will receive their private key that will be used to generate part of the signature of the group. +A group is created through a call by external module with a set of selected members. At first, when creating a group, each assigned member will have to go through a key generation process to generate a group key together. After that, they will receive their private key that will be used to generate part of the signature of the group. ### Signing -A signing is a request to sign some data from a module to the group. It contains all information of this request such as message, assigned members, and assigned nonce of each member. When a user requests a signing from the group, each member will have to use the key of the group to sign on the message that will combine to generate the final signature of the group. +A module creates a signing request to the group that the module owns. It contains all information of this request such as message, assigned members, and assigned nonce of each member. When a user requests a signing from the group, each member will have to use the key of the group to sign on the message that will combine to generate the final signature of the group. ## State From 9e71e5a3f8feb421036a72c3b7ad13b726aed65e Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 29 Apr 2024 09:24:26 +0700 Subject: [PATCH 056/132] rename function --- x/bandtss/keeper/hooks.go | 4 ++-- x/bandtss/keeper/signing.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/x/bandtss/keeper/hooks.go b/x/bandtss/keeper/hooks.go index f904c01db..b4b901ac5 100644 --- a/x/bandtss/keeper/hooks.go +++ b/x/bandtss/keeper/hooks.go @@ -65,7 +65,7 @@ func (h Hooks) AfterSigningFailed(ctx sdk.Context, signing tsstypes.Signing) err } // refund fee to requester. Unlikely to get an error from refund fee, but log it just in case. - if err := h.k.CheckRefundFee(ctx, signing, bandtssSigningID); err != nil { + if err := h.k.RefundFee(ctx, signing, bandtssSigningID); err != nil { return err } @@ -98,7 +98,7 @@ func (h Hooks) BeforeSetSigningExpired(ctx sdk.Context, signing tsstypes.Signing } // refund fee to requester and delete the signingID mapping. - if err := h.k.CheckRefundFee(ctx, signing, bandtssSigningID); err != nil { + if err := h.k.RefundFee(ctx, signing, bandtssSigningID); err != nil { return err } h.k.DeleteSigningIDMapping(ctx, signing.ID) diff --git a/x/bandtss/keeper/signing.go b/x/bandtss/keeper/signing.go index 83753089f..611778078 100644 --- a/x/bandtss/keeper/signing.go +++ b/x/bandtss/keeper/signing.go @@ -219,8 +219,8 @@ func (k Keeper) HandleCreateSigning( return bandtssSigningID, nil } -// CheckRefundFee refunds the fee to the requester. -func (k Keeper) CheckRefundFee(ctx sdk.Context, signing tsstypes.Signing, bandtssSigningID types.SigningID) error { +// RefundFee refunds the fee to the requester. +func (k Keeper) RefundFee(ctx sdk.Context, signing tsstypes.Signing, bandtssSigningID types.SigningID) error { bandtssSigning, err := k.GetSigning(ctx, bandtssSigningID) if err != nil { return err From 8aa783177975575bbf9552b493ad096eac0611d0 Mon Sep 17 00:00:00 2001 From: Natthakun Kitthaworn Date: Thu, 2 May 2024 09:18:08 +0700 Subject: [PATCH 057/132] Update proto/bandtss/v1beta1/query.proto Co-authored-by: Kitipong Sirirueangsakul --- proto/bandtss/v1beta1/query.proto | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/proto/bandtss/v1beta1/query.proto b/proto/bandtss/v1beta1/query.proto index 80577156b..0e0a9c418 100644 --- a/proto/bandtss/v1beta1/query.proto +++ b/proto/bandtss/v1beta1/query.proto @@ -90,7 +90,8 @@ message QueryCurrentGroupResponse { uint64 group_id = 1 [ (gogoproto.customname) = "GroupID", (gogoproto.casttype) = "github.com/bandprotocol/chain/v2/pkg/tss.GroupID" - ];// size is the number of members in the group. + ]; + // size is the number of members in the group. uint64 size = 2; // threshold is the minimum number of members needed to generate a valid signature. uint64 threshold = 3; From 2f65311eb588d9e30ec2e10e8ec64a51b9c10642 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 2 May 2024 09:20:12 +0700 Subject: [PATCH 058/132] fix readme --- x/bandtss/README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/x/bandtss/README.md b/x/bandtss/README.md index 837649349..1668b9ec2 100644 --- a/x/bandtss/README.md +++ b/x/bandtss/README.md @@ -375,7 +375,7 @@ A user can query the `bandtss` module using REST endpoints. The `current-group` command allows users to query for current group information. ```bash -/tss/v1beta1/current_group +/bandtss/v1beta1/current_group ``` ##### Member @@ -383,13 +383,13 @@ The `current-group` command allows users to query for current group information. The `Member` command allows users to query for member information by giving a member address. ```bash -/tss/v1beta1/current_group +/bandtss/v1beta1/current_group ``` Example: ```bash -curl localhost:1317/tss/v1beta1/groups/band1nx0xkpnytk35wvflsg7gszf9smw3vaeauk248q +curl localhost:1317/bandtss/v1beta1/groups/band1nx0xkpnytk35wvflsg7gszf9smw3vaeauk248q ``` ##### Replacement @@ -397,7 +397,7 @@ curl localhost:1317/tss/v1beta1/groups/band1nx0xkpnytk35wvflsg7gszf9smw3vaeauk24 The `Replacement` command allows users to query for replacement information. ```bash -/tss/v1beta1/replacement +/bandtss/v1beta1/replacement ``` ##### Signing @@ -405,13 +405,13 @@ The `Replacement` command allows users to query for replacement information. The `Signing` command allows users to query for bandtss signing information by giving a signing id. ```bash -/tss/v1beta1/signing +/bandtss/v1beta1/signing ``` Example: ```bash -curl localhost:1317/tss/v1beta1/signing/1 +curl localhost:1317/bandtss/v1beta1/signing/1 ``` ##### Params @@ -419,5 +419,5 @@ curl localhost:1317/tss/v1beta1/signing/1 The `Params` command allows users to query for module's configuration. ```bash -/tss/v1beta1/params +/bandtss/v1beta1/params ``` From d157492fe17b7cca48d2afeb2e272fc8521258fe Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 2 May 2024 09:51:51 +0700 Subject: [PATCH 059/132] fix comments in bandtss module --- x/bandtss/client/cli/tx.go | 2 +- x/bandtss/keeper/group.go | 5 +++++ x/bandtss/keeper/hooks.go | 3 +-- x/bandtss/keeper/keeper.go | 7 ++++--- x/bandtss/keeper/msg_server.go | 6 +++--- x/bandtss/types/codec.go | 3 +++ x/bandtss/types/constants.go | 1 + x/bandtss/types/params.go | 4 ++-- 8 files changed, 20 insertions(+), 11 deletions(-) diff --git a/x/bandtss/client/cli/tx.go b/x/bandtss/client/cli/tx.go index 57980e93e..4df0a1378 100644 --- a/x/bandtss/client/cli/tx.go +++ b/x/bandtss/client/cli/tx.go @@ -155,7 +155,7 @@ func GetTxCmdHealthCheck() *cobra.Command { cmd := &cobra.Command{ Use: "health-check", Args: cobra.NoArgs, - Short: "update the active status of the address to ensure that the TSS process is still running", + Short: "update the active status of the address to ensure that the member in the group is active", Example: fmt.Sprintf( `%s tx bandtss health-check`, version.AppName, diff --git a/x/bandtss/keeper/group.go b/x/bandtss/keeper/group.go index ee3620ea9..45b2614ed 100644 --- a/x/bandtss/keeper/group.go +++ b/x/bandtss/keeper/group.go @@ -11,6 +11,8 @@ import ( tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) +// CreateGroupReplacement creates a replacement request to replace a current group ID with a new one +// which must be approved, i.e. request must be signed, from the current group. func (k Keeper) CreateGroupReplacement( ctx sdk.Context, newGroupID tss.GroupID, @@ -116,6 +118,7 @@ func (k Keeper) HandleReplaceGroup(ctx sdk.Context, endBlockTime time.Time) erro return nil } +// HandleFailReplacementSigning update replacement status and emits an event. func (k Keeper) HandleFailReplacementSigning(ctx sdk.Context, replacement types.Replacement) error { replacement.Status = types.REPLACEMENT_STATUS_FALLEN k.SetReplacement(ctx, replacement) @@ -132,6 +135,8 @@ func (k Keeper) HandleFailReplacementSigning(ctx sdk.Context, replacement types. return nil } +// ReplaceGroup handle group replacement which includes manage members of the old and new group. +// and set new group ID to be a current one. It emits an event at the end. func (k Keeper) ReplaceGroup(ctx sdk.Context, replacement types.Replacement) error { // clear members from the current group and add members from the new group. oldMembers := k.tssKeeper.MustGetMembers(ctx, replacement.CurrentGroupID) diff --git a/x/bandtss/keeper/hooks.go b/x/bandtss/keeper/hooks.go index b4b901ac5..202f45db1 100644 --- a/x/bandtss/keeper/hooks.go +++ b/x/bandtss/keeper/hooks.go @@ -16,7 +16,7 @@ type Hooks struct { var _ tsstypes.TSSHooks = Hooks{} -// Create new Bandtss hooks +// Create new bandtss hooks func (k Keeper) Hooks() Hooks { return Hooks{k} } @@ -52,7 +52,6 @@ func (h Hooks) AfterCreatingGroupFailed(ctx sdk.Context, group tsstypes.Group) e } func (h Hooks) BeforeSetGroupExpired(ctx sdk.Context, group tsstypes.Group) error { - // TODO: Penalize members will be slashed in the future. return nil } diff --git a/x/bandtss/keeper/keeper.go b/x/bandtss/keeper/keeper.go index 750216b1f..912cf9b67 100644 --- a/x/bandtss/keeper/keeper.go +++ b/x/bandtss/keeper/keeper.go @@ -60,11 +60,12 @@ func NewKeeper( } } -// GetBandtssAccount returns the Bandtss ModuleAccount +// GetBandtssAccount returns the bandtss ModuleAccount func (k Keeper) GetBandtssAccount(ctx sdk.Context) authtypes.ModuleAccountI { return k.authKeeper.GetModuleAccount(ctx, types.ModuleName) } +// Logger gets logger object. func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } @@ -118,12 +119,12 @@ func (k Keeper) DeleteMember(ctx sdk.Context, address sdk.AccAddress) { ctx.KVStore(k.storeKey).Delete(types.MemberStoreKey(address)) } -// SetCurrentGroupID sets a current groupID of the Bandtss module. +// SetCurrentGroupID sets a current groupID of the bandtss module. func (k Keeper) SetCurrentGroupID(ctx sdk.Context, groupID tss.GroupID) { ctx.KVStore(k.storeKey).Set(types.CurrentGroupIDStoreKey, sdk.Uint64ToBigEndian(uint64(groupID))) } -// GetCurrentGroupID retrieves a current groupID of the Bandtss module. +// GetCurrentGroupID retrieves a current groupID of the bandtss module. func (k Keeper) GetCurrentGroupID(ctx sdk.Context) tss.GroupID { return tss.GroupID(sdk.BigEndianToUint64(ctx.KVStore(k.storeKey).Get(types.CurrentGroupIDStoreKey))) } diff --git a/x/bandtss/keeper/msg_server.go b/x/bandtss/keeper/msg_server.go index ee3ad7ff9..8f6ba5205 100644 --- a/x/bandtss/keeper/msg_server.go +++ b/x/bandtss/keeper/msg_server.go @@ -49,7 +49,7 @@ func (k msgServer) CreateGroup( return &types.MsgCreateGroupResponse{}, nil } -// ReplaceGroup handles the replacement of a group with another group. It passes the input to tss module. +// ReplaceGroup handles the replacement of a group with another group. func (k msgServer) ReplaceGroup( goCtx context.Context, req *types.MsgReplaceGroup, @@ -59,8 +59,7 @@ func (k msgServer) ReplaceGroup( } ctx := sdk.UnwrapSDKContext(goCtx) - _, err := k.CreateGroupReplacement(ctx, req.NewGroupID, req.ExecTime) - if err != nil { + if _, err := k.CreateGroupReplacement(ctx, req.NewGroupID, req.ExecTime); err != nil { return nil, err } @@ -134,6 +133,7 @@ func (k msgServer) HealthCheck( return &types.MsgHealthCheckResponse{}, nil } +// UpdateParams update the parameter of the module. func (k Keeper) UpdateParams( goCtx context.Context, req *types.MsgUpdateParams, diff --git a/x/bandtss/types/codec.go b/x/bandtss/types/codec.go index cc0aa4c3a..0e47339a3 100644 --- a/x/bandtss/types/codec.go +++ b/x/bandtss/types/codec.go @@ -7,6 +7,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// RegisterLegacyAminoCodec registers the necessary x/bandtss interfaces and concrete types +// on the provided LegacyAmino codec. These types are used for Amino JSON serialization. func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { legacy.RegisterAminoMsg(cdc, &MsgCreateGroup{}, "bandtss/CreateGroup") legacy.RegisterAminoMsg(cdc, &MsgReplaceGroup{}, "bandtss/ReplaceGroup") @@ -16,6 +18,7 @@ func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "bandtss/UpdateParams") } +// RegisterInterfaces register the bandtss module interfaces to protobuf Any. func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { registry.RegisterImplementations((*sdk.Msg)(nil), &MsgCreateGroup{}, diff --git a/x/bandtss/types/constants.go b/x/bandtss/types/constants.go index aa82c22d9..a504abf0f 100644 --- a/x/bandtss/types/constants.go +++ b/x/bandtss/types/constants.go @@ -4,6 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// GetBandtssGrantMsgTypes get message types that can be granted. func GetBandtssGrantMsgTypes() []string { return []string{ sdk.MsgTypeURL(&MsgHealthCheck{}), diff --git a/x/bandtss/types/params.go b/x/bandtss/types/params.go index a9d39059a..21de98986 100644 --- a/x/bandtss/types/params.go +++ b/x/bandtss/types/params.go @@ -12,8 +12,8 @@ import ( const ( DefaultActiveDuration time.Duration = time.Hour * 24 // 1 days DefaultInactivePenaltyDuration time.Duration = time.Minute * 10 // 10 minutes - // compute the BandTSS reward following the allocation to Oracle. If the Oracle reward amounts to 40%, - // the BandTSS reward will be determined from the remaining 60%. + // compute the bandtss reward following the allocation to Oracle. If the Oracle reward amounts to 40%, + // the bandtss reward will be determined from the remaining 60%. DefaultRewardPercentage = uint64(50) ) From d919d17a1bc762df6db65647549a17bccff276b9 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 2 May 2024 10:03:42 +0700 Subject: [PATCH 060/132] fix tss comments --- x/tss/keeper/msg_server.go | 1 + x/tss/keeper/signing.go | 3 +++ x/tss/types/codec.go | 3 +++ x/tss/types/constants.go | 1 + x/tss/types/expected_keepers.go | 2 +- x/tss/types/signing.go | 1 + 6 files changed, 10 insertions(+), 1 deletion(-) diff --git a/x/tss/keeper/msg_server.go b/x/tss/keeper/msg_server.go index 812e4e260..1fc7f4725 100644 --- a/x/tss/keeper/msg_server.go +++ b/x/tss/keeper/msg_server.go @@ -538,6 +538,7 @@ func (k msgServer) SubmitSignature( return &types.MsgSubmitSignatureResponse{}, nil } +// UpdateParams update parameter of the module. func (k Keeper) UpdateParams( goCtx context.Context, req *types.MsgUpdateParams, diff --git a/x/tss/keeper/signing.go b/x/tss/keeper/signing.go index 9cfcd4fe1..0816e2ee6 100644 --- a/x/tss/keeper/signing.go +++ b/x/tss/keeper/signing.go @@ -464,6 +464,7 @@ func (k Keeper) HandleExpiredSignings(ctx sdk.Context) { } } +// GetPenalizedMembersExpiredSigning get assigned members that do not sign a request. func (k Keeper) GetPenalizedMembersExpiredSigning(ctx sdk.Context, signing types.Signing) ([]sdk.AccAddress, error) { pzs := k.GetPartialSignaturesWithKey(ctx, signing.ID) var penalizedMembers []sdk.AccAddress @@ -487,6 +488,7 @@ func (k Keeper) GetPenalizedMembersExpiredSigning(ctx sdk.Context, signing types return penalizedMembers, nil } +// HandleProcessSigning combine and verify group signature. func (k Keeper) HandleProcessSigning(ctx sdk.Context, signingID tss.SigningID) { signing := k.MustGetSigning(ctx, signingID) pzs := k.GetPartialSignatures(ctx, signingID) @@ -544,6 +546,7 @@ func (k Keeper) handleFailedSigning(ctx sdk.Context, signing types.Signing, reas ) } +// HandleSigningContent convert content to message bytes by the registered router. func (k Keeper) HandleSigningContent( ctx sdk.Context, content types.Content, diff --git a/x/tss/types/codec.go b/x/tss/types/codec.go index 31024ffd3..71adda608 100644 --- a/x/tss/types/codec.go +++ b/x/tss/types/codec.go @@ -7,6 +7,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// RegisterLegacyAminoCodec registers the necessary x/bandtss interfaces and concrete types +// on the provided LegacyAmino codec. These types are used for Amino JSON serialization. func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { legacy.RegisterAminoMsg(cdc, &MsgSubmitDKGRound1{}, "tss/SubmitDKGRound1") legacy.RegisterAminoMsg(cdc, &MsgSubmitDKGRound2{}, "tss/SubmitDKGRound2") @@ -19,6 +21,7 @@ func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { cdc.RegisterConcrete(&TextSignatureOrder{}, "tss/TextSignatureOrder", nil) } +// RegisterInterfaces register the bandtss module interfaces to protobuf Any. func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { registry.RegisterImplementations((*sdk.Msg)(nil), &MsgSubmitDKGRound1{}, diff --git a/x/tss/types/constants.go b/x/tss/types/constants.go index 62bcf2333..aac3e09c9 100644 --- a/x/tss/types/constants.go +++ b/x/tss/types/constants.go @@ -4,6 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// GetTSSGrantMsgTypes get message types that can be granted. func GetTSSGrantMsgTypes() []string { return []string{ sdk.MsgTypeURL(&MsgSubmitDKGRound1{}), diff --git a/x/tss/types/expected_keepers.go b/x/tss/types/expected_keepers.go index 92b476894..34d3fe905 100644 --- a/x/tss/types/expected_keepers.go +++ b/x/tss/types/expected_keepers.go @@ -37,7 +37,7 @@ type AccountKeeper interface { GetModuleAccount(ctx sdk.Context, name string) types.ModuleAccountI } -// TSSHooks event hooks for staking validator object (noalias) +// TSSHooks event hooks for tss validator object (noalias) type TSSHooks interface { // Must be called when a group is created successfully. AfterCreatingGroupCompleted(ctx sdk.Context, group Group) error diff --git a/x/tss/types/signing.go b/x/tss/types/signing.go index 080654f31..caeae01fc 100644 --- a/x/tss/types/signing.go +++ b/x/tss/types/signing.go @@ -25,6 +25,7 @@ func NewSigning( } } +// IsFailed check whether the signing is failed due to expired or fail within the execution. func (s Signing) IsFailed() bool { return s.Status == SIGNING_STATUS_EXPIRED || s.Status == SIGNING_STATUS_FALLEN } From 8b21fdb3ed09a52f65c2c24a55719f24a95944c8 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 2 May 2024 10:20:25 +0700 Subject: [PATCH 061/132] add command is-grantee --- app/app.go | 1 + proto/bandtss/v1beta1/query.proto | 19 + x/bandtss/client/cli/query.go | 32 ++ x/bandtss/keeper/grpc_query.go | 23 + x/bandtss/keeper/keeper.go | 21 + x/bandtss/keeper/keeper_test.go | 21 + x/bandtss/testutil/mock_expected_keepers.go | 56 +- x/bandtss/testutil/mock_keeper.go | 2 + x/bandtss/types/expected_keepers.go | 20 + x/bandtss/types/query.pb.go | 574 +++++++++++++++++--- x/bandtss/types/query.pb.gw.go | 123 +++++ 11 files changed, 819 insertions(+), 73 deletions(-) diff --git a/app/app.go b/app/app.go index 85a041f72..57b950cfc 100644 --- a/app/app.go +++ b/app/app.go @@ -533,6 +533,7 @@ func NewBandApp( appCodec, keys[bandtsstypes.StoreKey], app.GetSubspace(bandtsstypes.ModuleName), + app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.DistrKeeper, diff --git a/proto/bandtss/v1beta1/query.proto b/proto/bandtss/v1beta1/query.proto index 0e0a9c418..bd49376ec 100644 --- a/proto/bandtss/v1beta1/query.proto +++ b/proto/bandtss/v1beta1/query.proto @@ -18,6 +18,11 @@ service Query { option (google.api.http).get = "/bandtss/v1beta1/params"; } + // IsGrantee queries grant of account on this granter. + rpc IsGrantee(QueryIsGranteeRequest) returns (QueryIsGranteeResponse) { + option (google.api.http).get = "/bandtss/v1beta1/is_grantee/{granter}/{grantee}"; + } + // Members queries all members. rpc Members(QueryMembersRequest) returns (QueryMembersResponse) { option (google.api.http).get = "/bandtss/v1beta1/members"; @@ -53,6 +58,20 @@ message QueryParamsResponse { Params params = 1 [(gogoproto.nullable) = false]; } +// QueryIsSignerRequest is request type for the Query/IsGrantee RPC method. +message QueryIsGranteeRequest { + // granter is a granter address + string granter = 1; + // grantee is a grantee address + string grantee = 2; +} + +// QueryIsGranteeResponse is response type for the Query/IsGrantee RPC method. +message QueryIsGranteeResponse { + // is_grantee is true if this account has been granted by granter + bool is_grantee = 1; +} + // QueryMembersRequest is the request type for the Query/Members RPC method. message QueryMembersRequest { // is_active define filter on members diff --git a/x/bandtss/client/cli/query.go b/x/bandtss/client/cli/query.go index 620549c4f..b2b3b0090 100644 --- a/x/bandtss/client/cli/query.go +++ b/x/bandtss/client/cli/query.go @@ -26,6 +26,7 @@ func GetQueryCmd() *cobra.Command { GetQueryCmdParams(), GetQueryCmdSigning(), GetQueryCmdReplacement(), + GetQueryCmdIsGrantee(), ) return cmd @@ -173,3 +174,34 @@ func GetQueryCmdReplacement() *cobra.Command { return cmd } + +// GetQueryCmdIsGrantee creates a CLI command for Query/IsGrantee. +func GetQueryCmdIsGrantee() *cobra.Command { + cmd := &cobra.Command{ + Use: "is-grantee [granter_address] [grantee_address]", + Short: "Query grantee status", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.IsGrantee(cmd.Context(), &types.QueryIsGranteeRequest{ + Granter: args[0], + Grantee: args[1], + }) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/bandtss/keeper/grpc_query.go b/x/bandtss/keeper/grpc_query.go index 79404a2aa..63eb4b977 100644 --- a/x/bandtss/keeper/grpc_query.go +++ b/x/bandtss/keeper/grpc_query.go @@ -21,6 +21,29 @@ func NewQueryServer(k *Keeper) types.QueryServer { return queryServer{k: k} } +// IsGrantee function handles the request to check if a specific address is a grantee of another. +func (q queryServer) IsGrantee( + goCtx context.Context, + req *types.QueryIsGranteeRequest, +) (*types.QueryIsGranteeResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + // Convert granter and grantee addresses from Bech32 to AccAddress + granter, err := sdk.AccAddressFromBech32(req.Granter) + if err != nil { + return nil, err + } + + grantee, err := sdk.AccAddressFromBech32(req.Grantee) + if err != nil { + return nil, err + } + + return &types.QueryIsGranteeResponse{ + IsGrantee: q.k.CheckIsGrantee(ctx, granter, grantee), + }, nil +} + // Member function handles the request to get the member of a given account address. func (q queryServer) Member( goCtx context.Context, diff --git a/x/bandtss/keeper/keeper.go b/x/bandtss/keeper/keeper.go index 912cf9b67..40769b09c 100644 --- a/x/bandtss/keeper/keeper.go +++ b/x/bandtss/keeper/keeper.go @@ -19,6 +19,7 @@ type Keeper struct { storeKey storetypes.StoreKey paramSpace paramtypes.Subspace + authzKeeper types.AuthzKeeper authKeeper types.AccountKeeper bankKeeper types.BankKeeper distrKeeper types.DistrKeeper @@ -33,6 +34,7 @@ func NewKeeper( cdc codec.BinaryCodec, storeKey storetypes.StoreKey, paramSpace paramtypes.Subspace, + authzKeeper types.AuthzKeeper, authKeeper types.AccountKeeper, bankKeeper types.BankKeeper, distrKeeper types.DistrKeeper, @@ -50,6 +52,7 @@ func NewKeeper( cdc: cdc, storeKey: storeKey, paramSpace: paramSpace, + authzKeeper: authzKeeper, authKeeper: authKeeper, bankKeeper: bankKeeper, distrKeeper: distrKeeper, @@ -144,3 +147,21 @@ func (k Keeper) GetReplacement(ctx sdk.Context) types.Replacement { k.cdc.MustUnmarshal(bz, &replacement) return replacement } + +// CheckIsGrantee checks if the granter granted permissions to the grantee. +func (k Keeper) CheckIsGrantee(ctx sdk.Context, granter sdk.AccAddress, grantee sdk.AccAddress) bool { + for _, msg := range types.GetBandtssGrantMsgTypes() { + cap, _ := k.authzKeeper.GetAuthorization( + ctx, + grantee, + granter, + msg, + ) + + if cap == nil { + return false + } + } + + return true +} diff --git a/x/bandtss/keeper/keeper_test.go b/x/bandtss/keeper/keeper_test.go index 226f62de8..54f25561f 100644 --- a/x/bandtss/keeper/keeper_test.go +++ b/x/bandtss/keeper/keeper_test.go @@ -8,6 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/authz" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/stretchr/testify/suite" @@ -233,6 +234,26 @@ func (s *KeeperTestSuite) TestParams() { } } +func (s *KeeperTestSuite) TestIsGrantee() { + ctx, k := s.ctx, s.app.BandtssKeeper + expTime := time.Unix(0, 0) + + // Init grantee address + grantee, _ := sdk.AccAddressFromBech32("band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs") + + // Init granter address + granter, _ := sdk.AccAddressFromBech32("band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun") + + // Save grant msgs to grantee + for _, m := range types.GetBandtssGrantMsgTypes() { + err := s.app.AuthzKeeper.SaveGrant(ctx, grantee, granter, authz.NewGenericAuthorization(m), &expTime) + s.Require().NoError(err) + } + + isGrantee := k.CheckIsGrantee(ctx, granter, grantee) + s.Require().True(isGrantee) +} + func TestKeeperTestSuite(t *testing.T) { suite.Run(t, new(KeeperTestSuite)) } diff --git a/x/bandtss/testutil/mock_expected_keepers.go b/x/bandtss/testutil/mock_expected_keepers.go index 3d807c60f..89a815f39 100644 --- a/x/bandtss/testutil/mock_expected_keepers.go +++ b/x/bandtss/testutil/mock_expected_keepers.go @@ -3,7 +3,7 @@ // // Generated by this command: // -// mockgen --destination x/bandtss/testutil/expected_keepers_mock.go --source x/bandtss/types/expected_keepers.go --package testutil +// mockgen --destination x/bandtss/testutil/mock_expected_keepers.go --source x/bandtss/types/expected_keepers.go --package testutil // // Package testutil is a generated GoMock package. @@ -11,16 +11,70 @@ package testutil import ( reflect "reflect" + time "time" tss "github.com/bandprotocol/chain/v2/pkg/tss" types "github.com/bandprotocol/chain/v2/x/tss/types" types0 "github.com/cosmos/cosmos-sdk/types" types1 "github.com/cosmos/cosmos-sdk/x/auth/types" + authz "github.com/cosmos/cosmos-sdk/x/authz" types2 "github.com/cosmos/cosmos-sdk/x/distribution/types" types3 "github.com/cosmos/cosmos-sdk/x/staking/types" gomock "go.uber.org/mock/gomock" ) +// MockAuthzKeeper is a mock of AuthzKeeper interface. +type MockAuthzKeeper struct { + ctrl *gomock.Controller + recorder *MockAuthzKeeperMockRecorder +} + +// MockAuthzKeeperMockRecorder is the mock recorder for MockAuthzKeeper. +type MockAuthzKeeperMockRecorder struct { + mock *MockAuthzKeeper +} + +// NewMockAuthzKeeper creates a new mock instance. +func NewMockAuthzKeeper(ctrl *gomock.Controller) *MockAuthzKeeper { + mock := &MockAuthzKeeper{ctrl: ctrl} + mock.recorder = &MockAuthzKeeperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockAuthzKeeper) EXPECT() *MockAuthzKeeperMockRecorder { + return m.recorder +} + +// GetAuthorization mocks base method. +func (m *MockAuthzKeeper) GetAuthorization(ctx types0.Context, grantee, granter types0.AccAddress, msgType string) (authz.Authorization, *time.Time) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAuthorization", ctx, grantee, granter, msgType) + ret0, _ := ret[0].(authz.Authorization) + ret1, _ := ret[1].(*time.Time) + return ret0, ret1 +} + +// GetAuthorization indicates an expected call of GetAuthorization. +func (mr *MockAuthzKeeperMockRecorder) GetAuthorization(ctx, grantee, granter, msgType any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAuthorization", reflect.TypeOf((*MockAuthzKeeper)(nil).GetAuthorization), ctx, grantee, granter, msgType) +} + +// SaveGrant mocks base method. +func (m *MockAuthzKeeper) SaveGrant(ctx types0.Context, grantee, granter types0.AccAddress, authorization authz.Authorization, expiration *time.Time) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SaveGrant", ctx, grantee, granter, authorization, expiration) + ret0, _ := ret[0].(error) + return ret0 +} + +// SaveGrant indicates an expected call of SaveGrant. +func (mr *MockAuthzKeeperMockRecorder) SaveGrant(ctx, grantee, granter, authorization, expiration any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveGrant", reflect.TypeOf((*MockAuthzKeeper)(nil).SaveGrant), ctx, grantee, granter, authorization, expiration) +} + // MockAccountKeeper is a mock of AccountKeeper interface. type MockAccountKeeper struct { ctrl *gomock.Controller diff --git a/x/bandtss/testutil/mock_keeper.go b/x/bandtss/testutil/mock_keeper.go index 22dd66cb4..68340a761 100644 --- a/x/bandtss/testutil/mock_keeper.go +++ b/x/bandtss/testutil/mock_keeper.go @@ -40,6 +40,7 @@ func NewTestSuite(t *testing.T) TestSuite { encCfg := moduletestutil.MakeTestEncodingConfig(bandtss.AppModuleBasic{}) ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: time.Now().UTC()}) + authzKeeper := NewMockAuthzKeeper(ctrl) accountKeeper := NewMockAccountKeeper(ctrl) bankKeeper := NewMockBankKeeper(ctrl) distrKeeper := NewMockDistrKeeper(ctrl) @@ -52,6 +53,7 @@ func NewTestSuite(t *testing.T) TestSuite { encCfg.Codec.(codec.BinaryCodec), key, paramtypes.Subspace{}, + authzKeeper, accountKeeper, bankKeeper, distrKeeper, diff --git a/x/bandtss/types/expected_keepers.go b/x/bandtss/types/expected_keepers.go index 90fc38f3d..a2eaa3f19 100644 --- a/x/bandtss/types/expected_keepers.go +++ b/x/bandtss/types/expected_keepers.go @@ -1,8 +1,11 @@ package types import ( + time "time" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/authz" distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -10,6 +13,23 @@ import ( tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) +// AuthzKeeper defines the expected authz keeper. for query and testing only; don't use to +// create/remove grant on deliver tx +type AuthzKeeper interface { + GetAuthorization( + ctx sdk.Context, + grantee sdk.AccAddress, + granter sdk.AccAddress, + msgType string, + ) (authz.Authorization, *time.Time) + SaveGrant( + ctx sdk.Context, + grantee, granter sdk.AccAddress, + authorization authz.Authorization, + expiration *time.Time, + ) error +} + // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI diff --git a/x/bandtss/types/query.pb.go b/x/bandtss/types/query.pb.go index 81ab1f482..31f11465b 100644 --- a/x/bandtss/types/query.pb.go +++ b/x/bandtss/types/query.pb.go @@ -117,6 +117,107 @@ func (m *QueryParamsResponse) GetParams() Params { return Params{} } +// QueryIsSignerRequest is request type for the Query/IsGrantee RPC method. +type QueryIsGranteeRequest struct { + // granter is a granter address + Granter string `protobuf:"bytes,1,opt,name=granter,proto3" json:"granter,omitempty"` + // grantee is a grantee address + Grantee string `protobuf:"bytes,2,opt,name=grantee,proto3" json:"grantee,omitempty"` +} + +func (m *QueryIsGranteeRequest) Reset() { *m = QueryIsGranteeRequest{} } +func (m *QueryIsGranteeRequest) String() string { return proto.CompactTextString(m) } +func (*QueryIsGranteeRequest) ProtoMessage() {} +func (*QueryIsGranteeRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_85d3a287ab772b87, []int{2} +} +func (m *QueryIsGranteeRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryIsGranteeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryIsGranteeRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryIsGranteeRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryIsGranteeRequest.Merge(m, src) +} +func (m *QueryIsGranteeRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryIsGranteeRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryIsGranteeRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryIsGranteeRequest proto.InternalMessageInfo + +func (m *QueryIsGranteeRequest) GetGranter() string { + if m != nil { + return m.Granter + } + return "" +} + +func (m *QueryIsGranteeRequest) GetGrantee() string { + if m != nil { + return m.Grantee + } + return "" +} + +// QueryIsGranteeResponse is response type for the Query/IsGrantee RPC method. +type QueryIsGranteeResponse struct { + // is_grantee is true if this account has been granted by granter + IsGrantee bool `protobuf:"varint,1,opt,name=is_grantee,json=isGrantee,proto3" json:"is_grantee,omitempty"` +} + +func (m *QueryIsGranteeResponse) Reset() { *m = QueryIsGranteeResponse{} } +func (m *QueryIsGranteeResponse) String() string { return proto.CompactTextString(m) } +func (*QueryIsGranteeResponse) ProtoMessage() {} +func (*QueryIsGranteeResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_85d3a287ab772b87, []int{3} +} +func (m *QueryIsGranteeResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryIsGranteeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryIsGranteeResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryIsGranteeResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryIsGranteeResponse.Merge(m, src) +} +func (m *QueryIsGranteeResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryIsGranteeResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryIsGranteeResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryIsGranteeResponse proto.InternalMessageInfo + +func (m *QueryIsGranteeResponse) GetIsGrantee() bool { + if m != nil { + return m.IsGrantee + } + return false +} + // QueryMembersRequest is the request type for the Query/Members RPC method. type QueryMembersRequest struct { // is_active define filter on members @@ -129,7 +230,7 @@ func (m *QueryMembersRequest) Reset() { *m = QueryMembersRequest{} } func (m *QueryMembersRequest) String() string { return proto.CompactTextString(m) } func (*QueryMembersRequest) ProtoMessage() {} func (*QueryMembersRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_85d3a287ab772b87, []int{2} + return fileDescriptor_85d3a287ab772b87, []int{4} } func (m *QueryMembersRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -184,7 +285,7 @@ func (m *QueryMembersResponse) Reset() { *m = QueryMembersResponse{} } func (m *QueryMembersResponse) String() string { return proto.CompactTextString(m) } func (*QueryMembersResponse) ProtoMessage() {} func (*QueryMembersResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_85d3a287ab772b87, []int{3} + return fileDescriptor_85d3a287ab772b87, []int{5} } func (m *QueryMembersResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -237,7 +338,7 @@ func (m *QueryMemberRequest) Reset() { *m = QueryMemberRequest{} } func (m *QueryMemberRequest) String() string { return proto.CompactTextString(m) } func (*QueryMemberRequest) ProtoMessage() {} func (*QueryMemberRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_85d3a287ab772b87, []int{4} + return fileDescriptor_85d3a287ab772b87, []int{6} } func (m *QueryMemberRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -283,7 +384,7 @@ func (m *QueryMemberResponse) Reset() { *m = QueryMemberResponse{} } func (m *QueryMemberResponse) String() string { return proto.CompactTextString(m) } func (*QueryMemberResponse) ProtoMessage() {} func (*QueryMemberResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_85d3a287ab772b87, []int{5} + return fileDescriptor_85d3a287ab772b87, []int{7} } func (m *QueryMemberResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -327,7 +428,7 @@ func (m *QueryCurrentGroupRequest) Reset() { *m = QueryCurrentGroupReque func (m *QueryCurrentGroupRequest) String() string { return proto.CompactTextString(m) } func (*QueryCurrentGroupRequest) ProtoMessage() {} func (*QueryCurrentGroupRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_85d3a287ab772b87, []int{6} + return fileDescriptor_85d3a287ab772b87, []int{8} } func (m *QueryCurrentGroupRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -360,7 +461,8 @@ var xxx_messageInfo_QueryCurrentGroupRequest proto.InternalMessageInfo type QueryCurrentGroupResponse struct { // group_id is the ID of the current group. GroupID github_com_bandprotocol_chain_v2_pkg_tss.GroupID `protobuf:"varint,1,opt,name=group_id,json=groupId,proto3,casttype=github.com/bandprotocol/chain/v2/pkg/tss.GroupID" json:"group_id,omitempty"` - Size_ uint64 `protobuf:"varint,2,opt,name=size,proto3" json:"size,omitempty"` + // size is the number of members in the group. + Size_ uint64 `protobuf:"varint,2,opt,name=size,proto3" json:"size,omitempty"` // threshold is the minimum number of members needed to generate a valid signature. Threshold uint64 `protobuf:"varint,3,opt,name=threshold,proto3" json:"threshold,omitempty"` // pub_key is the public key generated by the group. @@ -373,7 +475,7 @@ func (m *QueryCurrentGroupResponse) Reset() { *m = QueryCurrentGroupResp func (m *QueryCurrentGroupResponse) String() string { return proto.CompactTextString(m) } func (*QueryCurrentGroupResponse) ProtoMessage() {} func (*QueryCurrentGroupResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_85d3a287ab772b87, []int{7} + return fileDescriptor_85d3a287ab772b87, []int{9} } func (m *QueryCurrentGroupResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -447,7 +549,7 @@ func (m *QuerySigningRequest) Reset() { *m = QuerySigningRequest{} } func (m *QuerySigningRequest) String() string { return proto.CompactTextString(m) } func (*QuerySigningRequest) ProtoMessage() {} func (*QuerySigningRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_85d3a287ab772b87, []int{8} + return fileDescriptor_85d3a287ab772b87, []int{10} } func (m *QuerySigningRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -499,7 +601,7 @@ func (m *QuerySigningResponse) Reset() { *m = QuerySigningResponse{} } func (m *QuerySigningResponse) String() string { return proto.CompactTextString(m) } func (*QuerySigningResponse) ProtoMessage() {} func (*QuerySigningResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_85d3a287ab772b87, []int{9} + return fileDescriptor_85d3a287ab772b87, []int{11} } func (m *QuerySigningResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -564,7 +666,7 @@ func (m *QueryReplacementRequest) Reset() { *m = QueryReplacementRequest func (m *QueryReplacementRequest) String() string { return proto.CompactTextString(m) } func (*QueryReplacementRequest) ProtoMessage() {} func (*QueryReplacementRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_85d3a287ab772b87, []int{10} + return fileDescriptor_85d3a287ab772b87, []int{12} } func (m *QueryReplacementRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -603,7 +705,7 @@ func (m *QueryReplacementResponse) Reset() { *m = QueryReplacementRespon func (m *QueryReplacementResponse) String() string { return proto.CompactTextString(m) } func (*QueryReplacementResponse) ProtoMessage() {} func (*QueryReplacementResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_85d3a287ab772b87, []int{11} + return fileDescriptor_85d3a287ab772b87, []int{13} } func (m *QueryReplacementResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -642,6 +744,8 @@ func (m *QueryReplacementResponse) GetReplacement() Replacement { func init() { proto.RegisterType((*QueryParamsRequest)(nil), "bandtss.v1beta1.QueryParamsRequest") proto.RegisterType((*QueryParamsResponse)(nil), "bandtss.v1beta1.QueryParamsResponse") + proto.RegisterType((*QueryIsGranteeRequest)(nil), "bandtss.v1beta1.QueryIsGranteeRequest") + proto.RegisterType((*QueryIsGranteeResponse)(nil), "bandtss.v1beta1.QueryIsGranteeResponse") proto.RegisterType((*QueryMembersRequest)(nil), "bandtss.v1beta1.QueryMembersRequest") proto.RegisterType((*QueryMembersResponse)(nil), "bandtss.v1beta1.QueryMembersResponse") proto.RegisterType((*QueryMemberRequest)(nil), "bandtss.v1beta1.QueryMemberRequest") @@ -657,67 +761,72 @@ func init() { func init() { proto.RegisterFile("bandtss/v1beta1/query.proto", fileDescriptor_85d3a287ab772b87) } var fileDescriptor_85d3a287ab772b87 = []byte{ - // 945 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x55, 0x41, 0x6f, 0xdc, 0x44, - 0x14, 0x8e, 0x93, 0xed, 0x6e, 0x76, 0x52, 0x81, 0x34, 0x04, 0xc5, 0xeb, 0x6c, 0xbd, 0x2b, 0x13, - 0xc2, 0x36, 0x12, 0x76, 0xb2, 0xc0, 0x19, 0xb1, 0xad, 0xa8, 0x42, 0x41, 0x2a, 0xee, 0xad, 0x08, - 0x2d, 0x5e, 0x7b, 0x70, 0x46, 0xd9, 0xf5, 0xb8, 0x9e, 0x71, 0xd4, 0xb4, 0xaa, 0x90, 0x38, 0x20, - 0x2e, 0x48, 0x08, 0xae, 0xfc, 0x00, 0xc4, 0x2f, 0xe9, 0xb1, 0x88, 0x0b, 0xa7, 0x80, 0x12, 0x7e, - 0x45, 0x4f, 0xc8, 0x33, 0xcf, 0x6b, 0x3b, 0xde, 0x6d, 0x72, 0xca, 0x7a, 0xde, 0xf7, 0xde, 0xf7, - 0xcd, 0xf7, 0xde, 0xbc, 0xa0, 0xed, 0x89, 0x17, 0x05, 0x82, 0x73, 0xe7, 0xe4, 0x60, 0x42, 0x84, - 0x77, 0xe0, 0x3c, 0x4e, 0x49, 0x72, 0x6a, 0xc7, 0x09, 0x13, 0x0c, 0xbf, 0x09, 0x41, 0x1b, 0x82, - 0xc6, 0x66, 0xc8, 0x42, 0x26, 0x63, 0x4e, 0xf6, 0x4b, 0xc1, 0x8c, 0x3d, 0x9f, 0xf1, 0x19, 0xe3, - 0xce, 0xc4, 0xe3, 0x44, 0xe5, 0xcf, 0xab, 0xc5, 0x5e, 0x48, 0x23, 0x4f, 0x50, 0x16, 0x01, 0xd6, - 0x2c, 0x63, 0x73, 0x94, 0xcf, 0x68, 0x1e, 0xef, 0x86, 0x8c, 0x85, 0x53, 0xe2, 0x78, 0x31, 0x75, - 0xbc, 0x28, 0x62, 0x42, 0x26, 0x73, 0x88, 0xde, 0xba, 0xac, 0x36, 0x17, 0xb8, 0x24, 0x1c, 0x92, - 0x88, 0x70, 0x9a, 0x87, 0xdf, 0x2e, 0x87, 0xe6, 0x59, 0xd6, 0x26, 0xc2, 0x5f, 0x66, 0xa2, 0x1f, - 0x78, 0x89, 0x37, 0xe3, 0x2e, 0x79, 0x9c, 0x12, 0x2e, 0xac, 0xcf, 0xd1, 0x5b, 0x95, 0x53, 0x1e, - 0xb3, 0x88, 0x13, 0xfc, 0x11, 0x6a, 0xc6, 0xf2, 0x44, 0xd7, 0xfa, 0xda, 0x60, 0x63, 0xb8, 0x65, - 0x5f, 0xf2, 0xc8, 0x56, 0x09, 0xa3, 0xc6, 0x8b, 0xb3, 0xde, 0x8a, 0x0b, 0x60, 0xeb, 0x29, 0x54, - 0xfb, 0x82, 0xcc, 0x26, 0x24, 0xc9, 0x49, 0xf0, 0x36, 0x6a, 0x53, 0x3e, 0xf6, 0x7c, 0x41, 0x4f, - 0x88, 0x2c, 0xb8, 0xee, 0xae, 0x53, 0xfe, 0x89, 0xfc, 0xc6, 0x9f, 0x22, 0x54, 0xd8, 0xa7, 0xaf, - 0x4a, 0xba, 0x5d, 0x5b, 0xf9, 0x67, 0x67, 0xfe, 0xd9, 0xaa, 0x57, 0x05, 0x71, 0x48, 0xa0, 0xb0, - 0x5b, 0xca, 0xb4, 0x7e, 0xd1, 0xd0, 0x66, 0x95, 0x1c, 0xee, 0x72, 0x80, 0x5a, 0x33, 0x75, 0xa4, - 0x6b, 0xfd, 0xb5, 0x85, 0x97, 0x51, 0x29, 0x6e, 0x8e, 0xc3, 0xf7, 0x16, 0x68, 0x7a, 0xef, 0x4a, - 0x4d, 0x8a, 0xaf, 0x22, 0xca, 0x06, 0xd3, 0x81, 0x00, 0xfc, 0xd0, 0x51, 0xcb, 0x0b, 0x82, 0x84, - 0x70, 0x65, 0x6f, 0xdb, 0xcd, 0x3f, 0xe7, 0xed, 0xc8, 0xf1, 0x45, 0x3b, 0x94, 0xb4, 0xa5, 0xed, - 0x50, 0x09, 0x79, 0x3b, 0x14, 0xd8, 0x32, 0x90, 0x2e, 0xab, 0xdd, 0x49, 0x93, 0x84, 0x44, 0xe2, - 0x5e, 0xc2, 0xd2, 0x38, 0x6f, 0xfc, 0xef, 0xab, 0xa8, 0xb3, 0x20, 0x08, 0x84, 0x8f, 0xd0, 0x7a, - 0x98, 0x1d, 0x8c, 0x69, 0x20, 0x29, 0x1b, 0xa3, 0x8f, 0xcf, 0xcf, 0x7a, 0x2d, 0x09, 0x3a, 0xbc, - 0xfb, 0xea, 0xac, 0xb7, 0x1f, 0x52, 0x71, 0x94, 0x4e, 0x6c, 0x9f, 0xcd, 0xe4, 0x74, 0xca, 0x19, - 0xf3, 0xd9, 0xd4, 0xf1, 0x8f, 0x3c, 0x1a, 0x39, 0x27, 0x43, 0x27, 0x3e, 0x0e, 0xe5, 0xf4, 0x41, - 0x8e, 0xdb, 0x92, 0x05, 0x0f, 0x03, 0x8c, 0x51, 0x83, 0xd3, 0xa7, 0x44, 0xda, 0xda, 0x70, 0xe5, - 0x6f, 0xdc, 0x45, 0x6d, 0x71, 0x94, 0x10, 0x7e, 0xc4, 0xa6, 0x81, 0xbe, 0x26, 0x03, 0xc5, 0x01, - 0xbe, 0x8f, 0x5a, 0x71, 0x3a, 0x19, 0x1f, 0x93, 0x53, 0xbd, 0xd1, 0xd7, 0x06, 0x37, 0x47, 0xc3, - 0x57, 0x67, 0x3d, 0xfb, 0xda, 0x0a, 0x1e, 0x30, 0x1a, 0x09, 0xb7, 0x19, 0xa7, 0x93, 0xfb, 0xe4, - 0x14, 0xef, 0xa3, 0x26, 0x17, 0x9e, 0x48, 0xb9, 0x7e, 0xa3, 0xaf, 0x0d, 0xde, 0x18, 0xea, 0x76, - 0xd9, 0x47, 0xa9, 0xf6, 0xa1, 0x8c, 0xbb, 0x80, 0xb3, 0x3e, 0x84, 0xa6, 0x3c, 0xa4, 0x61, 0x44, - 0xa3, 0x30, 0xef, 0xe2, 0x2d, 0x84, 0xb8, 0x3a, 0x99, 0xbb, 0xe4, 0xb6, 0xe1, 0xe4, 0x30, 0xb0, - 0xfe, 0x5c, 0x85, 0x79, 0x9c, 0xa7, 0x81, 0xb7, 0x5f, 0xa3, 0xb5, 0x6f, 0x09, 0x81, 0x59, 0xec, - 0x54, 0xa6, 0x2a, 0x57, 0x71, 0x87, 0xd1, 0x68, 0xb4, 0x9f, 0xf5, 0xf2, 0x8f, 0x7f, 0x7a, 0x83, - 0xd2, 0x45, 0x61, 0xad, 0xa8, 0x3f, 0xef, 0xf3, 0xe0, 0xd8, 0x11, 0xa7, 0x31, 0xe1, 0x32, 0x81, - 0xbb, 0x59, 0xdd, 0xcc, 0xca, 0x44, 0x29, 0x24, 0x89, 0xf4, 0xb8, 0xed, 0x16, 0x07, 0xf8, 0x2b, - 0xd4, 0xf5, 0x55, 0xc3, 0xc7, 0xaa, 0xc1, 0xf9, 0x15, 0x12, 0xc2, 0xd3, 0xa9, 0x90, 0xde, 0x6f, - 0x0c, 0x8d, 0x8a, 0x27, 0xc5, 0x05, 0xd2, 0xa9, 0x70, 0x3b, 0x7e, 0x69, 0x60, 0x2a, 0x21, 0x3c, - 0x46, 0x66, 0x42, 0xe2, 0xa9, 0xe7, 0x67, 0x05, 0x17, 0x96, 0x6f, 0x5c, 0x59, 0x7e, 0x7b, 0x5e, - 0xa1, 0x4e, 0x60, 0x75, 0xd0, 0x96, 0xb4, 0xd4, 0x95, 0x18, 0x32, 0x23, 0x91, 0xc8, 0xe7, 0xf9, - 0x1b, 0x98, 0xf5, 0x4a, 0x08, 0x1c, 0xbf, 0x8b, 0x36, 0x92, 0xe2, 0x18, 0xde, 0x50, 0xb7, 0xf6, - 0x86, 0x4a, 0xa9, 0xf0, 0x90, 0xca, 0x69, 0xc3, 0xdf, 0x9a, 0xe8, 0x86, 0xa4, 0xc0, 0x02, 0x35, - 0xd5, 0xfa, 0xc3, 0xef, 0xd4, 0x8a, 0xd4, 0x77, 0xac, 0xb1, 0xf3, 0x7a, 0x90, 0x12, 0x69, 0xf5, - 0xbe, 0xff, 0xeb, 0xbf, 0x5f, 0x57, 0x3b, 0x78, 0xcb, 0xb9, 0xbc, 0xde, 0xd5, 0x72, 0xc5, 0x4f, - 0x50, 0x0b, 0x56, 0x1b, 0x5e, 0x52, 0xb1, 0xba, 0x76, 0x8d, 0x77, 0xaf, 0x40, 0x01, 0x71, 0x5f, - 0x12, 0x1b, 0x58, 0xaf, 0x11, 0xe7, 0xeb, 0xf0, 0x3b, 0xd4, 0x54, 0x49, 0xcb, 0xee, 0x5b, 0x59, - 0x6f, 0xc6, 0xce, 0xeb, 0x41, 0x40, 0xbb, 0x27, 0x69, 0x77, 0xb0, 0xb5, 0x8c, 0xd6, 0x79, 0x06, - 0x5b, 0xf1, 0x39, 0xfe, 0x49, 0x43, 0x37, 0xcb, 0x7b, 0x0a, 0xdf, 0x5e, 0x4c, 0xb1, 0x60, 0xd1, - 0x19, 0x7b, 0xd7, 0x81, 0x82, 0xa6, 0x5d, 0xa9, 0xa9, 0x8f, 0xcd, 0x9a, 0xa6, 0xca, 0xa3, 0xc1, - 0x3f, 0x68, 0xa8, 0x05, 0x93, 0xb9, 0xac, 0x17, 0xd5, 0x65, 0xb1, 0xac, 0x17, 0x97, 0x76, 0x83, - 0x65, 0x4b, 0x01, 0x03, 0xbc, 0x5b, 0x13, 0x00, 0x0f, 0x89, 0x3b, 0xcf, 0x8a, 0xa5, 0xf3, 0x1c, - 0xff, 0xa8, 0xa1, 0x8d, 0xd2, 0xd8, 0xe2, 0xc1, 0x62, 0x9a, 0xfa, 0x7b, 0x31, 0x6e, 0x5f, 0x03, - 0x09, 0xa2, 0x76, 0xa4, 0x28, 0x13, 0x77, 0x6b, 0xa2, 0x4a, 0xcf, 0x63, 0xf4, 0xd9, 0x8b, 0x73, - 0x53, 0x7b, 0x79, 0x6e, 0x6a, 0xff, 0x9e, 0x9b, 0xda, 0xcf, 0x17, 0xe6, 0xca, 0xcb, 0x0b, 0x73, - 0xe5, 0xef, 0x0b, 0x73, 0xe5, 0xd1, 0xd5, 0xff, 0x2b, 0x9e, 0xcc, 0x2b, 0xcb, 0x75, 0x36, 0x69, - 0x4a, 0xc8, 0x07, 0xff, 0x07, 0x00, 0x00, 0xff, 0xff, 0x66, 0x0a, 0x8b, 0xde, 0xb7, 0x09, 0x00, - 0x00, + // 1028 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x55, 0x5f, 0x6f, 0xdb, 0x54, + 0x14, 0xaf, 0xdb, 0x2c, 0x69, 0x4e, 0x27, 0x90, 0x2e, 0x1d, 0x75, 0xdc, 0xd4, 0x89, 0x4c, 0xe9, + 0xb2, 0x4a, 0xd8, 0x6d, 0x00, 0xed, 0x11, 0x91, 0x4d, 0x54, 0xa5, 0x20, 0x0d, 0xef, 0x6d, 0x08, + 0x05, 0xc7, 0xb9, 0xb8, 0x56, 0x13, 0xdb, 0xf3, 0xbd, 0xae, 0xd6, 0x55, 0x15, 0x12, 0x0f, 0x88, + 0x17, 0x24, 0x04, 0xe2, 0x3b, 0x20, 0x9e, 0xf9, 0x10, 0x7b, 0x1c, 0xe2, 0x85, 0xa7, 0x82, 0x5a, + 0x3e, 0xc5, 0x9e, 0x90, 0xef, 0x9f, 0xd8, 0x8e, 0x93, 0xa5, 0x4f, 0x71, 0xce, 0xf9, 0x9d, 0x73, + 0x7e, 0xe7, 0xef, 0x85, 0xcd, 0x81, 0x13, 0x0c, 0x29, 0x21, 0xd6, 0xe9, 0xfe, 0x00, 0x53, 0x67, + 0xdf, 0x7a, 0x9a, 0xe0, 0xf8, 0xcc, 0x8c, 0xe2, 0x90, 0x86, 0xe8, 0x4d, 0xa1, 0x34, 0x85, 0x52, + 0x5b, 0xf7, 0x42, 0x2f, 0x64, 0x3a, 0x2b, 0xfd, 0xe2, 0x30, 0x6d, 0xd7, 0x0d, 0xc9, 0x38, 0x24, + 0xd6, 0xc0, 0x21, 0x98, 0xdb, 0x4f, 0xbc, 0x45, 0x8e, 0xe7, 0x07, 0x0e, 0xf5, 0xc3, 0x40, 0x60, + 0xf5, 0x3c, 0x56, 0xa2, 0xdc, 0xd0, 0x97, 0xfa, 0xa6, 0x17, 0x86, 0xde, 0x08, 0x5b, 0x4e, 0xe4, + 0x5b, 0x4e, 0x10, 0x84, 0x94, 0x19, 0x13, 0xa1, 0xdd, 0x9a, 0x66, 0x2b, 0x09, 0xce, 0x51, 0x7b, + 0x38, 0xc0, 0xc4, 0x97, 0xea, 0x3b, 0x79, 0xd5, 0xc4, 0xca, 0x58, 0x07, 0xf4, 0x45, 0x4a, 0xfa, + 0x91, 0x13, 0x3b, 0x63, 0x62, 0xe3, 0xa7, 0x09, 0x26, 0xd4, 0xf8, 0x0c, 0xde, 0x2a, 0x48, 0x49, + 0x14, 0x06, 0x04, 0xa3, 0x0f, 0xa1, 0x1a, 0x31, 0x89, 0xaa, 0xb4, 0x95, 0xce, 0x5a, 0x77, 0xc3, + 0x9c, 0xaa, 0x91, 0xc9, 0x0d, 0x7a, 0x95, 0x17, 0x97, 0xad, 0x25, 0x5b, 0x80, 0x8d, 0x23, 0xb8, + 0xc3, 0xbc, 0x1d, 0x92, 0x83, 0xd8, 0x09, 0x28, 0xc6, 0x22, 0x0c, 0x52, 0xa1, 0xe6, 0x31, 0x49, + 0xcc, 0x1c, 0xd6, 0x6d, 0xf9, 0x37, 0xd3, 0x60, 0x75, 0x39, 0xaf, 0xc1, 0xc6, 0x7d, 0x78, 0x7b, + 0xda, 0x99, 0x60, 0xb7, 0x05, 0xe0, 0x93, 0xbe, 0x34, 0x4b, 0x1d, 0xae, 0xda, 0x75, 0x5f, 0xc2, + 0x8c, 0xe7, 0x22, 0xa7, 0xcf, 0xf1, 0x78, 0x80, 0x63, 0x99, 0x2a, 0xda, 0x84, 0xba, 0x4f, 0xfa, + 0x8e, 0x4b, 0xfd, 0x53, 0x69, 0xb4, 0xea, 0x93, 0x8f, 0xd9, 0x7f, 0xf4, 0x09, 0x40, 0xd6, 0x44, + 0xc6, 0x64, 0xad, 0xbb, 0x63, 0xf2, 0x2e, 0x9a, 0x69, 0x17, 0x4d, 0x3e, 0x31, 0x59, 0xfa, 0x9e, + 0x4c, 0xce, 0xce, 0x59, 0x1a, 0x3f, 0x2b, 0xb0, 0x5e, 0x0c, 0x2e, 0x38, 0xef, 0x43, 0x6d, 0xcc, + 0x45, 0xaa, 0xd2, 0x5e, 0x99, 0x59, 0x52, 0x6e, 0x62, 0x4b, 0x1c, 0x3a, 0x98, 0xc1, 0xe9, 0xee, + 0x42, 0x4e, 0x3c, 0x5e, 0x81, 0x94, 0x29, 0x5a, 0x2f, 0x02, 0x64, 0x3d, 0x71, 0x86, 0xc3, 0x18, + 0x13, 0x22, 0x7b, 0x22, 0xfe, 0x4e, 0x86, 0x42, 0xe2, 0xb3, 0xa1, 0xe0, 0xd4, 0xe6, 0x0e, 0x05, + 0x37, 0x90, 0x43, 0xc1, 0xc1, 0x86, 0x06, 0x2a, 0xf3, 0xf6, 0x20, 0x89, 0x63, 0x1c, 0xd0, 0x83, + 0x38, 0x4c, 0x22, 0x39, 0x7e, 0xbf, 0x2d, 0x43, 0x63, 0x86, 0x52, 0x04, 0x7c, 0x02, 0xab, 0x5e, + 0x2a, 0xe8, 0xfb, 0x43, 0x16, 0xb2, 0xd2, 0xfb, 0xe8, 0xea, 0xb2, 0x55, 0x63, 0xa0, 0xc3, 0x87, + 0xaf, 0x2e, 0x5b, 0x7b, 0x9e, 0x4f, 0x8f, 0x93, 0x81, 0xe9, 0x86, 0x63, 0xb6, 0x23, 0x6c, 0xd2, + 0xdd, 0x70, 0x64, 0xb9, 0xc7, 0x8e, 0x1f, 0x58, 0xa7, 0x5d, 0x2b, 0x3a, 0xf1, 0xd8, 0x0e, 0x08, + 0x9b, 0x74, 0xba, 0xd2, 0x8f, 0x21, 0x42, 0x50, 0x21, 0xfe, 0x73, 0x3e, 0x74, 0x15, 0x9b, 0x7d, + 0xa3, 0x26, 0xd4, 0xe9, 0x71, 0x8c, 0xc9, 0x71, 0x38, 0x1a, 0xaa, 0x2b, 0x4c, 0x91, 0x09, 0xd0, + 0x11, 0xd4, 0xa2, 0x64, 0xd0, 0x3f, 0xc1, 0x67, 0x6a, 0xa5, 0xad, 0x74, 0x6e, 0xf7, 0xba, 0xaf, + 0x2e, 0x5b, 0xe6, 0x8d, 0x19, 0x3c, 0x0a, 0xfd, 0x80, 0xda, 0xd5, 0x28, 0x19, 0x1c, 0xe1, 0x33, + 0xb4, 0x07, 0x55, 0x42, 0x1d, 0x9a, 0x10, 0xf5, 0x56, 0x5b, 0xe9, 0xbc, 0xd1, 0x55, 0xcd, 0x7c, + 0x1d, 0x19, 0xdb, 0xc7, 0x4c, 0x6f, 0x0b, 0x9c, 0xf1, 0x81, 0x68, 0xca, 0x63, 0xdf, 0x0b, 0xfc, + 0xc0, 0x93, 0x5d, 0xdc, 0x02, 0x20, 0x5c, 0x32, 0xa9, 0x92, 0x5d, 0x17, 0x92, 0xc3, 0xa1, 0xf1, + 0xe7, 0xb2, 0x98, 0xc7, 0x89, 0x99, 0xa8, 0xed, 0x57, 0xb0, 0xf2, 0x0d, 0x5b, 0x9e, 0x74, 0x16, + 0x1b, 0x85, 0xa9, 0x92, 0x2c, 0x1e, 0x84, 0x7e, 0xd0, 0xdb, 0x4b, 0x7b, 0xf9, 0xfb, 0x3f, 0xad, + 0x4e, 0x2e, 0x51, 0x71, 0xdc, 0xf8, 0xcf, 0x7b, 0x64, 0x78, 0x62, 0xd1, 0xb3, 0x08, 0x13, 0x66, + 0x40, 0xec, 0xd4, 0x6f, 0x5a, 0xca, 0x98, 0x33, 0xc4, 0xb1, 0x58, 0xec, 0x4c, 0x80, 0xbe, 0x84, + 0xa6, 0xcb, 0x1b, 0xde, 0xe7, 0x0d, 0x96, 0x29, 0xc4, 0x98, 0x24, 0x23, 0xca, 0x6a, 0xbf, 0xd6, + 0xd5, 0x0a, 0x35, 0xc9, 0x12, 0x48, 0x46, 0xd4, 0x6e, 0xb8, 0xb9, 0x81, 0x29, 0xa8, 0x50, 0x1f, + 0xf4, 0x18, 0x47, 0x23, 0xc7, 0x4d, 0x1d, 0xce, 0x74, 0x5f, 0x59, 0xe8, 0x7e, 0x73, 0xe2, 0xa1, + 0x1c, 0xc0, 0x68, 0xc0, 0x06, 0x2b, 0xa9, 0xcd, 0x30, 0x78, 0x8c, 0x03, 0x2a, 0xe7, 0xf9, 0x6b, + 0x31, 0xeb, 0x05, 0x95, 0xa8, 0xf8, 0x43, 0x58, 0x8b, 0x33, 0xb1, 0xd8, 0xa1, 0x66, 0x69, 0x87, + 0x72, 0xa6, 0x62, 0x91, 0xf2, 0x66, 0xdd, 0x3f, 0x6a, 0x70, 0x8b, 0x85, 0x40, 0x14, 0xaa, 0xfc, + 0x08, 0xa3, 0x77, 0x4a, 0x4e, 0xca, 0x97, 0x5e, 0xdb, 0x7e, 0x3d, 0x88, 0x93, 0x34, 0x5a, 0xdf, + 0xfd, 0xf5, 0xdf, 0x2f, 0xcb, 0x0d, 0xb4, 0x61, 0x4d, 0x3f, 0x32, 0xfc, 0xc4, 0xa3, 0x5f, 0x15, + 0xa8, 0x4f, 0x2e, 0x32, 0xda, 0x99, 0xed, 0x74, 0xfa, 0xfe, 0x6b, 0x77, 0x17, 0xe2, 0x44, 0xfc, + 0xfb, 0x2c, 0xfe, 0x3e, 0xb2, 0x4a, 0xf1, 0xb3, 0x8b, 0x6f, 0x9d, 0x8b, 0xc7, 0xe3, 0x42, 0x7e, + 0xe1, 0x0b, 0xf4, 0x0c, 0x6a, 0xe2, 0xe4, 0xa2, 0x39, 0x99, 0x16, 0x9f, 0x03, 0xed, 0xdd, 0x05, + 0x28, 0x41, 0xa8, 0xcd, 0x08, 0x69, 0x48, 0x2d, 0x11, 0x92, 0x67, 0xfa, 0x5b, 0xa8, 0x72, 0xa3, + 0x79, 0x7d, 0x28, 0x9c, 0x5d, 0x6d, 0xfb, 0xf5, 0x20, 0x11, 0x76, 0x97, 0x85, 0xdd, 0x46, 0xc6, + 0xbc, 0xb0, 0xd6, 0xb9, 0xb8, 0xd6, 0x17, 0xe8, 0x47, 0x05, 0x6e, 0xe7, 0xef, 0x27, 0xba, 0x37, + 0x3b, 0xc4, 0x8c, 0x03, 0xac, 0xed, 0xde, 0x04, 0x2a, 0x38, 0xed, 0x30, 0x4e, 0x6d, 0xa4, 0x97, + 0x38, 0x15, 0x96, 0x19, 0x7d, 0xaf, 0x40, 0x4d, 0x6c, 0xcc, 0xbc, 0x5e, 0x14, 0x8f, 0xd8, 0xbc, + 0x5e, 0x4c, 0xdd, 0x2c, 0xc3, 0x64, 0x04, 0x3a, 0x68, 0xa7, 0x44, 0x40, 0x2c, 0x38, 0xb1, 0xce, + 0xb3, 0x63, 0x78, 0x81, 0x7e, 0x50, 0x60, 0x2d, 0xb7, 0x4e, 0xa8, 0x33, 0x3b, 0x4c, 0x79, 0x8f, + 0xb5, 0x7b, 0x37, 0x40, 0x0a, 0x52, 0xdb, 0x8c, 0x94, 0x8e, 0x9a, 0x25, 0x52, 0xb9, 0xb5, 0xed, + 0x7d, 0xfa, 0xe2, 0x4a, 0x57, 0x5e, 0x5e, 0xe9, 0xca, 0xbf, 0x57, 0xba, 0xf2, 0xd3, 0xb5, 0xbe, + 0xf4, 0xf2, 0x5a, 0x5f, 0xfa, 0xfb, 0x5a, 0x5f, 0x7a, 0xb2, 0xf8, 0x0d, 0x7b, 0x36, 0xf1, 0xcc, + 0xce, 0xec, 0xa0, 0xca, 0x20, 0xef, 0xff, 0x1f, 0x00, 0x00, 0xff, 0xff, 0x0b, 0x3b, 0x44, 0xee, + 0xd5, 0x0a, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -734,6 +843,8 @@ const _ = grpc.SupportPackageIsVersion4 type QueryClient interface { // Params queries parameters of Bandtss module Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) + // IsGrantee queries grant of account on this granter. + IsGrantee(ctx context.Context, in *QueryIsGranteeRequest, opts ...grpc.CallOption) (*QueryIsGranteeResponse, error) // Members queries all members. Members(ctx context.Context, in *QueryMembersRequest, opts ...grpc.CallOption) (*QueryMembersResponse, error) // Member queries the member information of the address. @@ -763,6 +874,15 @@ func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts . return out, nil } +func (c *queryClient) IsGrantee(ctx context.Context, in *QueryIsGranteeRequest, opts ...grpc.CallOption) (*QueryIsGranteeResponse, error) { + out := new(QueryIsGranteeResponse) + err := c.cc.Invoke(ctx, "/bandtss.v1beta1.Query/IsGrantee", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *queryClient) Members(ctx context.Context, in *QueryMembersRequest, opts ...grpc.CallOption) (*QueryMembersResponse, error) { out := new(QueryMembersResponse) err := c.cc.Invoke(ctx, "/bandtss.v1beta1.Query/Members", in, out, opts...) @@ -812,6 +932,8 @@ func (c *queryClient) Replacement(ctx context.Context, in *QueryReplacementReque type QueryServer interface { // Params queries parameters of Bandtss module Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) + // IsGrantee queries grant of account on this granter. + IsGrantee(context.Context, *QueryIsGranteeRequest) (*QueryIsGranteeResponse, error) // Members queries all members. Members(context.Context, *QueryMembersRequest) (*QueryMembersResponse, error) // Member queries the member information of the address. @@ -831,6 +953,9 @@ type UnimplementedQueryServer struct { func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") } +func (*UnimplementedQueryServer) IsGrantee(ctx context.Context, req *QueryIsGranteeRequest) (*QueryIsGranteeResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method IsGrantee not implemented") +} func (*UnimplementedQueryServer) Members(ctx context.Context, req *QueryMembersRequest) (*QueryMembersResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Members not implemented") } @@ -869,6 +994,24 @@ func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interf return interceptor(ctx, in, info, handler) } +func _Query_IsGrantee_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryIsGranteeRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).IsGrantee(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/bandtss.v1beta1.Query/IsGrantee", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).IsGrantee(ctx, req.(*QueryIsGranteeRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _Query_Members_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(QueryMembersRequest) if err := dec(in); err != nil { @@ -967,6 +1110,10 @@ var _Query_serviceDesc = grpc.ServiceDesc{ MethodName: "Params", Handler: _Query_Params_Handler, }, + { + MethodName: "IsGrantee", + Handler: _Query_IsGrantee_Handler, + }, { MethodName: "Members", Handler: _Query_Members_Handler, @@ -1048,6 +1195,76 @@ func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *QueryIsGranteeRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryIsGranteeRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryIsGranteeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Grantee) > 0 { + i -= len(m.Grantee) + copy(dAtA[i:], m.Grantee) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Grantee))) + i-- + dAtA[i] = 0x12 + } + if len(m.Granter) > 0 { + i -= len(m.Granter) + copy(dAtA[i:], m.Granter) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Granter))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryIsGranteeResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryIsGranteeResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryIsGranteeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.IsGrantee { + i-- + if m.IsGrantee { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + func (m *QueryMembersRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -1461,6 +1678,35 @@ func (m *QueryParamsResponse) Size() (n int) { return n } +func (m *QueryIsGranteeRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Granter) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.Grantee) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryIsGranteeResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.IsGrantee { + n += 2 + } + return n +} + func (m *QueryMembersRequest) Size() (n int) { if m == nil { return 0 @@ -1752,6 +1998,190 @@ func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { } return nil } +func (m *QueryIsGranteeRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryIsGranteeRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryIsGranteeRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Granter", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Granter = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Grantee", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Grantee = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryIsGranteeResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryIsGranteeResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryIsGranteeResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field IsGrantee", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.IsGrantee = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *QueryMembersRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 diff --git a/x/bandtss/types/query.pb.gw.go b/x/bandtss/types/query.pb.gw.go index fd79e74ca..18a56f3a2 100644 --- a/x/bandtss/types/query.pb.gw.go +++ b/x/bandtss/types/query.pb.gw.go @@ -51,6 +51,82 @@ func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshal } +func request_Query_IsGrantee_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryIsGranteeRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["granter"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "granter") + } + + protoReq.Granter, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "granter", err) + } + + val, ok = pathParams["grantee"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "grantee") + } + + protoReq.Grantee, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "grantee", err) + } + + msg, err := client.IsGrantee(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_IsGrantee_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryIsGranteeRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["granter"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "granter") + } + + protoReq.Granter, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "granter", err) + } + + val, ok = pathParams["grantee"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "grantee") + } + + protoReq.Grantee, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "grantee", err) + } + + msg, err := server.IsGrantee(ctx, &protoReq) + return msg, metadata, err + +} + var ( filter_Query_Members_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} ) @@ -260,6 +336,29 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv }) + mux.Handle("GET", pattern_Query_IsGrantee_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_IsGrantee_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_IsGrantee_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + mux.Handle("GET", pattern_Query_Members_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -436,6 +535,26 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie }) + mux.Handle("GET", pattern_Query_IsGrantee_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_IsGrantee_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_IsGrantee_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + mux.Handle("GET", pattern_Query_Members_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -542,6 +661,8 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie var ( pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"bandtss", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_IsGrantee_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4}, []string{"bandtss", "v1beta1", "is_grantee", "granter", "grantee"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_Members_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"bandtss", "v1beta1", "members"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_Member_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"bandtss", "v1beta1", "members", "address"}, "", runtime.AssumeColonVerbOpt(false))) @@ -556,6 +677,8 @@ var ( var ( forward_Query_Params_0 = runtime.ForwardResponseMessage + forward_Query_IsGrantee_0 = runtime.ForwardResponseMessage + forward_Query_Members_0 = runtime.ForwardResponseMessage forward_Query_Member_0 = runtime.ForwardResponseMessage From c68550eafc72008947271061437a50b7b12c9a33 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 2 May 2024 12:53:54 +0700 Subject: [PATCH 062/132] fix group_test --- x/bandtss/keeper/group_test.go | 199 ++++++++++++++------------------- 1 file changed, 87 insertions(+), 112 deletions(-) diff --git a/x/bandtss/keeper/group_test.go b/x/bandtss/keeper/group_test.go index 364f3910c..d758bc5cc 100644 --- a/x/bandtss/keeper/group_test.go +++ b/x/bandtss/keeper/group_test.go @@ -57,9 +57,6 @@ func TestSuccessCreateGroupReplacement(t *testing.T) { } func TestFailCreateGroupReplacement(t *testing.T) { - s := testutil.NewTestSuite(t) - ctx, k := s.Ctx, s.Keeper - currentGroupID := tss.GroupID(1) newGroupID := tss.GroupID(2) currentGroup := tsstypes.Group{ @@ -67,142 +64,127 @@ func TestFailCreateGroupReplacement(t *testing.T) { PubKey: []byte("test-pubkey-group1"), } - k.SetCurrentGroupID(ctx, currentGroupID) - s.MockTSSKeeper.EXPECT().GetGroup(ctx, currentGroupID).Return(currentGroup, nil).AnyTimes() - type input struct { - groupID tss.GroupID - execTime time.Time + groupID tss.GroupID + waitDuration time.Duration } testCases := []struct { - name string - preProcess func() - input input - expectErr error - postProcess func() + name string + preProcess func(s *testutil.TestSuite) + input input + expectErr error }{ { name: "replacement in progress - waiting signing", - preProcess: func() { - k.SetReplacement(ctx, types.Replacement{ + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetReplacement(s.Ctx, types.Replacement{ Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, }) }, input: input{ - groupID: newGroupID, - execTime: ctx.BlockTime().Add(10 * time.Minute), + groupID: newGroupID, + waitDuration: 10 * time.Minute, }, expectErr: types.ErrReplacementInProgress, - postProcess: func() { - k.SetReplacement(ctx, types.Replacement{}) - }, }, { name: "replacement in progress - waiting replace", - preProcess: func() { - k.SetReplacement(ctx, types.Replacement{ + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetReplacement(s.Ctx, types.Replacement{ Status: types.REPLACEMENT_STATUS_WAITING_REPLACE, }) }, input: input{ - groupID: newGroupID, - execTime: ctx.BlockTime().Add(10 * time.Minute), + groupID: newGroupID, + waitDuration: 10 * time.Minute, }, expectErr: types.ErrReplacementInProgress, - postProcess: func() { - k.SetReplacement(ctx, types.Replacement{}) - }, }, { - name: "replacement exec time is in the past", - preProcess: func() {}, + name: "replacement exec time is in the past", input: input{ - groupID: newGroupID, - execTime: time.Now().UTC().Add(time.Duration(-10) * time.Hour), + groupID: newGroupID, + waitDuration: time.Duration(-10) * time.Hour, }, - expectErr: types.ErrInvalidExecTime, - postProcess: func() {}, + expectErr: types.ErrInvalidExecTime, }, { name: "no current group", - preProcess: func() { - k.SetCurrentGroupID(ctx, 0) + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetCurrentGroupID(s.Ctx, 0) }, input: input{ - groupID: newGroupID, - execTime: time.Now().UTC().Add(10 * time.Minute), + groupID: newGroupID, + waitDuration: 10 * time.Minute, }, expectErr: types.ErrNoActiveGroup, - postProcess: func() { - k.SetCurrentGroupID(ctx, currentGroupID) - }, }, { name: "replacing group is inactive", - preProcess: func() { - s.MockTSSKeeper.EXPECT().GetGroup(ctx, newGroupID).Return(tsstypes.Group{ + preProcess: func(s *testutil.TestSuite) { + s.MockTSSKeeper.EXPECT().GetGroup(s.Ctx, newGroupID).Return(tsstypes.Group{ ID: newGroupID, PubKey: []byte("test-pubkey-group2"), Status: tsstypes.GROUP_STATUS_FALLEN, }, nil) }, input: input{ - groupID: newGroupID, - execTime: time.Now().UTC().Add(10 * time.Minute), + groupID: newGroupID, + waitDuration: 10 * time.Minute, }, - expectErr: tsstypes.ErrGroupIsNotActive, - postProcess: func() {}, + expectErr: tsstypes.ErrGroupIsNotActive, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - tc.preProcess() - _, err := k.CreateGroupReplacement(ctx, tc.input.groupID, tc.input.execTime) + s := testutil.NewTestSuite(t) + ctx, k := s.Ctx, s.Keeper + + k.SetCurrentGroupID(ctx, currentGroupID) + s.MockTSSKeeper.EXPECT().GetGroup(ctx, currentGroupID).Return(currentGroup, nil).AnyTimes() + + if tc.preProcess != nil { + tc.preProcess(&s) + } + + execTime := s.Ctx.BlockTime().Add(tc.input.waitDuration) + _, err := k.CreateGroupReplacement(ctx, tc.input.groupID, execTime) require.ErrorIs(t, err, tc.expectErr) - tc.postProcess() }) } } func TestHandleReplaceGroup(t *testing.T) { - s := testutil.NewTestSuite(t) - ctx, k := s.Ctx, s.Keeper - currentGroupID := tss.GroupID(1) - k.SetCurrentGroupID(ctx, currentGroupID) - type expectOut struct { replacementStatus types.ReplacementStatus currentGroupID tss.GroupID } testCases := []struct { - name string - preProcess func() - expectOut expectOut - postProcess func() - postCheck func(t *testing.T) + name string + preProcess func(s *testutil.TestSuite) + expectOut expectOut + postCheck func(t *testing.T, s *testutil.TestSuite) }{ { - name: "no replacement setup", - preProcess: func() {}, + name: "no replacement setup", expectOut: expectOut{ replacementStatus: types.REPLACEMENT_STATUS_UNSPECIFIED, currentGroupID: currentGroupID, }, - postProcess: func() {}, }, { name: "have replacement but not signed", - preProcess: func() { - k.SetReplacement(ctx, types.Replacement{ + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - ExecTime: ctx.BlockTime().Add(10 * time.Minute), + ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), }) - s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ + s.MockTSSKeeper.EXPECT().GetSigning(s.Ctx, tss.SigningID(1)).Return(tsstypes.Signing{ ID: tss.SigningID(1), Status: tsstypes.SIGNING_STATUS_WAITING, }, nil) @@ -211,17 +193,16 @@ func TestHandleReplaceGroup(t *testing.T) { replacementStatus: types.REPLACEMENT_STATUS_WAITING_SIGNING, currentGroupID: currentGroupID, }, - postProcess: func() {}, }, { name: "have replacement and signed but not meet exec time", - preProcess: func() { - k.SetReplacement(ctx, types.Replacement{ + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - ExecTime: ctx.BlockTime().Add(10 * time.Minute), + ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), }) - s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ + s.MockTSSKeeper.EXPECT().GetSigning(s.Ctx, tss.SigningID(1)).Return(tsstypes.Signing{ ID: tss.SigningID(1), Status: tsstypes.SIGNING_STATUS_SUCCESS, }, nil) @@ -230,17 +211,16 @@ func TestHandleReplaceGroup(t *testing.T) { replacementStatus: types.REPLACEMENT_STATUS_WAITING_REPLACE, currentGroupID: currentGroupID, }, - postProcess: func() {}, }, { name: "have replacement and signing failed", - preProcess: func() { - k.SetReplacement(ctx, types.Replacement{ + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - ExecTime: ctx.BlockTime().Add(10 * time.Minute), + ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), }) - s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ + s.MockTSSKeeper.EXPECT().GetSigning(s.Ctx, tss.SigningID(1)).Return(tsstypes.Signing{ ID: tss.SigningID(1), Status: tsstypes.SIGNING_STATUS_FALLEN, }, nil) @@ -249,17 +229,16 @@ func TestHandleReplaceGroup(t *testing.T) { replacementStatus: types.REPLACEMENT_STATUS_FALLEN, currentGroupID: currentGroupID, }, - postProcess: func() {}, }, { name: "have replacement and signing expired", - preProcess: func() { - k.SetReplacement(ctx, types.Replacement{ + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - ExecTime: ctx.BlockTime().Add(10 * time.Minute), + ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), }) - s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ + s.MockTSSKeeper.EXPECT().GetSigning(s.Ctx, tss.SigningID(1)).Return(tsstypes.Signing{ ID: tss.SigningID(1), Status: tsstypes.SIGNING_STATUS_EXPIRED, }, nil) @@ -268,19 +247,18 @@ func TestHandleReplaceGroup(t *testing.T) { replacementStatus: types.REPLACEMENT_STATUS_FALLEN, currentGroupID: currentGroupID, }, - postProcess: func() {}, }, { name: "have replacement and signing is waiting but exec time is passed", - preProcess: func() { - k.SetReplacement(ctx, types.Replacement{ + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - ExecTime: ctx.BlockTime().Add(10 * time.Minute), + ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), }) - ctx = ctx.WithBlockTime(ctx.BlockTime().Add(11 * time.Minute)) - s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ + s.Ctx = s.Ctx.WithBlockTime(s.Ctx.BlockTime().Add(11 * time.Minute)) + s.MockTSSKeeper.EXPECT().GetSigning(s.Ctx, tss.SigningID(1)).Return(tsstypes.Signing{ ID: tss.SigningID(1), Status: tsstypes.SIGNING_STATUS_WAITING, }, nil) @@ -289,28 +267,27 @@ func TestHandleReplaceGroup(t *testing.T) { replacementStatus: types.REPLACEMENT_STATUS_FALLEN, currentGroupID: currentGroupID, }, - postProcess: func() {}, }, { name: "have replacement and signing is ready and passed exec time", - preProcess: func() { - k.SetReplacement(ctx, types.Replacement{ + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, - ExecTime: ctx.BlockTime().Add(10 * time.Minute), + ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), CurrentGroupID: currentGroupID, NewGroupID: tss.GroupID(2), }) - ctx = ctx.WithBlockTime(ctx.BlockTime().Add(11 * time.Minute)) + s.Ctx = s.Ctx.WithBlockTime(s.Ctx.BlockTime().Add(11 * time.Minute)) - s.MockTSSKeeper.EXPECT().GetSigning(ctx, tss.SigningID(1)).Return(tsstypes.Signing{ + s.MockTSSKeeper.EXPECT().GetSigning(s.Ctx, tss.SigningID(1)).Return(tsstypes.Signing{ ID: tss.SigningID(1), Status: tsstypes.SIGNING_STATUS_SUCCESS, }, nil) - s.MockTSSKeeper.EXPECT().MustGetMembers(ctx, tss.GroupID(1)).Return([]tsstypes.Member{ + s.MockTSSKeeper.EXPECT().MustGetMembers(s.Ctx, tss.GroupID(1)).Return([]tsstypes.Member{ {ID: 1, Address: "band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs"}, }) - s.MockTSSKeeper.EXPECT().MustGetMembers(ctx, tss.GroupID(2)).Return([]tsstypes.Member{ + s.MockTSSKeeper.EXPECT().MustGetMembers(s.Ctx, tss.GroupID(2)).Return([]tsstypes.Member{ {ID: 1, Address: "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun"}, }) }, @@ -318,48 +295,46 @@ func TestHandleReplaceGroup(t *testing.T) { replacementStatus: types.REPLACEMENT_STATUS_SUCCESS, currentGroupID: tss.GroupID(2), }, - postCheck: func(t *testing.T) { - members := k.GetMembers(ctx) + postCheck: func(t *testing.T, s *testutil.TestSuite) { + members := s.Keeper.GetMembers(s.Ctx) require.Len(t, members, 1) require.Equal(t, "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun", members[0].Address) }, - postProcess: func() { - k.SetCurrentGroupID(ctx, tss.GroupID(1)) - }, }, { name: "have replacement and only waiting to replace but not meet exec time", - preProcess: func() { - k.SetReplacement(ctx, types.Replacement{ + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), Status: types.REPLACEMENT_STATUS_WAITING_REPLACE, - ExecTime: ctx.BlockTime().Add(10 * time.Minute), + ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), }) }, expectOut: expectOut{ replacementStatus: types.REPLACEMENT_STATUS_WAITING_REPLACE, currentGroupID: currentGroupID, }, - postProcess: func() {}, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - require.Equal(t, currentGroupID, k.GetCurrentGroupID(ctx)) - tc.preProcess() + s := testutil.NewTestSuite(t) + s.Keeper.SetCurrentGroupID(s.Ctx, currentGroupID) - err := k.HandleReplaceGroup(ctx, ctx.BlockTime()) + if tc.preProcess != nil { + tc.preProcess(&s) + } + + err := s.Keeper.HandleReplaceGroup(s.Ctx, s.Ctx.BlockTime()) require.NoError(t, err) - require.Equal(t, tc.expectOut.replacementStatus, k.GetReplacement(ctx).Status) - require.Equal(t, tc.expectOut.currentGroupID, k.GetCurrentGroupID(ctx)) + require.Equal(t, tc.expectOut.replacementStatus, s.Keeper.GetReplacement(s.Ctx).Status) + require.Equal(t, tc.expectOut.currentGroupID, s.Keeper.GetCurrentGroupID(s.Ctx)) if tc.postCheck != nil { - tc.postCheck(t) + tc.postCheck(t, &s) } - - tc.postProcess() }) } } From c8dde6568d9b661b8775dc2f9a11cfbcca749bdd Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 2 May 2024 13:53:52 +0700 Subject: [PATCH 063/132] fix grpc query members --- x/bandtss/keeper/group_test.go | 10 +-- x/bandtss/keeper/grpc_query_test.go | 108 +++++++++++++++------------- x/bandtss/testutil/mock_keeper.go | 12 +++- 3 files changed, 73 insertions(+), 57 deletions(-) diff --git a/x/bandtss/keeper/group_test.go b/x/bandtss/keeper/group_test.go index d758bc5cc..f8e090ede 100644 --- a/x/bandtss/keeper/group_test.go +++ b/x/bandtss/keeper/group_test.go @@ -167,7 +167,7 @@ func TestHandleReplaceGroup(t *testing.T) { name string preProcess func(s *testutil.TestSuite) expectOut expectOut - postCheck func(t *testing.T, s *testutil.TestSuite) + postCheck func(s *testutil.TestSuite) }{ { name: "no replacement setup", @@ -295,10 +295,10 @@ func TestHandleReplaceGroup(t *testing.T) { replacementStatus: types.REPLACEMENT_STATUS_SUCCESS, currentGroupID: tss.GroupID(2), }, - postCheck: func(t *testing.T, s *testutil.TestSuite) { + postCheck: func(s *testutil.TestSuite) { members := s.Keeper.GetMembers(s.Ctx) - require.Len(t, members, 1) - require.Equal(t, "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun", members[0].Address) + require.Len(s.T(), members, 1) + require.Equal(s.T(), "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun", members[0].Address) }, }, { @@ -333,7 +333,7 @@ func TestHandleReplaceGroup(t *testing.T) { require.Equal(t, tc.expectOut.currentGroupID, s.Keeper.GetCurrentGroupID(s.Ctx)) if tc.postCheck != nil { - tc.postCheck(t, &s) + tc.postCheck(&s) } }) } diff --git a/x/bandtss/keeper/grpc_query_test.go b/x/bandtss/keeper/grpc_query_test.go index a6d9a1839..7c2d6bb9e 100644 --- a/x/bandtss/keeper/grpc_query_test.go +++ b/x/bandtss/keeper/grpc_query_test.go @@ -2,88 +2,92 @@ package keeper_test import ( "fmt" + "testing" + "time" - sdk "github.com/cosmos/cosmos-sdk/types" querytypes "github.com/cosmos/cosmos-sdk/types/query" + "github.com/stretchr/testify/require" + "github.com/bandprotocol/chain/v2/x/bandtss/testutil" "github.com/bandprotocol/chain/v2/x/bandtss/types" - tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) -func (s *KeeperTestSuite) TestGRPCQueryMembers() { - ctx, q := s.ctx, s.queryClient - - s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) - - result, err := s.queryClient.Members(ctx, &types.QueryMembersRequest{IsActive: true}) - s.Require().NoError(err) - s.Require().Len(result.Members, 2) - members := result.Members - +func TestGRPCQueryMembers(t *testing.T) { type expectOut struct { members []*types.Member } + since := time.Now().UTC() + lastActive := time.Now().UTC() + + members := []*types.Member{ + { + Address: "band1t5x8hrmht463eq4m0xhfgz95h62dyvkq049eek", + IsActive: true, + Since: since, + LastActive: lastActive, + }, + { + Address: "band1a22hgwm4tz8gj82y6zad3de2dcg5dpymtj20m5", + IsActive: true, + Since: since, + LastActive: lastActive, + }, + } + testCases := []struct { - name string - preProcess func() - input *types.QueryMembersRequest - expectOut expectOut - postProcess func() + name string + preProcess func(s *testutil.TestSuite) + input *types.QueryMembersRequest + expectOut expectOut }{ { - name: "get 2 active members", - preProcess: func() {}, + name: "get 2 active members", input: &types.QueryMembersRequest{ IsActive: true, }, - expectOut: expectOut{members: members}, - postProcess: func() {}, + expectOut: expectOut{members: members}, }, { - name: "get 1 active members; limit 1 offset 0", - preProcess: func() {}, + name: "get 1 active members; limit 1 offset 0", input: &types.QueryMembersRequest{ IsActive: true, Pagination: &querytypes.PageRequest{Limit: 1, Offset: 0}, }, - expectOut: expectOut{members: members[:1]}, - postProcess: func() {}, + expectOut: expectOut{members: members[:1]}, }, { - name: "get 1 active members limit 1 offset 1", - preProcess: func() {}, + name: "get 1 active members limit 1 offset 1", input: &types.QueryMembersRequest{ IsActive: true, Pagination: &querytypes.PageRequest{Limit: 1, Offset: 1}, }, - expectOut: expectOut{members: members[1:]}, - postProcess: func() {}, + expectOut: expectOut{members: members[1:]}, }, { - name: "get 0 active members; out of pages limit 1 offset 5", - preProcess: func() {}, + name: "get 0 active members; out of pages limit 1 offset 5", input: &types.QueryMembersRequest{ IsActive: true, Pagination: &querytypes.PageRequest{Limit: 1, Offset: 5}, }, - expectOut: expectOut{members: nil}, - postProcess: func() {}, + expectOut: expectOut{members: []*types.Member{}}, }, { - name: "get no active members", - preProcess: func() {}, + name: "get no inactive members", input: &types.QueryMembersRequest{ IsActive: false, }, - expectOut: expectOut{members: nil}, - postProcess: func() {}, + expectOut: expectOut{members: []*types.Member{}}, }, { name: "get inactive members", - preProcess: func() { - err := s.app.BandtssKeeper.DeactivateMember(ctx, sdk.MustAccAddressFromBech32(members[0].Address)) - s.Require().NoError(err) + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetMember(s.Ctx, types.Member{ + Address: members[0].Address, + IsActive: false, + Since: members[0].Since, + LastActive: members[0].LastActive, + }) }, input: &types.QueryMembersRequest{ IsActive: false, @@ -91,23 +95,25 @@ func (s *KeeperTestSuite) TestGRPCQueryMembers() { expectOut: expectOut{members: []*types.Member{ {Address: members[0].Address, IsActive: false, Since: members[0].Since, LastActive: members[0].LastActive}, }}, - postProcess: func() { - ctx = ctx.WithBlockTime(ctx.BlockTime().Add(types.DefaultInactivePenaltyDuration)) - err := s.app.BandtssKeeper.ActivateMember(ctx, sdk.MustAccAddressFromBech32(members[0].Address)) - s.Require().NoError(err) - }, }, } for _, tc := range testCases { - s.Run(fmt.Sprintf("Case %s", tc.name), func() { - tc.preProcess() + t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { + s := testutil.NewTestSuite(t) + q := s.QueryServer + + for _, member := range members { + s.Keeper.SetMember(s.Ctx, *member) + } - res, err := q.Members(ctx, tc.input) - s.Require().NoError(err) - s.Require().Equal(tc.expectOut.members, res.Members) + if tc.preProcess != nil { + tc.preProcess(&s) + } - tc.postProcess() + res, err := q.Members(s.Ctx, tc.input) + require.NoError(t, err) + require.Equal(t, tc.expectOut.members, res.Members) }) } } diff --git a/x/bandtss/testutil/mock_keeper.go b/x/bandtss/testutil/mock_keeper.go index 68340a761..a2585a3ab 100644 --- a/x/bandtss/testutil/mock_keeper.go +++ b/x/bandtss/testutil/mock_keeper.go @@ -21,7 +21,9 @@ import ( // NOTE: cannot put suite.Suite inside this struct, or else the test get timeout. type TestSuite struct { - Keeper *keeper.Keeper + t *testing.T + Keeper *keeper.Keeper + QueryServer types.QueryServer MockAccountKeeper *MockAccountKeeper MockBankKeeper *MockBankKeeper @@ -63,6 +65,8 @@ func NewTestSuite(t *testing.T) TestSuite { authtypes.FeeCollectorName, ) + queryServer := keeper.NewQueryServer(bandtssKeeper) + return TestSuite{ Keeper: bandtssKeeper, MockAccountKeeper: accountKeeper, @@ -72,5 +76,11 @@ func NewTestSuite(t *testing.T) TestSuite { MockTSSKeeper: tssKeeper, Ctx: ctx, Authority: authority, + QueryServer: queryServer, + t: t, } } + +func (s *TestSuite) T() *testing.T { + return s.t +} From 5b42159bf7f427b523dfd82a9b1ada215bf66dde Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 2 May 2024 16:35:25 +0700 Subject: [PATCH 064/132] test hook signing --- x/bandtss/keeper/hooks_test.go | 618 +++++++++++++++++++++++++++--- x/bandtss/testutil/mock_keeper.go | 2 + 2 files changed, 559 insertions(+), 61 deletions(-) diff --git a/x/bandtss/keeper/hooks_test.go b/x/bandtss/keeper/hooks_test.go index 1e282178b..88b0a1b6d 100644 --- a/x/bandtss/keeper/hooks_test.go +++ b/x/bandtss/keeper/hooks_test.go @@ -1,26 +1,58 @@ package keeper_test import ( + "testing" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/bandprotocol/chain/v2/x/bandtss/testutil" "github.com/bandprotocol/chain/v2/x/bandtss/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) -func (s *KeeperTestSuite) TestAfterSigningFailed() { - ctx, k := s.ctx, s.app.BandtssKeeper - hook := k.Hooks() - +func TestHookAfterSigningFailed(t *testing.T) { + requestor := sdk.MustAccAddressFromBech32("band1t5x8hrmht463eq4m0xhfgz95h62dyvkq049eek") testCases := []struct { - name string - signing tsstypes.Signing - bandtssSignign types.Signing - expCoins sdk.Coins + name string + input tsstypes.Signing + preProcess func(s *testutil.TestSuite) + postCheck func(s *testutil.TestSuite) }{ { - "10uband with 2 members", - tsstypes.Signing{ + name: "signing currentGroup with fee 10ubands 2 members", + input: tsstypes.Signing{ + ID: 1, + GroupID: 1, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + }, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 0, + }) + s.MockBankKeeper.EXPECT().SendCoinsFromModuleToAccount( + s.Ctx, + types.ModuleName, + requestor, + sdk.NewCoins(sdk.NewInt64Coin("uband", 20)), + ) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + }, + }, + { + name: "signing currentGroup with no fee 2 members", + input: tsstypes.Signing{ ID: 1, GroupID: 1, AssignedMembers: []tsstypes.AssignedMember{ @@ -28,87 +60,551 @@ func (s *KeeperTestSuite) TestAfterSigningFailed() { {MemberID: 2}, }, }, - types.Signing{ - ID: 1, - Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), - CurrentGroupSigningID: 1, - Requester: testapp.FeePayer.Address.String(), + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 0, + }) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) }, - sdk.NewCoins(sdk.NewInt64Coin("uband", 20)), }, { - "10uband,15token with 2 members", - tsstypes.Signing{ + name: "signing currentGroup with fee 10ubands 3 members", + input: tsstypes.Signing{ + ID: 1, + GroupID: 1, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + {MemberID: 3}, + }, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetSigningIDMapping(s.Ctx, 2, 1) + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 2, + }) + s.MockBankKeeper.EXPECT().SendCoinsFromModuleToAccount( + s.Ctx, + types.ModuleName, + requestor, + sdk.NewCoins(sdk.NewInt64Coin("uband", 30)), + ) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + require.Equal(s.T(), types.SigningID(1), s.Keeper.GetSigningIDMapping(s.Ctx, 2)) + }, + }, + { + name: "signing replacingGroup with fee 10ubands 3 members", + input: tsstypes.Signing{ ID: 2, + GroupID: 2, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + {MemberID: 3}, + }, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetSigningIDMapping(s.Ctx, 2, 1) + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 2, + }) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 2)) + require.Equal(s.T(), types.SigningID(1), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + }, + }, + { + name: "no signingID mapping", + input: tsstypes.Signing{ + ID: 2, + GroupID: 1, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + {MemberID: 3}, + }, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + s := testutil.NewTestSuite(t) + + if tc.preProcess != nil { + tc.preProcess(&s) + } + + err := s.Hook.AfterSigningFailed(s.Ctx, tc.input) + require.NoError(t, err) + + if tc.postCheck != nil { + tc.postCheck(&s) + } + }) + } +} + +func TestHookBeforeSigningExpired(t *testing.T) { + requestor := sdk.MustAccAddressFromBech32("band1t5x8hrmht463eq4m0xhfgz95h62dyvkq049eek") + penalizedMembers := []sdk.AccAddress{ + sdk.MustAccAddressFromBech32("band1t5x8hrmht463eq4m0xhfgz95h62dyvkq049eek"), + } + + testCases := []struct { + name string + input tsstypes.Signing + preProcess func(s *testutil.TestSuite) + postCheck func(s *testutil.TestSuite) + }{ + { + name: "signing currentGroup with fee 10ubands 2 members", + input: tsstypes.Signing{ + ID: 1, GroupID: 1, AssignedMembers: []tsstypes.AssignedMember{ {MemberID: 1}, {MemberID: 2}, }, }, - types.Signing{ - ID: 2, - Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10), sdk.NewInt64Coin("token", 15)), - CurrentGroupSigningID: 2, - Requester: testapp.FeePayer.Address.String(), + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetCurrentGroupID(s.Ctx, 1) + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetMember(s.Ctx, types.Member{ + Address: penalizedMembers[0].String(), + IsActive: true, + Since: s.Ctx.BlockTime(), + LastActive: s.Ctx.BlockTime(), + }) + + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 0, + }) + + s.MockTSSKeeper.EXPECT().GetPenalizedMembersExpiredSigning( + s.Ctx, + tsstypes.Signing{ + ID: 1, + GroupID: 1, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + }, + }, + ).Return(penalizedMembers, nil) + + s.MockTSSKeeper.EXPECT().DeactivateMember(s.Ctx, tss.GroupID(1), penalizedMembers[0]).Return(nil) + s.MockBankKeeper.EXPECT().SendCoinsFromModuleToAccount( + s.Ctx, + types.ModuleName, + requestor, + sdk.NewCoins(sdk.NewInt64Coin("uband", 20)), + ) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + + member, err := s.Keeper.GetMember(s.Ctx, penalizedMembers[0]) + require.NoError(s.T(), err) + require.False(s.T(), member.IsActive) }, - sdk.NewCoins(sdk.NewInt64Coin("uband", 20), sdk.NewInt64Coin("token", 30)), }, { - "0uband with 2 members", - tsstypes.Signing{ - ID: 3, + name: "signing currentGroup with no fee 2 members", + input: tsstypes.Signing{ + ID: 1, GroupID: 1, AssignedMembers: []tsstypes.AssignedMember{ {MemberID: 1}, {MemberID: 2}, }, }, - types.Signing{ - ID: 3, - Fee: sdk.NewCoins(), - CurrentGroupSigningID: 3, - Requester: testapp.FeePayer.Address.String(), + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetCurrentGroupID(s.Ctx, 1) + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetMember(s.Ctx, types.Member{ + Address: penalizedMembers[0].String(), + IsActive: true, + Since: s.Ctx.BlockTime(), + LastActive: s.Ctx.BlockTime(), + }) + + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 0, + }) + + s.MockTSSKeeper.EXPECT().GetPenalizedMembersExpiredSigning( + s.Ctx, + tsstypes.Signing{ + ID: 1, + GroupID: 1, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + }, + }, + ).Return(penalizedMembers, nil) + + s.MockTSSKeeper.EXPECT().DeactivateMember(s.Ctx, tss.GroupID(1), penalizedMembers[0]).Return(nil) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + + member, err := s.Keeper.GetMember(s.Ctx, penalizedMembers[0]) + require.NoError(s.T(), err) + require.False(s.T(), member.IsActive) }, - sdk.NewCoins(), }, { - "10uband with 0 member", - tsstypes.Signing{ - ID: 4, - GroupID: 1, - AssignedMembers: []tsstypes.AssignedMember{}, - }, - types.Signing{ - ID: 4, - Fee: sdk.NewCoins(), - CurrentGroupSigningID: 4, - Requester: testapp.FeePayer.Address.String(), - }, - sdk.NewCoins(), + name: "signing currentGroup with fee 10ubands 3 members", + input: tsstypes.Signing{ + ID: 1, + GroupID: 1, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + {MemberID: 3}, + }, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetCurrentGroupID(s.Ctx, 1) + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetMember(s.Ctx, types.Member{ + Address: penalizedMembers[0].String(), + IsActive: true, + Since: s.Ctx.BlockTime(), + LastActive: s.Ctx.BlockTime(), + }) + + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 0, + }) + + s.MockTSSKeeper.EXPECT().GetPenalizedMembersExpiredSigning( + s.Ctx, + tsstypes.Signing{ + ID: 1, + GroupID: 1, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + {MemberID: 3}, + }, + }, + ).Return(penalizedMembers, nil) + + s.MockTSSKeeper.EXPECT().DeactivateMember(s.Ctx, tss.GroupID(1), penalizedMembers[0]).Return(nil) + s.MockBankKeeper.EXPECT().SendCoinsFromModuleToAccount( + s.Ctx, + types.ModuleName, + requestor, + sdk.NewCoins(sdk.NewInt64Coin("uband", 30)), + ) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + + member, err := s.Keeper.GetMember(s.Ctx, penalizedMembers[0]) + require.NoError(s.T(), err) + require.False(s.T(), member.IsActive) + }, + }, + { + name: "signing replacingGroup with fee 10ubands 2 members", + input: tsstypes.Signing{ + ID: 2, + GroupID: 2, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + }, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetCurrentGroupID(s.Ctx, 1) + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetSigningIDMapping(s.Ctx, 2, 1) + s.Keeper.SetMember(s.Ctx, types.Member{ + Address: penalizedMembers[0].String(), + IsActive: true, + Since: s.Ctx.BlockTime(), + LastActive: s.Ctx.BlockTime(), + }) + + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 2, + }) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 2)) + require.Equal(s.T(), types.SigningID(1), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + + member, err := s.Keeper.GetMember(s.Ctx, penalizedMembers[0]) + require.NoError(s.T(), err) + require.True(s.T(), member.IsActive) + }, + }, + { + name: "signing old currentGroup with fee 10ubands 2 members", + input: tsstypes.Signing{ + ID: 1, + GroupID: 1, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + }, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetCurrentGroupID(s.Ctx, 2) + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetSigningIDMapping(s.Ctx, 2, 1) + s.Keeper.SetMember(s.Ctx, types.Member{ + Address: penalizedMembers[0].String(), + IsActive: true, + Since: s.Ctx.BlockTime(), + LastActive: s.Ctx.BlockTime(), + }) + + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 2, + }) + s.MockBankKeeper.EXPECT().SendCoinsFromModuleToAccount( + s.Ctx, + types.ModuleName, + requestor, + sdk.NewCoins(sdk.NewInt64Coin("uband", 20)), + ) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + require.Equal(s.T(), types.SigningID(1), s.Keeper.GetSigningIDMapping(s.Ctx, 2)) + + member, err := s.Keeper.GetMember(s.Ctx, penalizedMembers[0]) + require.NoError(s.T(), err) + require.True(s.T(), member.IsActive) + }, + }, + { + name: "signing no ID mapping", + input: tsstypes.Signing{ + ID: 3, + GroupID: 2, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + }, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetCurrentGroupID(s.Ctx, 1) + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetMember(s.Ctx, types.Member{ + Address: penalizedMembers[0].String(), + IsActive: true, + Since: s.Ctx.BlockTime(), + LastActive: s.Ctx.BlockTime(), + }) + + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 0, + }) + }, + postCheck: func(s *testutil.TestSuite) { + require.Equal(s.T(), types.SigningID(1), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + + member, err := s.Keeper.GetMember(s.Ctx, penalizedMembers[0]) + require.NoError(s.T(), err) + require.True(s.T(), member.IsActive) + }, }, } - s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) for _, tc := range testCases { - s.Run(tc.name, func() { - k.SetSigning(ctx, tc.bandtssSignign) - k.SetSigningIDMapping(ctx, tc.signing.ID, tc.bandtssSignign.ID) + t.Run(tc.name, func(t *testing.T) { + s := testutil.NewTestSuite(t) + + if tc.preProcess != nil { + tc.preProcess(&s) + } + + err := s.Hook.BeforeSetSigningExpired(s.Ctx, tc.input) + require.NoError(t, err) + + if tc.postCheck != nil { + tc.postCheck(&s) + } + }) + } +} + +func TestHookAfterSigningComplete(t *testing.T) { + requestor := sdk.MustAccAddressFromBech32("band1t5x8hrmht463eq4m0xhfgz95h62dyvkq049eek") - balancesBefore := s.app.BankKeeper.GetAllBalances(ctx, testapp.FeePayer.Address) - balancesModuleBefore := s.app.BankKeeper.GetAllBalances(ctx, k.GetBandtssAccount(ctx).GetAddress()) + testCases := []struct { + name string + input tsstypes.Signing + preProcess func(s *testutil.TestSuite) + postCheck func(s *testutil.TestSuite) + }{ - err := hook.AfterSigningFailed(ctx, tc.signing) - s.Require().NoError(err) + { + name: "signing currentGroup with fee 10ubands 2 members", + input: tsstypes.Signing{ + ID: 1, + GroupID: 1, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1, Address: "band1t5x8hrmht463eq4m0xhfgz95h62dyvkq049eek"}, + {MemberID: 2, Address: "band1a22hgwm4tz8gj82y6zad3de2dcg5dpymtj20m5"}, + }, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 0, + }) + s.MockBankKeeper.EXPECT().SendCoinsFromModuleToAccount( + s.Ctx, + types.ModuleName, + sdk.MustAccAddressFromBech32("band1t5x8hrmht463eq4m0xhfgz95h62dyvkq049eek"), + sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + ) + s.MockBankKeeper.EXPECT().SendCoinsFromModuleToAccount( + s.Ctx, + types.ModuleName, + sdk.MustAccAddressFromBech32("band1a22hgwm4tz8gj82y6zad3de2dcg5dpymtj20m5"), + sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + ) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + }, + }, + { + name: "signing currentGroup with no fee 2 members", + input: tsstypes.Signing{ + ID: 1, + GroupID: 1, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + }, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 0, + }) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + }, + }, + { + name: "signing replacingGroup with fee 10ubands 3 members", + input: tsstypes.Signing{ + ID: 2, + GroupID: 2, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + {MemberID: 3}, + }, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetSigningIDMapping(s.Ctx, 2, 1) + s.Keeper.SetSigningIDMapping(s.Ctx, 1, 1) + s.Keeper.SetSigning(s.Ctx, types.Signing{ + ID: 1, + Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), + Requester: requestor.String(), + CurrentGroupSigningID: 1, + ReplacingGroupSigningID: 2, + }) + }, + postCheck: func(s *testutil.TestSuite) { + require.Zero(s.T(), s.Keeper.GetSigningIDMapping(s.Ctx, 2)) + require.Equal(s.T(), types.SigningID(1), s.Keeper.GetSigningIDMapping(s.Ctx, 1)) + }, + }, + { + name: "no signingID mapping", + input: tsstypes.Signing{ + ID: 2, + GroupID: 1, + AssignedMembers: []tsstypes.AssignedMember{ + {MemberID: 1}, + {MemberID: 2}, + {MemberID: 3}, + }, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + s := testutil.NewTestSuite(t) - balancesAfter := s.app.BankKeeper.GetAllBalances(ctx, testapp.FeePayer.Address) - balancesModuleAfter := s.app.BankKeeper.GetAllBalances(ctx, k.GetBandtssAccount(ctx).GetAddress()) + if tc.preProcess != nil { + tc.preProcess(&s) + } - gain := balancesAfter.Sub(balancesBefore...) - s.Require().Equal(tc.expCoins, gain) + err := s.Hook.AfterSigningCompleted(s.Ctx, tc.input) + require.NoError(t, err) - lose := balancesModuleBefore.Sub(balancesModuleAfter...) - s.Require().Equal(tc.expCoins, lose) + if tc.postCheck != nil { + tc.postCheck(&s) + } }) } } diff --git a/x/bandtss/testutil/mock_keeper.go b/x/bandtss/testutil/mock_keeper.go index a2585a3ab..5a99fadd6 100644 --- a/x/bandtss/testutil/mock_keeper.go +++ b/x/bandtss/testutil/mock_keeper.go @@ -24,6 +24,7 @@ type TestSuite struct { t *testing.T Keeper *keeper.Keeper QueryServer types.QueryServer + Hook keeper.Hooks MockAccountKeeper *MockAccountKeeper MockBankKeeper *MockBankKeeper @@ -77,6 +78,7 @@ func NewTestSuite(t *testing.T) TestSuite { Ctx: ctx, Authority: authority, QueryServer: queryServer, + Hook: bandtssKeeper.Hooks(), t: t, } } From 7b07f9afb8417a0d2832de93dde7affe99a944a1 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 2 May 2024 17:31:46 +0700 Subject: [PATCH 065/132] add hook createGroup --- x/bandtss/keeper/hooks_test.go | 87 ++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/x/bandtss/keeper/hooks_test.go b/x/bandtss/keeper/hooks_test.go index 88b0a1b6d..2a3f573ea 100644 --- a/x/bandtss/keeper/hooks_test.go +++ b/x/bandtss/keeper/hooks_test.go @@ -608,3 +608,90 @@ func TestHookAfterSigningComplete(t *testing.T) { }) } } + +func TestHookAfterCreatingGroupComplete(t *testing.T) { + members := []sdk.AccAddress{ + sdk.MustAccAddressFromBech32("band1t5x8hrmht463eq4m0xhfgz95h62dyvkq049eek"), + sdk.MustAccAddressFromBech32("band1a22hgwm4tz8gj82y6zad3de2dcg5dpymtj20m5"), + } + + testCases := []struct { + name string + input tsstypes.Group + preProcess func(s *testutil.TestSuite) + postCheck func(s *testutil.TestSuite) + }{ + { + name: "no currentGroup", + input: tsstypes.Group{ + ID: 1, + ModuleOwner: types.ModuleName, + Status: tsstypes.GROUP_STATUS_ACTIVE, + }, + preProcess: func(s *testutil.TestSuite) { + s.MockTSSKeeper.EXPECT().MustGetMembers(s.Ctx, tss.GroupID(1)).Return([]tsstypes.Member{ + {ID: 1, Address: members[0].String(), GroupID: 1}, + {ID: 2, Address: members[1].String(), GroupID: 1}, + }) + }, + postCheck: func(s *testutil.TestSuite) { + require.Equal(t, tss.GroupID(1), s.Keeper.GetCurrentGroupID(s.Ctx)) + + for _, member_addr := range members { + member, err := s.Keeper.GetMember(s.Ctx, member_addr) + + require.NoError(s.T(), err) + require.True(s.T(), member.IsActive) + require.Equal(s.T(), s.Ctx.BlockTime(), member.Since) + require.Equal(s.T(), s.Ctx.BlockTime(), member.LastActive) + } + }, + }, + { + name: "already set currentGroup", + input: tsstypes.Group{ + ID: 2, + ModuleOwner: types.ModuleName, + Status: tsstypes.GROUP_STATUS_ACTIVE, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetCurrentGroupID(s.Ctx, 1) + }, + postCheck: func(s *testutil.TestSuite) { + require.Equal(t, tss.GroupID(1), s.Keeper.GetCurrentGroupID(s.Ctx)) + }, + }, + { + name: "group from another module", + input: tsstypes.Group{ + ID: 2, + ModuleOwner: tsstypes.ModuleName, + Status: tsstypes.GROUP_STATUS_ACTIVE, + }, + preProcess: func(s *testutil.TestSuite) { + s.Keeper.SetCurrentGroupID(s.Ctx, 1) + }, + postCheck: func(s *testutil.TestSuite) { + require.Equal(t, tss.GroupID(1), s.Keeper.GetCurrentGroupID(s.Ctx)) + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + s := testutil.NewTestSuite(t) + + if tc.preProcess != nil { + tc.preProcess(&s) + } + + err := s.Hook.AfterCreatingGroupCompleted(s.Ctx, tc.input) + require.NoError(t, err) + + if tc.postCheck != nil { + tc.postCheck(&s) + } + }) + } + +} From 97055b0f163215a73303dbe1bf6eea605c29420d Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Fri, 3 May 2024 10:39:56 +0700 Subject: [PATCH 066/132] fix comments --- x/bandtss/keeper/group.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x/bandtss/keeper/group.go b/x/bandtss/keeper/group.go index 45b2614ed..59d8575db 100644 --- a/x/bandtss/keeper/group.go +++ b/x/bandtss/keeper/group.go @@ -80,7 +80,8 @@ func (k Keeper) CreateGroupReplacement( return signing.ID, nil } -// HandleReplaceGroup updates the group information after a successful signing process. +// HandleReplaceGroup updates the replacement status or update the current group information after +// passing the replacement execution time and signing is completed. It emits an event at the end. func (k Keeper) HandleReplaceGroup(ctx sdk.Context, endBlockTime time.Time) error { replacement := k.GetReplacement(ctx) From 75feb8ba521ac34fd2d5caae8f5cd164939779f3 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Fri, 3 May 2024 10:43:15 +0700 Subject: [PATCH 067/132] fix lint --- x/bandtss/keeper/hooks_test.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/x/bandtss/keeper/hooks_test.go b/x/bandtss/keeper/hooks_test.go index 2a3f573ea..615a0502d 100644 --- a/x/bandtss/keeper/hooks_test.go +++ b/x/bandtss/keeper/hooks_test.go @@ -489,7 +489,6 @@ func TestHookAfterSigningComplete(t *testing.T) { preProcess func(s *testutil.TestSuite) postCheck func(s *testutil.TestSuite) }{ - { name: "signing currentGroup with fee 10ubands 2 members", input: tsstypes.Signing{ @@ -693,5 +692,4 @@ func TestHookAfterCreatingGroupComplete(t *testing.T) { } }) } - } From 9cef4b89877b7f0ac7b4f0116d0ec28b7d8977b1 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Fri, 3 May 2024 15:28:49 +0700 Subject: [PATCH 068/132] merge tss-move-replacement-logic into this branch --- .github/workflows/golangci-lint.yml | 2 +- CHANGELOG.md | 5 +- SECURITY.md | 21 + benchmark/app_test.go | 14 +- benchmark/helper_test.go | 10 +- go.mod | 84 +- go.sum | 225 +++-- testing/{ => ibctesting}/chain.go | 28 +- testing/{ => ibctesting}/config.go | 0 testing/{ => ibctesting}/coordinator.go | 0 testing/{ => ibctesting}/endpoint.go | 0 testing/{ => ibctesting}/events.go | 0 testing/{ => ibctesting}/path.go | 0 testing/{ => ibctesting}/value.go | 0 testing/{testapp/setup.go => test_helpers.go} | 485 ++++++----- testing/{testapp => }/util.go | 2 +- x/bandtss/abci_test.go | 6 +- x/bandtss/genesis_test.go | 6 +- x/bandtss/keeper/keeper_test.go | 6 +- x/bandtss/keeper/msg_server_test.go | 20 +- x/bandtss/keeper/signing_test.go | 24 +- x/bandtss/keeper/validator_test.go | 36 +- x/globalfee/feechecker/feechecker_test.go | 258 +++++- x/oracle/abci_test.go | 44 +- x/oracle/app_test.go | 54 +- x/oracle/handler_test.go | 372 +++++---- x/oracle/ibc_test.go | 166 ++-- x/oracle/keeper/data_source_test.go | 98 ++- x/oracle/keeper/grpc_query_test.go | 138 ++-- x/oracle/keeper/keeper_test.go | 37 +- x/oracle/keeper/oracle_script_test.go | 60 +- x/oracle/keeper/owasm_test.go | 767 ++++++++++-------- x/oracle/keeper/params_test.go | 6 +- x/oracle/keeper/report_test.go | 108 ++- x/oracle/keeper/request_test.go | 112 +-- x/oracle/keeper/result_test.go | 36 +- x/oracle/keeper/signing_test.go | 8 +- .../keeper/snapshotter_integration_test.go | 7 +- x/oracle/keeper/validator_status_test.go | 123 +-- x/oracle/simulation/operations_test.go | 10 +- x/rollingseed/abci_test.go | 4 +- x/rollingseed/keeper/keeper_test.go | 6 +- x/tss/keeper/keeper_test.go | 6 +- x/tss/keeper/msg_server_test.go | 4 +- x/tss/keeper/signing_test.go | 6 +- 45 files changed, 1934 insertions(+), 1470 deletions(-) create mode 100644 SECURITY.md rename testing/{ => ibctesting}/chain.go (96%) rename testing/{ => ibctesting}/config.go (100%) rename testing/{ => ibctesting}/coordinator.go (100%) rename testing/{ => ibctesting}/endpoint.go (100%) rename testing/{ => ibctesting}/events.go (100%) rename testing/{ => ibctesting}/path.go (100%) rename testing/{ => ibctesting}/value.go (100%) rename testing/{testapp/setup.go => test_helpers.go} (81%) rename testing/{testapp => }/util.go (99%) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 832906f52..1be62a7f7 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -10,7 +10,7 @@ jobs: go-version: 1.21.7 - uses: actions/checkout@v4 - name: golangci-lint - uses: golangci/golangci-lint-action@v4 + uses: golangci/golangci-lint-action@v5 with: version: v1.55.2 args: --timeout=5m0s diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b53c71d0..23a31fb6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,10 @@ ## Unreleased -- (bump) Use cosmos-sdk package v0.47.8 / ibc-go v7.2.3 -- (bump) replace github.com/tendermint/tendermint by github.com/cometbft/cometbft v0.37.4 +- (bump) Use cosmos-sdk package v0.47.11 / ibc-go v7.4.0 +- (bump) replace github.com/tendermint/tendermint by github.com/cometbft/cometbft v0.37.5 - (bump) migrated from gogo/protobuf to cosmos/gogoproto +- (bump) Use go-owasm v0.3.1 - (chain) Remove disablefeeless flag - (chain) Remove old oracle ante - (chain) Remove legacy migrate cmd diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..afcb02caa --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Reporting a Vulnerability + +The security of our network is a top priority. If you have discovered a security vulnerability within our repository, we appreciate your cooperation in disclosing it to us in a responsible manner. + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, we kindly ask that you email us directly at `security@bandprotocol.com`. We will review your report and may follow up to request additional information. + +### What to Include + +If possible, please provide as much of the following information as you can. This will help us understand the nature and scope of the potential issue: + +- A clear and concise description of the potential vulnerability. +- Steps to reproduce the issue or a proof-of-concept (if possible). +- Any relevant tools, versions, or dependencies. +- Any possible mitigations or workarounds you have identified. + + +Thank you for helping keep our BandChain safe! diff --git a/benchmark/app_test.go b/benchmark/app_test.go index 23646fe00..19faa4459 100644 --- a/benchmark/app_test.go +++ b/benchmark/app_test.go @@ -5,7 +5,6 @@ import ( "testing" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" @@ -15,7 +14,7 @@ import ( "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" - testapp "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" bandtsskeeper "github.com/bandprotocol/chain/v2/x/bandtss/keeper" bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" "github.com/bandprotocol/chain/v2/x/oracle/keeper" @@ -25,7 +24,7 @@ import ( ) type BenchmarkApp struct { - *testapp.TestingApp + *bandtesting.TestingApp Sender *Account Validator *Account Oid uint64 @@ -59,15 +58,16 @@ func GetDEs() []tsstypes.DE { } func InitializeBenchmarkApp(tb testing.TB, maxGasPerBlock int64) *BenchmarkApp { + app, _ := bandtesting.CreateTestApp(&testing.T{}, false) ba := &BenchmarkApp{ - TestingApp: testapp.NewTestApp("", log.NewNopLogger()), + TestingApp: app, Sender: &Account{ - Account: testapp.Owner, + Account: bandtesting.Owner, Num: 0, Seq: 0, }, Validator: &Account{ - Account: testapp.Validators[0], + Account: bandtesting.Validators[0], Num: 5, Seq: 0, }, @@ -290,7 +290,7 @@ func (ba *BenchmarkApp) GetPendingSignTxs( sig, err := CreateSignature(m.ID, signing, group.PubKey, ownPrivkey) require.NoError(ba.TB, err) - tx, err := testapp.GenTx( + tx, err := bandtesting.GenTx( ba.TxConfig, GenMsgSubmitSignature(tss.SigningID(sid), m.ID, sig, ba.Sender.Address), sdk.Coins{sdk.NewInt64Coin("uband", 1)}, diff --git a/benchmark/helper_test.go b/benchmark/helper_test.go index e9a236080..d2bd9ec70 100644 --- a/benchmark/helper_test.go +++ b/benchmark/helper_test.go @@ -21,14 +21,14 @@ import ( "github.com/bandprotocol/chain/v2/pkg/obi" "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) type Account struct { - testapp.Account + bandtesting.Account Num uint64 Seq uint64 } @@ -215,7 +215,7 @@ func GenSequenceOfTxs( txs := make([]sdk.Tx, numTxs) for i := 0; i < numTxs; i++ { - txs[i], _ = testapp.GenTx( + txs[i], _ = bandtesting.GenTx( txConfig, msgs, sdk.Coins{sdk.NewInt64Coin("uband", 1)}, @@ -286,8 +286,8 @@ func InitOwasmTestEnv( Text: strings.Repeat("#", stringLength), }), []sdk.ValAddress{[]byte{}}, 1, 1, time.Now(), "", nil, nil, ExecuteGasLimit, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ) return owasmVM, compiledCode, req diff --git a/go.mod b/go.mod index c30351fa9..74604f970 100644 --- a/go.mod +++ b/go.mod @@ -8,18 +8,18 @@ require ( cosmossdk.io/api v0.3.1 cosmossdk.io/errors v1.0.1 cosmossdk.io/math v1.3.0 - github.com/bandprotocol/go-owasm v0.2.3 - github.com/cometbft/cometbft v0.37.4 + github.com/bandprotocol/go-owasm v0.3.1 + github.com/cometbft/cometbft v0.37.5 github.com/cometbft/cometbft-db v0.10.0 github.com/confio/ics23/go v0.9.0 - github.com/cosmos/cosmos-proto v1.0.0-beta.4 - github.com/cosmos/cosmos-sdk v0.47.10 + github.com/cosmos/cosmos-proto v1.0.0-beta.5 + github.com/cosmos/cosmos-sdk v0.47.11 github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/gogoproto v1.4.10 - github.com/cosmos/ibc-go/v7 v7.3.2 + github.com/cosmos/ibc-go/v7 v7.4.0 github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 github.com/ethereum/go-ethereum v1.11.6 - github.com/golang/protobuf v1.5.3 + github.com/golang/protobuf v1.5.4 github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 github.com/gorilla/mux v1.8.1 github.com/grpc-ecosystem/grpc-gateway v1.16.0 @@ -30,24 +30,24 @@ require ( github.com/peterbourgon/diskv v2.0.1+incompatible github.com/prometheus/client_golang v1.14.0 github.com/rakyll/statik v0.1.7 - github.com/spf13/cast v1.5.1 - github.com/spf13/cobra v1.7.0 - github.com/spf13/viper v1.16.0 + github.com/spf13/cast v1.6.0 + github.com/spf13/cobra v1.8.0 + github.com/spf13/viper v1.18.2 github.com/stretchr/testify v1.9.0 go.uber.org/mock v0.4.0 - golang.org/x/crypto v0.18.0 - golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb - google.golang.org/genproto/googleapis/api v0.0.0-20240123012728-ef4313101c80 - google.golang.org/grpc v1.62.1 - google.golang.org/protobuf v1.32.0 + golang.org/x/crypto v0.21.0 + golang.org/x/exp v0.0.0-20230905200255-921286631fa9 + google.golang.org/genproto/googleapis/api v0.0.0-20240227224415-6ceb2ff114de + google.golang.org/grpc v1.63.2 + google.golang.org/protobuf v1.34.0 sigs.k8s.io/yaml v1.4.0 ) require ( cloud.google.com/go v0.112.0 // indirect - cloud.google.com/go/compute v1.23.3 // indirect + cloud.google.com/go/compute v1.24.0 // indirect cloud.google.com/go/compute/metadata v0.2.3 // indirect - cloud.google.com/go/iam v1.1.5 // indirect + cloud.google.com/go/iam v1.1.6 // indirect cloud.google.com/go/storage v1.36.0 // indirect cosmossdk.io/core v0.5.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.4 // indirect @@ -82,7 +82,7 @@ require ( github.com/cosmos/rosetta-sdk-go v0.10.0 // indirect github.com/creachadair/taskgroup v0.4.2 // indirect github.com/danieljoos/wincred v1.1.2 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect github.com/dgraph-io/badger/v2 v2.2007.4 // indirect github.com/dgraph-io/ristretto v0.1.1 // indirect @@ -90,12 +90,12 @@ require ( github.com/dustin/go-humanize v1.0.1 // indirect github.com/dvsekhvalnov/jose2go v1.6.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/getsentry/sentry-go v0.23.0 // indirect github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect - github.com/go-logr/logr v1.3.0 // indirect + github.com/go-logr/logr v1.4.1 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gogo/googleapis v1.4.1 // indirect @@ -119,7 +119,7 @@ require ( github.com/gtank/merlin v0.1.1 // indirect github.com/gtank/ristretto255 v0.1.2 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect - github.com/hashicorp/go-getter v1.7.1 // indirect + github.com/hashicorp/go-getter v1.7.4 // indirect github.com/hashicorp/go-immutable-radix v1.3.1 // indirect github.com/hashicorp/go-safetemp v1.0.0 // indirect github.com/hashicorp/go-version v1.6.0 // indirect @@ -132,7 +132,7 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.16.7 // indirect + github.com/klauspost/compress v1.17.0 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lib/pq v1.10.7 // indirect @@ -148,10 +148,10 @@ require ( github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/go-testing-interface v1.14.1 // indirect github.com/mtibben/percent v0.2.1 // indirect - github.com/pelletier/go-toml/v2 v2.0.8 // indirect + github.com/pelletier/go-toml/v2 v2.1.0 // indirect github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.9.0 // indirect @@ -159,11 +159,13 @@ require ( github.com/rogpeppe/go-internal v1.11.0 // indirect github.com/rs/cors v1.8.3 // indirect github.com/rs/zerolog v1.32.0 // indirect + github.com/sagikazarmark/locafero v0.4.0 // indirect + github.com/sagikazarmark/slog-shim v0.1.0 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect - github.com/spf13/afero v1.9.5 // indirect - github.com/spf13/jwalterweatherman v1.1.0 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spf13/afero v1.11.0 // indirect github.com/spf13/pflag v1.0.5 // indirect - github.com/subosito/gotenv v1.4.2 // indirect + github.com/subosito/gotenv v1.6.0 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect github.com/tendermint/go-amino v0.16.0 // indirect github.com/tidwall/btree v1.6.0 // indirect @@ -172,22 +174,24 @@ require ( github.com/zondax/ledger-go v0.14.3 // indirect go.etcd.io/bbolt v1.3.8 // indirect go.opencensus.io v0.24.0 // indirect - go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.46.1 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1 // indirect - go.opentelemetry.io/otel v1.21.0 // indirect - go.opentelemetry.io/otel/metric v1.21.0 // indirect - go.opentelemetry.io/otel/trace v1.21.0 // indirect - golang.org/x/net v0.20.0 // indirect - golang.org/x/oauth2 v0.16.0 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.47.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.47.0 // indirect + go.opentelemetry.io/otel v1.22.0 // indirect + go.opentelemetry.io/otel/metric v1.22.0 // indirect + go.opentelemetry.io/otel/trace v1.22.0 // indirect + go.uber.org/atomic v1.10.0 // indirect + go.uber.org/multierr v1.9.0 // indirect + golang.org/x/net v0.23.0 // indirect + golang.org/x/oauth2 v0.17.0 // indirect golang.org/x/sync v0.6.0 // indirect - golang.org/x/sys v0.16.0 // indirect - golang.org/x/term v0.16.0 // indirect + golang.org/x/sys v0.18.0 // indirect + golang.org/x/term v0.18.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/time v0.5.0 // indirect - google.golang.org/api v0.155.0 // indirect + google.golang.org/api v0.162.0 // indirect google.golang.org/appengine v1.6.8 // indirect - google.golang.org/genproto v0.0.0-20240123012728-ef4313101c80 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20240123012728-ef4313101c80 // indirect + google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect @@ -206,4 +210,8 @@ replace ( github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.9.0 // replace broken goleveldb github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 + // stick with compatible version or x/exp in v0.47.x line + golang.org/x/exp => golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb + // stick with compatible version of rapid in v0.47.x line + pgregory.net/rapid => pgregory.net/rapid v0.5.5 ) diff --git a/go.sum b/go.sum index 355aab1d4..b11092f23 100644 --- a/go.sum +++ b/go.sum @@ -3,7 +3,6 @@ cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.44.3/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= @@ -16,7 +15,6 @@ cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOY cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= -cloud.google.com/go v0.75.0/go.mod h1:VGuuCn7PG0dwsd5XPVm2Mm3wlh3EL55/79EKB6hlPTY= cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= @@ -70,8 +68,8 @@ cloud.google.com/go/compute v1.6.0/go.mod h1:T29tfhtVbq1wvAPo0E3+7vhgmkOYeXjhFvz cloud.google.com/go/compute v1.6.1/go.mod h1:g85FgpzFvNULZ+S8AYq87axRKuf2Kh7deLqV/jJ3thU= cloud.google.com/go/compute v1.7.0/go.mod h1:435lt8av5oL9P3fv1OEzSbSUe+ybHXGMPQHHZWZxy9U= cloud.google.com/go/compute v1.10.0/go.mod h1:ER5CLbMxl90o2jtNbGSbtfOpQKR0t15FOtRsugnLrlU= -cloud.google.com/go/compute v1.23.3 h1:6sVlXXBmbd7jNX0Ipq0trII3e4n1/MsADLK6a+aiVlk= -cloud.google.com/go/compute v1.23.3/go.mod h1:VCgBUoMnIVIR0CscqQiPJLAG25E3ZRZMzcFZeQ+h8CI= +cloud.google.com/go/compute v1.24.0 h1:phWcR2eWzRJaL/kOiJwfFsPs4BaKq1j6vnpZrc1YlVg= +cloud.google.com/go/compute v1.24.0/go.mod h1:kw1/T+h/+tK2LJK0wiPPx1intgdAM3j/g3hFDlscY40= cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= cloud.google.com/go/containeranalysis v0.5.1/go.mod h1:1D92jd8gRR/c0fGMlymRgxWD3Qw9C1ff6/T7mLgVL8I= @@ -111,8 +109,8 @@ cloud.google.com/go/gkehub v0.10.0/go.mod h1:UIPwxI0DsrpsVoWpLB0stwKCP+WFVG9+y97 cloud.google.com/go/grafeas v0.2.0/go.mod h1:KhxgtF2hb0P191HlY5besjYm6MqTSTj3LSI+M+ByZHc= cloud.google.com/go/iam v0.3.0/go.mod h1:XzJPvDayI+9zsASAFO68Hk07u3z+f+JrT2xXNdp4bnY= cloud.google.com/go/iam v0.5.0/go.mod h1:wPU9Vt0P4UmCux7mqtRu6jcpPAb74cP1fh50J3QpkUc= -cloud.google.com/go/iam v1.1.5 h1:1jTsCu4bcsNsE4iiqNT5SHwrDRCfRmIaaaVFhRveTJI= -cloud.google.com/go/iam v1.1.5/go.mod h1:rB6P/Ic3mykPbFio+vo7403drjlgvoWfYpJhMXEbzv8= +cloud.google.com/go/iam v1.1.6 h1:bEa06k05IO4f4uJonbB5iAgKTPpABy1ayxaIZV/GHVc= +cloud.google.com/go/iam v1.1.6/go.mod h1:O0zxdPeGBoFdWW3HWmBxJsk0pfvNM/p/qa82rWOGTwI= cloud.google.com/go/language v1.4.0/go.mod h1:F9dRpNFQmJbkaop6g0JhSBXCNlO90e1KWx5iDdxbWic= cloud.google.com/go/language v1.6.0/go.mod h1:6dJ8t3B+lUYfStgls25GusK04NLh3eDLQnWM3mdEbhI= cloud.google.com/go/lifesciences v0.5.0/go.mod h1:3oIKy8ycWGPUyZDR/8RNnTOYevhaMLqh5vLUXs9zvT8= @@ -170,7 +168,6 @@ cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0Zeo cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= cloud.google.com/go/storage v1.22.1/go.mod h1:S8N1cAStu7BOeFfE8KAQzmyyLkK8p/vmRq6kuBTW58Y= cloud.google.com/go/storage v1.23.0/go.mod h1:vOEEDNFnciUMhBeT6hsJIn3ieU5cFRmzeLgDvXzfIXc= cloud.google.com/go/storage v1.27.0/go.mod h1:x9DOL8TK/ygDUMieqwfhdpQryTeEkhGKMi80i/iqR2s= @@ -201,7 +198,6 @@ cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE= cosmossdk.io/math v1.3.0/go.mod h1:vnRTxewy+M7BtXBNFybkuhSH4WfedVAAnERHgVFhp3k= cosmossdk.io/tools/rosetta v0.2.1 h1:ddOMatOH+pbxWbrGJKRAawdBkPYLfKXutK9IETnjYxw= cosmossdk.io/tools/rosetta v0.2.1/go.mod h1:Pqdc1FdvkNV3LcNIkYWt2RQY6IP1ge6YWZk8MhhO9Hw= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs= @@ -209,15 +205,14 @@ github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/ChainSafe/go-schnorrkel v1.0.0 h1:3aDA67lAykLaG1y3AOjs88dMxC88PgUuHRrLeDnvGIM= github.com/ChainSafe/go-schnorrkel v1.0.0/go.mod h1:dpzHYVxLZcp8pjlV+O+UR8K0Hp/z7vcchBSbMBEhCw4= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= github.com/DataDog/zstd v1.5.2 h1:vUG4lAyuPCXO0TLbXvPv7EB7cNK1QV/luu55UHLrrn8= github.com/DataDog/zstd v1.5.2/go.mod h1:g4AWEaM3yOg3HYfnJ3YIawPnVdXJh9QME85blwSAmyw= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= -github.com/Microsoft/go-winio v0.6.0 h1:slsWYD/zyx7lCXoZVlvQrj0hPTM1HI4+v1sIda2yDvg= -github.com/Microsoft/go-winio v0.6.0/go.mod h1:cTAf44im0RAYeL23bpB+fzCyDH2MJiz2BO69KH/soAE= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw= github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk= github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= @@ -250,8 +245,8 @@ github.com/aws/aws-sdk-go v1.44.122/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX github.com/aws/aws-sdk-go v1.44.203 h1:pcsP805b9acL3wUqa4JR2vg1k2wnItkDYNvfmcy6F+U= github.com/aws/aws-sdk-go v1.44.203/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= -github.com/bandprotocol/go-owasm v0.2.3 h1:AGvsUPNKmi+jwY+ZaVePkpeygpav86IK/t/icmTI2fo= -github.com/bandprotocol/go-owasm v0.2.3/go.mod h1:G1ZNqG9+h3Ye82odMF+SWknV0m41Q3Zu6qSKf1vJrHU= +github.com/bandprotocol/go-owasm v0.3.1 h1:L38qAEmb0KyTICHBHJaBoo6yy5+BlbOzQeQ+ioUV5Uw= +github.com/bandprotocol/go-owasm v0.3.1/go.mod h1:SAzGihlBl8eZDXA1dO2aeAZLm8J2QkNd+KvnA2Dw9Kg= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -329,8 +324,8 @@ github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZ github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/coinbase/rosetta-sdk-go/types v1.0.0 h1:jpVIwLcPoOeCR6o1tU+Xv7r5bMONNbHU7MuEHboiFuA= github.com/coinbase/rosetta-sdk-go/types v1.0.0/go.mod h1:eq7W2TMRH22GTW0N0beDnN931DW0/WOI1R2sdHNHG4c= -github.com/cometbft/cometbft v0.37.4 h1:xyvvEqlyfK8MgNIIKVJaMsuIp03wxOcFmVkT26+Ikpg= -github.com/cometbft/cometbft v0.37.4/go.mod h1:Cmg5Hp4sNpapm7j+x0xRyt2g0juQfmB752ous+pA0G8= +github.com/cometbft/cometbft v0.37.5 h1:/U/TlgMh4NdnXNo+YU9T2NMCWyhXNDF34Mx582jlvq0= +github.com/cometbft/cometbft v0.37.5/go.mod h1:QC+mU0lBhKn8r9qvmnq53Dmf3DWBt4VtkcKw2C81wxY= github.com/cometbft/cometbft-db v0.10.0 h1:VMBQh88zXn64jXVvj39tlu/IgsGR84T7ImjS523DCiU= github.com/cometbft/cometbft-db v0.10.0/go.mod h1:7RR7NRv99j7keWJ5IkE9iZibUTKYdtepXTp7Ra0FxKk= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= @@ -345,10 +340,10 @@ github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSV github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= -github.com/cosmos/cosmos-proto v1.0.0-beta.4 h1:aEL7tU/rLOmxZQ9z4i7mzxcLbSCY48OdY7lIWTLG7oU= -github.com/cosmos/cosmos-proto v1.0.0-beta.4/go.mod h1:oeB+FyVzG3XrQJbJng0EnV8Vljfk9XvTIpGILNU/9Co= -github.com/cosmos/cosmos-sdk v0.47.10 h1:Wxf5yEN3jZbG4fftxAMKB6rpd8ME0mxuCVihpz65dt0= -github.com/cosmos/cosmos-sdk v0.47.10/go.mod h1:UWpgWkhcsBIATS68uUC0del7IiBN4hPv/vqg8Zz23uw= +github.com/cosmos/cosmos-proto v1.0.0-beta.5 h1:eNcayDLpip+zVLRLYafhzLvQlSmyab+RC5W7ZfmxJLA= +github.com/cosmos/cosmos-proto v1.0.0-beta.5/go.mod h1:hQGLpiIUloJBMdQMMWb/4wRApmI9hjHH05nefC0Ojec= +github.com/cosmos/cosmos-sdk v0.47.11 h1:0Qx7eORw0RJqPv+mvDuU8NQ1LV3nJJKJnPoYblWHolc= +github.com/cosmos/cosmos-sdk v0.47.11/go.mod h1:ADjORYzUQqQv/FxDi0H0K5gW/rAk1CiDR3ZKsExfJV0= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= @@ -359,8 +354,8 @@ github.com/cosmos/gogoproto v1.4.10 h1:QH/yT8X+c0F4ZDacDv3z+xE3WU1P1Z3wQoLMBRJoK github.com/cosmos/gogoproto v1.4.10/go.mod h1:3aAZzeRWpAwr+SS/LLkICX2/kDFyaYVzckBDzygIxek= github.com/cosmos/iavl v0.20.1 h1:rM1kqeG3/HBT85vsZdoSNsehciqUQPWrR4BYmqE2+zg= github.com/cosmos/iavl v0.20.1/go.mod h1:WO7FyvaZJoH65+HFOsDir7xU9FWk2w9cHXNW1XHcl7A= -github.com/cosmos/ibc-go/v7 v7.3.2 h1:FeUDcBX7VYY0e0iRmcVkPPUjYfAqIc//QuHXo8JHz9c= -github.com/cosmos/ibc-go/v7 v7.3.2/go.mod h1:IMeOXb7gwpZ+/nOG5BuUkdW4weM1ezvN4PQPws4uzOI= +github.com/cosmos/ibc-go/v7 v7.4.0 h1:8FqYMptvksgMvlbN4UW9jFxTXzsPyfAzEZurujXac8M= +github.com/cosmos/ibc-go/v7 v7.4.0/go.mod h1:L/KaEhzV5TGUCTfGysVgMBQtl5Dm7hHitfpk+GIeoAo= github.com/cosmos/ics23/go v0.10.0 h1:iXqLLgp2Lp+EdpIuwXTYIQU+AiHj9mOC2X9ab++bZDM= github.com/cosmos/ics23/go v0.10.0/go.mod h1:ZfJSmng/TBNTBkFemHHHj5YY7VAU/MBU980F4VU1NG0= github.com/cosmos/keyring v1.2.0 h1:8C1lBP9xhImmIabyXW4c3vFjjLiBdGCmfLUfeZlV1Yo= @@ -371,7 +366,7 @@ github.com/cosmos/rosetta-sdk-go v0.10.0 h1:E5RhTruuoA7KTIXUcMicL76cffyeoyvNybzU github.com/cosmos/rosetta-sdk-go v0.10.0/go.mod h1:SImAZkb96YbwvoRkzSMQB6noNJXFgWl/ENIznEoYQI4= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creachadair/taskgroup v0.4.2 h1:jsBLdAJE42asreGss2xZGZ8fJra7WtwnHWeJFxv2Li8= github.com/creachadair/taskgroup v0.4.2/go.mod h1:qiXUOSrbwAY3u0JPGTzObbE3yf9hcXHDKBZ2ZjpCbgM= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= @@ -379,8 +374,9 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3 github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0= github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= @@ -432,12 +428,12 @@ github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8 github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4= github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20= -github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= -github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/getsentry/sentry-go v0.23.0 h1:dn+QRCeJv4pPt9OjVXiMcGIBIefaTJPw/h0bZWO05nE= github.com/getsentry/sentry-go v0.23.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= @@ -447,9 +443,6 @@ github.com/gin-gonic/gin v1.9.0 h1:OjyFBKICoexlu99ctXNR2gg+c5pKrKMuyjgARg9qeY8= github.com/gin-gonic/gin v1.9.0/go.mod h1:W1Me9+hsUSyj3CePGrd1/QrKJMSJ1Tu/0hFEH89961k= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= @@ -463,8 +456,8 @@ github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY= -github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= @@ -535,8 +528,8 @@ github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= @@ -587,7 +580,6 @@ github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hf github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= @@ -620,7 +612,6 @@ github.com/googleapis/gax-go/v2 v2.6.0/go.mod h1:1mjbznJAPHFpesgE5ucqfYEscaz5kMd github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas= github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qKpsEkdD5+I6QGU= github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= -github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= @@ -655,8 +646,8 @@ github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtng github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= -github.com/hashicorp/go-getter v1.7.1 h1:SWiSWN/42qdpR0MdhaOc/bLR48PLuP1ZQtYLRlM69uY= -github.com/hashicorp/go-getter v1.7.1/go.mod h1:W7TalhMmbPmsSMdNjD0ZskARur/9GJ17cfHTRtXV744= +github.com/hashicorp/go-getter v1.7.4 h1:3yQjWuxICvSpYwqSayAdKRFcvBl1y/vogCxczWSmix0= +github.com/hashicorp/go-getter v1.7.4/go.mod h1:W7TalhMmbPmsSMdNjD0ZskARur/9GJ17cfHTRtXV744= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= @@ -734,14 +725,13 @@ github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYs github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM= -github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I= -github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM= +github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.1.1 h1:t0wUqjowdm8ezddV5k0tLWVklVuvLJpoHeb4WBdydm0= github.com/klauspost/cpuid/v2 v2.1.1/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= @@ -870,8 +860,8 @@ github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144T github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= -github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= -github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= +github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= +github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= @@ -888,9 +878,9 @@ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= -github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= @@ -947,6 +937,10 @@ github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= +github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= +github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= +github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= github.com/sasha-s/go-deadlock v0.3.1 h1:sqv7fDNShgjcaxkO0JNcOAlr8B9+cV5Ey/OB71efZx0= github.com/sasha-s/go-deadlock v0.3.1/go.mod h1:F73l+cr82YSh10GxyRI6qZiCgK64VaZjwesgfQ1/iLM= @@ -962,29 +956,29 @@ github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1 github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= -github.com/spf13/afero v1.9.5 h1:stMpOSZFs//0Lv29HduCmli3GUfpFoF3Y1Q/aXj/wVM= -github.com/spf13/afero v1.9.5/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cast v1.5.1 h1:R+kOtfhWQE6TVQzY+4D7wJLBgkdVasCEFxSUBYBYIlA= -github.com/spf13/cast v1.5.1/go.mod h1:b9PdjNptOpzXr7Rq1q9gJML/2cdGQAo69NKzQ10KN48= +github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= +github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= -github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= +github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= +github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= -github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= -github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= -github.com/spf13/viper v1.16.0 h1:rGGH0XDZhdUOryiDWjmIvUSWpbNqisK8Wk0Vyefw8hc= -github.com/spf13/viper v1.16.0/go.mod h1:yg78JgCJcbrQOvV9YLXgkLaZqUidkY9K+Dd1FofRzQg= +github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ= +github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk= github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= @@ -1003,11 +997,11 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/subosito/gotenv v1.4.2 h1:X1TuBLAMDFbaTAChgCBLu3DU3UPyELpnF2jjJ2cz/S8= -github.com/subosito/gotenv v1.4.2/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= @@ -1053,26 +1047,30 @@ go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.46.1 h1:SpGay3w+nEwMpfVnbqOLH5gY52/foP8RE8UzTZ1pdSE= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.46.1/go.mod h1:4UoMYEZOC0yN/sPGH76KPkkU7zgiEWYWL9vwmbnTJPE= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1 h1:aFJWCqJMNjENlcleuuOkGAPH82y0yULBScfXcIEdS24= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1/go.mod h1:sEGXWArGqc3tVa+ekntsN65DmVbVeW+7lTKTjZF3/Fo= -go.opentelemetry.io/otel v1.21.0 h1:hzLeKBZEL7Okw2mGzZ0cc4k/A7Fta0uoPgaJCr8fsFc= -go.opentelemetry.io/otel v1.21.0/go.mod h1:QZzNPQPm1zLX4gZK4cMi+71eaorMSGT3A4znnUvNNEo= -go.opentelemetry.io/otel/metric v1.21.0 h1:tlYWfeo+Bocx5kLEloTjbcDwBuELRrIFxwdQ36PlJu4= -go.opentelemetry.io/otel/metric v1.21.0/go.mod h1:o1p3CA8nNHW8j5yuQLdc1eeqEaPfzug24uvsyIEJRWM= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.47.0 h1:UNQQKPfTDe1J81ViolILjTKPr9WetKW6uei2hFgJmFs= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.47.0/go.mod h1:r9vWsPS/3AQItv3OSlEJ/E4mbrhUbbw18meOjArPtKQ= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.47.0 h1:sv9kVfal0MK0wBMCOGr+HeJm9v803BkJxGrk2au7j08= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.47.0/go.mod h1:SK2UL73Zy1quvRPonmOmRDiWk1KBV3LyIeeIxcEApWw= +go.opentelemetry.io/otel v1.22.0 h1:xS7Ku+7yTFvDfDraDIJVpw7XPyuHlB9MCiqqX5mcJ6Y= +go.opentelemetry.io/otel v1.22.0/go.mod h1:eoV4iAi3Ea8LkAEI9+GFT44O6T/D0GWAVFyZVCC6pMI= +go.opentelemetry.io/otel/metric v1.22.0 h1:lypMQnGyJYeuYPhOM/bgjbFM6WE44W1/T45er4d8Hhg= +go.opentelemetry.io/otel/metric v1.22.0/go.mod h1:evJGjVpZv0mQ5QBRJoBF64yMuOf4xCWdXjK8pzFvliY= go.opentelemetry.io/otel/sdk v1.21.0 h1:FTt8qirL1EysG6sTQRZ5TokkU8d0ugCj8htOgThZXQ8= go.opentelemetry.io/otel/sdk v1.21.0/go.mod h1:Nna6Yv7PWTdgJHVRD9hIYywQBRx7pbox6nwBnZIxl/E= -go.opentelemetry.io/otel/trace v1.21.0 h1:WD9i5gzvoUPuXIXH24ZNBudiarZDKuekPqi/E8fpfLc= -go.opentelemetry.io/otel/trace v1.21.0/go.mod h1:LGbsEB0f9LGjN+OZaQQ26sohbOmiMR+BaslueVtS/qQ= +go.opentelemetry.io/otel/trace v1.22.0 h1:Hg6pPujv0XG9QaVbGOBVHunyuLcCC3jN7WEhPx83XD0= +go.opentelemetry.io/otel/trace v1.22.0/go.mod h1:RbbHXVqKES9QhzZq/fE5UnOSILqRt40a21sPw2He1xo= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU= go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= +go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= +go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= +go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= +go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= @@ -1089,27 +1087,13 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU= -golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc= -golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= -golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= +golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA= +golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb h1:xIApU0ow1zwMa2uL1VDNeQlNVFTWMQxZUZCMDy0Q4Us= golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -1122,20 +1106,18 @@ golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPI golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.11.0 h1:bUO06HqtnRcc/7l71XBe4WcqTZ+3AH1J59zWDDwLKgU= +golang.org/x/mod v0.6.0/go.mod h1:4mET923SAdbXp2ki8ey+zGs1SLqsuM2Y0uvdZR/fUNI= golang.org/x/mod v0.11.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1178,14 +1160,12 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= @@ -1200,8 +1180,8 @@ golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfS golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= -golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= +golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= +golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1227,8 +1207,8 @@ golang.org/x/oauth2 v0.0.0-20220822191816-0ebed06d0094/go.mod h1:h4gKUeWbJ4rQPri golang.org/x/oauth2 v0.0.0-20220909003341-f21342109be1/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= golang.org/x/oauth2 v0.1.0/go.mod h1:G9FE4dLTsbXUu90h/Pf85g4w1D+SSAgR+q46nJZ8M4A= -golang.org/x/oauth2 v0.16.0 h1:aDkGMBSYxElaoP81NpoUoz2oo2R2wHdZpGToUxfyQrQ= -golang.org/x/oauth2 v0.16.0/go.mod h1:hqZ+0LWXsiVoZpeld6jVt06P3adbS2Uu911W1SsJv2o= +golang.org/x/oauth2 v0.17.0 h1:6m3ZPmLEFdVxKKWnKq4VqZ60gutO35zm+zrAHVmHyDQ= +golang.org/x/oauth2 v0.17.0/go.mod h1:OzPDGQiuQMguemayvdylqddI7qcD9lnSDb+1FiwQ5HA= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -1256,7 +1236,6 @@ golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190130150945-aca44879d564/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1267,7 +1246,6 @@ golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1300,13 +1278,11 @@ golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210603125802-9665404d3644/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1337,22 +1313,21 @@ golang.org/x/sys v0.0.0-20220624220833-87e55d714810/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= -golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.16.0 h1:m+B6fahuftsE9qjo0VWp2FW0mB3MTJvR0BaMQrq0pmE= -golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= +golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8= +golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1381,7 +1356,6 @@ golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= @@ -1390,9 +1364,7 @@ golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBn golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= @@ -1407,7 +1379,6 @@ golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapK golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= @@ -1428,7 +1399,6 @@ golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= @@ -1436,8 +1406,9 @@ golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.7.0 h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4= -golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= +golang.org/x/tools v0.2.0/go.mod h1:y4OqIKeOV/fWJetJ8bXPU1sEVniLMIyDAZWeHdV+NTA= +golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= +golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1496,8 +1467,8 @@ google.golang.org/api v0.96.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ google.golang.org/api v0.97.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= google.golang.org/api v0.98.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= google.golang.org/api v0.100.0/go.mod h1:ZE3Z2+ZOr87Rx7dqFsdRQkRBk36kDtp/h+QpHbB7a70= -google.golang.org/api v0.155.0 h1:vBmGhCYs0djJttDNynWo44zosHlPvHmA0XiN2zP2DtA= -google.golang.org/api v0.155.0/go.mod h1:GI5qK5f40kCpHfPn6+YzGAByIKWv8ujFnmoWm7Igduk= +google.golang.org/api v0.162.0 h1:Vhs54HkaEpkMBdgGdOT2P6F0csGG/vxDS0hWHJzmmps= +google.golang.org/api v0.162.0/go.mod h1:6SulDkfoBIg4NFmCuZ39XeeAgSHCPecfSUuDyYlAHs0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -1546,10 +1517,8 @@ google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210126160654-44e461bb6506/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= @@ -1616,12 +1585,12 @@ google.golang.org/genproto v0.0.0-20221010155953-15ba04fc1c0e/go.mod h1:3526vdqw google.golang.org/genproto v0.0.0-20221014173430-6e2ab493f96b/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221025140454-527a21cfbd71/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= -google.golang.org/genproto v0.0.0-20240123012728-ef4313101c80 h1:KAeGQVN3M9nD0/bQXnr/ClcEMJ968gUXJQ9pwfSynuQ= -google.golang.org/genproto v0.0.0-20240123012728-ef4313101c80/go.mod h1:cc8bqMqtv9gMOr0zHg2Vzff5ULhhL2IXP4sbcn32Dro= -google.golang.org/genproto/googleapis/api v0.0.0-20240123012728-ef4313101c80 h1:Lj5rbfG876hIAYFjqiJnPHfhXbv+nzTWfm04Fg/XSVU= -google.golang.org/genproto/googleapis/api v0.0.0-20240123012728-ef4313101c80/go.mod h1:4jWUdICTdgc3Ibxmr8nAJiiLHwQBY0UI0XZcEMaFKaA= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240123012728-ef4313101c80 h1:AjyfHzEPEFp/NpvfN5g+KDla3EMojjhRVZc1i7cj+oM= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240123012728-ef4313101c80/go.mod h1:PAREbraiVEVGVdTZsVWjSbbTtSyGbAgIIvni8a8CD5s= +google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de h1:F6qOa9AZTYJXOUEr4jDysRDLrm4PHePlge4v4TGAlxY= +google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:VUhTRKeHn9wwcdrk73nvdC9gF178Tzhmt/qyaFcPLSo= +google.golang.org/genproto/googleapis/api v0.0.0-20240227224415-6ceb2ff114de h1:jFNzHPIeuzhdRwVhbZdiym9q0ory/xY3sA+v2wPg8I0= +google.golang.org/genproto/googleapis/api v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:5iCWqnniDlqZHrd3neWVTOwvh/v6s3232omMecelax8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de h1:cZGRis4/ot9uVm639a+rHCUaG0JJHEsdyzSQTMX+suY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:H4O17MA/PE9BsGx3w+a+W2VOLLD1Qf7oJneAoU6WktY= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= @@ -1663,8 +1632,8 @@ google.golang.org/grpc v1.48.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACu google.golang.org/grpc v1.49.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= google.golang.org/grpc v1.50.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= google.golang.org/grpc v1.50.1/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= -google.golang.org/grpc v1.62.1 h1:B4n+nfKzOICUXMgyrNd19h/I9oH0L1pizfk1d4zSgTk= -google.golang.org/grpc v1.62.1/go.mod h1:IWTG0VlJLCh1SkC58F7np9ka9mx/WNkjl4PGJaiq+QE= +google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM= +google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= @@ -1681,8 +1650,8 @@ google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I= -google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +google.golang.org/protobuf v1.34.0 h1:Qo/qEd2RZPCf2nKuorzksSknv0d3ERwp1vFG38gSmH4= +google.golang.org/protobuf v1.34.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -1728,8 +1697,8 @@ honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9 honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= nhooyr.io/websocket v1.8.6 h1:s+C3xAMLwGmlI31Nyn/eAehUlZPwfYZu2JXM621Q5/k= nhooyr.io/websocket v1.8.6/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= -pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= -pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= +pgregory.net/rapid v0.5.5 h1:jkgx1TjbQPD/feRoK+S/mXw9e1uj6WilpHrXJowi6oA= +pgregory.net/rapid v0.5.5/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= diff --git a/testing/chain.go b/testing/ibctesting/chain.go similarity index 96% rename from testing/chain.go rename to testing/ibctesting/chain.go index 5fec5f286..bceb018df 100644 --- a/testing/chain.go +++ b/testing/ibctesting/chain.go @@ -33,7 +33,7 @@ import ( "github.com/stretchr/testify/require" bandapp "github.com/bandprotocol/chain/v2/app" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -48,7 +48,7 @@ type TestChain struct { t *testing.T Coordinator *Coordinator - App *testapp.TestingApp + App *bandtesting.TestingApp ChainID string LastHeader *ibctmtypes.Header // header for last block height committed CurrentHeader tmproto.Header // header for current block height @@ -83,8 +83,8 @@ func NewTestChain(t *testing.T, coord *Coordinator, chainID string) *TestChain { for i := uint64(0); i < valSize; i++ { // generate validator private/public key - privVal := mock.PV{PrivKey: testapp.Validators[i].PrivKey} - tmPub, err := cryptocodec.ToTmPubKeyInterface(testapp.Validators[i].PubKey) + privVal := mock.PV{PrivKey: bandtesting.Validators[i].PrivKey} + tmPub, err := cryptocodec.ToTmPubKeyInterface(bandtesting.Validators[i].PubKey) require.NoError(t, err) // create validator set with two validators @@ -92,13 +92,13 @@ func NewTestChain(t *testing.T, coord *Coordinator, chainID string) *TestChain { signers[i] = privVal - senders[testapp.Validators[i].Address.String()] = authtypes.NewBaseAccount( - testapp.Validators[i].PubKey.Address().Bytes(), - testapp.Validators[i].PubKey, + senders[bandtesting.Validators[i].Address.String()] = authtypes.NewBaseAccount( + bandtesting.Validators[i].PubKey.Address().Bytes(), + bandtesting.Validators[i].PubKey, i, 0, ) - genesisAccount[i] = senders[testapp.Validators[i].Address.String()] + genesisAccount[i] = senders[bandtesting.Validators[i].Address.String()] balances[i] = banktypes.Balance{ Address: genesisAccount[i].GetAddress().String(), Coins: sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(10000000))), @@ -107,7 +107,7 @@ func NewTestChain(t *testing.T, coord *Coordinator, chainID string) *TestChain { valSet := tmtypes.NewValidatorSet(validators) - app := testapp.SetupWithGenesisValSet(t, valSet, genesisAccount, chainID, balances...) + app := bandtesting.SetupWithGenesisValSet(t, valSet, genesisAccount, chainID, balances...) ctx := app.NewContext(false, tmproto.Header{Height: app.LastBlockHeight()}) vals := app.StakingKeeper.GetAllValidators(ctx) for _, v := range vals { @@ -136,9 +136,9 @@ func NewTestChain(t *testing.T, coord *Coordinator, chainID string) *TestChain { Codec: app.AppCodec(), Vals: valSet, Signers: signers, - SenderPrivKey: testapp.Validators[0].PrivKey, + SenderPrivKey: bandtesting.Validators[0].PrivKey, SenderAccount: genesisAccount[0], - Treasury: testapp.Treasury.Address, + Treasury: bandtesting.Treasury.Address, senders: senders, } @@ -254,7 +254,7 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { // ensure the chain has the latest time chain.Coordinator.UpdateTimeForChain(chain) - _, r, err := testapp.SignAndDeliver( + _, r, err := bandtesting.SignAndDeliver( chain.t, chain.TxConfig, chain.App.GetBaseApp(), @@ -287,14 +287,14 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { func (chain *TestChain) SendReport( rid types.RequestID, rawReps []types.RawReport, - sender testapp.Account, + sender bandtesting.Account, ) (*sdk.Result, error) { senderAccount := chain.senders[sender.Address.String()] // ensure the chain has the latest time chain.Coordinator.UpdateTimeForChain(chain) - _, r, err := testapp.SignAndDeliver( + _, r, err := bandtesting.SignAndDeliver( chain.t, chain.TxConfig, chain.App.GetBaseApp(), diff --git a/testing/config.go b/testing/ibctesting/config.go similarity index 100% rename from testing/config.go rename to testing/ibctesting/config.go diff --git a/testing/coordinator.go b/testing/ibctesting/coordinator.go similarity index 100% rename from testing/coordinator.go rename to testing/ibctesting/coordinator.go diff --git a/testing/endpoint.go b/testing/ibctesting/endpoint.go similarity index 100% rename from testing/endpoint.go rename to testing/ibctesting/endpoint.go diff --git a/testing/events.go b/testing/ibctesting/events.go similarity index 100% rename from testing/events.go rename to testing/ibctesting/events.go diff --git a/testing/path.go b/testing/ibctesting/path.go similarity index 100% rename from testing/path.go rename to testing/ibctesting/path.go diff --git a/testing/value.go b/testing/ibctesting/value.go similarity index 100% rename from testing/value.go rename to testing/ibctesting/value.go diff --git a/testing/testapp/setup.go b/testing/test_helpers.go similarity index 81% rename from testing/testapp/setup.go rename to testing/test_helpers.go index 8e99de175..e713963db 100644 --- a/testing/testapp/setup.go +++ b/testing/test_helpers.go @@ -1,4 +1,4 @@ -package testapp +package testing import ( "encoding/json" @@ -46,7 +46,6 @@ import ( "github.com/bandprotocol/chain/v2/pkg/tss/testutil" "github.com/bandprotocol/chain/v2/testing/testdata" bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" - "github.com/bandprotocol/chain/v2/x/oracle/keeper" "github.com/bandprotocol/chain/v2/x/oracle/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) @@ -82,16 +81,17 @@ var ( Coins100000000uband = sdk.NewCoins(sdk.NewInt64Coin("uband", 100000000)) Coins100000000token = sdk.NewCoins(sdk.NewInt64Coin("token", 100000000)) BadCoins = []sdk.Coin{{Denom: "uband", Amount: sdk.NewInt(-1)}} - Port1 = "port-1" - Port2 = "port-2" - Channel1 = "channel-1" - Channel2 = "channel-2" ) const ( ChainID string = "BANDCHAIN" + Port1 = "port-1" + Port2 = "port-2" + Channel1 = "channel-1" + Channel2 = "channel-2" TestDefaultPrepareGas uint64 = 40000 TestDefaultExecuteGas uint64 = 300000 + DefaultGenTxGas = 1000000 ) // DefaultConsensusParams defines the default Tendermint consensus params used in TestingApp. @@ -165,100 +165,10 @@ func init() { OwasmVM = owasmVM } -func createArbitraryAccount(r *rand.Rand) Account { - privkeySeed := make([]byte, 12) - r.Read(privkeySeed) - privKey := secp256k1.GenPrivKeyFromSecret(privkeySeed) - return Account{ - PrivKey: privKey, - PubKey: privKey.PubKey(), - Address: sdk.AccAddress(privKey.PubKey().Address()), - ValAddress: sdk.ValAddress(privKey.PubKey().Address()), - } -} - -func getGenesisDataSources(homePath string) []types.DataSource { - dir := filepath.Join(homePath, "files") - fc := filecache.New(dir) - DataSources = []types.DataSource{{}} // 0th index should be ignored - for idx := 0; idx < 5; idx++ { - idxStr := fmt.Sprintf("%d", idx+1) - hash := fc.AddFile([]byte("code" + idxStr)) - DataSources = append(DataSources, types.NewDataSource( - Owner.Address, "name"+idxStr, "desc"+idxStr, hash, Coins1000000uband, Treasury.Address, - )) - } - return DataSources[1:] -} +// CreateTestApp creates a new test environment for unit tests. +func CreateTestApp(t *testing.T, autoActivate bool) (*TestingApp, sdk.Context) { + t.Helper() -func getGenesisOracleScripts(homePath string) []types.OracleScript { - dir := filepath.Join(homePath, "files") - fc := filecache.New(dir) - OracleScripts = []types.OracleScript{{}} // 0th index should be ignored - wasms := [][]byte{ - testdata.Wasm1, testdata.Wasm2, testdata.Wasm3, testdata.Wasm4, testdata.Wasm56(10), testdata.Wasm56(10000000), testdata.Wasm78(10), testdata.Wasm78(2000), testdata.Wasm9, - } - for idx := 0; idx < len(wasms); idx++ { - idxStr := fmt.Sprintf("%d", idx+1) - hash := fc.AddFile(testdata.Compile(wasms[idx])) - OracleScripts = append(OracleScripts, types.NewOracleScript( - Owner.Address, "name"+idxStr, "desc"+idxStr, hash, "schema"+idxStr, "url"+idxStr, - )) - } - return OracleScripts[1:] -} - -// EmptyAppOptions is a stub implementing AppOptions -type EmptyAppOptions struct{} - -// Get implements AppOptions -func (ao EmptyAppOptions) Get(o string) interface{} { - return nil -} - -// NewTestApp creates instance of our app using in test. -func NewTestApp(chainID string, logger log.Logger) *TestingApp { - // Set HomeFlag to a temp folder for simulation run. - dir, err := os.MkdirTemp("", "bandd") - if err != nil { - panic(err) - } - // db := dbm.NewMemDB() - db, _ := dbm.NewGoLevelDB("db", dir) - - appOptions := make(simtestutil.AppOptionsMap, 0) - appOptions[flags.FlagHome] = dir - appOptions[server.FlagInvCheckPeriod] = 0 - - snapshotDir := filepath.Join(dir, "data", "snapshots") - snapshotDB, err := dbm.NewDB("metadata", dbm.GoLevelDBBackend, snapshotDir) - if err != nil { - panic(err) - } - snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir) - if err != nil { - panic(err) - } - - snapshotOptions := snapshottypes.NewSnapshotOptions( - 1000, - 2, - ) - - app := &TestingApp{ - BandApp: bandapp.NewBandApp( - log.NewNopLogger(), - db, - nil, - true, - map[int64]bool{}, - appOptions, - 100, - baseapp.SetSnapshot(snapshotStore, snapshotOptions), - baseapp.SetChainID(chainID), - ), - } - genesis := bandapp.NewDefaultGenesisState() acc := []authtypes.GenesisAccount{ &authtypes.BaseAccount{Address: Owner.Address.String()}, &authtypes.BaseAccount{Address: FeePayer.Address.String()}, @@ -269,64 +179,6 @@ func NewTestApp(chainID string, logger log.Logger) *TestingApp { &authtypes.BaseAccount{Address: Validators[1].Address.String()}, &authtypes.BaseAccount{Address: Validators[2].Address.String()}, } - authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), acc) - genesis[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) - - validators := make([]stakingtypes.Validator, 0, len(Validators)) - signingInfos := make([]slashingtypes.SigningInfo, 0, len(Validators)) - delegations := make([]stakingtypes.Delegation, 0, len(Validators)) - bamt := []sdkmath.Int{Coins100000000uband[0].Amount, Coins1000000uband[0].Amount, Coins99999999uband[0].Amount} - // bondAmt := sdk.NewInt(1000000) - for idx, val := range Validators { - tmpk, err := cryptocodec.ToTmPubKeyInterface(val.PubKey) - if err != nil { - panic(err) - } - pk, err := cryptocodec.FromTmPubKeyInterface(tmpk) - if err != nil { - panic(err) - } - pkAny, err := codectypes.NewAnyWithValue(pk) - if err != nil { - panic(err) - } - validator := stakingtypes.Validator{ - OperatorAddress: sdk.ValAddress(val.Address).String(), - ConsensusPubkey: pkAny, - Jailed: false, - Status: stakingtypes.Bonded, - Tokens: bamt[idx], - DelegatorShares: sdk.OneDec(), - Description: stakingtypes.Description{}, - UnbondingHeight: int64(0), - UnbondingTime: time.Unix(0, 0).UTC(), - Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - MinSelfDelegation: sdk.ZeroInt(), - } - consAddr, err := validator.GetConsAddr() - validatorSigningInfo := slashingtypes.NewValidatorSigningInfo(consAddr, 0, 0, time.Unix(0, 0), false, 0) - if err != nil { - panic(err) - } - validators = append(validators, validator) - signingInfos = append( - signingInfos, - slashingtypes.SigningInfo{Address: consAddr.String(), ValidatorSigningInfo: validatorSigningInfo}, - ) - delegations = append( - delegations, - stakingtypes.NewDelegation(acc[4+idx].GetAddress(), val.Address.Bytes(), sdk.OneDec()), - ) - } - // set validators and delegations - stakingParams := stakingtypes.DefaultParams() - stakingParams.BondDenom = "uband" - stakingGenesis := stakingtypes.NewGenesisState(stakingParams, validators, delegations) - genesis[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis) - - slashingParams := slashingtypes.DefaultParams() - slashingGenesis := slashingtypes.NewGenesisState(slashingParams, signingInfos, nil) - genesis[slashingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(slashingGenesis) // Fund seed accounts and validators with 1000000uband and 100000000uband initially. balances := []banktypes.Balance{ @@ -341,99 +193,85 @@ func NewTestApp(chainID string, logger log.Logger) *TestingApp { {Address: Validators[0].Address.String(), Coins: Coins100000000uband}, {Address: Validators[1].Address.String(), Coins: Coins100000000uband}, {Address: Validators[2].Address.String(), Coins: Coins100000000uband}, - { - Address: authtypes.NewModuleAddress(bandtsstypes.ModuleName).String(), - Coins: Coins100000000uband, - }, - { - Address: authtypes.NewModuleAddress(bandtsstypes.ModuleName).String(), - Coins: Coins100000000token, - }, } - totalSupply := sdk.NewCoins() - for idx := 0; idx < len(balances)-len(validators); idx++ { - // add genesis acc tokens and delegated tokens to total supply - totalSupply = totalSupply.Add(balances[idx].Coins...) - } - for idx := 0; idx < len(validators); idx++ { - // add genesis acc tokens and delegated tokens to total supply - totalSupply = totalSupply.Add( - balances[idx+len(balances)-len(validators)].Coins.Add(sdk.NewCoin("uband", bamt[idx]))...) - } - - // add bonded amount to bonded pool module account - balances = append(balances, banktypes.Balance{ - Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), - Coins: sdk.Coins{sdk.NewCoin("uband", sdk.NewInt(200999999))}, - }) - - bankGenesis := banktypes.NewGenesisState( - banktypes.DefaultGenesisState().Params, - balances, - totalSupply, - []banktypes.Metadata{}, - []banktypes.SendEnabled{}, - ) - genesis[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) - // Add genesis data sources and oracle scripts - oracleGenesis := types.DefaultGenesisState() - oracleGenesis.DataSources = getGenesisDataSources(dir) - oracleGenesis.OracleScripts = getGenesisOracleScripts(dir) - genesis[types.ModuleName] = app.AppCodec().MustMarshalJSON(oracleGenesis) - stateBytes, err := json.MarshalIndent(genesis, "", " ") - if err != nil { - panic(err) - } - - // Initialize the sim blockchain. We are ready for testing! - app.InitChain(abci.RequestInitChain{ - ChainId: chainID, - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: DefaultConsensusParams, - AppStateBytes: stateBytes, - }) - return app -} - -// CreateTestInput creates a new test environment for unit tests. -func CreateTestInput(autoActivate bool) (*TestingApp, sdk.Context, keeper.Keeper) { - app := NewTestApp(ChainID, log.NewNopLogger()) - ctx := app.NewContext(false, tmproto.Header{Height: app.LastBlockHeight()}) + isCheckTx := false + app := setupWithGenesis(t, Validators, acc, ChainID, balances...) + ctx := app.NewContext(isCheckTx, tmproto.Header{Height: app.LastBlockHeight()}) if autoActivate { // active oracle status - _ = app.OracleKeeper.Activate(ctx, Validators[0].ValAddress) - _ = app.OracleKeeper.Activate(ctx, Validators[1].ValAddress) - _ = app.OracleKeeper.Activate(ctx, Validators[2].ValAddress) + err := app.OracleKeeper.Activate(ctx, Validators[0].ValAddress) + require.NoError(t, err) + err = app.OracleKeeper.Activate(ctx, Validators[1].ValAddress) + require.NoError(t, err) + err = app.OracleKeeper.Activate(ctx, Validators[2].ValAddress) + require.NoError(t, err) + // active tss status - _ = app.TSSKeeper.HandleSetDEs(ctx, Validators[0].Address, []tsstypes.DE{ + err = app.TSSKeeper.HandleSetDEs(ctx, Validators[0].Address, []tsstypes.DE{ { PubD: testutil.HexDecode("dddd"), PubE: testutil.HexDecode("eeee"), }, }) - _ = app.TSSKeeper.HandleSetDEs(ctx, Validators[1].Address, []tsstypes.DE{ + require.NoError(t, err) + err = app.TSSKeeper.HandleSetDEs(ctx, Validators[1].Address, []tsstypes.DE{ { PubD: testutil.HexDecode("dddd"), PubE: testutil.HexDecode("eeee"), }, }) - _ = app.TSSKeeper.HandleSetDEs(ctx, Validators[2].Address, []tsstypes.DE{ + require.NoError(t, err) + err = app.TSSKeeper.HandleSetDEs(ctx, Validators[2].Address, []tsstypes.DE{ { PubD: testutil.HexDecode("dddd"), PubE: testutil.HexDecode("eeee"), }, }) + require.NoError(t, err) } - return app, ctx, app.OracleKeeper + + return &TestingApp{app}, ctx +} + +// setupWithGenesis sets up a BandApp for testing with a specified genesis state. +func setupWithGenesis( + t *testing.T, + valSet []Account, + genAccs []authtypes.GenesisAccount, + chainID string, + balances ...banktypes.Balance, +) *bandapp.BandApp { + t.Helper() + + app, genesisState, dir := setup(t, chainID, true) + genesisState = generateGenesisState(t, app, dir, genesisState, valSet, genAccs, balances...) + + stateBytes, err := json.MarshalIndent(genesisState, "", " ") + if err != nil { + panic(err) + } + + // Initialize the sim blockchain. We are ready for testing! + app.InitChain(abci.RequestInitChain{ + ChainId: chainID, + Validators: []abci.ValidatorUpdate{}, + ConsensusParams: DefaultConsensusParams, + AppStateBytes: stateBytes, + }) + return app } -func setup(withGenesis bool, invCheckPeriod uint, chainID string) (*TestingApp, bandapp.GenesisState, string) { - dir, err := os.MkdirTemp("", "bandibc") +// setup initializes a BandApp instance for simulation testing. +func setup(t *testing.T, chainID string, withGenesis bool) (*bandapp.BandApp, bandapp.GenesisState, string) { + t.Helper() + + // Set HomeFlag to a temp folder for simulation run. + dir, err := os.MkdirTemp("", "bandd") if err != nil { panic(err) } - db := dbm.NewMemDB() + db, _ := dbm.NewGoLevelDB("db", dir) appOptions := make(simtestutil.AppOptionsMap, 0) appOptions[flags.FlagHome] = dir @@ -454,33 +292,34 @@ func setup(withGenesis bool, invCheckPeriod uint, chainID string) (*TestingApp, 2, ) - app := &TestingApp{ - BandApp: bandapp.NewBandApp( - log.NewNopLogger(), - db, - nil, - true, - map[int64]bool{}, - appOptions, - 0, - baseapp.SetSnapshot(snapshotStore, snapshotOptions), - baseapp.SetChainID(chainID), - ), - } + app := bandapp.NewBandApp( + log.NewNopLogger(), + db, + nil, + true, + map[int64]bool{}, + appOptions, + 100, + baseapp.SetSnapshot(snapshotStore, snapshotOptions), + baseapp.SetChainID(chainID), + ) if withGenesis { return app, bandapp.NewDefaultGenesisState(), dir } + return app, bandapp.GenesisState{}, dir } -// SetupWithEmptyStore setup a TestingApp instance with empty DB -func SetupWithEmptyStore() *TestingApp { - app, _, _ := setup(false, 0, ChainID) +// SetupWithEmptyStore setup a instance with empty DB. +func SetupWithEmptyStore(t *testing.T, chainID string) *bandapp.BandApp { + t.Helper() + + app, _, _ := setup(t, chainID, false) return app } // SetupWithGenesisValSet initializes a new TestingApp with a validator set and genesis accounts -// that also act as delegators. For simplicity, each validator is bonded with a delegation +// that also act as delegator. For simplicity, each validator is bonded with a delegation // of one consensus engine unit (10^6) in the default token of the BandChain from first genesis // account. A Nop logger is set in TestingApp. func SetupWithGenesisValSet( @@ -490,7 +329,10 @@ func SetupWithGenesisValSet( chainID string, balances ...banktypes.Balance, ) *TestingApp { - app, genesisState, dir := setup(true, 5, chainID) + t.Helper() + + app, genesisState, dir := setup(t, chainID, true) + // set genesis accounts authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) @@ -555,8 +397,8 @@ func SetupWithGenesisValSet( // Add genesis data sources and oracle scripts oracleGenesis := types.DefaultGenesisState() - oracleGenesis.DataSources = getGenesisDataSources(dir) - oracleGenesis.OracleScripts = getGenesisOracleScripts(dir) + oracleGenesis.DataSources = generateDataSources(dir) + oracleGenesis.OracleScripts = generateOracleScripts(dir) genesisState[types.ModuleName] = app.AppCodec().MustMarshalJSON(oracleGenesis) // Add tss genesis @@ -590,12 +432,159 @@ func SetupWithGenesisValSet( NextValidatorsHash: valSet.Hash(), }, Hash: app.LastCommitID().Hash}) - return app + return &TestingApp{app} } -const ( - DefaultGenTxGas = 1000000 -) +// createArbitraryAccount generates a random Account using a provided random number generator. +func createArbitraryAccount(r *rand.Rand) Account { + privkeySeed := make([]byte, 12) + r.Read(privkeySeed) + privKey := secp256k1.GenPrivKeyFromSecret(privkeySeed) + return Account{ + PrivKey: privKey, + PubKey: privKey.PubKey(), + Address: sdk.AccAddress(privKey.PubKey().Address()), + ValAddress: sdk.ValAddress(privKey.PubKey().Address()), + } +} + +// generateGenesisState initializes the genesis state of a BandApp for testing. +func generateGenesisState( + t *testing.T, + app *bandapp.BandApp, + dir string, + genesisState bandapp.GenesisState, + valSet []Account, + genAccs []authtypes.GenesisAccount, + balances ...banktypes.Balance, +) bandapp.GenesisState { + t.Helper() + + authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) + genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) + + validators := make([]stakingtypes.Validator, 0, len(valSet)) + signingInfos := make([]slashingtypes.SigningInfo, 0, len(valSet)) + delegations := make([]stakingtypes.Delegation, 0, len(valSet)) + bamt := []sdkmath.Int{Coins100000000uband[0].Amount, Coins1000000uband[0].Amount, Coins99999999uband[0].Amount} + for idx, val := range valSet { + tmpk, err := cryptocodec.ToTmPubKeyInterface(val.PubKey) + if err != nil { + panic(err) + } + pk, err := cryptocodec.FromTmPubKeyInterface(tmpk) + if err != nil { + panic(err) + } + pkAny, err := codectypes.NewAnyWithValue(pk) + if err != nil { + panic(err) + } + validator := stakingtypes.Validator{ + OperatorAddress: sdk.ValAddress(val.Address).String(), + ConsensusPubkey: pkAny, + Jailed: false, + Status: stakingtypes.Bonded, + Tokens: bamt[idx], + DelegatorShares: sdk.OneDec(), + Description: stakingtypes.Description{}, + UnbondingHeight: int64(0), + UnbondingTime: time.Unix(0, 0).UTC(), + Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), + MinSelfDelegation: sdk.ZeroInt(), + } + consAddr, err := validator.GetConsAddr() + validatorSigningInfo := slashingtypes.NewValidatorSigningInfo(consAddr, 0, 0, time.Unix(0, 0), false, 0) + if err != nil { + panic(err) + } + validators = append(validators, validator) + signingInfos = append( + signingInfos, + slashingtypes.SigningInfo{Address: consAddr.String(), ValidatorSigningInfo: validatorSigningInfo}, + ) + delegations = append( + delegations, + stakingtypes.NewDelegation(genAccs[4+idx].GetAddress(), val.Address.Bytes(), sdk.OneDec()), + ) + } + // set validators and delegations + stakingParams := stakingtypes.DefaultParams() + stakingParams.BondDenom = "uband" + stakingGenesis := stakingtypes.NewGenesisState(stakingParams, validators, delegations) + genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis) + + slashingParams := slashingtypes.DefaultParams() + slashingGenesis := slashingtypes.NewGenesisState(slashingParams, signingInfos, nil) + genesisState[slashingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(slashingGenesis) + + totalSupply := sdk.NewCoins() + for idx := 0; idx < len(balances)-len(validators); idx++ { + // add genesis acc tokens and delegated tokens to total supply + totalSupply = totalSupply.Add(balances[idx].Coins...) + } + for idx := 0; idx < len(validators); idx++ { + // add genesis acc tokens and delegated tokens to total supply + totalSupply = totalSupply.Add( + balances[idx+len(balances)-len(validators)].Coins.Add(sdk.NewCoin("uband", bamt[idx]))...) + } + + // add bonded amount to bonded pool module account + balances = append(balances, banktypes.Balance{ + Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), + Coins: sdk.Coins{sdk.NewCoin("uband", sdk.NewInt(200999999))}, + }) + + bankGenesis := banktypes.NewGenesisState( + banktypes.DefaultGenesisState().Params, + balances, + totalSupply, + []banktypes.Metadata{}, + []banktypes.SendEnabled{}, + ) + genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) + + // Add genesis data sources and oracle scripts + oracleGenesis := types.DefaultGenesisState() + oracleGenesis.DataSources = generateDataSources(dir) + oracleGenesis.OracleScripts = generateOracleScripts(dir) + genesisState[types.ModuleName] = app.AppCodec().MustMarshalJSON(oracleGenesis) + + return genesisState +} + +// generateDataSources generates a set of data sources for the BandApp. +func generateDataSources(homePath string) []types.DataSource { + dir := filepath.Join(homePath, "files") + fc := filecache.New(dir) + DataSources = []types.DataSource{{}} // 0th index should be ignored + for idx := 0; idx < 5; idx++ { + idxStr := fmt.Sprintf("%d", idx+1) + hash := fc.AddFile([]byte("code" + idxStr)) + DataSources = append(DataSources, types.NewDataSource( + Owner.Address, "name"+idxStr, "desc"+idxStr, hash, Coins1000000uband, Treasury.Address, + )) + } + return DataSources[1:] +} + +// generateOracleScripts generates a set of oracle scripts for the BandApp. +func generateOracleScripts(homePath string) []types.OracleScript { + dir := filepath.Join(homePath, "files") + fc := filecache.New(dir) + OracleScripts = []types.OracleScript{{}} // 0th index should be ignored + wasms := [][]byte{ + testdata.Wasm1, testdata.Wasm2, testdata.Wasm3, testdata.Wasm4, testdata.Wasm56(10), testdata.Wasm56(10000000), testdata.Wasm78(10), testdata.Wasm78(2000), testdata.Wasm9, + } + for idx := 0; idx < len(wasms); idx++ { + idxStr := fmt.Sprintf("%d", idx+1) + hash := fc.AddFile(testdata.Compile(wasms[idx])) + OracleScripts = append(OracleScripts, types.NewOracleScript( + Owner.Address, "name"+idxStr, "desc"+idxStr, hash, "schema"+idxStr, "url"+idxStr, + )) + } + return OracleScripts[1:] +} // GenTx generates a signed mock transaction. func GenTx( diff --git a/testing/testapp/util.go b/testing/util.go similarity index 99% rename from testing/testapp/util.go rename to testing/util.go index e45ffc483..e6b928297 100644 --- a/testing/testapp/util.go +++ b/testing/util.go @@ -1,4 +1,4 @@ -package testapp +package testing import ( "fmt" diff --git a/x/bandtss/abci_test.go b/x/bandtss/abci_test.go index b9640c015..be3266845 100644 --- a/x/bandtss/abci_test.go +++ b/x/bandtss/abci_test.go @@ -9,14 +9,14 @@ import ( "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/bandtss/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) func TestReplaceGroups(t *testing.T) { - app, ctx, _ := testapp.CreateTestInput(true) - bandtssKeeper, tssKeeper := app.BandtssKeeper, app.TSSKeeper + app, ctx := bandtesting.CreateTestApp(t, true) + tssKeeper, bandtssKeeper := app.TSSKeeper, app.BandtssKeeper // Set new block time ctx = ctx.WithBlockTime(time.Now().UTC()) diff --git a/x/bandtss/genesis_test.go b/x/bandtss/genesis_test.go index 9a4088b2e..98acdd1c8 100644 --- a/x/bandtss/genesis_test.go +++ b/x/bandtss/genesis_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" "github.com/bandprotocol/chain/v2/pkg/tss" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/bandtss" "github.com/bandprotocol/chain/v2/x/bandtss/testutil" "github.com/bandprotocol/chain/v2/x/bandtss/types" @@ -19,12 +19,12 @@ func TestExportGenesis(t *testing.T) { data := types.GenesisState{ Params: types.DefaultParams(), Members: []types.Member{ - {Address: testapp.Alice.Address.String(), Since: ctx.BlockTime(), IsActive: true, LastActive: ctx.BlockTime()}, + {Address: bandtesting.Alice.Address.String(), Since: ctx.BlockTime(), IsActive: true, LastActive: ctx.BlockTime()}, }, CurrentGroupID: tss.GroupID(1), SigningCount: 1, Signings: []types.Signing{ - {ID: types.SigningID(1), Requester: testapp.Alice.Address.String(), CurrentGroupSigningID: tss.SigningID(3)}, + {ID: types.SigningID(1), Requester: bandtesting.Alice.Address.String(), CurrentGroupSigningID: tss.SigningID(3)}, }, SigningIDMappings: []types.SigningIDMappingGenesis{ {SigningID: tss.SigningID(1), BandtssSigningID: types.SigningID(3)}, diff --git a/x/bandtss/keeper/keeper_test.go b/x/bandtss/keeper/keeper_test.go index 54f25561f..ed42c67b5 100644 --- a/x/bandtss/keeper/keeper_test.go +++ b/x/bandtss/keeper/keeper_test.go @@ -14,7 +14,7 @@ import ( "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/bandtss/keeper" "github.com/bandprotocol/chain/v2/x/bandtss/types" tsskeeper "github.com/bandprotocol/chain/v2/x/tss/keeper" @@ -24,7 +24,7 @@ import ( type KeeperTestSuite struct { suite.Suite - app *testapp.TestingApp + app *bandtesting.TestingApp ctx sdk.Context queryClient types.QueryClient msgSrvr types.MsgServer @@ -40,7 +40,7 @@ var ( ) func (s *KeeperTestSuite) SetupTest() { - app, ctx, _ := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(s.T(), true) s.app = app s.ctx = ctx diff --git a/x/bandtss/keeper/msg_server_test.go b/x/bandtss/keeper/msg_server_test.go index a82bfd57c..fa53cd044 100644 --- a/x/bandtss/keeper/msg_server_test.go +++ b/x/bandtss/keeper/msg_server_test.go @@ -10,7 +10,7 @@ import ( "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/bandtss/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) @@ -122,7 +122,7 @@ func (s *KeeperTestSuite) TestFailCreateGroup() { { name: "over max group size", input: &types.MsgCreateGroup{ - Members: []string{"band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", testapp.Alice.Address.String()}, + Members: []string{"band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", bandtesting.Alice.Address.String()}, Threshold: 1, Authority: s.authority.String(), }, @@ -272,7 +272,7 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { req, err = types.NewMsgRequestSignature( tsstypes.NewTextSignatureOrder([]byte("msg")), sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), - testapp.FeePayer.Address, + bandtesting.FeePayer.Address, ) s.Require().NoError(err) }, @@ -297,7 +297,7 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { req, err = types.NewMsgRequestSignature( tsstypes.NewTextSignatureOrder([]byte("msg")), sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), - testapp.FeePayer.Address, + bandtesting.FeePayer.Address, ) s.Require().NoError(err) }, @@ -312,7 +312,7 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { req, err = types.NewMsgRequestSignature( tsstypes.NewTextSignatureOrder([]byte("msg")), sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), - testapp.FeePayer.Address, + bandtesting.FeePayer.Address, ) }, func() {}, @@ -324,7 +324,7 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { s.Run(fmt.Sprintf("Case %s", tc.Msg), func() { tc.Malleate() - balancesBefore := s.app.BankKeeper.GetAllBalances(ctx, testapp.FeePayer.Address) + balancesBefore := s.app.BankKeeper.GetAllBalances(ctx, bandtesting.FeePayer.Address) balancesModuleBefore := s.app.BankKeeper.GetAllBalances( ctx, s.app.BandtssKeeper.GetBandtssAccount(ctx).GetAddress(), @@ -333,7 +333,7 @@ func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { _, err := msgSrvr.RequestSignature(ctx, req) s.Require().ErrorIs(tc.ExpectedErr, err) - balancesAfter := s.app.BankKeeper.GetAllBalances(ctx, testapp.FeePayer.Address) + balancesAfter := s.app.BankKeeper.GetAllBalances(ctx, bandtesting.FeePayer.Address) balancesModuleAfter := s.app.BankKeeper.GetAllBalances( ctx, s.app.BandtssKeeper.GetBandtssAccount(ctx).GetAddress(), @@ -359,7 +359,7 @@ func (s *KeeperTestSuite) TestSuccessRequestSignatureReq() { for _, signing := range tc.Signings { k.SetCurrentGroupID(ctx, tc.Group.ID) - balancesBefore := s.app.BankKeeper.GetAllBalances(ctx, testapp.FeePayer.Address) + balancesBefore := s.app.BankKeeper.GetAllBalances(ctx, bandtesting.FeePayer.Address) balancesModuleBefore := s.app.BankKeeper.GetAllBalances( ctx, s.app.BandtssKeeper.GetBandtssAccount(ctx).GetAddress(), @@ -368,7 +368,7 @@ func (s *KeeperTestSuite) TestSuccessRequestSignatureReq() { msg, err := types.NewMsgRequestSignature( tsstypes.NewTextSignatureOrder(signing.Data), sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), - testapp.FeePayer.Address, + bandtesting.FeePayer.Address, ) s.Require().NoError(err) @@ -376,7 +376,7 @@ func (s *KeeperTestSuite) TestSuccessRequestSignatureReq() { s.Require().NoError(err) // Fee should be paid after requesting signature - balancesAfter := s.app.BankKeeper.GetAllBalances(ctx, testapp.FeePayer.Address) + balancesAfter := s.app.BankKeeper.GetAllBalances(ctx, bandtesting.FeePayer.Address) balancesModuleAfter := s.app.BankKeeper.GetAllBalances( ctx, s.app.BandtssKeeper.GetBandtssAccount(ctx).GetAddress(), diff --git a/x/bandtss/keeper/signing_test.go b/x/bandtss/keeper/signing_test.go index 253d3a328..912424df9 100644 --- a/x/bandtss/keeper/signing_test.go +++ b/x/bandtss/keeper/signing_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" "github.com/bandprotocol/chain/v2/pkg/tss" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/bandtss/testutil" "github.com/bandprotocol/chain/v2/x/bandtss/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" @@ -63,7 +63,7 @@ func TestHandleCreateSigning(t *testing.T) { ).Return(expectCurrentGroupSigning, nil) s.MockBankKeeper.EXPECT().SendCoinsFromAccountToModule( ctx, - testapp.Alice.Address, + bandtesting.Alice.Address, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("uband", 20)), ).Return(nil) @@ -79,12 +79,12 @@ func TestHandleCreateSigning(t *testing.T) { require.Equal(t, types.Signing{ ID: types.SigningID(1), Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), - Requester: testapp.Alice.Address.String(), + Requester: bandtesting.Alice.Address.String(), CurrentGroupSigningID: tss.SigningID(1), ReplacingGroupSigningID: tss.SigningID(0), }, bandtssSigning) }, - input: input{sender: testapp.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, + input: input{sender: bandtesting.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, postProcess: func() { k.SetSigningCount(ctx, 0) k.DeleteSigningIDMapping(ctx, tss.SigningID(1)) @@ -172,7 +172,7 @@ func TestHandleCreateSigning(t *testing.T) { ).Return(expectReplaceGroupSigning, nil) s.MockBankKeeper.EXPECT().SendCoinsFromAccountToModule( ctx, - testapp.Alice.Address, + bandtesting.Alice.Address, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("uband", 20)), ).Return(nil) @@ -190,12 +190,12 @@ func TestHandleCreateSigning(t *testing.T) { require.Equal(t, types.Signing{ ID: types.SigningID(1), Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), - Requester: testapp.Alice.Address.String(), + Requester: bandtesting.Alice.Address.String(), CurrentGroupSigningID: tss.SigningID(2), ReplacingGroupSigningID: tss.SigningID(3), }, bandtssSigning) }, - input: input{sender: testapp.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, + input: input{sender: bandtesting.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, postProcess: func() { k.SetReplacement(ctx, types.Replacement{}) k.SetSigningCount(ctx, 0) @@ -227,7 +227,7 @@ func TestHandleCreateSigning(t *testing.T) { ).Return(expectCurrentGroupSigning, nil) s.MockBankKeeper.EXPECT().SendCoinsFromAccountToModule( ctx, - testapp.Alice.Address, + bandtesting.Alice.Address, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("uband", 20)), ).Return(nil) @@ -243,12 +243,12 @@ func TestHandleCreateSigning(t *testing.T) { require.Equal(t, types.Signing{ ID: types.SigningID(1), Fee: sdk.NewCoins(sdk.NewInt64Coin("uband", 10)), - Requester: testapp.Alice.Address.String(), + Requester: bandtesting.Alice.Address.String(), CurrentGroupSigningID: tss.SigningID(4), ReplacingGroupSigningID: tss.SigningID(0), }, bandtssSigning) }, - input: input{sender: testapp.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, + input: input{sender: bandtesting.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, postProcess: func() { k.SetReplacement(ctx, types.Replacement{}) k.SetSigningCount(ctx, 0) @@ -260,7 +260,7 @@ func TestHandleCreateSigning(t *testing.T) { name: "error no active group", preProcess: func() { k.SetCurrentGroupID(ctx, 0) }, postProcess: func() { k.SetCurrentGroupID(ctx, currentGroupID) }, - input: input{sender: testapp.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, + input: input{sender: bandtesting.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, expectErr: types.ErrNoActiveGroup, }, { @@ -275,7 +275,7 @@ func TestHandleCreateSigning(t *testing.T) { err := k.SetParams(ctx, params) require.NoError(t, err) }, - input: input{sender: testapp.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, + input: input{sender: bandtesting.Alice.Address, feeLimit: sdk.NewCoins(sdk.NewInt64Coin("uband", 100))}, expectErr: types.ErrFeeExceedsLimit, }, } diff --git a/x/bandtss/keeper/validator_test.go b/x/bandtss/keeper/validator_test.go index 9019b7a58..4e6861dea 100644 --- a/x/bandtss/keeper/validator_test.go +++ b/x/bandtss/keeper/validator_test.go @@ -10,7 +10,7 @@ import ( minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/bandtss/keeper" "github.com/bandprotocol/chain/v2/x/bandtss/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" @@ -21,26 +21,26 @@ var Coins1000000uband = sdk.NewCoins(sdk.NewInt64Coin("uband", 1000000)) func defaultVotes() []abci.VoteInfo { return []abci.VoteInfo{{ Validator: abci.Validator{ - Address: testapp.Validators[0].PubKey.Address(), + Address: bandtesting.Validators[0].PubKey.Address(), Power: 70, }, SignedLastBlock: true, }, { Validator: abci.Validator{ - Address: testapp.Validators[1].PubKey.Address(), + Address: bandtesting.Validators[1].PubKey.Address(), Power: 20, }, SignedLastBlock: true, }, { Validator: abci.Validator{ - Address: testapp.Validators[2].PubKey.Address(), + Address: bandtesting.Validators[2].PubKey.Address(), Power: 10, }, SignedLastBlock: true, }} } -func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper) (authtypes.ModuleAccountI, error) { +func SetupFeeCollector(app *bandtesting.TestingApp, ctx sdk.Context, k keeper.Keeper) (authtypes.ModuleAccountI, error) { // Set collected fee to 1000000uband and 50% tss reward proportion. feeCollector := app.AccountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) if err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, Coins1000000uband); err != nil { @@ -67,13 +67,13 @@ func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper } func (s *KeeperTestSuite) TestAllocateTokenNoActiveValidators() { - app, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(s.T(), false) feeCollector, err := SetupFeeCollector(app, ctx, *app.BandtssKeeper) s.Require().NoError(err) s.Require().Equal(Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // No active tss validators so nothing should happen. - k.AllocateTokens(ctx, defaultVotes()) + app.OracleKeeper.AllocateTokens(ctx, defaultVotes()) distAccount := app.AccountKeeper.GetModuleAccount(ctx, disttypes.ModuleName) s.Require().Equal(Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) @@ -81,14 +81,14 @@ func (s *KeeperTestSuite) TestAllocateTokenNoActiveValidators() { } func (s *KeeperTestSuite) TestAllocateTokensOneActive() { - app, ctx, _ := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(s.T(), false) tssKeeper, k := app.TSSKeeper, app.BandtssKeeper feeCollector, err := SetupFeeCollector(app, ctx, *k) s.Require().NoError(err) s.Require().Equal(Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // From 50% of fee, 1% should go to community pool, the rest goes to the only active validator. - err = tssKeeper.HandleSetDEs(ctx, testapp.Validators[1].Address, []tsstypes.DE{ + err = tssKeeper.HandleSetDEs(ctx, bandtesting.Validators[1].Address, []tsstypes.DE{ { PubD: testutil.HexDecode("dddd"), PubE: testutil.HexDecode("eeee"), @@ -96,7 +96,7 @@ func (s *KeeperTestSuite) TestAllocateTokensOneActive() { }) s.Require().NoError(err) - for _, validator := range testapp.Validators { + for _, validator := range bandtesting.Validators { err := k.AddNewMember(ctx, validator.Address) s.Require().NoError(err) } @@ -116,12 +116,12 @@ func (s *KeeperTestSuite) TestAllocateTokensOneActive() { sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(10000)}}, app.DistrKeeper.GetFeePool(ctx).CommunityPool, ) - s.Require().Empty(app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress)) + s.Require().Empty(app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress)) s.Require().Equal( sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(490000)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) - s.Require().Empty(app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[2].ValAddress)) + s.Require().Empty(app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[2].ValAddress)) } func (s *KeeperTestSuite) TestAllocateTokensAllActive() { @@ -131,7 +131,7 @@ func (s *KeeperTestSuite) TestAllocateTokensAllActive() { s.Require().NoError(err) s.Require().Equal(Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) - for _, validator := range testapp.Validators { + for _, validator := range bandtesting.Validators { err := k.AddNewMember(ctx, validator.Address) s.Require().NoError(err) deCount := s.app.TSSKeeper.GetDECount(ctx, validator.Address) @@ -156,22 +156,22 @@ func (s *KeeperTestSuite) TestAllocateTokensAllActive() { ) s.Require().Equal( sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(343000)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress).Rewards, ) s.Require().Equal( sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(98000)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) s.Require().Equal( sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(49000)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[2].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[2].ValAddress).Rewards, ) } func (s *KeeperTestSuite) TestHandleInactiveValidators() { ctx, k := s.ctx, s.app.BandtssKeeper s.SetupGroup(tsstypes.GROUP_STATUS_ACTIVE) - address := testapp.Validators[0].Address + address := bandtesting.Validators[0].Address member := types.Member{ Address: address.String(), diff --git a/x/globalfee/feechecker/feechecker_test.go b/x/globalfee/feechecker/feechecker_test.go index d7783a95e..8a56f8ee7 100644 --- a/x/globalfee/feechecker/feechecker_test.go +++ b/x/globalfee/feechecker/feechecker_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/suite" "github.com/bandprotocol/chain/v2/pkg/tss" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/globalfee/feechecker" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" @@ -62,19 +62,20 @@ type FeeCheckerTestSuite struct { } func (suite *FeeCheckerTestSuite) SetupTest() { - app, ctx, oracleKeeper := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(suite.T(), true) + suite.ctx = ctx.WithBlockHeight(999). WithIsCheckTx(true). WithMinGasPrices(sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(1, 4)}}) - err := oracleKeeper.GrantReporter(suite.ctx, testapp.Validators[0].ValAddress, testapp.Alice.Address) + err := app.OracleKeeper.GrantReporter(suite.ctx, bandtesting.Validators[0].ValAddress, bandtesting.Alice.Address) suite.Require().NoError(err) expiration := ctx.BlockTime().Add(1000 * time.Hour) err = app.AuthzKeeper.SaveGrant( ctx, - testapp.Alice.Address, - testapp.Validators[0].Address, + bandtesting.Alice.Address, + bandtesting.Validators[0].Address, authz.NewGenericAuthorization( sdk.MsgTypeURL(&tsstypes.MsgSubmitDEs{}), ), @@ -85,24 +86,24 @@ func (suite *FeeCheckerTestSuite) SetupTest() { req := oracletypes.NewRequest( 1, BasicCalldata, - []sdk.ValAddress{testapp.Validators[0].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress}, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", nil, nil, 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ) - suite.requestID = oracleKeeper.AddRequest(suite.ctx, req) + suite.requestID = app.OracleKeeper.AddRequest(suite.ctx, req) suite.FeeChecker = feechecker.NewFeeChecker( &app.AuthzKeeper, - &oracleKeeper, + &app.OracleKeeper, &app.GlobalfeeKeeper, app.StakingKeeper, app.TSSKeeper, @@ -110,6 +111,185 @@ func (suite *FeeCheckerTestSuite) SetupTest() { ) } +func (suite *FeeCheckerTestSuite) TestValidRawReport() { + msgs := []sdk.Msg{ + oracletypes.NewMsgReportData(suite.requestID, []oracletypes.RawReport{}, bandtesting.Validators[0].ValAddress), + } + stubTx := &StubTx{Msgs: msgs} + + // test - check report tx + isReportTx := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, msgs[0]) + suite.Require().True(isReportTx) + + // test - check tx fee with min gas prices + fee, priority, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + suite.Require().NoError(err) + suite.Require().Equal(sdk.Coins{}, fee) + suite.Require().Equal(int64(math.MaxInt64), priority) +} + +func (suite *FeeCheckerTestSuite) TestNotValidRawReport() { + msgs := []sdk.Msg{oracletypes.NewMsgReportData(1, []oracletypes.RawReport{}, bandtesting.Alice.ValAddress)} + stubTx := &StubTx{Msgs: msgs} + + // test - check report tx + isReportTx := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, msgs[0]) + suite.Require().False(isReportTx) + + // test - check tx fee with min gas prices + _, _, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + suite.Require().Error(err) +} + +func (suite *FeeCheckerTestSuite) TestValidReport() { + reportMsgs := []sdk.Msg{ + oracletypes.NewMsgReportData(suite.requestID, []oracletypes.RawReport{}, bandtesting.Validators[0].ValAddress), + } + authzMsg := authz.NewMsgExec(bandtesting.Alice.Address, reportMsgs) + stubTx := &StubTx{Msgs: []sdk.Msg{&authzMsg}} + + // test - check bypass min fee + isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, reportMsgs[0]) + suite.Require().True(isBypassMinFeeMsg) + + // test - check tx fee with min gas prices + fee, priority, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + suite.Require().NoError(err) + suite.Require().Equal(sdk.Coins{}, fee) + suite.Require().Equal(int64(math.MaxInt64), priority) +} + +func (suite *FeeCheckerTestSuite) TestNoAuthzReport() { + reportMsgs := []sdk.Msg{ + oracletypes.NewMsgReportData(suite.requestID, []oracletypes.RawReport{}, bandtesting.Validators[0].ValAddress), + } + authzMsg := authz.NewMsgExec(bandtesting.Bob.Address, reportMsgs) + stubTx := &StubTx{Msgs: []sdk.Msg{&authzMsg}, GasPrices: sdk.NewDecCoins(sdk.NewDecCoin("uband", sdk.NewInt(1)))} + + // test - check bypass min fee + isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, &authzMsg) + suite.Require().False(isBypassMinFeeMsg) + + // test - check tx fee with min gas prices + _, _, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + suite.Require().NoError(err) +} + +func (suite *FeeCheckerTestSuite) TestNotValidReport() { + reportMsgs := []sdk.Msg{ + oracletypes.NewMsgReportData(suite.requestID+1, []oracletypes.RawReport{}, bandtesting.Validators[0].ValAddress), + } + authzMsg := authz.NewMsgExec(bandtesting.Alice.Address, reportMsgs) + stubTx := &StubTx{Msgs: []sdk.Msg{&authzMsg}} + + // test - check bypass min fee + isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, &authzMsg) + suite.Require().False(isBypassMinFeeMsg) + + // test - check tx fee with min gas prices + _, _, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + suite.Require().Error(err) +} + +func (suite *FeeCheckerTestSuite) TestNotReportMsg() { + requestMsg := oracletypes.NewMsgRequestData( + 1, + BasicCalldata, + 1, + 1, + BasicClientID, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, + 0, + 0, + ) + stubTx := &StubTx{ + Msgs: []sdk.Msg{requestMsg}, + GasPrices: sdk.NewDecCoins( + sdk.NewDecCoinFromDec("uaaaa", sdk.NewDecWithPrec(100, 3)), + sdk.NewDecCoinFromDec("uaaab", sdk.NewDecWithPrec(1, 3)), + sdk.NewDecCoinFromDec("uaaac", sdk.NewDecWithPrec(0, 3)), + sdk.NewDecCoinFromDec("uband", sdk.NewDecWithPrec(3, 3)), + sdk.NewDecCoinFromDec("uccca", sdk.NewDecWithPrec(0, 3)), + sdk.NewDecCoinFromDec("ucccb", sdk.NewDecWithPrec(1, 3)), + sdk.NewDecCoinFromDec("ucccc", sdk.NewDecWithPrec(100, 3)), + ), + } + + // test - check bypass min fee + isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, requestMsg) + suite.Require().False(isBypassMinFeeMsg) + + // test - check tx fee with min gas prices + fee, priority, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + suite.Require().NoError(err) + suite.Require().Equal(stubTx.GetFee(), fee) + suite.Require().Equal(int64(30), priority) +} + +func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameAuthzMsgs() { + reportMsg := oracletypes.NewMsgReportData(suite.requestID, []oracletypes.RawReport{}, bandtesting.Validators[0].ValAddress) + requestMsg := oracletypes.NewMsgRequestData( + 1, + BasicCalldata, + 1, + 1, + BasicClientID, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, + 0, + 0, + ) + msgs := []sdk.Msg{reportMsg, requestMsg} + authzMsg := authz.NewMsgExec(bandtesting.Alice.Address, msgs) + stubTx := &StubTx{Msgs: []sdk.Msg{&authzMsg}, GasPrices: sdk.NewDecCoins(sdk.NewDecCoin("uband", sdk.NewInt(1)))} + + // test - check bypass min fee + isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, &authzMsg) + suite.Require().False(isBypassMinFeeMsg) + + // test - check tx fee with min gas prices + fee, priority, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + suite.Require().NoError(err) + suite.Require().Equal(stubTx.GetFee(), fee) + suite.Require().Equal(int64(10000), priority) +} + +func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameTx() { + reportMsg := oracletypes.NewMsgReportData(suite.requestID, []oracletypes.RawReport{}, bandtesting.Validators[0].ValAddress) + requestMsg := oracletypes.NewMsgRequestData( + 1, + BasicCalldata, + 1, + 1, + BasicClientID, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, + 0, + 0, + ) + stubTx := &StubTx{ + Msgs: []sdk.Msg{reportMsg, requestMsg}, + GasPrices: sdk.NewDecCoins(sdk.NewDecCoin("uband", sdk.NewInt(1))), + } + + // test - check bypass min fee + isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, requestMsg) + suite.Require().False(isBypassMinFeeMsg) + + // test - check tx fee with min gas prices + fee, priority, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + suite.Require().NoError(err) + suite.Require().Equal(stubTx.GetFee(), fee) + suite.Require().Equal(int64(10000), priority) +} + func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPrices() { testCases := []struct { name string @@ -127,7 +307,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri oracletypes.NewMsgReportData( suite.requestID, []oracletypes.RawReport{}, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ), }, } @@ -152,7 +332,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri PubE: privE.Point(), }, }, - Address: testapp.Validators[0].Address.String(), + Address: bandtesting.Validators[0].Address.String(), }, }, } @@ -190,7 +370,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri privD, _ := tss.GenerateSigningNonce([]byte{}) privE, _ := tss.GenerateSigningNonce([]byte{}) - msgExec := authz.NewMsgExec(testapp.Alice.Address, []sdk.Msg{ + msgExec := authz.NewMsgExec(bandtesting.Alice.Address, []sdk.Msg{ &tsstypes.MsgSubmitDEs{ DEs: []tsstypes.DE{ { @@ -198,7 +378,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri PubE: privE.Point(), }, }, - Address: testapp.Validators[0].Address.String(), + Address: bandtesting.Validators[0].Address.String(), }, }) @@ -219,7 +399,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri privD, _ := tss.GenerateSigningNonce([]byte{}) privE, _ := tss.GenerateSigningNonce([]byte{}) - msgExec := authz.NewMsgExec(testapp.Bob.Address, []sdk.Msg{ + msgExec := authz.NewMsgExec(bandtesting.Bob.Address, []sdk.Msg{ &tsstypes.MsgSubmitDEs{ DEs: []tsstypes.DE{ { @@ -227,7 +407,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri PubE: privE.Point(), }, }, - Address: testapp.Validators[0].Address.String(), + Address: bandtesting.Validators[0].Address.String(), }, }) @@ -245,11 +425,11 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri { name: "valid MsgReportData in valid MsgExec", stubTx: func() *StubTx { - msgExec := authz.NewMsgExec(testapp.Alice.Address, []sdk.Msg{ + msgExec := authz.NewMsgExec(bandtesting.Alice.Address, []sdk.Msg{ oracletypes.NewMsgReportData( suite.requestID, []oracletypes.RawReport{}, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ), }) @@ -269,7 +449,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri stubTx: func() *StubTx { return &StubTx{ Msgs: []sdk.Msg{ - oracletypes.NewMsgReportData(1, []oracletypes.RawReport{}, testapp.Alice.ValAddress), + oracletypes.NewMsgReportData(1, []oracletypes.RawReport{}, bandtesting.Alice.ValAddress), }, } }, @@ -281,11 +461,11 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri { name: "invalid MsgReportData in valid MsgExec with not enough fee", stubTx: func() *StubTx { - msgExec := authz.NewMsgExec(testapp.Alice.Address, []sdk.Msg{ + msgExec := authz.NewMsgExec(bandtesting.Alice.Address, []sdk.Msg{ oracletypes.NewMsgReportData( suite.requestID+1, []oracletypes.RawReport{}, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ), }) @@ -303,11 +483,11 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri { name: "valid MsgReportData in invalid MsgExec with enough fee", stubTx: func() *StubTx { - msgExec := authz.NewMsgExec(testapp.Bob.Address, []sdk.Msg{ + msgExec := authz.NewMsgExec(bandtesting.Bob.Address, []sdk.Msg{ oracletypes.NewMsgReportData( suite.requestID, []oracletypes.RawReport{}, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ), }) @@ -332,10 +512,10 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ) @@ -370,7 +550,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri msgReportData := oracletypes.NewMsgReportData( suite.requestID, []oracletypes.RawReport{}, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ) msgRequestData := oracletypes.NewMsgRequestData( 1, @@ -378,15 +558,15 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ) msgs := []sdk.Msg{msgReportData, msgRequestData} - authzMsg := authz.NewMsgExec(testapp.Alice.Address, msgs) + authzMsg := authz.NewMsgExec(bandtesting.Alice.Address, msgs) return &StubTx{ Msgs: []sdk.Msg{&authzMsg}, @@ -406,7 +586,7 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri msgReportData := oracletypes.NewMsgReportData( suite.requestID, []oracletypes.RawReport{}, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ) msgRequestData := oracletypes.NewMsgRequestData( 1, @@ -414,10 +594,10 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ) diff --git a/x/oracle/abci_test.go b/x/oracle/abci_test.go index cc224375c..54358610b 100644 --- a/x/oracle/abci_test.go +++ b/x/oracle/abci_test.go @@ -11,7 +11,7 @@ import ( minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" ) func fromHex(hexStr string) []byte { @@ -23,12 +23,14 @@ func fromHex(hexStr string) []byte { } func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + votes := []abci.VoteInfo{{ - Validator: abci.Validator{Address: testapp.Validators[0].PubKey.Address(), Power: 70}, + Validator: abci.Validator{Address: bandtesting.Validators[0].PubKey.Address(), Power: 70}, SignedLastBlock: true, }, { - Validator: abci.Validator{Address: testapp.Validators[1].PubKey.Address(), Power: 30}, + Validator: abci.Validator{Address: bandtesting.Validators[1].PubKey.Address(), Power: 30}, SignedLastBlock: true, }} // Set collected fee to 100uband + 70% oracle reward proportion + disable minting inflation. @@ -73,7 +75,7 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress()), ) // 1 validator active, begin block should take 70% of the fee. 2% of that goes to comm pool. - err = k.Activate(ctx, testapp.Validators[1].ValAddress) + err = k.Activate(ctx, bandtesting.Validators[1].ValAddress) require.NoError(t, err) app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), @@ -96,15 +98,15 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { app.DistrKeeper.GetFeePool(ctx).CommunityPool, ) // 0uband - require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress)) + require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress)) // 100*70%*98% = 68.6uband require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(686, 1)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) // 2 validators active now. 70% of the remaining fee pool will be split 3 ways (comm pool + val1 + val2). - err = k.Activate(ctx, testapp.Validators[0].ValAddress) + err = k.Activate(ctx, bandtesting.Validators[0].ValAddress) require.NoError(t, err) app.BeginBlocker(ctx, abci.RequestBeginBlock{ @@ -131,16 +133,16 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(14406, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress).Rewards, ) // 68.6uband + 30*70%*98%*30% = 74.774uband require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(74774, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) // 1 validator becomes in active, and will not get reward this time. - k.MissReport(ctx, testapp.Validators[1].ValAddress, testapp.ParseTime(100)) + k.MissReport(ctx, bandtesting.Validators[1].ValAddress, bandtesting.ParseTime(100)) app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), LastCommitInfo: abci.CommitInfo{Votes: votes}, @@ -165,24 +167,26 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(20286, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress).Rewards, ) // 74.774uband require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(74774, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) } func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + ctx = ctx.WithBlockHeight(10) // Set block height to ensure distr's AllocateTokens gets called. votes := []abci.VoteInfo{{ - Validator: abci.Validator{Address: testapp.Validators[0].PubKey.Address(), Power: 70}, + Validator: abci.Validator{Address: bandtesting.Validators[0].PubKey.Address(), Power: 70}, SignedLastBlock: true, }, { - Validator: abci.Validator{Address: testapp.Validators[1].PubKey.Address(), Power: 30}, + Validator: abci.Validator{Address: bandtesting.Validators[1].PubKey.Address(), Power: 30}, SignedLastBlock: true, }} @@ -210,7 +214,7 @@ func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { err = k.SetParams(ctx, params) require.NoError(t, err) // Set block proposer to Validators[1], who will receive 5% bonus. - app.DistrKeeper.SetPreviousProposerConsAddr(ctx, testapp.Validators[1].Address.Bytes()) + app.DistrKeeper.SetPreviousProposerConsAddr(ctx, bandtesting.Validators[1].Address.Bytes()) require.Equal( t, sdk.NewCoins(sdk.NewInt64Coin("uband", 50)), @@ -230,7 +234,7 @@ func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { // Community pool: 0.7 + 0.3 = 1 // Validators[0]: 34.3 + 8.715 = 43.015 // Validators[1]: 2.25 + 3.735 = 5.985 - err = k.Activate(ctx, testapp.Validators[0].ValAddress) + err = k.Activate(ctx, bandtesting.Validators[0].ValAddress) require.NoError(t, err) app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), @@ -250,11 +254,11 @@ func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(44590, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress).Rewards, ) require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(4410, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) } diff --git a/x/oracle/app_test.go b/x/oracle/app_test.go index df8faba75..70461272f 100644 --- a/x/oracle/app_test.go +++ b/x/oracle/app_test.go @@ -9,13 +9,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestSuccessRequestOracleData(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper ctx = ctx.WithBlockHeight(4).WithBlockTime(time.Unix(1581589790, 0)) handler := oracle.NewHandler(k) @@ -26,9 +27,9 @@ func TestSuccessRequestOracleData(t *testing.T) { 2, "app_test", sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(9000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Validators[0].Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Validators[0].Address, 0, 0, ) @@ -40,13 +41,13 @@ func TestSuccessRequestOracleData(t *testing.T) { types.OracleScriptID(1), []byte("calldata"), []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, 2, 4, - testapp.ParseTime(1581589790), + bandtesting.ParseTime(1581589790), "app_test", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -54,10 +55,10 @@ func TestSuccessRequestOracleData(t *testing.T) { types.NewRawRequest(3, 3, []byte("beeb")), }, nil, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, 0, 0, - testapp.Validators[0].Address.String(), + bandtesting.Validators[0].Address.String(), nil, ) app.EndBlocker(ctx, abci.RequestEndBlock{Height: 4}) @@ -71,7 +72,7 @@ func TestSuccessRequestOracleData(t *testing.T) { types.NewRawReport(2, 0, []byte("answer2")), types.NewRawReport(3, 0, []byte("answer3")), }, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ) res, err = handler(ctx, reportMsg1) require.NotNil(t, res) @@ -94,7 +95,7 @@ func TestSuccessRequestOracleData(t *testing.T) { types.NewRawReport(2, 0, []byte("answer2")), types.NewRawReport(3, 0, []byte("answer3")), }, - testapp.Validators[1].ValAddress, + bandtesting.Validators[1].ValAddress, ) res, err = handler(ctx, reportMsg2) require.NotNil(t, res) @@ -136,7 +137,8 @@ func TestSuccessRequestOracleData(t *testing.T) { } func TestExpiredRequestOracleData(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper ctx = ctx.WithBlockHeight(4).WithBlockTime(time.Unix(1581589790, 0)) handler := oracle.NewHandler(k) @@ -147,9 +149,9 @@ func TestExpiredRequestOracleData(t *testing.T) { 2, "app_test", sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(9000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Validators[0].Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Validators[0].Address, 0, 0, ) @@ -161,13 +163,13 @@ func TestExpiredRequestOracleData(t *testing.T) { types.OracleScriptID(1), []byte("calldata"), []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, 2, 4, - testapp.ParseTime(1581589790), + bandtesting.ParseTime(1581589790), "app_test", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -175,10 +177,10 @@ func TestExpiredRequestOracleData(t *testing.T) { types.NewRawRequest(3, 3, []byte("beeb")), }, nil, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, 0, 0, - testapp.Validators[0].Address.String(), + bandtesting.Validators[0].Address.String(), nil, ) app.EndBlocker(ctx, abci.RequestEndBlock{Height: 4}) @@ -211,7 +213,7 @@ func TestExpiredRequestOracleData(t *testing.T) { Attributes: []abci.EventAttribute{ { Key: types.AttributeKeyValidator, - Value: fmt.Sprint(testapp.Validators[2].ValAddress.String()), + Value: fmt.Sprint(bandtesting.Validators[2].ValAddress.String()), }, }, }, { @@ -219,7 +221,7 @@ func TestExpiredRequestOracleData(t *testing.T) { Attributes: []abci.EventAttribute{ { Key: types.AttributeKeyValidator, - Value: fmt.Sprint(testapp.Validators[0].ValAddress.String()), + Value: fmt.Sprint(bandtesting.Validators[0].ValAddress.String()), }, }, }, { @@ -227,7 +229,7 @@ func TestExpiredRequestOracleData(t *testing.T) { Attributes: []abci.EventAttribute{ { Key: types.AttributeKeyValidator, - Value: fmt.Sprint(testapp.Validators[1].ValAddress.String()), + Value: fmt.Sprint(bandtesting.Validators[1].ValAddress.String()), }, }, }} diff --git a/x/oracle/handler_test.go b/x/oracle/handler_test.go index bf751be63..0f80972c1 100644 --- a/x/oracle/handler_test.go +++ b/x/oracle/handler_test.go @@ -16,17 +16,19 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/testing/testdata" "github.com/bandprotocol/chain/v2/x/oracle" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestCreateDataSourceSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + dsCount := k.GetDataSourceCount(ctx) - treasury := testapp.Treasury.Address - owner := testapp.Owner.Address + treasury := bandtesting.Treasury.Address + owner := bandtesting.Owner.Address name := "data_source_1" description := "description" executable := []byte("executable") @@ -36,10 +38,10 @@ func TestCreateDataSourceSuccess(t *testing.T) { name, description, executable, - testapp.EmptyCoins, + bandtesting.EmptyCoins, treasury, owner, - testapp.Alice.Address, + bandtesting.Alice.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) @@ -47,7 +49,7 @@ func TestCreateDataSourceSuccess(t *testing.T) { require.NoError(t, err) require.Equal( t, - types.NewDataSource(testapp.Owner.Address, name, description, filename, testapp.EmptyCoins, treasury), + types.NewDataSource(bandtesting.Owner.Address, name, description, filename, bandtesting.EmptyCoins, treasury), ds, ) event := abci.Event{ @@ -60,9 +62,11 @@ func TestCreateDataSourceSuccess(t *testing.T) { } func TestCreateGzippedExecutableDataSourceFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - treasury := testapp.Treasury.Address - owner := testapp.Owner.Address + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + treasury := bandtesting.Treasury.Address + owner := bandtesting.Owner.Address name := "data_source_1" description := "description" executable := []byte("executable") @@ -71,12 +75,12 @@ func TestCreateGzippedExecutableDataSourceFail(t *testing.T) { _, err := zw.Write(executable) require.NoError(t, err) zw.Close() - sender := testapp.Alice.Address + sender := bandtesting.Alice.Address msg := types.NewMsgCreateDataSource( name, description, buf.Bytes()[:5], - testapp.EmptyCoins, + bandtesting.EmptyCoins, treasury, owner, sender, @@ -87,7 +91,9 @@ func TestCreateGzippedExecutableDataSourceFail(t *testing.T) { } func TestEditDataSourceSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + newName := "beeb" newDescription := "new_description" newExecutable := []byte("executable2") @@ -98,10 +104,10 @@ func TestEditDataSourceSuccess(t *testing.T) { newName, newDescription, newExecutable, - testapp.Coins1000000uband, - testapp.Treasury.Address, - testapp.Alice.Address, - testapp.Owner.Address, + bandtesting.Coins1000000uband, + bandtesting.Treasury.Address, + bandtesting.Alice.Address, + bandtesting.Owner.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) @@ -110,12 +116,12 @@ func TestEditDataSourceSuccess(t *testing.T) { require.Equal( t, types.NewDataSource( - testapp.Alice.Address, + bandtesting.Alice.Address, newName, newDescription, newFilename, - testapp.Coins1000000uband, - testapp.Treasury.Address, + bandtesting.Coins1000000uband, + bandtesting.Treasury.Address, ), ds, ) @@ -127,7 +133,9 @@ func TestEditDataSourceSuccess(t *testing.T) { } func TestEditDataSourceFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + newName := "beeb" newDescription := "new_description" newExecutable := []byte("executable2") @@ -137,13 +145,13 @@ func TestEditDataSourceFail(t *testing.T) { newName, newDescription, newExecutable, - testapp.EmptyCoins, - testapp.Treasury.Address, - testapp.Owner.Address, - testapp.Owner.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, + bandtesting.Owner.Address, + bandtesting.Owner.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) - testapp.CheckErrorf(t, err, types.ErrDataSourceNotFound, "id: 42") + bandtesting.CheckErrorf(t, err, types.ErrDataSourceNotFound, "id: 42") require.Nil(t, res) // Not owner msg = types.NewMsgEditDataSource( @@ -151,10 +159,10 @@ func TestEditDataSourceFail(t *testing.T) { newName, newDescription, newExecutable, - testapp.EmptyCoins, - testapp.Treasury.Address, - testapp.Owner.Address, - testapp.Bob.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, + bandtesting.Owner.Address, + bandtesting.Bob.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrEditorNotAuthorized) @@ -170,10 +178,10 @@ func TestEditDataSourceFail(t *testing.T) { newName, newDescription, buf.Bytes()[:5], - testapp.EmptyCoins, - testapp.Treasury.Address, - testapp.Owner.Address, - testapp.Owner.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, + bandtesting.Owner.Address, + bandtesting.Owner.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrUncompressionFailed) @@ -181,7 +189,9 @@ func TestEditDataSourceFail(t *testing.T) { } func TestCreateOracleScriptSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + osCount := k.GetOracleScriptCount(ctx) name := "os_1" description := "beeb" @@ -194,8 +204,8 @@ func TestCreateOracleScriptSuccess(t *testing.T) { schema, url, code, - testapp.Owner.Address, - testapp.Alice.Address, + bandtesting.Owner.Address, + bandtesting.Alice.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) @@ -203,7 +213,14 @@ func TestCreateOracleScriptSuccess(t *testing.T) { require.NoError(t, err) require.Equal( t, - types.NewOracleScript(testapp.Owner.Address, name, description, testdata.WasmExtra1FileName, schema, url), + types.NewOracleScript( + bandtesting.Owner.Address, + name, + description, + testdata.WasmExtra1FileName, + schema, + url, + ), os, ) @@ -217,7 +234,9 @@ func TestCreateOracleScriptSuccess(t *testing.T) { } func TestCreateGzippedOracleScriptSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + osCount := k.GetOracleScriptCount(ctx) name := "os_1" description := "beeb" @@ -234,8 +253,8 @@ func TestCreateGzippedOracleScriptSuccess(t *testing.T) { schema, url, buf.Bytes(), - testapp.Owner.Address, - testapp.Alice.Address, + bandtesting.Owner.Address, + bandtesting.Alice.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) @@ -243,7 +262,14 @@ func TestCreateGzippedOracleScriptSuccess(t *testing.T) { require.NoError(t, err) require.Equal( t, - types.NewOracleScript(testapp.Owner.Address, name, description, testdata.WasmExtra1FileName, schema, url), + types.NewOracleScript( + bandtesting.Owner.Address, + name, + description, + testdata.WasmExtra1FileName, + schema, + url, + ), os, ) @@ -257,7 +283,9 @@ func TestCreateGzippedOracleScriptSuccess(t *testing.T) { } func TestCreateOracleScriptFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + name := "os_1" description := "beeb" schema := "schema" @@ -269,11 +297,11 @@ func TestCreateOracleScriptFail(t *testing.T) { schema, url, []byte("BAD"), - testapp.Owner.Address, - testapp.Alice.Address, + bandtesting.Owner.Address, + bandtesting.Alice.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) - testapp.CheckErrorf(t, err, types.ErrOwasmCompilation, "caused by %s", api.ErrValidation) + bandtesting.CheckErrorf(t, err, types.ErrOwasmCompilation, "caused by %s", api.ErrValidation) require.Nil(t, res) // Bad Gzip var buf bytes.Buffer @@ -287,8 +315,8 @@ func TestCreateOracleScriptFail(t *testing.T) { schema, url, buf.Bytes()[:5], - testapp.Owner.Address, - testapp.Alice.Address, + bandtesting.Owner.Address, + bandtesting.Alice.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrUncompressionFailed) @@ -296,7 +324,9 @@ func TestCreateOracleScriptFail(t *testing.T) { } func TestEditOracleScriptSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + newName := "os_2" newDescription := "beebbeeb" newCode := testdata.WasmExtra2 @@ -309,8 +339,8 @@ func TestEditOracleScriptSuccess(t *testing.T) { newSchema, newURL, newCode, - testapp.Alice.Address, - testapp.Owner.Address, + bandtesting.Alice.Address, + bandtesting.Owner.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) @@ -319,7 +349,7 @@ func TestEditOracleScriptSuccess(t *testing.T) { require.Equal( t, types.NewOracleScript( - testapp.Alice.Address, + bandtesting.Alice.Address, newName, newDescription, testdata.WasmExtra2FileName, @@ -337,7 +367,9 @@ func TestEditOracleScriptSuccess(t *testing.T) { } func TestEditOracleScriptFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + newName := "os_2" newDescription := "beebbeeb" newCode := testdata.WasmExtra2 @@ -351,11 +383,11 @@ func TestEditOracleScriptFail(t *testing.T) { newSchema, newURL, newCode, - testapp.Owner.Address, - testapp.Owner.Address, + bandtesting.Owner.Address, + bandtesting.Owner.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) - testapp.CheckErrorf(t, err, types.ErrOracleScriptNotFound, "id: 999") + bandtesting.CheckErrorf(t, err, types.ErrOracleScriptNotFound, "id: 999") require.Nil(t, res) // Not owner msg = types.NewMsgEditOracleScript( @@ -365,8 +397,8 @@ func TestEditOracleScriptFail(t *testing.T) { newSchema, newURL, newCode, - testapp.Owner.Address, - testapp.Bob.Address, + bandtesting.Owner.Address, + bandtesting.Bob.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) require.EqualError(t, err, "editor not authorized") @@ -379,11 +411,11 @@ func TestEditOracleScriptFail(t *testing.T) { newSchema, newURL, []byte("BAD_CODE"), - testapp.Owner.Address, - testapp.Owner.Address, + bandtesting.Owner.Address, + bandtesting.Owner.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) - testapp.CheckErrorf(t, err, types.ErrOwasmCompilation, "caused by %s", api.ErrValidation) + bandtesting.CheckErrorf(t, err, types.ErrOwasmCompilation, "caused by %s", api.ErrValidation) require.Nil(t, res) // Bad Gzip var buf bytes.Buffer @@ -398,8 +430,8 @@ func TestEditOracleScriptFail(t *testing.T) { newSchema, newURL, buf.Bytes()[:5], - testapp.Owner.Address, - testapp.Owner.Address, + bandtesting.Owner.Address, + bandtesting.Owner.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrUncompressionFailed) @@ -407,18 +439,20 @@ func TestEditOracleScriptFail(t *testing.T) { } func TestRequestDataSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockHeight(124).WithBlockTime(testapp.ParseTime(1581589790)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockHeight(124).WithBlockTime(bandtesting.ParseTime(1581589790)) msg := types.NewMsgRequestData( 1, []byte("beeb"), 2, 2, "CID", - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ) @@ -427,10 +461,10 @@ func TestRequestDataSuccess(t *testing.T) { require.Equal(t, types.NewRequest( 1, []byte("beeb"), - []sdk.ValAddress{testapp.Validators[2].ValAddress, testapp.Validators[0].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[2].ValAddress, bandtesting.Validators[0].ValAddress}, 2, 124, - testapp.ParseTime(1581589790), + bandtesting.ParseTime(1581589790), "CID", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -438,16 +472,16 @@ func TestRequestDataSuccess(t *testing.T) { types.NewRawRequest(3, 3, []byte("beeb")), }, nil, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, 0, 0, - testapp.FeePayer.Address.String(), + bandtesting.FeePayer.Address.String(), sdk.NewCoins(sdk.NewInt64Coin("uband", 94000000)), ), k.MustGetRequest(ctx, 1)) event := abci.Event{ Type: authtypes.EventTypeCoinSpent, Attributes: []abci.EventAttribute{ - {Key: authtypes.AttributeKeySpender, Value: testapp.FeePayer.Address.String()}, + {Key: authtypes.AttributeKeySpender, Value: bandtesting.FeePayer.Address.String()}, {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } @@ -457,7 +491,7 @@ func TestRequestDataSuccess(t *testing.T) { event = abci.Event{ Type: authtypes.EventTypeCoinReceived, Attributes: []abci.EventAttribute{ - {Key: authtypes.AttributeKeyReceiver, Value: testapp.Treasury.Address.String()}, + {Key: authtypes.AttributeKeyReceiver, Value: bandtesting.Treasury.Address.String()}, {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } @@ -467,8 +501,8 @@ func TestRequestDataSuccess(t *testing.T) { event = abci.Event{ Type: authtypes.EventTypeTransfer, Attributes: []abci.EventAttribute{ - {Key: authtypes.AttributeKeyRecipient, Value: testapp.Treasury.Address.String()}, - {Key: authtypes.AttributeKeySender, Value: testapp.FeePayer.Address.String()}, + {Key: authtypes.AttributeKeyRecipient, Value: bandtesting.Treasury.Address.String()}, + {Key: authtypes.AttributeKeySender, Value: bandtesting.FeePayer.Address.String()}, {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } @@ -478,7 +512,7 @@ func TestRequestDataSuccess(t *testing.T) { event = abci.Event{ Type: sdk.EventTypeMessage, Attributes: []abci.EventAttribute{ - {Key: authtypes.AttributeKeySender, Value: testapp.FeePayer.Address.String()}, + {Key: authtypes.AttributeKeySender, Value: bandtesting.FeePayer.Address.String()}, }, } require.Equal(t, event, res.Events[3]) @@ -497,8 +531,8 @@ func TestRequestDataSuccess(t *testing.T) { {Key: types.AttributeKeyTSSGroupID, Value: "0"}, {Key: types.AttributeKeyGasUsed, Value: "5294700000"}, {Key: types.AttributeKeyTotalFees, Value: "6000000uband"}, - {Key: types.AttributeKeyValidator, Value: testapp.Validators[2].ValAddress.String()}, - {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[2].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[0].ValAddress.String()}, }, } require.Equal(t, event, res.Events[12]) @@ -506,7 +540,7 @@ func TestRequestDataSuccess(t *testing.T) { Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyDataSourceID, Value: "1"}, - {Key: types.AttributeKeyDataSourceHash, Value: testapp.DataSources[1].Filename}, + {Key: types.AttributeKeyDataSourceHash, Value: bandtesting.DataSources[1].Filename}, {Key: types.AttributeKeyExternalID, Value: "1"}, {Key: types.AttributeKeyCalldata, Value: "beeb"}, {Key: types.AttributeKeyFee, Value: "1000000uband"}, @@ -517,7 +551,7 @@ func TestRequestDataSuccess(t *testing.T) { Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyDataSourceID, Value: "2"}, - {Key: types.AttributeKeyDataSourceHash, Value: testapp.DataSources[2].Filename}, + {Key: types.AttributeKeyDataSourceHash, Value: bandtesting.DataSources[2].Filename}, {Key: types.AttributeKeyExternalID, Value: "2"}, {Key: types.AttributeKeyCalldata, Value: "beeb"}, {Key: types.AttributeKeyFee, Value: "1000000uband"}, @@ -528,7 +562,7 @@ func TestRequestDataSuccess(t *testing.T) { Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyDataSourceID, Value: "3"}, - {Key: types.AttributeKeyDataSourceHash, Value: testapp.DataSources[3].Filename}, + {Key: types.AttributeKeyDataSourceHash, Value: bandtesting.DataSources[3].Filename}, {Key: types.AttributeKeyExternalID, Value: "3"}, {Key: types.AttributeKeyCalldata, Value: "beeb"}, {Key: types.AttributeKeyFee, Value: "1000000uband"}, @@ -538,7 +572,9 @@ func TestRequestDataSuccess(t *testing.T) { } func TestRequestDataFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + // No active oracle validators res, err := oracle.NewHandler( k, @@ -550,19 +586,19 @@ func TestRequestDataFail(t *testing.T) { 2, 2, "CID", - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ), ) - testapp.CheckErrorf(t, err, types.ErrInsufficientValidators, "0 < 2") + bandtesting.CheckErrorf(t, err, types.ErrInsufficientValidators, "0 < 2") require.Nil(t, res) - err = k.Activate(ctx, testapp.Validators[0].ValAddress) + err = k.Activate(ctx, bandtesting.Validators[0].ValAddress) require.NoError(t, err) - err = k.Activate(ctx, testapp.Validators[1].ValAddress) + err = k.Activate(ctx, bandtesting.Validators[1].ValAddress) require.NoError(t, err) // Too large calldata res, err = oracle.NewHandler( @@ -575,15 +611,15 @@ func TestRequestDataFail(t *testing.T) { 2, 2, "CID", - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ), ) - testapp.CheckErrorf(t, err, types.ErrTooLargeCalldata, "got: 8000, max: 512") + bandtesting.CheckErrorf(t, err, types.ErrTooLargeCalldata, "got: 8000, max: 512") require.Nil(t, res) // Too high ask count res, err = oracle.NewHandler( @@ -596,15 +632,15 @@ func TestRequestDataFail(t *testing.T) { 3, 2, "CID", - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ), ) - testapp.CheckErrorf(t, err, types.ErrInsufficientValidators, "2 < 3") + bandtesting.CheckErrorf(t, err, types.ErrInsufficientValidators, "2 < 3") require.Nil(t, res) // Bad oracle script ID res, err = oracle.NewHandler( @@ -617,15 +653,15 @@ func TestRequestDataFail(t *testing.T) { 2, 2, "CID", - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ), ) - testapp.CheckErrorf(t, err, types.ErrOracleScriptNotFound, "id: 999") + bandtesting.CheckErrorf(t, err, types.ErrOracleScriptNotFound, "id: 999") require.Nil(t, res) // Pay not enough fee res, err = oracle.NewHandler( @@ -638,32 +674,34 @@ func TestRequestDataFail(t *testing.T) { 2, 2, "CID", - testapp.EmptyCoins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.EmptyCoins, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ), ) - testapp.CheckErrorf(t, err, types.ErrNotEnoughFee, "require: 2000000uband, max: 0uband") + bandtesting.CheckErrorf(t, err, types.ErrNotEnoughFee, "require: 2000000uband, max: 0uband") require.Nil(t, res) } func TestReportSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Set up a mock request asking 3 validators with min count 2. k.SetRequest(ctx, 42, types.NewRequest( 1, []byte("beeb"), []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[1].ValAddress, - testapp.Validators[0].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, }, 2, 124, - testapp.ParseTime(1581589790), + bandtesting.ParseTime(1581589790), "CID", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -673,32 +711,32 @@ func TestReportSuccess(t *testing.T) { 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) // Common raw reports for everyone. reports := []types.RawReport{types.NewRawReport(1, 0, []byte("data1")), types.NewRawReport(2, 0, []byte("data2"))} // Validators[0] reports data. - res, err := oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Validators[0].ValAddress)) + res, err := oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, bandtesting.Validators[0].ValAddress)) require.NoError(t, err) require.Equal(t, []types.RequestID{}, k.GetPendingResolveList(ctx)) event := abci.Event{ Type: types.EventTypeReport, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyID, Value: "42"}, - {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[0].ValAddress.String()}, }, } require.Equal(t, event, res.Events[0]) // Validators[1] reports data. Now the request should move to pending resolve. - res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Validators[1].ValAddress)) + res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, bandtesting.Validators[1].ValAddress)) require.NoError(t, err) require.Equal(t, []types.RequestID{42}, k.GetPendingResolveList(ctx)) event = abci.Event{ Type: types.EventTypeReport, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyID, Value: "42"}, - {Key: types.AttributeKeyValidator, Value: testapp.Validators[1].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[1].ValAddress.String()}, }, } require.Equal(t, event, res.Events[0]) @@ -707,44 +745,46 @@ func TestReportSuccess(t *testing.T) { k.ResolveSuccess( ctx, 42, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, []byte("RESOLVE_RESULT!"), 1234, 0, 0, ) - res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Validators[2].ValAddress)) + res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, bandtesting.Validators[2].ValAddress)) require.NoError(t, err) event = abci.Event{ Type: types.EventTypeReport, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyID, Value: "42"}, - {Key: types.AttributeKeyValidator, Value: testapp.Validators[2].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[2].ValAddress.String()}, }, } require.Equal(t, event, res.Events[0]) // Check the reports of this request. We should see 3 reports, with report from Validators[2] comes after resolve. finalReport := k.GetReports(ctx, 42) - require.Contains(t, finalReport, types.NewReport(testapp.Validators[0].ValAddress, true, reports)) - require.Contains(t, finalReport, types.NewReport(testapp.Validators[1].ValAddress, true, reports)) - require.Contains(t, finalReport, types.NewReport(testapp.Validators[2].ValAddress, false, reports)) + require.Contains(t, finalReport, types.NewReport(bandtesting.Validators[0].ValAddress, true, reports)) + require.Contains(t, finalReport, types.NewReport(bandtesting.Validators[1].ValAddress, true, reports)) + require.Contains(t, finalReport, types.NewReport(bandtesting.Validators[2].ValAddress, false, reports)) } func TestReportFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Set up a mock request asking 3 validators with min count 2. k.SetRequest(ctx, 42, types.NewRequest( 1, []byte("beeb"), []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[1].ValAddress, - testapp.Validators[0].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, }, 2, 124, - testapp.ParseTime(1581589790), + bandtesting.ParseTime(1581589790), "CID", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -754,23 +794,23 @@ func TestReportFail(t *testing.T) { 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) // Common raw reports for everyone. reports := []types.RawReport{types.NewRawReport(1, 0, []byte("data1")), types.NewRawReport(2, 0, []byte("data2"))} // Bad ID - res, err := oracle.NewHandler(k)(ctx, types.NewMsgReportData(999, reports, testapp.Validators[0].ValAddress)) - testapp.CheckErrorf(t, err, types.ErrRequestNotFound, "id: 999") + res, err := oracle.NewHandler(k)(ctx, types.NewMsgReportData(999, reports, bandtesting.Validators[0].ValAddress)) + bandtesting.CheckErrorf(t, err, types.ErrRequestNotFound, "id: 999") require.Nil(t, res) // Not-asked validator - res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Alice.ValAddress)) - testapp.CheckErrorf( + res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, bandtesting.Alice.ValAddress)) + bandtesting.CheckErrorf( t, err, types.ErrValidatorNotRequested, "reqID: 42, val: %s", - testapp.Alice.ValAddress.String(), + bandtesting.Alice.ValAddress.String(), ) require.Nil(t, res) // Too large report data size @@ -784,10 +824,10 @@ func TestReportFail(t *testing.T) { types.NewRawReport(1, 0, []byte("data1")), types.NewRawReport(2, 0, []byte(strings.Repeat("data2", 2000))), }, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ), ) - testapp.CheckErrorf(t, err, types.ErrTooLargeRawReportData, "got: 10000, max: 512") + bandtesting.CheckErrorf(t, err, types.ErrTooLargeRawReportData, "got: 10000, max: 512") require.Nil(t, res) // Not having all raw reports res, err = oracle.NewHandler( @@ -797,7 +837,7 @@ func TestReportFail(t *testing.T) { types.NewMsgReportData( 42, []types.RawReport{types.NewRawReport(1, 0, []byte("data1"))}, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ), ) require.ErrorIs(t, err, types.ErrInvalidReportSize) @@ -810,63 +850,69 @@ func TestReportFail(t *testing.T) { types.NewMsgReportData( 42, []types.RawReport{types.NewRawReport(1, 0, []byte("data1")), types.NewRawReport(42, 0, []byte("data2"))}, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ), ) - testapp.CheckErrorf(t, err, types.ErrRawRequestNotFound, "reqID: 42, extID: 42") + bandtesting.CheckErrorf(t, err, types.ErrRawRequestNotFound, "reqID: 42, extID: 42") require.Nil(t, res) // Request already expired k.SetRequestLastExpired(ctx, 42) - res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Validators[0].ValAddress)) + res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, bandtesting.Validators[0].ValAddress)) require.ErrorIs(t, err, types.ErrRequestAlreadyExpired) require.Nil(t, res) } func TestActivateSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) - ctx = ctx.WithBlockTime(testapp.ParseTime(1000000)) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1000000)) require.Equal(t, types.NewValidatorStatus(false, time.Time{}), - k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress), + k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress), ) - msg := types.NewMsgActivate(testapp.Validators[0].ValAddress) + msg := types.NewMsgActivate(bandtesting.Validators[0].ValAddress) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) require.Equal(t, - types.NewValidatorStatus(true, testapp.ParseTime(1000000)), - k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress), + types.NewValidatorStatus(true, bandtesting.ParseTime(1000000)), + k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress), ) event := abci.Event{ Type: types.EventTypeActivate, Attributes: []abci.EventAttribute{ - {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[0].ValAddress.String()}, }, } require.Equal(t, event, res.Events[0]) } func TestActivateFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - msg := types.NewMsgActivate(testapp.Validators[0].ValAddress) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + msg := types.NewMsgActivate(bandtesting.Validators[0].ValAddress) // Already active. res, err := oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrValidatorAlreadyActive) require.Nil(t, res) // Too soon to activate. - ctx = ctx.WithBlockTime(testapp.ParseTime(100000)) - k.MissReport(ctx, testapp.Validators[0].ValAddress, testapp.ParseTime(99999)) - ctx = ctx.WithBlockTime(testapp.ParseTime(100001)) + ctx = ctx.WithBlockTime(bandtesting.ParseTime(100000)) + k.MissReport(ctx, bandtesting.Validators[0].ValAddress, bandtesting.ParseTime(99999)) + ctx = ctx.WithBlockTime(bandtesting.ParseTime(100001)) res, err = oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrTooSoonToActivate) require.Nil(t, res) // OK - ctx = ctx.WithBlockTime(testapp.ParseTime(200000)) + ctx = ctx.WithBlockTime(bandtesting.ParseTime(200000)) _, err = oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) } func TestUpdateParamsSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + expectedParams := types.Params{ MaxRawRequestCount: 1, MaxAskCount: 10, @@ -919,7 +965,9 @@ func TestUpdateParamsSuccess(t *testing.T) { } func TestUpdateParamsFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + expectedParams := types.Params{ MaxRawRequestCount: 1, MaxAskCount: 10, diff --git a/x/oracle/ibc_test.go b/x/oracle/ibc_test.go index c1605fb51..0a89b3d4c 100644 --- a/x/oracle/ibc_test.go +++ b/x/oracle/ibc_test.go @@ -12,8 +12,8 @@ import ( "github.com/stretchr/testify/suite" "github.com/bandprotocol/chain/v2/pkg/obi" - ibctesting "github.com/bandprotocol/chain/v2/testing" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" + "github.com/bandprotocol/chain/v2/testing/ibctesting" "github.com/bandprotocol/chain/v2/testing/testdata" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -87,8 +87,8 @@ func (suite *OracleTestSuite) TestHandleIBCRequestSuccess() { 2, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(6000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -103,7 +103,7 @@ func (suite *OracleTestSuite) TestHandleIBCRequestSuccess() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - _, err = suite.chainB.SendReport(1, raws1, testapp.Validators[0]) + _, err = suite.chainB.SendReport(1, raws1, bandtesting.Validators[0]) suite.Require().NoError(err) raws2 := []types.RawReport{ @@ -111,7 +111,7 @@ func (suite *OracleTestSuite) TestHandleIBCRequestSuccess() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - _, err = suite.chainB.SendReport(1, raws2, testapp.Validators[1]) + _, err = suite.chainB.SendReport(1, raws2, bandtesting.Validators[1]) suite.Require().NoError(err) oracleResponsePacket := types.NewOracleResponsePacketData( @@ -158,8 +158,8 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { 1, 0, coins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ), types.NewOracleRequestPacketData( clientID, @@ -169,8 +169,8 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { 0, 0, coins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ), types.NewOracleRequestPacketData( clientID, @@ -180,8 +180,8 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { 2, 0, coins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ), types.NewOracleRequestPacketData( strings.Repeat(clientID, 9), @@ -191,8 +191,8 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { 1, 0, coins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ), types.NewOracleRequestPacketData( clientID, @@ -203,7 +203,7 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { 0, coins, 0, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, ), types.NewOracleRequestPacketData( clientID, @@ -213,7 +213,29 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { 1, 0, coins, - testapp.TestDefaultPrepareGas, + bandtesting.TestDefaultPrepareGas, + 0, + ), + types.NewOracleRequestPacketData( + clientID, + 1, + []byte("beeb"), + 1, + 1, + 0, + coins, + 0, + bandtesting.TestDefaultExecuteGas, + ), + types.NewOracleRequestPacketData( + clientID, + 1, + []byte("beeb"), + 1, + 1, + 0, + coins, + bandtesting.TestDefaultPrepareGas, 0, ), types.NewOracleRequestPacketData( @@ -234,9 +256,9 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { 1, 1, 0, - testapp.BadCoins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.BadCoins, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ), } @@ -262,12 +284,12 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestNotEnoughFund() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) // Use Carol as a relayer - carol := testapp.Carol + carol := bandtesting.Carol carolExpectedBalance := sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2492500))) _, err := suite.chainB.SendMsgs(banktypes.NewMsgSend( suite.chainB.SenderAccount.GetAddress(), @@ -305,8 +327,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestNotEnoughFeeLimit() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -329,8 +351,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidCalldataSize() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -351,7 +373,7 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestNotEnoughPrepareGas() { 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), 1, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -372,8 +394,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidAskCountFail() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -388,8 +410,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidAskCountFail() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet = suite.sendOracleRequestPacket(path, 2, oracleRequestPacket, timeoutHeight) @@ -416,8 +438,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestBaseOwasmFeePanic() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -444,8 +466,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestPerValidatorRequestFeePanic() 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -467,8 +489,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestOracleScriptNotFound() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -489,8 +511,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestBadWasmExecutionFail() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -511,8 +533,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestWithEmptyRawRequest() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -533,8 +555,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestUnknownDataSource() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -563,8 +585,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidDataSourceCount() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(4000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -585,8 +607,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestTooMuchWasmGas() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -606,8 +628,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestTooLargeCalldata() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -628,7 +650,7 @@ func (suite *OracleTestSuite) TestIBCResolveRequestOutOfGas() { 1, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(6000000))), - testapp.TestDefaultPrepareGas, + bandtesting.TestDefaultPrepareGas, 1, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -644,7 +666,7 @@ func (suite *OracleTestSuite) TestIBCResolveRequestOutOfGas() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - _, err = suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err = suite.chainB.SendReport(1, raws, bandtesting.Validators[0]) suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( @@ -690,8 +712,8 @@ func (suite *OracleTestSuite) TestIBCResolveReadNilExternalData() { 2, 0, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(4000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -702,11 +724,11 @@ func (suite *OracleTestSuite) TestIBCResolveReadNilExternalData() { suite.checkChainBSenderBalances(sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(5970000)))) raws1 := []types.RawReport{types.NewRawReport(0, 0, nil), types.NewRawReport(1, 0, []byte("beebd2v1"))} - _, err = suite.chainB.SendReport(1, raws1, testapp.Validators[0]) + _, err = suite.chainB.SendReport(1, raws1, bandtesting.Validators[0]) suite.Require().NoError(err) raws2 := []types.RawReport{types.NewRawReport(0, 0, []byte("beebd1v2")), types.NewRawReport(1, 0, nil)} - _, err = suite.chainB.SendReport(1, raws2, testapp.Validators[1]) + _, err = suite.chainB.SendReport(1, raws2, bandtesting.Validators[1]) suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( @@ -746,12 +768,12 @@ func (suite *OracleTestSuite) TestIBCResolveRequestNoReturnData() { // 3rd Wasm - do nothing 3, []byte("beeb"), - []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, 1, suite.chainB.GetContext(). BlockHeight()- 1, - testapp.ParseTime(1577923380), + bandtesting.ParseTime(1577923380), path.EndpointA.ClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -760,12 +782,12 @@ func (suite *OracleTestSuite) TestIBCResolveRequestNoReturnData() { 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - _, err := suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err := suite.chainB.SendReport(1, raws, bandtesting.Validators[0]) suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( @@ -805,26 +827,26 @@ func (suite *OracleTestSuite) TestIBCResolveRequestWasmFailure() { // 6th Wasm - out-of-gas 6, []byte("beeb"), - []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, 1, suite.chainB.GetContext(). BlockHeight()- 1, - testapp.ParseTime(1577923380), + bandtesting.ParseTime(1577923380), path.EndpointA.ClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), }, &types.IBCChannel{PortId: path.EndpointB.ChannelConfig.PortID, ChannelId: path.EndpointB.ChannelID}, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - _, err := suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err := suite.chainB.SendReport(1, raws, bandtesting.Validators[0]) suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( @@ -864,26 +886,26 @@ func (suite *OracleTestSuite) TestIBCResolveRequestCallReturnDataSeveralTimes() // 9th Wasm - set return data several times 9, []byte("beeb"), - []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, 1, suite.chainB.GetContext(). BlockHeight()- 1, - testapp.ParseTime(1577923380), + bandtesting.ParseTime(1577923380), path.EndpointA.ClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), }, &types.IBCChannel{PortId: path.EndpointB.ChannelConfig.PortID, ChannelId: path.EndpointB.ChannelID}, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - _, err := suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err := suite.chainB.SendReport(1, raws, bandtesting.Validators[0]) suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( diff --git a/x/oracle/keeper/data_source_test.go b/x/oracle/keeper/data_source_test.go index 5178327d1..3bc912ae2 100644 --- a/x/oracle/keeper/data_source_test.go +++ b/x/oracle/keeper/data_source_test.go @@ -6,43 +6,52 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestHasDataSource(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should not have a data source ID 42 without setting it. require.False(t, k.HasDataSource(ctx, 42)) // After we set it, we should be able to find it. k.SetDataSource(ctx, 42, types.NewDataSource( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, testapp.EmptyCoins, testapp.Treasury.Address, + bandtesting.Owner.Address, + BasicName, + BasicDesc, + BasicFilename, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, )) require.True(t, k.HasDataSource(ctx, 42)) } func TestSetterGetterDataSource(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Getting a non-existent data source should return error. _, err := k.GetDataSource(ctx, 42) require.ErrorIs(t, err, types.ErrDataSourceNotFound) require.Panics(t, func() { _ = k.MustGetDataSource(ctx, 42) }) // Creates some basic data sources. dataSource1 := types.NewDataSource( - testapp.Alice.Address, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "filename1", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) dataSource2 := types.NewDataSource( - testapp.Bob.Address, + bandtesting.Bob.Address, "NAME2", "DESCRIPTION2", "filename2", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) // Sets id 42 with data soure 1 and id 42 with data source 2. k.SetDataSource(ctx, 42, dataSource1) @@ -63,23 +72,25 @@ func TestSetterGetterDataSource(t *testing.T) { } func TestAddDataSourceEditDataSourceBasic(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Creates some basic data sources. dataSource1 := types.NewDataSource( - testapp.Alice.Address, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) dataSource2 := types.NewDataSource( - testapp.Bob.Address, + bandtesting.Bob.Address, "NAME2", "DESCRIPTION2", "FILENAME2", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) // Adds a new data source to the store. We should be able to retrieve it back. id := k.AddDataSource(ctx, dataSource1) @@ -91,30 +102,32 @@ func TestAddDataSourceEditDataSourceBasic(t *testing.T) { require.NoError(t, err) // Edits the data source. We should get the updated data source. k.MustEditDataSource(ctx, id, types.NewDataSource( - owner, dataSource2.Name, dataSource2.Description, dataSource2.Filename, testapp.EmptyCoins, treasury, + owner, dataSource2.Name, dataSource2.Description, dataSource2.Filename, bandtesting.EmptyCoins, treasury, )) require.NotEqual(t, dataSource1, k.MustGetDataSource(ctx, id)) require.Equal(t, dataSource2, k.MustGetDataSource(ctx, id)) } func TestEditDataSourceDoNotModify(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Creates some basic data sources. dataSource1 := types.NewDataSource( - testapp.Alice.Address, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) dataSource2 := types.NewDataSource( - testapp.Bob.Address, + bandtesting.Bob.Address, types.DoNotModify, types.DoNotModify, "FILENAME2", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) // Adds a new data source to the store. We should be able to retrieve it back. id := k.AddDataSource(ctx, dataSource1) @@ -134,20 +147,23 @@ func TestEditDataSourceDoNotModify(t *testing.T) { } func TestAddDataSourceDataSourceMustReturnCorrectID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially we expect the data source count to be what we have on genesis state. - genesisCount := uint64(len(testapp.DataSources)) - 1 + genesisCount := uint64(len(bandtesting.DataSources)) - 1 require.Equal(t, genesisCount, k.GetDataSourceCount(ctx)) + // Every new data source we add should return a new ID. id1 := k.AddDataSource( ctx, types.NewDataSource( - testapp.Owner.Address, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ), ) require.Equal(t, types.DataSourceID(genesisCount+1), id1) @@ -155,12 +171,12 @@ func TestAddDataSourceDataSourceMustReturnCorrectID(t *testing.T) { id2 := k.AddDataSource( ctx, types.NewDataSource( - testapp.Owner.Address, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ), ) require.Equal(t, types.DataSourceID(genesisCount+2), id2) @@ -169,18 +185,24 @@ func TestAddDataSourceDataSourceMustReturnCorrectID(t *testing.T) { } func TestEditDataSourceNonExistentDataSource(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - require.Panics(t, func() { k.MustEditDataSource(ctx, 9999, testapp.DataSources[1]) }) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + require.Panics(t, func() { k.MustEditDataSource(ctx, 9999, bandtesting.DataSources[1]) }) } func TestGetAllDataSources(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should be able to get all genesis data sources. - require.Equal(t, testapp.DataSources[1:], k.GetAllDataSources(ctx)) + require.Equal(t, bandtesting.DataSources[1:], k.GetAllDataSources(ctx)) } func TestAddExecutableFile(t *testing.T) { - _, _, k := testapp.CreateTestInput(true) + app, _ := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Adding do-not-modify should simply return do-not-modify. require.Equal(t, types.DoNotModify, k.AddExecutableFile(types.DoNotModifyBytes)) // After we add an executable file, we should be able to retrieve it back. diff --git a/x/oracle/keeper/grpc_query_test.go b/x/oracle/keeper/grpc_query_test.go index 207f22d6c..adc3c7dc2 100644 --- a/x/oracle/keeper/grpc_query_test.go +++ b/x/oracle/keeper/grpc_query_test.go @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/keeper" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -33,7 +33,8 @@ type RequestVerificationTestSuite struct { func (suite *RequestVerificationTestSuite) SetupTest() { suite.assert = require.New(suite.T()) - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(suite.T(), true) + k := app.OracleKeeper suite.querier = keeper.Querier{ Keeper: k, @@ -43,10 +44,10 @@ func (suite *RequestVerificationTestSuite) SetupTest() { suite.request = types.NewRequest( 1, BasicCalldata, - []sdk.ValAddress{testapp.Validators[0].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress}, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("testdata")), @@ -57,8 +58,8 @@ func (suite *RequestVerificationTestSuite) SetupTest() { 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ) suite.reporterPrivKey = secp256k1.GenPrivKey() suite.reporterAddr = sdk.AccAddress(suite.reporterPrivKey.PubKey().Address()) @@ -66,11 +67,11 @@ func (suite *RequestVerificationTestSuite) SetupTest() { k.SetRequest(ctx, types.RequestID(1), suite.request) k.SetRequestCount(ctx, 1) - err := k.GrantReporter(ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + err := k.GrantReporter(ctx, bandtesting.Validators[0].ValAddress, suite.reporterAddr) suite.assert.NoError(err) expiration := ctx.BlockTime().Add(10 * time.Minute) - err = app.AuthzKeeper.SaveGrant(ctx, suite.granteeAddr, sdk.AccAddress(testapp.Validators[0].ValAddress), + err = app.AuthzKeeper.SaveGrant(ctx, suite.granteeAddr, sdk.AccAddress(bandtesting.Validators[0].ValAddress), authz.NewGenericAuthorization("some url"), &expiration, ) suite.assert.NoError(err) @@ -79,7 +80,7 @@ func (suite *RequestVerificationTestSuite) SetupTest() { func (suite *RequestVerificationTestSuite) TestSuccess() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -88,7 +89,7 @@ func (suite *RequestVerificationTestSuite) TestSuccess() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -101,7 +102,7 @@ func (suite *RequestVerificationTestSuite) TestSuccess() { expectedResult := &types.QueryRequestVerificationResponse{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -114,7 +115,7 @@ func (suite *RequestVerificationTestSuite) TestSuccess() { func (suite *RequestVerificationTestSuite) TestFailedRequestIDNotExist() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 2, ExternalId: 1, DataSourceId: 1, @@ -123,7 +124,7 @@ func (suite *RequestVerificationTestSuite) TestFailedRequestIDNotExist() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -141,7 +142,7 @@ func (suite *RequestVerificationTestSuite) TestFailedRequestIDNotExist() { func (suite *RequestVerificationTestSuite) TestRequestInDelayRange() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 6, ExternalId: 1, DataSourceId: 1, @@ -151,7 +152,7 @@ func (suite *RequestVerificationTestSuite) TestRequestInDelayRange() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -164,7 +165,7 @@ func (suite *RequestVerificationTestSuite) TestRequestInDelayRange() { expectedResult := &types.QueryRequestVerificationResponse{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 6, ExternalId: 1, DataSourceId: 1, @@ -177,7 +178,7 @@ func (suite *RequestVerificationTestSuite) TestRequestInDelayRange() { func (suite *RequestVerificationTestSuite) TestFailedExceedDelayRange() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 7, ExternalId: 1, DataSourceId: 1, @@ -187,7 +188,7 @@ func (suite *RequestVerificationTestSuite) TestFailedExceedDelayRange() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -205,7 +206,7 @@ func (suite *RequestVerificationTestSuite) TestFailedExceedDelayRange() { func (suite *RequestVerificationTestSuite) TestFailedDataSourceIDNotMatch() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 2, @@ -214,7 +215,7 @@ func (suite *RequestVerificationTestSuite) TestFailedDataSourceIDNotMatch() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -243,7 +244,7 @@ func (suite *RequestVerificationTestSuite) TestFailedEmptyRequest() { func (suite *RequestVerificationTestSuite) TestFailedChainIDNotMatch() { req := &types.QueryRequestVerificationRequest{ ChainId: "other-chain-id", - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -252,7 +253,7 @@ func (suite *RequestVerificationTestSuite) TestFailedChainIDNotMatch() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -283,7 +284,7 @@ func (suite *RequestVerificationTestSuite) TestFailedInvalidValidatorAddr() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -301,7 +302,7 @@ func (suite *RequestVerificationTestSuite) TestFailedInvalidValidatorAddr() { func (suite *RequestVerificationTestSuite) TestFailedInvalidReporterPubKey() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -310,7 +311,7 @@ func (suite *RequestVerificationTestSuite) TestFailedInvalidReporterPubKey() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -328,7 +329,7 @@ func (suite *RequestVerificationTestSuite) TestFailedInvalidReporterPubKey() { func (suite *RequestVerificationTestSuite) TestFailedEmptySignature() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, Reporter: hex.EncodeToString(suite.reporterPrivKey.PubKey().Bytes()), @@ -341,12 +342,12 @@ func (suite *RequestVerificationTestSuite) TestFailedEmptySignature() { } func (suite *RequestVerificationTestSuite) TestFailedReporterUnauthorized() { - err := suite.querier.Keeper.RevokeReporter(suite.ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + err := suite.querier.Keeper.RevokeReporter(suite.ctx, bandtesting.Validators[0].ValAddress, suite.reporterAddr) suite.assert.NoError(err) req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -355,7 +356,7 @@ func (suite *RequestVerificationTestSuite) TestFailedReporterUnauthorized() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -371,12 +372,12 @@ func (suite *RequestVerificationTestSuite) TestFailedReporterUnauthorized() { } func (suite *RequestVerificationTestSuite) TestFailedUnselectedValidator() { - suite.request.RequestedValidators = []string{testapp.Validators[1].ValAddress.String()} + suite.request.RequestedValidators = []string{bandtesting.Validators[1].ValAddress.String()} suite.querier.Keeper.SetRequest(suite.ctx, types.RequestID(1), suite.request) req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -385,7 +386,7 @@ func (suite *RequestVerificationTestSuite) TestFailedUnselectedValidator() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -406,7 +407,7 @@ func (suite *RequestVerificationTestSuite) TestFailedNoDataSourceFound() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -415,7 +416,7 @@ func (suite *RequestVerificationTestSuite) TestFailedNoDataSourceFound() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -434,7 +435,7 @@ func (suite *RequestVerificationTestSuite) TestFailedValidatorAlreadyReported() err := suite.querier.Keeper.AddReport( suite.ctx, types.RequestID(1), - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("testdata")), types.NewRawReport(2, 0, []byte("testdata")), types.NewRawReport(3, 0, []byte("testdata")), @@ -444,7 +445,7 @@ func (suite *RequestVerificationTestSuite) TestFailedValidatorAlreadyReported() req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -453,7 +454,7 @@ func (suite *RequestVerificationTestSuite) TestFailedValidatorAlreadyReported() requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -471,7 +472,7 @@ func (suite *RequestVerificationTestSuite) TestFailedValidatorAlreadyReported() func (suite *RequestVerificationTestSuite) TestFailedRequestAlreadyExpired() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -482,7 +483,7 @@ func (suite *RequestVerificationTestSuite) TestFailedRequestAlreadyExpired() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -499,7 +500,7 @@ func (suite *RequestVerificationTestSuite) TestFailedRequestAlreadyExpired() { func (suite *RequestVerificationTestSuite) TestGetReporters() { req := &types.QueryReportersRequest{ - ValidatorAddress: testapp.Validators[0].ValAddress.String(), + ValidatorAddress: bandtesting.Validators[0].ValAddress.String(), } res, err := suite.querier.Reporters(sdk.WrapSDKContext(suite.ctx), req) @@ -513,7 +514,7 @@ func (suite *RequestVerificationTestSuite) TestGetReporters() { func (suite *RequestVerificationTestSuite) TestGetExpiredReporters() { suite.ctx = suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(10 * time.Minute)) req := &types.QueryReportersRequest{ - ValidatorAddress: testapp.Validators[0].ValAddress.String(), + ValidatorAddress: bandtesting.Validators[0].ValAddress.String(), } res, err := suite.querier.Reporters(sdk.WrapSDKContext(suite.ctx), req) @@ -526,7 +527,7 @@ func (suite *RequestVerificationTestSuite) TestGetExpiredReporters() { func (suite *RequestVerificationTestSuite) TestIsReporter() { req := &types.QueryIsReporterRequest{ - ValidatorAddress: testapp.Validators[0].ValAddress.String(), + ValidatorAddress: bandtesting.Validators[0].ValAddress.String(), ReporterAddress: suite.reporterAddr.String(), } res, err := suite.querier.IsReporter(sdk.WrapSDKContext(suite.ctx), req) @@ -540,7 +541,7 @@ func (suite *RequestVerificationTestSuite) TestIsReporter() { func (suite *RequestVerificationTestSuite) TestIsNotReporter() { req := &types.QueryIsReporterRequest{ - ValidatorAddress: testapp.Validators[0].ValAddress.String(), + ValidatorAddress: bandtesting.Validators[0].ValAddress.String(), ReporterAddress: suite.granteeAddr.String(), } res, err := suite.querier.IsReporter(sdk.WrapSDKContext(suite.ctx), req) @@ -553,10 +554,10 @@ func (suite *RequestVerificationTestSuite) TestIsNotReporter() { } func (suite *RequestVerificationTestSuite) TestRevokeReporters() { - err := suite.querier.Keeper.RevokeReporter(suite.ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + err := suite.querier.Keeper.RevokeReporter(suite.ctx, bandtesting.Validators[0].ValAddress, suite.reporterAddr) suite.assert.NoError(err) req := &types.QueryReportersRequest{ - ValidatorAddress: testapp.Validators[0].ValAddress.String(), + ValidatorAddress: bandtesting.Validators[0].ValAddress.String(), } res, err := suite.querier.Reporters(sdk.WrapSDKContext(suite.ctx), req) @@ -578,7 +579,8 @@ type PendingRequestsTestSuite struct { func (suite *PendingRequestsTestSuite) SetupTest() { suite.assert = require.New(suite.T()) - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(suite.T(), true) + k := app.OracleKeeper suite.querier = keeper.Querier{ Keeper: k, @@ -590,10 +592,10 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { assignedButPendingReq := types.NewRequest( 1, BasicCalldata, - []sdk.ValAddress{testapp.Validators[0].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress}, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("testdata")), @@ -604,16 +606,16 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ) notBeAssignedReq := types.NewRequest( 1, BasicCalldata, - []sdk.ValAddress{testapp.Validators[1].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[1].ValAddress}, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("testdata")), @@ -624,19 +626,19 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ) alreadyReportAllReq := types.NewRequest( 1, BasicCalldata, []sdk.ValAddress{ - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("testdata")), @@ -647,19 +649,19 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ) assignedButReportedReq := types.NewRequest( 1, BasicCalldata, []sdk.ValAddress{ - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("testdata")), @@ -670,8 +672,8 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ) suite.querier.Keeper.SetRequest(suite.ctx, types.RequestID(3), assignedButPendingReq) @@ -683,7 +685,7 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { suite.querier.Keeper.SetReport( suite.ctx, 5, - types.NewReport(testapp.Validators[0].ValAddress, true, []types.RawReport{ + types.NewReport(bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("testdata")), types.NewRawReport(2, 0, []byte("testdata")), types.NewRawReport(3, 0, []byte("testdata")), @@ -692,7 +694,7 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { suite.querier.Keeper.SetReport( suite.ctx, 5, - types.NewReport(testapp.Validators[1].ValAddress, true, []types.RawReport{ + types.NewReport(bandtesting.Validators[1].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("testdata")), types.NewRawReport(2, 0, []byte("testdata")), types.NewRawReport(3, 0, []byte("testdata")), @@ -701,7 +703,7 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { suite.querier.Keeper.SetReport( suite.ctx, 6, - types.NewReport(testapp.Validators[0].ValAddress, true, []types.RawReport{ + types.NewReport(bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("testdata")), types.NewRawReport(2, 0, []byte("testdata")), types.NewRawReport(3, 0, []byte("testdata")), @@ -709,7 +711,7 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { ) r, err := suite.querier.PendingRequests(sdk.WrapSDKContext(suite.ctx), &types.QueryPendingRequestsRequest{ - ValidatorAddress: sdk.ValAddress(testapp.Validators[0].Address).String(), + ValidatorAddress: sdk.ValAddress(bandtesting.Validators[0].Address).String(), }) suite.assert.Equal(&types.QueryPendingRequestsResponse{RequestIDs: []uint64{3}}, r) diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 43de93338..8e2079424 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -5,12 +5,14 @@ import ( "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestGetSetRequestCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially request count must be 0. require.Equal(t, uint64(0), k.GetRequestCount(ctx)) // After we set the count manually, it should be reflected. @@ -19,19 +21,32 @@ func TestGetSetRequestCount(t *testing.T) { } func TestGetDataSourceCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetDataSourceCount(ctx, 42) require.Equal(t, uint64(42), k.GetDataSourceCount(ctx)) } func TestGetSetOracleScriptCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetOracleScriptCount(ctx, 42) require.Equal(t, uint64(42), k.GetOracleScriptCount(ctx)) } +func TestGetSetRollingSeed(t *testing.T) { + app, ctx := bandtesting.CreateTestApp(t, true) + + app.RollingseedKeeper.SetRollingSeed(ctx, []byte("HELLO_WORLD")) + require.Equal(t, []byte("HELLO_WORLD"), app.RollingseedKeeper.GetRollingSeed(ctx)) +} + func TestGetNextRequestID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // First request id must be 1. require.Equal(t, types.RequestID(1), k.GetNextRequestID(ctx)) // After we add new requests, the request count must increase accordingly. @@ -43,7 +58,9 @@ func TestGetNextRequestID(t *testing.T) { } func TestGetNextDataSourceID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + initialID := k.GetDataSourceCount(ctx) require.Equal(t, types.DataSourceID(initialID+1), k.GetNextDataSourceID(ctx)) require.Equal(t, types.DataSourceID(initialID+2), k.GetNextDataSourceID(ctx)) @@ -51,7 +68,9 @@ func TestGetNextDataSourceID(t *testing.T) { } func TestGetNextOracleScriptID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + initialID := k.GetOracleScriptCount(ctx) require.Equal(t, types.OracleScriptID(initialID+1), k.GetNextOracleScriptID(ctx)) require.Equal(t, types.OracleScriptID(initialID+2), k.GetNextOracleScriptID(ctx)) @@ -59,7 +78,9 @@ func TestGetNextOracleScriptID(t *testing.T) { } func TestGetSetRequestLastExpiredID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially last expired request must be 0. require.Equal(t, types.RequestID(0), k.GetRequestLastExpired(ctx)) k.SetRequestLastExpired(ctx, 20) diff --git a/x/oracle/keeper/oracle_script_test.go b/x/oracle/keeper/oracle_script_test.go index d570fe357..da21de952 100644 --- a/x/oracle/keeper/oracle_script_test.go +++ b/x/oracle/keeper/oracle_script_test.go @@ -6,34 +6,38 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/testing/testdata" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestHasOracleScript(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should not have a oracle script ID 42 without setting it. require.False(t, k.HasOracleScript(ctx, 42)) // After we set it, we should be able to find it. k.SetOracleScript(ctx, 42, types.NewOracleScript( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, )) require.True(t, k.HasOracleScript(ctx, 42)) } func TestSetterGetterOracleScript(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Getting a non-existent oracle script should return error. _, err := k.GetOracleScript(ctx, 42) require.ErrorIs(t, err, types.ErrOracleScriptNotFound) require.Panics(t, func() { _ = k.MustGetOracleScript(ctx, 42) }) // Creates some basic oracle scripts. oracleScript1 := types.NewOracleScript( - testapp.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, ) oracleScript2 := types.NewOracleScript( - testapp.Bob.Address, "NAME2", "DESCRIPTION2", "FILENAME2", BasicSchema, BasicSourceCodeURL, + bandtesting.Bob.Address, "NAME2", "DESCRIPTION2", "FILENAME2", BasicSchema, BasicSourceCodeURL, ) // Sets id 42 with oracle script 1 and id 42 with oracle script 2. k.SetOracleScript(ctx, 42, oracleScript1) @@ -54,13 +58,15 @@ func TestSetterGetterOracleScript(t *testing.T) { } func TestAddEditOracleScriptBasic(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Creates some basic oracle scripts. oracleScript1 := types.NewOracleScript( - testapp.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, ) oracleScript2 := types.NewOracleScript( - testapp.Bob.Address, "NAME2", "DESCRIPTION2", "FILENAME2", BasicSchema, BasicSourceCodeURL, + bandtesting.Bob.Address, "NAME2", "DESCRIPTION2", "FILENAME2", BasicSchema, BasicSourceCodeURL, ) // Adds a new oracle script to the store. We should be able to retrieve it back. id := k.AddOracleScript(ctx, oracleScript1) @@ -80,13 +86,15 @@ func TestAddEditOracleScriptBasic(t *testing.T) { } func TestAddEditOracleScriptDoNotModify(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Creates some basic oracle scripts. oracleScript1 := types.NewOracleScript( - testapp.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, ) oracleScript2 := types.NewOracleScript( - testapp.Bob.Address, types.DoNotModify, types.DoNotModify, "FILENAME2", + bandtesting.Bob.Address, types.DoNotModify, types.DoNotModify, "FILENAME2", types.DoNotModify, types.DoNotModify, ) // Adds a new oracle script to the store. We should be able to retrieve it back. @@ -107,18 +115,20 @@ func TestAddEditOracleScriptDoNotModify(t *testing.T) { } func TestAddOracleScriptMustReturnCorrectID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially we expect the oracle script count to be what we have on genesis state. - genesisCount := uint64(len(testapp.OracleScripts)) - 1 + genesisCount := uint64(len(bandtesting.OracleScripts)) - 1 require.Equal(t, genesisCount, k.GetOracleScriptCount(ctx)) // Every new oracle script we add should return a new ID. id1 := k.AddOracleScript(ctx, types.NewOracleScript( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, )) require.Equal(t, types.OracleScriptID(genesisCount+1), id1) // Adds another oracle script so now ID should increase by 2. id2 := k.AddOracleScript(ctx, types.NewOracleScript( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, )) require.Equal(t, types.OracleScriptID(genesisCount+2), id2) // Finally we expect the oracle script to increase as well. @@ -126,25 +136,31 @@ func TestAddOracleScriptMustReturnCorrectID(t *testing.T) { } func TestEditNonExistentOracleScript(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Editing a non-existent oracle script should return error. require.Panics(t, func() { k.MustEditOracleScript(ctx, 42, types.NewOracleScript( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, )) }) } func TestGetAllOracleScripts(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should be able to get all genesis oracle scripts. - require.Equal(t, testapp.OracleScripts[1:], k.GetAllOracleScripts(ctx)) + require.Equal(t, bandtesting.OracleScripts[1:], k.GetAllOracleScripts(ctx)) } func TestAddOracleScriptFile(t *testing.T) { - _, _, k := testapp.CreateTestInput(true) + app, _ := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Code should be perferctly compilable. - compiledCode, err := testapp.OwasmVM.Compile(testdata.WasmExtra1, types.MaxCompiledWasmCodeSize) + compiledCode, err := bandtesting.OwasmVM.Compile(testdata.WasmExtra1, types.MaxCompiledWasmCodeSize) require.NoError(t, err) // We start by adding the Owasm content to the storage. filename, err := k.AddOracleScriptFile(testdata.WasmExtra1) diff --git a/x/oracle/keeper/owasm_test.go b/x/oracle/keeper/owasm_test.go index 10be82d91..d1a914920 100644 --- a/x/oracle/keeper/owasm_test.go +++ b/x/oracle/keeper/owasm_test.go @@ -13,14 +13,16 @@ import ( "github.com/stretchr/testify/require" "github.com/bandprotocol/chain/v2/pkg/obi" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/testing/testdata" "github.com/bandprotocol/chain/v2/x/oracle/keeper" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestGetRandomValidatorsSuccessActivateAll(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Getting 3 validators using ROLLING_SEED_1_WITH_LONG_ENOUGH_ENTROPY app.RollingseedKeeper.SetRollingSeed(ctx, []byte("ROLLING_SEED_1_WITH_LONG_ENOUGH_ENTROPY")) vals, err := k.GetRandomValidators(ctx, 3, 1) @@ -28,9 +30,9 @@ func TestGetRandomValidatorsSuccessActivateAll(t *testing.T) { require.Equal( t, []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, vals, ) @@ -41,9 +43,9 @@ func TestGetRandomValidatorsSuccessActivateAll(t *testing.T) { require.Equal( t, []sdk.ValAddress{ - testapp.Validators[0].ValAddress, - testapp.Validators[2].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[1].ValAddress, }, vals, ) @@ -54,9 +56,9 @@ func TestGetRandomValidatorsSuccessActivateAll(t *testing.T) { require.Equal( t, []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, vals, ) @@ -67,16 +69,18 @@ func TestGetRandomValidatorsSuccessActivateAll(t *testing.T) { require.Equal( t, []sdk.ValAddress{ - testapp.Validators[0].ValAddress, - testapp.Validators[2].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[1].ValAddress, }, vals, ) } func TestGetRandomValidatorsTooBigSize(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + _, err := k.GetRandomValidators(ctx, 1, 1) require.NoError(t, err) _, err = k.GetRandomValidators(ctx, 2, 1) @@ -90,43 +94,51 @@ func TestGetRandomValidatorsTooBigSize(t *testing.T) { } func TestGetRandomValidatorsWithActivate(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + app.RollingseedKeeper.SetRollingSeed(ctx, []byte("ROLLING_SEED_WITH_LONG_ENOUGH_ENTROPY")) // If no validators are active, you must not be able to get random validators _, err := k.GetRandomValidators(ctx, 1, 1) require.ErrorIs(t, err, types.ErrInsufficientValidators) // If we activate 2 validators, we should be able to get at most 2 from the function. - err = k.Activate(ctx, testapp.Validators[0].ValAddress) + err = k.Activate(ctx, bandtesting.Validators[0].ValAddress) require.NoError(t, err) - err = k.Activate(ctx, testapp.Validators[1].ValAddress) + err = k.Activate(ctx, bandtesting.Validators[1].ValAddress) require.NoError(t, err) vals, err := k.GetRandomValidators(ctx, 1, 1) require.NoError(t, err) - require.Equal(t, []sdk.ValAddress{testapp.Validators[0].ValAddress}, vals) + require.Equal(t, []sdk.ValAddress{bandtesting.Validators[0].ValAddress}, vals) vals, err = k.GetRandomValidators(ctx, 2, 1) require.NoError(t, err) - require.Equal(t, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, vals) + require.Equal( + t, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + vals, + ) _, err = k.GetRandomValidators(ctx, 3, 1) require.ErrorIs(t, err, types.ErrInsufficientValidators) // After we deactivate 1 validator due to missing a report, we can only get at most 1 validator. - k.MissReport(ctx, testapp.Validators[0].ValAddress, time.Now()) + k.MissReport(ctx, bandtesting.Validators[0].ValAddress, time.Now()) vals, err = k.GetRandomValidators(ctx, 1, 1) require.NoError(t, err) - require.Equal(t, []sdk.ValAddress{testapp.Validators[1].ValAddress}, vals) + require.Equal(t, []sdk.ValAddress{bandtesting.Validators[1].ValAddress}, vals) _, err = k.GetRandomValidators(ctx, 2, 1) require.ErrorIs(t, err, types.ErrInsufficientValidators) } func TestPrepareRequestSuccessBasic(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589790)).WithBlockHeight(42) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589790)).WithBlockHeight(42) - wrappedGasMeter := testapp.NewGasMeterWrapper(ctx.GasMeter()) + wrappedGasMeter := bandtesting.NewGasMeterWrapper(ctx.GasMeter()) ctx = ctx.WithGasMeter(wrappedGasMeter) balancesRes, err := app.BankKeeper.AllBalances( sdk.WrapSDKContext(ctx), - authtypes.NewQueryAllBalancesRequest(testapp.FeePayer.Address, &query.PageRequest{}), + authtypes.NewQueryAllBalancesRequest(bandtesting.FeePayer.Address, &query.PageRequest{}), ) require.NoError(t, err) feePayerBalances := balancesRes.Balances @@ -138,75 +150,75 @@ func TestPrepareRequestSuccessBasic(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) require.Equal(t, types.NewRequest( - 1, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 1, BasicCalldata, []sdk.ValAddress{bandtesting.Validators[0].ValAddress}, 1, + 42, bandtesting.ParseTime(1581589790), BasicClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), types.NewRawRequest(2, 2, []byte("beeb")), types.NewRawRequest(3, 3, []byte("beeb")), - }, nil, testapp.TestDefaultExecuteGas, 0, 0, - testapp.FeePayer.Address.String(), + }, nil, bandtesting.TestDefaultExecuteGas, 0, 0, + bandtesting.FeePayer.Address.String(), sdk.NewCoins(sdk.NewInt64Coin("uband", 97000000)), ), k.MustGetRequest(ctx, 1)) require.Equal(t, sdk.Events{ sdk.NewEvent( authtypes.EventTypeCoinSpent, - sdk.NewAttribute(authtypes.AttributeKeySpender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeySpender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeCoinReceived, - sdk.NewAttribute(authtypes.AttributeKeyReceiver, testapp.Treasury.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyReceiver, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeTransfer, - sdk.NewAttribute(authtypes.AttributeKeyRecipient, testapp.Treasury.Address.String()), - sdk.NewAttribute(authtypes.AttributeKeySender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyRecipient, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(authtypes.AttributeKeySender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeySender, testapp.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeySender, bandtesting.FeePayer.Address.String()), ), sdk.NewEvent( authtypes.EventTypeCoinSpent, - sdk.NewAttribute(authtypes.AttributeKeySpender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeySpender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeCoinReceived, - sdk.NewAttribute(authtypes.AttributeKeyReceiver, testapp.Treasury.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyReceiver, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeTransfer, - sdk.NewAttribute(authtypes.AttributeKeyRecipient, testapp.Treasury.Address.String()), - sdk.NewAttribute(authtypes.AttributeKeySender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyRecipient, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(authtypes.AttributeKeySender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeySender, testapp.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeySender, bandtesting.FeePayer.Address.String()), ), sdk.NewEvent( authtypes.EventTypeCoinSpent, - sdk.NewAttribute(authtypes.AttributeKeySpender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeySpender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeCoinReceived, - sdk.NewAttribute(authtypes.AttributeKeyReceiver, testapp.Treasury.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyReceiver, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeTransfer, - sdk.NewAttribute(authtypes.AttributeKeyRecipient, testapp.Treasury.Address.String()), - sdk.NewAttribute(authtypes.AttributeKeySender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyRecipient, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(authtypes.AttributeKeySender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeySender, testapp.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeySender, bandtesting.FeePayer.Address.String()), ), sdk.NewEvent( types.EventTypeRequest, sdk.NewAttribute(types.AttributeKeyID, "1"), @@ -218,25 +230,25 @@ func TestPrepareRequestSuccessBasic(t *testing.T) { sdk.NewAttribute(types.AttributeKeyTSSGroupID, "0"), sdk.NewAttribute(types.AttributeKeyGasUsed, "5294700000"), sdk.NewAttribute(types.AttributeKeyTotalFees, "3000000uband"), - sdk.NewAttribute(types.AttributeKeyValidator, testapp.Validators[0].ValAddress.String()), + sdk.NewAttribute(types.AttributeKeyValidator, bandtesting.Validators[0].ValAddress.String()), ), sdk.NewEvent( types.EventTypeRawRequest, sdk.NewAttribute(types.AttributeKeyDataSourceID, "1"), - sdk.NewAttribute(types.AttributeKeyDataSourceHash, testapp.DataSources[1].Filename), + sdk.NewAttribute(types.AttributeKeyDataSourceHash, bandtesting.DataSources[1].Filename), sdk.NewAttribute(types.AttributeKeyExternalID, "1"), sdk.NewAttribute(types.AttributeKeyCalldata, "beeb"), sdk.NewAttribute(types.AttributeKeyFee, "1000000uband"), ), sdk.NewEvent( types.EventTypeRawRequest, sdk.NewAttribute(types.AttributeKeyDataSourceID, "2"), - sdk.NewAttribute(types.AttributeKeyDataSourceHash, testapp.DataSources[2].Filename), + sdk.NewAttribute(types.AttributeKeyDataSourceHash, bandtesting.DataSources[2].Filename), sdk.NewAttribute(types.AttributeKeyExternalID, "2"), sdk.NewAttribute(types.AttributeKeyCalldata, "beeb"), sdk.NewAttribute(types.AttributeKeyFee, "1000000uband"), ), sdk.NewEvent( types.EventTypeRawRequest, sdk.NewAttribute(types.AttributeKeyDataSourceID, "3"), - sdk.NewAttribute(types.AttributeKeyDataSourceHash, testapp.DataSources[3].Filename), + sdk.NewAttribute(types.AttributeKeyDataSourceHash, bandtesting.DataSources[3].Filename), sdk.NewAttribute(types.AttributeKeyExternalID, "3"), sdk.NewAttribute(types.AttributeKeyCalldata, "beeb"), sdk.NewAttribute(types.AttributeKeyFee, "1000000uband"), @@ -246,18 +258,20 @@ func TestPrepareRequestSuccessBasic(t *testing.T) { // assert gas consumption params := k.GetParams(ctx) require.Equal(t, 2, wrappedGasMeter.CountRecord(params.BaseOwasmGas, "BASE_OWASM_FEE")) - require.Equal(t, 1, wrappedGasMeter.CountRecord(testapp.TestDefaultPrepareGas, "OWASM_PREPARE_FEE")) - require.Equal(t, 1, wrappedGasMeter.CountRecord(testapp.TestDefaultExecuteGas, "OWASM_EXECUTE_FEE")) + require.Equal(t, 1, wrappedGasMeter.CountRecord(bandtesting.TestDefaultPrepareGas, "OWASM_PREPARE_FEE")) + require.Equal(t, 1, wrappedGasMeter.CountRecord(bandtesting.TestDefaultExecuteGas, "OWASM_EXECUTE_FEE")) paid := sdk.NewCoins(sdk.NewInt64Coin("uband", 3000000)) feePayerBalances = feePayerBalances.Sub(paid...) - testapp.CheckBalances(t, ctx, app.BankKeeper, testapp.FeePayer.Address, feePayerBalances) - testapp.CheckBalances(t, ctx, app.BankKeeper, testapp.Treasury.Address, paid) + bandtesting.CheckBalances(t, ctx, app.BankKeeper, bandtesting.FeePayer.Address, feePayerBalances) + bandtesting.CheckBalances(t, ctx, app.BankKeeper, bandtesting.Treasury.Address, paid) } func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589790)).WithBlockHeight(42) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589790)).WithBlockHeight(42) // OracleScript#1: Prepare asks for DS#1,2,3 with ExtID#1,2,3 and calldata "beeb" m := types.NewMsgRequestData( 1, @@ -265,14 +279,14 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { 1, 1, BasicClientID, - testapp.EmptyCoins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.EmptyCoins, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 1000000uband, max: 0uband: not enough fee") m = types.NewMsgRequestData( 1, @@ -281,13 +295,13 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { 1, BasicClientID, sdk.NewCoins(sdk.NewInt64Coin("uband", 1000000)), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 2000000uband, max: 1000000uband: not enough fee") m = types.NewMsgRequestData( 1, @@ -296,13 +310,13 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { 1, BasicClientID, sdk.NewCoins(sdk.NewInt64Coin("uband", 2000000)), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 3000000uband, max: 2000000uband: not enough fee") m = types.NewMsgRequestData( 1, @@ -311,13 +325,13 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { 1, BasicClientID, sdk.NewCoins(sdk.NewInt64Coin("uband", 2999999)), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 3000000uband, max: 2999999uband: not enough fee") m = types.NewMsgRequestData( 1, @@ -326,20 +340,22 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { 1, BasicClientID, sdk.NewCoins(sdk.NewInt64Coin("uband", 3000000)), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, 0, 0, ) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.NoError(t, err) require.Equal(t, types.RequestID(1), id) } func TestPrepareRequestNotEnoughFund(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589790)).WithBlockHeight(42) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589790)).WithBlockHeight(42) // OracleScript#1: Prepare asks for DS#1,2,3 with ExtID#1,2,3 and calldata "beeb" m := types.NewMsgRequestData( 1, @@ -347,41 +363,45 @@ func TestPrepareRequestNotEnoughFund(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - _, err := k.PrepareRequest(ctx, m, testapp.Alice.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.Alice.Address, nil) require.EqualError(t, err, "spendable balance is smaller than 1000000uband: insufficient funds") } func TestPrepareRequestInvalidCalldataSize(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + m := types.NewMsgRequestData( 1, []byte(strings.Repeat("x", 2000)), 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "got: 2000, max: 512: too large calldata") } func TestPrepareRequestNotEnoughPrepareGas(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589790)).WithBlockHeight(42) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589790)).WithBlockHeight(42) - wrappedGasMeter := testapp.NewGasMeterWrapper(ctx.GasMeter()) + wrappedGasMeter := bandtesting.NewGasMeterWrapper(ctx.GasMeter()) ctx = ctx.WithGasMeter(wrappedGasMeter) m := types.NewMsgRequestData( @@ -390,14 +410,14 @@ func TestPrepareRequestNotEnoughPrepareGas(t *testing.T) { 1, 1, BasicClientID, - testapp.EmptyCoins, + bandtesting.EmptyCoins, 1, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrBadWasmExecution) require.Contains(t, err.Error(), "out-of-gas") @@ -408,13 +428,15 @@ func TestPrepareRequestNotEnoughPrepareGas(t *testing.T) { } func TestPrepareRequestInvalidAskCountFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + params := k.GetParams(ctx) params.MaxAskCount = 5 err := k.SetParams(ctx, params) require.NoError(t, err) - wrappedGasMeter := testapp.NewGasMeterWrapper(ctx.GasMeter()) + wrappedGasMeter := bandtesting.NewGasMeterWrapper(ctx.GasMeter()) ctx = ctx.WithGasMeter(wrappedGasMeter) m := types.NewMsgRequestData( @@ -423,14 +445,14 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { 10, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrInvalidAskCount) require.Equal(t, 0, wrappedGasMeter.CountDescriptor("BASE_OWASM_FEE")) @@ -443,14 +465,14 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { 4, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrInsufficientValidators) require.Equal(t, 0, wrappedGasMeter.CountDescriptor("BASE_OWASM_FEE")) @@ -463,14 +485,14 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) require.Equal(t, 2, wrappedGasMeter.CountDescriptor("BASE_OWASM_FEE")) @@ -479,7 +501,9 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { } func TestPrepareRequestBaseOwasmFeePanic(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + params := k.GetParams(ctx) params.BaseOwasmGas = 100000 params.PerValidatorRequestGas = 0 @@ -491,10 +515,10 @@ func TestPrepareRequestBaseOwasmFeePanic(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) @@ -502,16 +526,18 @@ func TestPrepareRequestBaseOwasmFeePanic(t *testing.T) { require.PanicsWithValue( t, sdk.ErrorOutOfGas{Descriptor: "BASE_OWASM_FEE"}, - func() { _, _ = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, + func() { _, _ = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) }, ) ctx = ctx.WithGasMeter(sdk.NewGasMeter(1000000)) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) } func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + params := k.GetParams(ctx) params.BaseOwasmGas = 100000 params.PerValidatorRequestGas = 50000 @@ -523,10 +549,10 @@ func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { 2, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) @@ -534,7 +560,7 @@ func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { require.PanicsWithValue( t, sdk.ErrorOutOfGas{Descriptor: "PER_VALIDATOR_REQUEST_FEE"}, - func() { _, _ = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, + func() { _, _ = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) }, ) m = types.NewMsgRequestData( 1, @@ -542,107 +568,119 @@ func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) ctx = ctx.WithGasMeter(sdk.NewGasMeter(1000000)) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) } func TestPrepareRequestEmptyCalldata(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) // Send nil while oracle script expects calldata + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Send nil while oracle script expects calldata m := types.NewMsgRequestData( 4, nil, 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "runtime error while executing the Wasm script: bad wasm execution") } func TestPrepareRequestOracleScriptNotFound(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + m := types.NewMsgRequestData( 999, BasicCalldata, 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "id: 999: oracle script not found") } func TestPrepareRequestBadWasmExecutionFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + m := types.NewMsgRequestData( 2, BasicCalldata, 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "OEI action to invoke is not available: bad wasm execution") } func TestPrepareRequestWithEmptyRawRequest(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + m := types.NewMsgRequestData( 3, BasicCalldata, 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "empty raw requests") } func TestPrepareRequestUnknownDataSource(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + m := types.NewMsgRequestData(4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2, 99}, Calldata: "beeb", - }), 1, 1, BasicClientID, testapp.Coins100000000uband, testapp.TestDefaultPrepareGas, testapp.TestDefaultExecuteGas, testapp.Alice.Address, 0, 0) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, 0) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "id: 99: data source not found") } func TestPrepareRequestInvalidDataSourceCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + params := k.GetParams(ctx) params.MaxRawRequestCount = 3 err := k.SetParams(ctx, params) @@ -650,20 +688,21 @@ func TestPrepareRequestInvalidDataSourceCount(t *testing.T) { m := types.NewMsgRequestData(4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2, 3, 4}, Calldata: "beeb", - }), 1, 1, BasicClientID, testapp.Coins100000000uband, testapp.TestDefaultPrepareGas, testapp.TestDefaultExecuteGas, testapp.Alice.Address, 0, 0) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, 0) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrBadWasmExecution) m = types.NewMsgRequestData(4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2, 3}, Calldata: "beeb", - }), 1, 1, BasicClientID, testapp.Coins100000000uband, testapp.TestDefaultPrepareGas, testapp.TestDefaultExecuteGas, testapp.Alice.Address, 0, 0) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, 0) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) } func TestPrepareRequestTooMuchWasmGas(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper m := types.NewMsgRequestData( 5, @@ -671,14 +710,14 @@ func TestPrepareRequestTooMuchWasmGas(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) m = types.NewMsgRequestData( @@ -687,19 +726,20 @@ func TestPrepareRequestTooMuchWasmGas(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "out-of-gas while executing the wasm script: bad wasm execution") } func TestPrepareRequestTooLargeCalldata(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper m := types.NewMsgRequestData( 7, @@ -707,14 +747,14 @@ func TestPrepareRequestTooLargeCalldata(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) m = types.NewMsgRequestData( @@ -723,39 +763,47 @@ func TestPrepareRequestTooLargeCalldata(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, 0, 0, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "span to write is too small: bad wasm execution") } func TestResolveRequestSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 1st Wasm - return "beeb" - 1, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 1, + BasicCalldata, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 1, + 42, + bandtesting.ParseTime(1581589790), + BasicClientID, + []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, testapp.TestDefaultExecuteGas, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + }, nil, bandtesting.TestDefaultExecuteGas, 0, 0, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("beeb")), }, )) k.ResolveRequest(ctx, 42) expectResult := types.NewResult( BasicClientID, 1, BasicCalldata, 2, 1, - 42, 1, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, []byte("beeb"), + 42, 1, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, []byte("beeb"), ) require.Equal(t, expectResult, k.MustGetResult(ctx, 42)) @@ -774,29 +822,31 @@ func TestResolveRequestSuccess(t *testing.T) { } func TestResolveRequestSuccessComplex(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 4th Wasm. Append all reports from all validators. 4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2}, Calldata: string(BasicCalldata), - }), []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + }), []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, 1, + 42, bandtesting.ParseTime(1581589790), BasicClientID, []types.RawRequest{ types.NewRawRequest(0, 1, BasicCalldata), types.NewRawRequest(1, 2, BasicCalldata), - }, nil, testapp.TestDefaultExecuteGas, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + }, nil, bandtesting.TestDefaultExecuteGas, 0, 0, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(0, 0, []byte("beebd1v1")), types.NewRawReport(1, 0, []byte("beebd2v1")), }, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[1].ValAddress, true, []types.RawReport{ + bandtesting.Validators[1].ValAddress, true, []types.RawReport{ types.NewRawReport(0, 0, []byte("beebd1v2")), types.NewRawReport(1, 0, []byte("beebd2v2")), }, @@ -807,8 +857,8 @@ func TestResolveRequestSuccessComplex(t *testing.T) { IDs: []int64{1, 2}, Calldata: string(BasicCalldata), }), 2, 1, - 42, 2, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, + 42, 2, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, obi.MustEncode(testdata.Wasm4Output{Ret: "beebd1v1beebd1v2beebd2v1beebd2v2"}), ) require.Equal(t, result, k.MustGetResult(ctx, 42)) @@ -827,55 +877,65 @@ func TestResolveRequestSuccessComplex(t *testing.T) { } func TestResolveRequestOutOfGas(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 1st Wasm - return "beeb" - 1, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 1, + BasicCalldata, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 1, + 42, + bandtesting.ParseTime(1581589790), + BasicClientID, + []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), }, nil, 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("beeb")), }, )) k.ResolveRequest(ctx, 42) result := types.NewResult( BasicClientID, 1, BasicCalldata, 2, 1, - 42, 1, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, + 42, 1, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, ) require.Equal(t, result, k.MustGetResult(ctx, 42)) } func TestResolveReadNilExternalData(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 4th Wasm. Append all reports from all validators. 4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2}, Calldata: string(BasicCalldata), - }), []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + }), []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, 1, + 42, bandtesting.ParseTime(1581589790), BasicClientID, []types.RawRequest{ types.NewRawRequest(0, 1, BasicCalldata), types.NewRawRequest(1, 2, BasicCalldata), - }, nil, testapp.TestDefaultExecuteGas, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + }, nil, bandtesting.TestDefaultExecuteGas, 0, 0, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(0, 0, nil), types.NewRawReport(1, 0, []byte("beebd2v1")), }, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[1].ValAddress, true, []types.RawReport{ + bandtesting.Validators[1].ValAddress, true, []types.RawReport{ types.NewRawReport(0, 0, []byte("beebd1v2")), types.NewRawReport(1, 0, nil), }, @@ -886,8 +946,8 @@ func TestResolveReadNilExternalData(t *testing.T) { IDs: []int64{1, 2}, Calldata: string(BasicCalldata), }), 2, 1, - 42, 2, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, + 42, 2, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, obi.MustEncode(testdata.Wasm4Output{Ret: "beebd1v2beebd2v1"}), ) require.Equal(t, result, k.MustGetResult(ctx, 42)) @@ -902,26 +962,34 @@ func TestResolveReadNilExternalData(t *testing.T) { } func TestResolveRequestNoReturnData(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 3rd Wasm - do nothing - 3, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 3, + BasicCalldata, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 1, + 42, + bandtesting.ParseTime(1581589790), + BasicClientID, + []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), }, nil, 1, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("beeb")), }, )) k.ResolveRequest(ctx, 42) result := types.NewResult( - BasicClientID, 3, BasicCalldata, 2, 1, 42, 1, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, + BasicClientID, 3, BasicCalldata, 2, 1, 42, 1, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, ) require.Equal(t, result, k.MustGetResult(ctx, 42)) require.Equal(t, sdk.Events{sdk.NewEvent( @@ -933,26 +1001,34 @@ func TestResolveRequestNoReturnData(t *testing.T) { } func TestResolveRequestWasmFailure(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 6th Wasm - out-of-gas - 6, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 6, + BasicCalldata, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 1, + 42, + bandtesting.ParseTime(1581589790), + BasicClientID, + []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), }, nil, 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("beeb")), }, )) k.ResolveRequest(ctx, 42) result := types.NewResult( - BasicClientID, 6, BasicCalldata, 2, 1, 42, 1, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, + BasicClientID, 6, BasicCalldata, 2, 1, 42, 1, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, ) require.Equal(t, result, k.MustGetResult(ctx, 42)) require.Equal(t, sdk.Events{sdk.NewEvent( @@ -964,22 +1040,30 @@ func TestResolveRequestWasmFailure(t *testing.T) { } func TestResolveRequestCallReturnDataSeveralTimes(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 9th Wasm - set return data several times - 9, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 9, + BasicCalldata, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 1, + 42, + bandtesting.ParseTime(1581589790), + BasicClientID, + []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, testapp.TestDefaultExecuteGas, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + }, nil, bandtesting.TestDefaultExecuteGas, 0, 0, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, )) k.ResolveRequest(ctx, 42) result := types.NewResult( - BasicClientID, 9, BasicCalldata, 2, 1, 42, 0, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, + BasicClientID, 9, BasicCalldata, 2, 1, 42, 0, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, ) require.Equal(t, result, k.MustGetResult(ctx, 42)) @@ -995,12 +1079,12 @@ func rawRequestsFromFees(ctx sdk.Context, k keeper.Keeper, fees []sdk.Coins) []t var rawRequests []types.RawRequest for _, f := range fees { id := k.AddDataSource(ctx, types.NewDataSource( - testapp.Owner.Address, + bandtesting.Owner.Address, "mock ds", "there is no real code", "no file", f, - testapp.Treasury.Address, + bandtesting.Treasury.Address, )) rawRequests = append(rawRequests, types.NewRawRequest( @@ -1012,131 +1096,136 @@ func rawRequestsFromFees(ctx sdk.Context, k keeper.Keeper, fees []sdk.Coins) []t } func TestCollectFeeEmptyFee(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.EmptyCoins, - testapp.EmptyCoins, - testapp.EmptyCoins, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.EmptyCoins, }) - coins, err := k.CollectFee(ctx, testapp.Alice.Address, testapp.EmptyCoins, 1, raws) + coins, err := k.CollectFee(ctx, bandtesting.Alice.Address, bandtesting.EmptyCoins, 1, raws) require.NoError(t, err) require.Empty(t, coins) - coins, err = k.CollectFee(ctx, testapp.Alice.Address, testapp.Coins100000000uband, 1, raws) + coins, err = k.CollectFee(ctx, bandtesting.Alice.Address, bandtesting.Coins100000000uband, 1, raws) require.NoError(t, err) require.Empty(t, coins) - coins, err = k.CollectFee(ctx, testapp.Alice.Address, testapp.EmptyCoins, 2, raws) + coins, err = k.CollectFee(ctx, bandtesting.Alice.Address, bandtesting.EmptyCoins, 2, raws) require.NoError(t, err) require.Empty(t, coins) - coins, err = k.CollectFee(ctx, testapp.Alice.Address, testapp.Coins100000000uband, 2, raws) + coins, err = k.CollectFee(ctx, bandtesting.Alice.Address, bandtesting.Coins100000000uband, 2, raws) require.NoError(t, err) require.Empty(t, coins) } func TestCollectFeeBasicSuccess(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) balancesRes, err := app.BankKeeper.AllBalances( sdk.WrapSDKContext(ctx), - authtypes.NewQueryAllBalancesRequest(testapp.FeePayer.Address, &query.PageRequest{}), + authtypes.NewQueryAllBalancesRequest(bandtesting.FeePayer.Address, &query.PageRequest{}), ) require.NoError(t, err) feePayerBalances := balancesRes.Balances feePayerBalances[0].Amount = feePayerBalances[0].Amount.Sub(sdk.NewInt(3000000)) - coins, err := k.CollectFee(ctx, testapp.FeePayer.Address, testapp.Coins100000000uband, 1, raws) + coins, err := k.CollectFee(ctx, bandtesting.FeePayer.Address, bandtesting.Coins100000000uband, 1, raws) require.NoError(t, err) require.Equal(t, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), coins) - testapp.CheckBalances(t, ctx, app.BankKeeper, testapp.FeePayer.Address, feePayerBalances) - testapp.CheckBalances( + bandtesting.CheckBalances(t, ctx, app.BankKeeper, bandtesting.FeePayer.Address, feePayerBalances) + bandtesting.CheckBalances( t, ctx, app.BankKeeper, - testapp.Treasury.Address, + bandtesting.Treasury.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), ) } func TestCollectFeeBasicSuccessWithOtherAskCount(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) balancesRes, err := app.BankKeeper.AllBalances( sdk.WrapSDKContext(ctx), - authtypes.NewQueryAllBalancesRequest(testapp.FeePayer.Address, &query.PageRequest{}), + authtypes.NewQueryAllBalancesRequest(bandtesting.FeePayer.Address, &query.PageRequest{}), ) require.NoError(t, err) feePayerBalances := balancesRes.Balances feePayerBalances[0].Amount = feePayerBalances[0].Amount.Sub(sdk.NewInt(12000000)) - coins, err := k.CollectFee(ctx, testapp.FeePayer.Address, testapp.Coins100000000uband, 4, raws) + coins, err := k.CollectFee(ctx, bandtesting.FeePayer.Address, bandtesting.Coins100000000uband, 4, raws) require.NoError(t, err) require.Equal(t, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(12000000))), coins) - testapp.CheckBalances(t, ctx, app.BankKeeper, testapp.FeePayer.Address, feePayerBalances) - testapp.CheckBalances( + bandtesting.CheckBalances(t, ctx, app.BankKeeper, bandtesting.FeePayer.Address, feePayerBalances) + bandtesting.CheckBalances( t, ctx, app.BankKeeper, - testapp.Treasury.Address, + bandtesting.Treasury.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(12000000))), ) } func TestCollectFeeWithMixedAndFeeNotEnough(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) - coins, err := k.CollectFee(ctx, testapp.FeePayer.Address, testapp.EmptyCoins, 1, raws) + coins, err := k.CollectFee(ctx, bandtesting.FeePayer.Address, bandtesting.EmptyCoins, 1, raws) require.ErrorIs(t, err, types.ErrNotEnoughFee) require.Nil(t, coins) - coins, err = k.CollectFee(ctx, testapp.FeePayer.Address, testapp.Coins1000000uband, 1, raws) + coins, err = k.CollectFee(ctx, bandtesting.FeePayer.Address, bandtesting.Coins1000000uband, 1, raws) require.ErrorIs(t, err, types.ErrNotEnoughFee) require.Nil(t, coins) } func TestCollectFeeWithEnoughFeeButInsufficientBalance(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) - coins, err := k.CollectFee(ctx, testapp.Alice.Address, testapp.Coins100000000uband, 1, raws) + coins, err := k.CollectFee(ctx, bandtesting.Alice.Address, bandtesting.Coins100000000uband, 1, raws) require.Nil(t, coins) // MAX is 100m but have only 1m in account // First ds collect 1m so there no balance enough for next ds but it doesn't touch limit @@ -1144,14 +1233,15 @@ func TestCollectFeeWithEnoughFeeButInsufficientBalance(t *testing.T) { } func TestCollectFeeWithWithManyUnitSuccess(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000)), sdk.NewCoin("uabc", sdk.NewInt(1000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(2000000)))) @@ -1161,15 +1251,15 @@ func TestCollectFeeWithWithManyUnitSuccess(t *testing.T) { err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, - testapp.FeePayer.Address, + bandtesting.FeePayer.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(2000000))), ) require.NoError(t, err) coins, err := k.CollectFee( ctx, - testapp.FeePayer.Address, - testapp.MustGetBalances(ctx, app.BankKeeper, testapp.FeePayer.Address), + bandtesting.FeePayer.Address, + bandtesting.MustGetBalances(ctx, app.BankKeeper, bandtesting.FeePayer.Address), 1, raws, ) @@ -1186,35 +1276,36 @@ func TestCollectFeeWithWithManyUnitSuccess(t *testing.T) { // start: 100band, 0abc // top-up: 100band, 2abc // collect 3 band and 1 abc => 97band, 1abc - testapp.CheckBalances( + bandtesting.CheckBalances( t, ctx, app.BankKeeper, - testapp.FeePayer.Address, + bandtesting.FeePayer.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(97000000)), sdk.NewCoin("uabc", sdk.NewInt(1000000))), ) // Treasury balance // start: 0band, 0abc // collect 3 band and 1 abc => 3band, 1abc - testapp.CheckBalances( + bandtesting.CheckBalances( t, ctx, app.BankKeeper, - testapp.Treasury.Address, + bandtesting.Treasury.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000)), sdk.NewCoin("uabc", sdk.NewInt(1000000))), ) } func TestCollectFeeWithWithManyUnitFail(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000)), sdk.NewCoin("uabc", sdk.NewInt(1000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) err := app.BankKeeper.MintCoins( @@ -1229,7 +1320,7 @@ func TestCollectFeeWithWithManyUnitFail(t *testing.T) { err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, - testapp.Bob.Address, + bandtesting.Bob.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), ) require.NoError(t, err) @@ -1237,7 +1328,7 @@ func TestCollectFeeWithWithManyUnitFail(t *testing.T) { err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, - testapp.Bob.Address, + bandtesting.Bob.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(1))), ) require.NoError(t, err) @@ -1246,7 +1337,7 @@ func TestCollectFeeWithWithManyUnitFail(t *testing.T) { err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, - testapp.Carol.Address, + bandtesting.Carol.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(1000000))), ) require.NoError(t, err) @@ -1254,8 +1345,8 @@ func TestCollectFeeWithWithManyUnitFail(t *testing.T) { // Alice _, err = k.CollectFee( ctx, - testapp.Alice.Address, - testapp.MustGetBalances(ctx, app.BankKeeper, testapp.Alice.Address), + bandtesting.Alice.Address, + bandtesting.MustGetBalances(ctx, app.BankKeeper, bandtesting.Alice.Address), 1, raws, ) @@ -1264,8 +1355,8 @@ func TestCollectFeeWithWithManyUnitFail(t *testing.T) { // Bob _, err = k.CollectFee( ctx, - testapp.Bob.Address, - testapp.MustGetBalances(ctx, app.BankKeeper, testapp.Bob.Address), + bandtesting.Bob.Address, + bandtesting.MustGetBalances(ctx, app.BankKeeper, bandtesting.Bob.Address), 1, raws, ) @@ -1274,8 +1365,8 @@ func TestCollectFeeWithWithManyUnitFail(t *testing.T) { // Carol _, err = k.CollectFee( ctx, - testapp.Carol.Address, - testapp.MustGetBalances(ctx, app.BankKeeper, testapp.Carol.Address), + bandtesting.Carol.Address, + bandtesting.MustGetBalances(ctx, app.BankKeeper, bandtesting.Carol.Address), 1, raws, ) diff --git a/x/oracle/keeper/params_test.go b/x/oracle/keeper/params_test.go index 58fdb502a..6c5889e45 100644 --- a/x/oracle/keeper/params_test.go +++ b/x/oracle/keeper/params_test.go @@ -6,12 +6,14 @@ import ( "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestGetSetParams(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + expectedParams := types.Params{ MaxRawRequestCount: 1, MaxAskCount: 10, diff --git a/x/oracle/keeper/report_test.go b/x/oracle/keeper/report_test.go index 3b58970c1..a24b89352 100644 --- a/x/oracle/keeper/report_test.go +++ b/x/oracle/keeper/report_test.go @@ -6,45 +6,49 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func defaultRequest() types.Request { return types.NewRequest( 1, BasicCalldata, - []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, - 2, 0, testapp.ParseTime(0), + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 2, 0, bandtesting.ParseTime(0), BasicClientID, []types.RawRequest{ types.NewRawRequest(42, 1, BasicCalldata), types.NewRawRequest(43, 2, BasicCalldata), }, nil, 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ) } func TestHasReport(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should not have a report to request ID 42 from Alice without setting it. - require.False(t, k.HasReport(ctx, 42, testapp.Alice.ValAddress)) + require.False(t, k.HasReport(ctx, 42, bandtesting.Alice.ValAddress)) // After we set it, we should be able to find it. - k.SetReport(ctx, 42, types.NewReport(testapp.Alice.ValAddress, true, nil)) - require.True(t, k.HasReport(ctx, 42, testapp.Alice.ValAddress)) + k.SetReport(ctx, 42, types.NewReport(bandtesting.Alice.ValAddress, true, nil)) + require.True(t, k.HasReport(ctx, 42, bandtesting.Alice.ValAddress)) } func TestAddReportSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 1, defaultRequest()) err := k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }, ) require.NoError(t, err) require.Equal(t, []types.Report{ - types.NewReport(testapp.Validators[0].ValAddress, true, []types.RawReport{ + types.NewReport(bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }), @@ -52,9 +56,11 @@ func TestAddReportSuccess(t *testing.T) { } func TestReportOnNonExistingRequest(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + err := k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }, @@ -63,10 +69,12 @@ func TestReportOnNonExistingRequest(t *testing.T) { } func TestReportByNotRequestedValidator(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 1, defaultRequest()) err := k.AddReport(ctx, 1, - testapp.Alice.ValAddress, true, []types.RawReport{ + bandtesting.Alice.ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }, @@ -75,17 +83,19 @@ func TestReportByNotRequestedValidator(t *testing.T) { } func TestDuplicateReport(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 1, defaultRequest()) err := k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }, ) require.NoError(t, err) err = k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }, @@ -94,10 +104,12 @@ func TestDuplicateReport(t *testing.T) { } func TestReportInvalidDataSourceCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 1, defaultRequest()) err := k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), }, ) @@ -105,10 +117,12 @@ func TestReportInvalidDataSourceCount(t *testing.T) { } func TestReportInvalidExternalIDs(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 1, defaultRequest()) err := k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(44, 1, []byte("data2/1")), // BAD EXTERNAL ID! }, @@ -117,37 +131,41 @@ func TestReportInvalidExternalIDs(t *testing.T) { } func TestGetReportCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We start by setting some aribrary reports. - k.SetReport(ctx, types.RequestID(1), types.NewReport(testapp.Alice.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(1), types.NewReport(testapp.Bob.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Alice.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Bob.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Carol.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(1), types.NewReport(bandtesting.Alice.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(1), types.NewReport(bandtesting.Bob.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Alice.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Bob.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Carol.ValAddress, true, []types.RawReport{})) // GetReportCount should return the correct values. require.Equal(t, uint64(2), k.GetReportCount(ctx, types.RequestID(1))) require.Equal(t, uint64(3), k.GetReportCount(ctx, types.RequestID(2))) } func TestDeleteReports(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We start by setting some arbitrary reports. - k.SetReport(ctx, types.RequestID(1), types.NewReport(testapp.Alice.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(1), types.NewReport(testapp.Bob.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Alice.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Bob.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Carol.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(1), types.NewReport(bandtesting.Alice.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(1), types.NewReport(bandtesting.Bob.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Alice.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Bob.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Carol.ValAddress, true, []types.RawReport{})) // All reports should exist on the state. - require.True(t, k.HasReport(ctx, types.RequestID(1), testapp.Alice.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(1), testapp.Bob.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Alice.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Bob.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Carol.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(1), bandtesting.Alice.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(1), bandtesting.Bob.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Alice.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Bob.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Carol.ValAddress)) // After we delete reports related to request#1, they must disappear. k.DeleteReports(ctx, types.RequestID(1)) - require.False(t, k.HasReport(ctx, types.RequestID(1), testapp.Alice.ValAddress)) - require.False(t, k.HasReport(ctx, types.RequestID(1), testapp.Bob.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Alice.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Bob.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Carol.ValAddress)) + require.False(t, k.HasReport(ctx, types.RequestID(1), bandtesting.Alice.ValAddress)) + require.False(t, k.HasReport(ctx, types.RequestID(1), bandtesting.Bob.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Alice.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Bob.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Carol.ValAddress)) } diff --git a/x/oracle/keeper/request_test.go b/x/oracle/keeper/request_test.go index 3ad5df372..902ea6a7f 100644 --- a/x/oracle/keeper/request_test.go +++ b/x/oracle/keeper/request_test.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/keeper" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -34,7 +34,9 @@ func testRequest( } func TestHasRequest(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should not have a request ID 42 without setting it. require.False(t, k.HasRequest(ctx, 42)) // After we set it, we should be able to find it. @@ -47,22 +49,24 @@ func TestHasRequest(t *testing.T) { nil, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", nil, nil, 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ), ) require.True(t, k.HasRequest(ctx, 42)) } func TestDeleteRequest(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // After we set it, we should be able to find it. k.SetRequest( ctx, @@ -73,15 +77,15 @@ func TestDeleteRequest(t *testing.T) { nil, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", nil, nil, 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ), ) require.True(t, k.HasRequest(ctx, 42)) @@ -94,7 +98,9 @@ func TestDeleteRequest(t *testing.T) { } func TestSetterGetterRequest(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Getting a non-existent request should return error. _, err := k.GetRequest(ctx, 42) require.ErrorIs(t, err, types.ErrRequestNotFound) @@ -106,15 +112,15 @@ func TestSetterGetterRequest(t *testing.T) { nil, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", nil, nil, 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ) req2 := types.NewRequest( 2, @@ -122,15 +128,15 @@ func TestSetterGetterRequest(t *testing.T) { nil, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", nil, nil, 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ) // Sets id 42 with request 1 and id 42 with request 2. k.SetRequest(ctx, 42, req1) @@ -151,7 +157,9 @@ func TestSetterGetterRequest(t *testing.T) { } func TestSetterGettterPendingResolveList(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially, we should get an empty list of pending resolves. require.Equal(t, k.GetPendingResolveList(ctx), []types.RequestID{}) // After we set something, we should get that thing back. @@ -166,10 +174,12 @@ func TestSetterGettterPendingResolveList(t *testing.T) { } func TestAddDataSourceBasic(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We start by setting an oracle request available at ID 42. k.SetOracleScript(ctx, 42, types.NewOracleScript( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, )) // Adding the first request should return ID 1. id := k.AddRequest( @@ -180,15 +190,15 @@ func TestAddDataSourceBasic(t *testing.T) { []sdk.ValAddress{}, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", nil, nil, 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ), ) require.Equal(t, id, types.RequestID(1)) @@ -201,22 +211,24 @@ func TestAddDataSourceBasic(t *testing.T) { []sdk.ValAddress{}, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", nil, nil, 0, 0, 0, - testapp.FeePayer.Address.String(), - testapp.Coins100000000uband, + bandtesting.FeePayer.Address.String(), + bandtesting.Coins100000000uband, ), ) require.Equal(t, id, types.RequestID(2)) } func TestAddPendingResolveList(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially, we should get an empty list of pending resolves. require.Equal(t, k.GetPendingResolveList(ctx), []types.RequestID{}) // Everytime we append a new request ID, it should show up. @@ -227,7 +239,9 @@ func TestAddPendingResolveList(t *testing.T) { } func TestProcessExpiredRequests(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + params := k.GetParams(ctx) params.ExpirationBlockCount = 3 err := k.SetParams(ctx, params) @@ -248,24 +262,24 @@ func TestProcessExpiredRequests(t *testing.T) { k.AddRequest(ctx, req4) // Initially all validators are active. - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress).IsActive) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress).IsActive) // Validator 1 reports all requests. Validator 2 misses request#3. rawReports := []types.RawReport{types.NewRawReport(42, 0, BasicReport), types.NewRawReport(43, 0, BasicReport)} - err = k.AddReport(ctx, 1, testapp.Validators[0].ValAddress, false, rawReports) + err = k.AddReport(ctx, 1, bandtesting.Validators[0].ValAddress, false, rawReports) require.NoError(t, err) - err = k.AddReport(ctx, 2, testapp.Validators[0].ValAddress, true, rawReports) + err = k.AddReport(ctx, 2, bandtesting.Validators[0].ValAddress, true, rawReports) require.NoError(t, err) - err = k.AddReport(ctx, 3, testapp.Validators[0].ValAddress, false, rawReports) + err = k.AddReport(ctx, 3, bandtesting.Validators[0].ValAddress, false, rawReports) require.NoError(t, err) - err = k.AddReport(ctx, 4, testapp.Validators[0].ValAddress, true, rawReports) + err = k.AddReport(ctx, 4, bandtesting.Validators[0].ValAddress, true, rawReports) require.NoError(t, err) - err = k.AddReport(ctx, 1, testapp.Validators[1].ValAddress, true, rawReports) + err = k.AddReport(ctx, 1, bandtesting.Validators[1].ValAddress, true, rawReports) require.NoError(t, err) - err = k.AddReport(ctx, 2, testapp.Validators[1].ValAddress, true, rawReports) + err = k.AddReport(ctx, 2, bandtesting.Validators[1].ValAddress, true, rawReports) require.NoError(t, err) - err = k.AddReport(ctx, 4, testapp.Validators[1].ValAddress, true, rawReports) + err = k.AddReport(ctx, 4, bandtesting.Validators[1].ValAddress, true, rawReports) require.NoError(t, err) // Request 1, 2 and 4 gets resolved. Request 3 does not. @@ -276,31 +290,31 @@ func TestProcessExpiredRequests(t *testing.T) { require.Equal(t, types.RequestID(0), k.GetRequestLastExpired(ctx)) // At block 7, nothing should happen. - ctx = ctx.WithBlockHeight(7).WithBlockTime(testapp.ParseTime(7000)).WithEventManager(sdk.NewEventManager()) + ctx = ctx.WithBlockHeight(7).WithBlockTime(bandtesting.ParseTime(7000)).WithEventManager(sdk.NewEventManager()) k.ProcessExpiredRequests(ctx) require.Equal(t, sdk.Events{}, ctx.EventManager().Events()) require.Equal(t, types.RequestID(0), k.GetRequestLastExpired(ctx)) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress).IsActive) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress).IsActive) testRequest(t, k, ctx, types.RequestID(1), types.RESOLVE_STATUS_SUCCESS, 2, true) testRequest(t, k, ctx, types.RequestID(2), types.RESOLVE_STATUS_FAILURE, 2, true) testRequest(t, k, ctx, types.RequestID(3), types.RESOLVE_STATUS_OPEN, 1, true) testRequest(t, k, ctx, types.RequestID(4), types.RESOLVE_STATUS_SUCCESS, 2, true) // At block 8, now last request ID should move to 1. No events should be emitted. - ctx = ctx.WithBlockHeight(8).WithBlockTime(testapp.ParseTime(8000)).WithEventManager(sdk.NewEventManager()) + ctx = ctx.WithBlockHeight(8).WithBlockTime(bandtesting.ParseTime(8000)).WithEventManager(sdk.NewEventManager()) k.ProcessExpiredRequests(ctx) require.Equal(t, sdk.Events{}, ctx.EventManager().Events()) require.Equal(t, types.RequestID(1), k.GetRequestLastExpired(ctx)) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress).IsActive) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress).IsActive) testRequest(t, k, ctx, types.RequestID(1), types.RESOLVE_STATUS_SUCCESS, 0, false) testRequest(t, k, ctx, types.RequestID(2), types.RESOLVE_STATUS_FAILURE, 2, true) testRequest(t, k, ctx, types.RequestID(3), types.RESOLVE_STATUS_OPEN, 1, true) testRequest(t, k, ctx, types.RequestID(4), types.RESOLVE_STATUS_SUCCESS, 2, true) // At block 9, request#3 is expired and validator 2 becomes inactive. - ctx = ctx.WithBlockHeight(9).WithBlockTime(testapp.ParseTime(9000)).WithEventManager(sdk.NewEventManager()) + ctx = ctx.WithBlockHeight(9).WithBlockTime(bandtesting.ParseTime(9000)).WithEventManager(sdk.NewEventManager()) k.ProcessExpiredRequests(ctx) require.Equal(t, sdk.Events{sdk.NewEvent( types.EventTypeResolve, @@ -308,14 +322,14 @@ func TestProcessExpiredRequests(t *testing.T) { sdk.NewAttribute(types.AttributeKeyResolveStatus, "3"), ), sdk.NewEvent( types.EventTypeDeactivate, - sdk.NewAttribute(types.AttributeKeyValidator, testapp.Validators[1].ValAddress.String()), + sdk.NewAttribute(types.AttributeKeyValidator, bandtesting.Validators[1].ValAddress.String()), )}, ctx.EventManager().Events()) require.Equal(t, types.RequestID(3), k.GetRequestLastExpired(ctx)) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress).IsActive) - require.False(t, k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress).IsActive) + require.False(t, k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress).IsActive) require.Equal(t, types.NewResult( BasicClientID, req3.OracleScriptID, req3.Calldata, uint64(len(req3.RequestedValidators)), req3.MinCount, - 3, 1, req3.RequestTime, testapp.ParseTime(9000).Unix(), + 3, 1, req3.RequestTime, bandtesting.ParseTime(9000).Unix(), types.RESOLVE_STATUS_EXPIRED, nil, ), k.MustGetResult(ctx, 3)) testRequest(t, k, ctx, types.RequestID(1), types.RESOLVE_STATUS_SUCCESS, 0, false) @@ -324,7 +338,7 @@ func TestProcessExpiredRequests(t *testing.T) { testRequest(t, k, ctx, types.RequestID(4), types.RESOLVE_STATUS_SUCCESS, 2, true) // At block 10, nothing should happen - ctx = ctx.WithBlockHeight(10).WithBlockTime(testapp.ParseTime(10000)).WithEventManager(sdk.NewEventManager()) + ctx = ctx.WithBlockHeight(10).WithBlockTime(bandtesting.ParseTime(10000)).WithEventManager(sdk.NewEventManager()) k.ProcessExpiredRequests(ctx) require.Equal(t, sdk.Events{}, ctx.EventManager().Events()) require.Equal(t, types.RequestID(3), k.GetRequestLastExpired(ctx)) @@ -334,7 +348,7 @@ func TestProcessExpiredRequests(t *testing.T) { testRequest(t, k, ctx, types.RequestID(4), types.RESOLVE_STATUS_SUCCESS, 2, true) // At block 13, last expired request becomes 4. - ctx = ctx.WithBlockHeight(13).WithBlockTime(testapp.ParseTime(13000)).WithEventManager(sdk.NewEventManager()) + ctx = ctx.WithBlockHeight(13).WithBlockTime(bandtesting.ParseTime(13000)).WithEventManager(sdk.NewEventManager()) k.ProcessExpiredRequests(ctx) require.Equal(t, sdk.Events{}, ctx.EventManager().Events()) require.Equal(t, types.RequestID(4), k.GetRequestLastExpired(ctx)) diff --git a/x/oracle/keeper/result_test.go b/x/oracle/keeper/result_test.go index 2b1f276ba..61c83e8b4 100644 --- a/x/oracle/keeper/result_test.go +++ b/x/oracle/keeper/result_test.go @@ -6,12 +6,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestResultBasicFunctions(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We start by setting result of request#1. result := types.NewResult( "alice", 1, BasicCalldata, 1, 1, 1, 1, 1589535020, 1589535022, 1, BasicResult, @@ -33,14 +35,16 @@ func TestResultBasicFunctions(t *testing.T) { } func TestSaveResultOK(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(200)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(200)) k.SetRequest(ctx, 42, defaultRequest()) // See report_test.go - k.SetReport(ctx, 42, types.NewReport(testapp.Validators[0].ValAddress, true, nil)) + k.SetReport(ctx, 42, types.NewReport(bandtesting.Validators[0].ValAddress, true, nil)) k.SaveResult(ctx, 42, types.RESOLVE_STATUS_SUCCESS, BasicResult) expect := types.NewResult( - BasicClientID, 1, BasicCalldata, 2, 2, 42, 1, testapp.ParseTime(0).Unix(), - testapp.ParseTime(200).Unix(), types.RESOLVE_STATUS_SUCCESS, BasicResult, + BasicClientID, 1, BasicCalldata, 2, 2, 42, 1, bandtesting.ParseTime(0).Unix(), + bandtesting.ParseTime(200).Unix(), types.RESOLVE_STATUS_SUCCESS, BasicResult, ) result, err := k.GetResult(ctx, 42) require.NoError(t, err) @@ -48,9 +52,11 @@ func TestSaveResultOK(t *testing.T) { } func TestResolveSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 42, defaultRequest()) // See report_test.go - k.SetReport(ctx, 42, types.NewReport(testapp.Validators[0].ValAddress, true, nil)) + k.SetReport(ctx, 42, types.NewReport(bandtesting.Validators[0].ValAddress, true, nil)) k.ResolveSuccess(ctx, 42, defaultRequest().Requester, defaultRequest().FeeLimit, BasicResult, 1234, 0, 0) require.Equal(t, types.RESOLVE_STATUS_SUCCESS, k.MustGetResult(ctx, 42).ResolveStatus) require.Equal(t, BasicResult, k.MustGetResult(ctx, 42).Result) @@ -64,9 +70,11 @@ func TestResolveSuccess(t *testing.T) { } func TestResolveFailure(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 42, defaultRequest()) // See report_test.go - k.SetReport(ctx, 42, types.NewReport(testapp.Validators[0].ValAddress, true, nil)) + k.SetReport(ctx, 42, types.NewReport(bandtesting.Validators[0].ValAddress, true, nil)) k.ResolveFailure(ctx, 42, "REASON") require.Equal(t, types.RESOLVE_STATUS_FAILURE, k.MustGetResult(ctx, 42).ResolveStatus) require.Empty(t, k.MustGetResult(ctx, 42).Result) @@ -79,9 +87,11 @@ func TestResolveFailure(t *testing.T) { } func TestResolveExpired(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 42, defaultRequest()) // See report_test.go - k.SetReport(ctx, 42, types.NewReport(testapp.Validators[0].ValAddress, true, nil)) + k.SetReport(ctx, 42, types.NewReport(bandtesting.Validators[0].ValAddress, true, nil)) k.ResolveExpired(ctx, 42) require.Equal(t, types.RESOLVE_STATUS_EXPIRED, k.MustGetResult(ctx, 42).ResolveStatus) require.Empty(t, k.MustGetResult(ctx, 42).Result) diff --git a/x/oracle/keeper/signing_test.go b/x/oracle/keeper/signing_test.go index 002c05e62..c9d46251f 100644 --- a/x/oracle/keeper/signing_test.go +++ b/x/oracle/keeper/signing_test.go @@ -5,13 +5,13 @@ import ( "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestGetSetSigningResult(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) rid := types.RequestID(123) signingResult := types.SigningResult{ SigningID: bandtsstypes.SigningID(456), @@ -20,10 +20,10 @@ func TestGetSetSigningResult(t *testing.T) { } // Set the signing result by request ID - k.SetSigningResult(ctx, rid, signingResult) + app.OracleKeeper.SetSigningResult(ctx, rid, signingResult) // Get the signing result associated with the request ID - got, err := k.GetSigningResult(ctx, rid) + got, err := app.OracleKeeper.GetSigningResult(ctx, rid) require.NoError(t, err) require.Equal(t, signingResult, got) } diff --git a/x/oracle/keeper/snapshotter_integration_test.go b/x/oracle/keeper/snapshotter_integration_test.go index a7d55d6ed..89f013272 100644 --- a/x/oracle/keeper/snapshotter_integration_test.go +++ b/x/oracle/keeper/snapshotter_integration_test.go @@ -8,13 +8,14 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/keeper" ) func TestSnapshotter(t *testing.T) { // setup source app - srcApp, srcCtx, srcKeeper := testapp.CreateTestInput(true) + srcApp, srcCtx := bandtesting.CreateTestApp(t, true) + srcKeeper := srcApp.OracleKeeper // create snapshot srcApp.Commit() @@ -25,7 +26,7 @@ func TestSnapshotter(t *testing.T) { assert.NotNil(t, snapshot) // restore snapshot - destApp := testapp.SetupWithEmptyStore() + destApp := bandtesting.SetupWithEmptyStore(t, "testing") destCtx := destApp.NewUncachedContext(false, tmproto.Header{}) destKeeper := destApp.OracleKeeper require.NoError(t, destApp.SnapshotManager().Restore(*snapshot)) diff --git a/x/oracle/keeper/validator_status_test.go b/x/oracle/keeper/validator_status_test.go index 8baa5e122..690f6ebdd 100644 --- a/x/oracle/keeper/validator_status_test.go +++ b/x/oracle/keeper/validator_status_test.go @@ -11,7 +11,8 @@ import ( minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandapp "github.com/bandprotocol/chain/v2/app" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/keeper" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -19,26 +20,26 @@ import ( func defaultVotes() []abci.VoteInfo { return []abci.VoteInfo{{ Validator: abci.Validator{ - Address: testapp.Validators[0].PubKey.Address(), + Address: bandtesting.Validators[0].PubKey.Address(), Power: 70, }, SignedLastBlock: true, }, { Validator: abci.Validator{ - Address: testapp.Validators[1].PubKey.Address(), + Address: bandtesting.Validators[1].PubKey.Address(), Power: 20, }, SignedLastBlock: true, }, { Validator: abci.Validator{ - Address: testapp.Validators[2].PubKey.Address(), + Address: bandtesting.Validators[2].PubKey.Address(), Power: 10, }, SignedLastBlock: true, }} } -func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper) authtypes.ModuleAccountI { +func SetupFeeCollector(app *bandapp.BandApp, ctx sdk.Context, k keeper.Keeper) authtypes.ModuleAccountI { // Set collected fee to 1000000uband and 70% oracle reward proportion. feeCollector := app.AccountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) _ = app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, Coins1000000uband) @@ -58,8 +59,10 @@ func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper } func TestAllocateTokenNoActiveValidators(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(false) - feeCollector := SetupFeeCollector(app, ctx, k) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + + feeCollector := SetupFeeCollector(app.BandApp, ctx, k) require.Equal(t, Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // No active oracle validators so nothing should happen. @@ -71,12 +74,14 @@ func TestAllocateTokenNoActiveValidators(t *testing.T) { } func TestAllocateTokensOneActive(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(false) - feeCollector := SetupFeeCollector(app, ctx, k) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + + feeCollector := SetupFeeCollector(app.BandApp, ctx, k) require.Equal(t, Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // From 70% of fee, 2% should go to community pool, the rest goes to the only active validator. - err := k.Activate(ctx, testapp.Validators[1].ValAddress) + err := k.Activate(ctx, bandtesting.Validators[1].ValAddress) require.NoError(t, err) k.AllocateTokens(ctx, defaultVotes()) @@ -96,18 +101,20 @@ func TestAllocateTokensOneActive(t *testing.T) { sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(14000)}}, app.DistrKeeper.GetFeePool(ctx).CommunityPool, ) - require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress)) + require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress)) require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(686000)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) - require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[2].ValAddress)) + require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[2].ValAddress)) } func TestAllocateTokensAllActive(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) - feeCollector := SetupFeeCollector(app, ctx, k) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + feeCollector := SetupFeeCollector(app.BandApp, ctx, k) require.Equal(t, Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // From 70% of fee, 2% should go to community pool, the rest get split to validators. @@ -132,114 +139,130 @@ func TestAllocateTokensAllActive(t *testing.T) { require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(480200)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress).Rewards, ) require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(137200)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(68600)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[2].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[2].ValAddress).Rewards, ) } func TestGetDefaultValidatorStatus(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(false, time.Time{}), vs) } func TestGetSetValidatorStatus(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() // After setting status of the 1st validator, we should be able to get it back. - k.SetValidatorStatus(ctx, testapp.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + k.SetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(true, now), vs) - vs = k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress) + vs = k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress) require.Equal(t, types.NewValidatorStatus(false, time.Time{}), vs) } func TestActivateValidatorOK(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() ctx = ctx.WithBlockTime(now) - err := k.Activate(ctx, testapp.Validators[0].ValAddress) + err := k.Activate(ctx, bandtesting.Validators[0].ValAddress) require.NoError(t, err) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(true, now), vs) - vs = k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress) + vs = k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress) require.Equal(t, types.NewValidatorStatus(false, time.Time{}), vs) } func TestFailActivateAlreadyActive(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() ctx = ctx.WithBlockTime(now) - err := k.Activate(ctx, testapp.Validators[0].ValAddress) + err := k.Activate(ctx, bandtesting.Validators[0].ValAddress) require.NoError(t, err) - err = k.Activate(ctx, testapp.Validators[0].ValAddress) + err = k.Activate(ctx, bandtesting.Validators[0].ValAddress) require.ErrorIs(t, err, types.ErrValidatorAlreadyActive) } func TestFailActivateTooSoon(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() // Set validator to be inactive just now. - k.SetValidatorStatus(ctx, testapp.Validators[0].ValAddress, types.NewValidatorStatus(false, now)) + k.SetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress, types.NewValidatorStatus(false, now)) // You can't activate until it's been at least InactivePenaltyDuration nanosec. penaltyDuration := k.GetParams(ctx).InactivePenaltyDuration require.ErrorIs( t, - k.Activate(ctx.WithBlockTime(now), testapp.Validators[0].ValAddress), + k.Activate(ctx.WithBlockTime(now), bandtesting.Validators[0].ValAddress), types.ErrTooSoonToActivate, ) require.ErrorIs( t, - k.Activate(ctx.WithBlockTime(now.Add(time.Duration(penaltyDuration/2))), testapp.Validators[0].ValAddress), + k.Activate(ctx.WithBlockTime(now.Add(time.Duration(penaltyDuration/2))), bandtesting.Validators[0].ValAddress), types.ErrTooSoonToActivate, ) // So far there must be no changes to the validator's status. - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(false, now), vs) // Now the time has come. require.NoError( t, - k.Activate(ctx.WithBlockTime(now.Add(time.Duration(penaltyDuration))), testapp.Validators[0].ValAddress), + k.Activate(ctx.WithBlockTime(now.Add(time.Duration(penaltyDuration))), bandtesting.Validators[0].ValAddress), ) - vs = k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + vs = k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(true, now.Add(time.Duration(penaltyDuration))), vs) } func TestMissReportSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() next := now.Add(time.Duration(10)) - k.SetValidatorStatus(ctx, testapp.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) - k.MissReport(ctx.WithBlockTime(next), testapp.Validators[0].ValAddress, next) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + k.SetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) + k.MissReport(ctx.WithBlockTime(next), bandtesting.Validators[0].ValAddress, next) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(false, next), vs) } func TestMissReportTooSoonNoop(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + prev := time.Now().UTC() now := prev.Add(time.Duration(10)) - k.SetValidatorStatus(ctx, testapp.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) - k.MissReport(ctx.WithBlockTime(prev), testapp.Validators[0].ValAddress, prev) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + k.SetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) + k.MissReport(ctx.WithBlockTime(prev), bandtesting.Validators[0].ValAddress, prev) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(true, now), vs) } func TestMissReportAlreadyInactiveNoop(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() next := now.Add(time.Duration(10)) - k.SetValidatorStatus(ctx, testapp.Validators[0].ValAddress, types.NewValidatorStatus(false, now)) - k.MissReport(ctx.WithBlockTime(next), testapp.Validators[0].ValAddress, next) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + k.SetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress, types.NewValidatorStatus(false, now)) + k.MissReport(ctx.WithBlockTime(next), bandtesting.Validators[0].ValAddress, next) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(false, now), vs) } diff --git a/x/oracle/simulation/operations_test.go b/x/oracle/simulation/operations_test.go index 2db252334..947405d59 100644 --- a/x/oracle/simulation/operations_test.go +++ b/x/oracle/simulation/operations_test.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/bank/testutil" "github.com/stretchr/testify/suite" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/simulation" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -22,15 +22,15 @@ type SimTestSuite struct { suite.Suite ctx sdk.Context - app *testapp.TestingApp + app *bandtesting.TestingApp r *rand.Rand accs []simtypes.Account } func (suite *SimTestSuite) SetupTest() { - app, _, _ := testapp.CreateTestInput(true) + app, _ := bandtesting.CreateTestApp(suite.T(), true) suite.app = app - suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{ChainID: testapp.ChainID}) + suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{ChainID: bandtesting.ChainID}) s := rand.NewSource(1) suite.r = rand.New(s) suite.accs = suite.getTestingAccounts(suite.r, 10) @@ -39,7 +39,7 @@ func (suite *SimTestSuite) SetupTest() { suite.app.BeginBlock( abci.RequestBeginBlock{ Header: tmproto.Header{ - ChainID: testapp.ChainID, + ChainID: bandtesting.ChainID, Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash, }, diff --git a/x/rollingseed/abci_test.go b/x/rollingseed/abci_test.go index 9cf1f28eb..a7c5e5c24 100644 --- a/x/rollingseed/abci_test.go +++ b/x/rollingseed/abci_test.go @@ -7,7 +7,7 @@ import ( abci "github.com/cometbft/cometbft/abci/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" ) func fromHex(hexStr string) []byte { @@ -19,7 +19,7 @@ func fromHex(hexStr string) []byte { } func TestRollingSeedCorrect(t *testing.T) { - app, ctx, _ := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) // Initially rolling seed should be all zeros. require.Equal( diff --git a/x/rollingseed/keeper/keeper_test.go b/x/rollingseed/keeper/keeper_test.go index 3550bbecd..9d4d7cd4a 100644 --- a/x/rollingseed/keeper/keeper_test.go +++ b/x/rollingseed/keeper/keeper_test.go @@ -6,18 +6,18 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" ) type KeeperTestSuite struct { suite.Suite - app *testapp.TestingApp + app *bandtesting.TestingApp ctx sdk.Context } func (s *KeeperTestSuite) SetupTest() { - app, ctx, _ := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(s.T(), false) s.app = app s.ctx = ctx } diff --git a/x/tss/keeper/keeper_test.go b/x/tss/keeper/keeper_test.go index e7f6fc60f..2f7dae662 100644 --- a/x/tss/keeper/keeper_test.go +++ b/x/tss/keeper/keeper_test.go @@ -14,7 +14,7 @@ import ( "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" bandtsskeeper "github.com/bandprotocol/chain/v2/x/bandtss/keeper" bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" "github.com/bandprotocol/chain/v2/x/tss/keeper" @@ -24,7 +24,7 @@ import ( type KeeperTestSuite struct { suite.Suite - app *testapp.TestingApp + app *bandtesting.TestingApp ctx sdk.Context queryClient types.QueryClient msgSrvr types.MsgServer @@ -39,7 +39,7 @@ var ( ) func (s *KeeperTestSuite) SetupTest() { - app, ctx, _ := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(s.T(), true) s.app = app s.ctx = ctx diff --git a/x/tss/keeper/msg_server_test.go b/x/tss/keeper/msg_server_test.go index 378a497c1..eeb3df744 100644 --- a/x/tss/keeper/msg_server_test.go +++ b/x/tss/keeper/msg_server_test.go @@ -8,7 +8,7 @@ import ( "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" bandtsskeeper "github.com/bandprotocol/chain/v2/x/bandtss/keeper" bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" "github.com/bandprotocol/chain/v2/x/tss/types" @@ -567,7 +567,7 @@ func (s *KeeperTestSuite) TestSuccessSubmitSignatureReq() { msg, err := bandtsstypes.NewMsgRequestSignature( types.NewTextSignatureOrder([]byte("msg")), sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), - testapp.FeePayer.Address, + bandtesting.FeePayer.Address, ) s.Require().NoError(err) _, err = bandtssMsgSrvr.RequestSignature(ctx, msg) diff --git a/x/tss/keeper/signing_test.go b/x/tss/keeper/signing_test.go index 8fe2e71ea..547def3d2 100644 --- a/x/tss/keeper/signing_test.go +++ b/x/tss/keeper/signing_test.go @@ -5,7 +5,7 @@ import ( "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" "github.com/bandprotocol/chain/v2/x/tss/types" ) @@ -186,7 +186,7 @@ func (s *KeeperTestSuite) TestGetPendingSigns() { AssignedMembers: []types.AssignedMember{ { MemberID: memberID, - Address: testapp.Alice.Address.String(), + Address: bandtesting.Alice.Address.String(), PubD: testutil.HexDecode("02234d901b8d6404b509e9926407d1a2749f456d18b159af647a65f3e907d61ef1"), PubE: testutil.HexDecode("028a1f3e214831b2f2d6e27384817132ddaa222928b05e9372472aa2735cf1f797"), PubNonce: testutil.HexDecode("03cbb6a27c62baa195dff6c75eae7b6b7713f978732a671855f7d7b86b06e6ac67"), @@ -198,7 +198,7 @@ func (s *KeeperTestSuite) TestGetPendingSigns() { signingID := k.AddSigning(ctx, signing) // Get all PendingSignIDs - got := k.GetPendingSignings(ctx, testapp.Alice.Address) + got := k.GetPendingSignings(ctx, bandtesting.Alice.Address) // Check if the returned signings are equal to the ones we set s.Require().Equal(uint64(signingID), got[0]) From ef9fa5a03d1290601c9ef58de55c460805a2fdc7 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 6 May 2024 09:55:42 +0700 Subject: [PATCH 069/132] remove package rename --- x/bandtss/types/expected_keepers.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/bandtss/types/expected_keepers.go b/x/bandtss/types/expected_keepers.go index a2eaa3f19..108f08de7 100644 --- a/x/bandtss/types/expected_keepers.go +++ b/x/bandtss/types/expected_keepers.go @@ -1,7 +1,7 @@ package types import ( - time "time" + "time" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" From b12e4f992f0a223c5868d93015b2567942fc8536 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 13 May 2024 14:18:40 +0700 Subject: [PATCH 070/132] merge extra/rest-tss into extra/rest-tss-full-db --- .github/workflows/ci.yaml | 2 +- .github/workflows/golangci-lint.yml | 2 +- .github/workflows/simulation.yml | 10 +- .golangci.yml | 3 +- CHANGELOG.md | 6 +- Dockerfile | 2 +- Dockerfile.static | 2 +- Makefile | 8 +- app/ante.go | 10 +- app/app.go | 36 +- app/genesis.go | 3 + app/keepers/keepers.go | 2 + app/upgrades/v2_6/constants.go | 6 +- benchmark/app_test.go | 127 +- benchmark/helper_test.go | 21 +- benchmark/tss_bench_test.go | 40 +- client/grpc/oracle/proof/abi.go | 8 +- client/grpc/oracle/proof/multi_store.go | 36 +- client/grpc/oracle/proof/multi_store_test.go | 62 +- client/grpc/oracle/proof/proof.pb.go | 332 +- client/grpc/oracle/proof/proof_test.go | 8 +- cmd/grogu/main.go | 7 + contrib/devtools/Dockerfile | 2 +- flusher/flusher/db.py | 72 + flusher/flusher/handler.py | 49 + go.mod | 17 +- go.sum | 22 +- grogu/README.md | 20 + grogu/cmd/config.go | 20 + grogu/cmd/keys.go | 220 + grogu/cmd/run.go | 150 + grogu/context/context.go | 57 + grogu/context/logger.go | 32 + grogu/event/event.go | 35 + grogu/feed/check.go | 203 + grogu/feed/query.go | 106 + grogu/feed/query_test.go | 158 + grogu/feed/submit.go | 217 + grogu/main.go | 75 + grogu/priceservice/grpc.go | 37 + grogu/priceservice/priceservice.go | 82 + grogu/priceservice/rest.go | 48 + hasura/hasura-metadata/tables.yaml | 120 + hooks/emitter/bandtss.go | 84 + hooks/emitter/decoder.go | 135 +- hooks/emitter/decoder_test.go | 3 +- hooks/emitter/emitter.go | 30 +- hooks/emitter/group.go | 412 ++ hooks/emitter/handler.go | 90 +- hooks/emitter/oracle.go | 1 - hooks/emitter/tss.go | 108 +- hooks/request/types.go | 1 - proto/bandchain/v1/oracle/proof.proto | 45 +- proto/bandtss/v1beta1/bandtss.proto | 16 +- proto/bandtss/v1beta1/genesis.proto | 14 +- proto/bandtss/v1beta1/query.proto | 10 +- proto/bandtss/v1beta1/tx.proto | 17 +- proto/feeds/v1beta1/feeds.proto | 129 + proto/feeds/v1beta1/genesis.proto | 23 + proto/feeds/v1beta1/params.proto | 46 + proto/feeds/v1beta1/query.proto | 192 + proto/feeds/v1beta1/tx.proto | 88 + proto/oracle/v1/oracle.proto | 32 +- proto/oracle/v1/query.proto | 2 +- proto/oracle/v1/tx.proto | 9 +- proto/tss/v1beta1/genesis.proto | 8 +- proto/tss/v1beta1/query.proto | 12 +- scripts/bandtss/proposal_create_group.json | 6 +- scripts/bandtss/request_signature_oracle.sh | 1 - scripts/bandtss/request_signature_text.sh | 1 - scripts/feeds/submit_signals.sh | 8 + scripts/generate_genesis.sh | 19 +- scripts/group/create_group.sh | 18 + scripts/group/create_policy.sh | 18 + scripts/group/group_members.json | 14 + scripts/group/threshold_policy.json | 8 + scripts/mockgen.sh | 6 + scripts/start_grogu.sh | 47 + x/bandtss/abci_test.go | 1 - x/bandtss/client/cli/query.go | 9 +- x/bandtss/client/cli/tx.go | 14 +- x/bandtss/client/request_signature_handler.go | 20 + x/bandtss/genesis.go | 2 +- x/bandtss/genesis_test.go | 2 +- x/bandtss/keeper/group.go | 29 +- x/bandtss/keeper/group_test.go | 23 +- x/bandtss/keeper/grpc_query.go | 24 +- x/bandtss/keeper/hooks.go | 5 +- x/bandtss/keeper/keeper.go | 12 +- x/bandtss/keeper/keeper_test.go | 2 +- x/bandtss/keeper/msg_server.go | 13 +- x/bandtss/keeper/msg_server_test.go | 4 +- x/bandtss/keeper/params.go | 7 +- x/bandtss/keeper/signing.go | 12 +- x/bandtss/keeper/signing_test.go | 4 +- x/bandtss/keeper/validator.go | 2 +- x/bandtss/module.go | 8 +- x/bandtss/testutil/mock_expected_keepers.go | 73 +- x/bandtss/testutil/mock_keeper.go | 3 +- x/bandtss/types/bandtss.pb.go | 124 +- x/bandtss/types/codec.go | 30 +- x/bandtss/types/constants.go | 7 +- x/bandtss/types/errors.go | 26 +- x/bandtss/types/events.go | 5 +- x/bandtss/types/expected_keepers.go | 6 +- x/bandtss/types/genesis.go | 30 +- x/bandtss/types/genesis.pb.go | 14 +- x/bandtss/types/helpers.go | 14 - x/bandtss/types/keys.go | 9 +- x/bandtss/types/msgs.go | 53 +- x/bandtss/types/params.go | 3 +- x/bandtss/types/query.pb.go | 18 +- x/bandtss/types/signature_order.go | 4 +- x/bandtss/types/tx.pb.go | 23 +- x/feeds/README.md | 360 ++ x/feeds/abci.go | 39 + x/feeds/client/cli/query.go | 275 ++ x/feeds/client/cli/tx.go | 246 + x/feeds/client/cli/utils.go | 59 + x/feeds/keeper/calculate.go | 35 + x/feeds/keeper/calculate_test.go | 71 + x/feeds/keeper/emit.go | 78 + x/feeds/keeper/genesis.go | 29 + x/feeds/keeper/genesis_test.go | 76 + x/feeds/keeper/grpc_query.go | 265 + x/feeds/keeper/grpc_query_test.go | 457 ++ x/feeds/keeper/hooks.go | 88 + x/feeds/keeper/keeper.go | 63 + x/feeds/keeper/keeper_feed.go | 118 + x/feeds/keeper/keeper_price.go | 238 + x/feeds/keeper/keeper_price_service.go | 29 + x/feeds/keeper/keeper_price_service_test.go | 22 + x/feeds/keeper/keeper_price_test.go | 144 + x/feeds/keeper/keeper_signal.go | 60 + x/feeds/keeper/keeper_signal_test.go | 29 + x/feeds/keeper/keeper_symbol_test.go | 89 + x/feeds/keeper/keeper_test.go | 133 + x/feeds/keeper/msg_server.go | 163 + x/feeds/keeper/msg_server_test.go | 362 ++ x/feeds/keeper/params.go | 28 + x/feeds/keeper/params_test.go | 14 + x/feeds/keeper/price.go | 68 + x/feeds/keeper/signal.go | 42 + x/feeds/module.go | 143 + x/feeds/testutil/mock_expected_keepers.go | 149 + x/feeds/types/codec.go | 46 + x/feeds/types/errors.go | 22 + x/feeds/types/events.go | 27 + x/feeds/types/expected_keepers.go | 32 + x/feeds/types/feed.go | 10 + x/feeds/types/feeds.pb.go | 2300 +++++++++ x/feeds/types/genesis.go | 60 + x/feeds/types/genesis.pb.go | 508 ++ x/feeds/types/genesis_test.go | 77 + x/feeds/types/keys.go | 84 + x/feeds/types/keys_test.go | 41 + x/feeds/types/median.go | 150 + x/feeds/types/median_test.go | 107 + x/feeds/types/msgs.go | 200 + x/feeds/types/msgs_test.go | 219 + x/feeds/types/params.go | 103 + x/feeds/types/params.pb.go | 713 +++ x/feeds/types/params_test.go | 40 + x/feeds/types/price.go | 12 + x/feeds/types/price_service.go | 36 + x/feeds/types/price_service_test.go | 31 + x/feeds/types/query.pb.go | 4334 +++++++++++++++++ x/feeds/types/query.pb.gw.go | 976 ++++ x/feeds/types/tx.pb.go | 1815 +++++++ x/feeds/types/utils.go | 10 + x/feeds/types/utils_test.go | 15 + x/feeds/types/validate.go | 39 + x/globalfee/feechecker/feechecker.go | 99 +- x/globalfee/feechecker/feechecker_test.go | 178 +- x/globalfee/keeper/grpc_query_test.go | 12 +- x/oracle/app_test.go | 4 - x/oracle/client/cli/tx.go | 16 +- x/oracle/client/signature_order_handler.go | 6 +- x/oracle/handler_test.go | 11 - x/oracle/ibc_test.go | 3 - x/oracle/keeper/grpc_query.go | 3 - x/oracle/keeper/grpc_query_test.go | 5 - x/oracle/keeper/owasm.go | 4 +- x/oracle/keeper/owasm_test.go | 98 +- x/oracle/keeper/report_test.go | 2 +- x/oracle/keeper/request_test.go | 10 +- x/oracle/keeper/result.go | 12 +- x/oracle/keeper/result_test.go | 2 +- x/oracle/keeper/signing.go | 2 +- x/oracle/simulation/decoder_test.go | 1 - x/oracle/simulation/operations_test.go | 1 - x/oracle/tss_handler.go | 15 +- x/oracle/types/error.go | 2 + x/oracle/types/events.go | 1 - x/oracle/types/exec_env_test.go | 8 +- x/oracle/types/msgs.go | 6 +- x/oracle/types/msgs_test.go | 34 +- x/oracle/types/oracle.pb.go | 366 +- x/oracle/types/packets.go | 6 +- x/oracle/types/packets_test.go | 3 +- x/oracle/types/query.pb.go | 2 +- x/oracle/types/request.go | 5 - x/oracle/types/signature_order.go | 17 +- x/oracle/types/tx.pb.go | 206 +- x/tss/README.md | 2 +- x/tss/client/cli/query.go | 10 +- x/tss/client/cli/tx.go | 17 +- x/tss/client/cli/utils.go | 55 - x/tss/client/cli/utils_test.go | 47 - x/tss/client/signature_order_handler.go | 20 - x/tss/genesis.go | 30 +- x/tss/genesis_test.go | 87 + x/tss/keeper/de.go | 41 +- x/tss/keeper/de_test.go | 23 +- x/tss/keeper/groups.go | 94 + x/tss/keeper/groups_endblock.go | 182 + x/tss/keeper/groups_test.go | 245 + x/tss/keeper/grpc_query.go | 26 +- x/tss/keeper/grpc_query_test.go | 2 +- x/tss/keeper/keeper.go | 442 +- x/tss/keeper/keeper_test.go | 322 +- x/tss/keeper/member.go | 182 + x/tss/keeper/member_test.go | 86 + x/tss/keeper/msg_server.go | 202 +- x/tss/keeper/params.go | 7 +- x/tss/keeper/round1.go | 31 +- x/tss/keeper/round2.go | 27 +- x/tss/keeper/round3.go | 46 +- x/tss/keeper/signing.go | 446 +- x/tss/keeper/signing_endblock.go | 163 + x/tss/keeper/signing_test.go | 42 +- x/tss/testutil/mock_expected_keepers.go | 216 + x/tss/testutil/mock_keeper.go | 75 + .../{tss_test.go => assigned_members_test.go} | 0 x/tss/types/codec.go | 18 +- x/tss/types/constants.go | 21 +- x/tss/types/errors.go | 98 +- x/tss/types/events.go | 52 +- x/tss/types/expected_keepers.go | 15 +- x/tss/types/genesis.go | 3 - x/tss/types/genesis.pb.go | 176 +- x/tss/types/handler.go | 6 +- x/tss/types/keys.go | 44 +- x/tss/types/msgs.go | 87 +- x/tss/types/query.pb.go | 20 +- x/tss/types/router.go | 5 +- x/tss/types/signature_order.go | 4 +- x/tss/types/signing.go | 5 - yoda/executor/rest.go | 1 + 249 files changed, 22239 insertions(+), 3366 deletions(-) create mode 100644 cmd/grogu/main.go create mode 100644 grogu/README.md create mode 100644 grogu/cmd/config.go create mode 100644 grogu/cmd/keys.go create mode 100644 grogu/cmd/run.go create mode 100644 grogu/context/context.go create mode 100644 grogu/context/logger.go create mode 100644 grogu/event/event.go create mode 100644 grogu/feed/check.go create mode 100644 grogu/feed/query.go create mode 100644 grogu/feed/query_test.go create mode 100644 grogu/feed/submit.go create mode 100644 grogu/main.go create mode 100644 grogu/priceservice/grpc.go create mode 100644 grogu/priceservice/priceservice.go create mode 100644 grogu/priceservice/rest.go create mode 100644 hooks/emitter/bandtss.go create mode 100644 hooks/emitter/group.go create mode 100644 proto/feeds/v1beta1/feeds.proto create mode 100644 proto/feeds/v1beta1/genesis.proto create mode 100644 proto/feeds/v1beta1/params.proto create mode 100644 proto/feeds/v1beta1/query.proto create mode 100644 proto/feeds/v1beta1/tx.proto create mode 100755 scripts/feeds/submit_signals.sh create mode 100755 scripts/group/create_group.sh create mode 100755 scripts/group/create_policy.sh create mode 100644 scripts/group/group_members.json create mode 100644 scripts/group/threshold_policy.json create mode 100755 scripts/mockgen.sh create mode 100755 scripts/start_grogu.sh create mode 100644 x/bandtss/client/request_signature_handler.go delete mode 100644 x/bandtss/types/helpers.go create mode 100644 x/feeds/README.md create mode 100644 x/feeds/abci.go create mode 100644 x/feeds/client/cli/query.go create mode 100644 x/feeds/client/cli/tx.go create mode 100644 x/feeds/client/cli/utils.go create mode 100644 x/feeds/keeper/calculate.go create mode 100644 x/feeds/keeper/calculate_test.go create mode 100644 x/feeds/keeper/emit.go create mode 100644 x/feeds/keeper/genesis.go create mode 100644 x/feeds/keeper/genesis_test.go create mode 100644 x/feeds/keeper/grpc_query.go create mode 100644 x/feeds/keeper/grpc_query_test.go create mode 100644 x/feeds/keeper/hooks.go create mode 100644 x/feeds/keeper/keeper.go create mode 100644 x/feeds/keeper/keeper_feed.go create mode 100644 x/feeds/keeper/keeper_price.go create mode 100644 x/feeds/keeper/keeper_price_service.go create mode 100644 x/feeds/keeper/keeper_price_service_test.go create mode 100644 x/feeds/keeper/keeper_price_test.go create mode 100644 x/feeds/keeper/keeper_signal.go create mode 100644 x/feeds/keeper/keeper_signal_test.go create mode 100644 x/feeds/keeper/keeper_symbol_test.go create mode 100644 x/feeds/keeper/keeper_test.go create mode 100644 x/feeds/keeper/msg_server.go create mode 100644 x/feeds/keeper/msg_server_test.go create mode 100644 x/feeds/keeper/params.go create mode 100644 x/feeds/keeper/params_test.go create mode 100644 x/feeds/keeper/price.go create mode 100644 x/feeds/keeper/signal.go create mode 100644 x/feeds/module.go create mode 100644 x/feeds/testutil/mock_expected_keepers.go create mode 100644 x/feeds/types/codec.go create mode 100644 x/feeds/types/errors.go create mode 100644 x/feeds/types/events.go create mode 100644 x/feeds/types/expected_keepers.go create mode 100644 x/feeds/types/feed.go create mode 100644 x/feeds/types/feeds.pb.go create mode 100644 x/feeds/types/genesis.go create mode 100644 x/feeds/types/genesis.pb.go create mode 100644 x/feeds/types/genesis_test.go create mode 100644 x/feeds/types/keys.go create mode 100644 x/feeds/types/keys_test.go create mode 100644 x/feeds/types/median.go create mode 100644 x/feeds/types/median_test.go create mode 100644 x/feeds/types/msgs.go create mode 100644 x/feeds/types/msgs_test.go create mode 100644 x/feeds/types/params.go create mode 100644 x/feeds/types/params.pb.go create mode 100644 x/feeds/types/params_test.go create mode 100644 x/feeds/types/price.go create mode 100644 x/feeds/types/price_service.go create mode 100644 x/feeds/types/price_service_test.go create mode 100644 x/feeds/types/query.pb.go create mode 100644 x/feeds/types/query.pb.gw.go create mode 100644 x/feeds/types/tx.pb.go create mode 100644 x/feeds/types/utils.go create mode 100644 x/feeds/types/utils_test.go create mode 100644 x/feeds/types/validate.go delete mode 100644 x/tss/client/signature_order_handler.go create mode 100644 x/tss/genesis_test.go create mode 100644 x/tss/keeper/groups_endblock.go create mode 100644 x/tss/keeper/groups_test.go create mode 100644 x/tss/keeper/member.go create mode 100644 x/tss/keeper/member_test.go create mode 100644 x/tss/keeper/signing_endblock.go create mode 100644 x/tss/testutil/mock_expected_keepers.go create mode 100644 x/tss/testutil/mock_keeper.go rename x/tss/types/{tss_test.go => assigned_members_test.go} (100%) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ce7b7b9a5..b9a08cc71 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -11,7 +11,7 @@ jobs: - name: Install Go uses: actions/setup-go@v5 with: - go-version: '1.21.7' + go-version: '1.22.3' - name: Check go mod cache uses: actions/cache@v4 diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 1be62a7f7..8d6e78a45 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -7,7 +7,7 @@ jobs: steps: - uses: actions/setup-go@v5 with: - go-version: 1.21.7 + go-version: 1.22.3 - uses: actions/checkout@v4 - name: golangci-lint uses: golangci/golangci-lint-action@v5 diff --git a/.github/workflows/simulation.yml b/.github/workflows/simulation.yml index 8246ec673..db735c534 100644 --- a/.github/workflows/simulation.yml +++ b/.github/workflows/simulation.yml @@ -9,7 +9,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: "1.21.7" + go-version: "1.22.3" check-latest: true - name: Install runsim run: go install github.com/cosmos/tools/cmd/runsim@v1.0.0 @@ -26,7 +26,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: "1.21.7" + go-version: "1.22.3" check-latest: true - uses: actions/cache@v4 with: @@ -44,7 +44,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: "1.21.7" + go-version: "1.22.3" check-latest: true - uses: actions/cache@v4 with: @@ -62,7 +62,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: "1.21.7" + go-version: "1.22.3" check-latest: true - uses: actions/cache@v4 with: @@ -80,7 +80,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: "1.21.7" + go-version: "1.22.3" check-latest: true - uses: actions/cache@v4 with: diff --git a/.golangci.yml b/.golangci.yml index 882a2106d..941d3085a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,6 +1,6 @@ run: timeout: 5m - go: '1.21.7' + go: '1.22.3' skip-files: - ".*\\.pb\\.go$" - ".*\\.pb\\.gw\\.\\.go$" @@ -67,7 +67,6 @@ linters-settings: # Available rules: https://github.com/securego/gosec#available-rules # Default: [] - means include all rules includes: - # - G101 # Look for hard coded credentials - G102 # Bind to all interfaces - G103 # Audit the use of unsafe block - G104 # Audit errors not checked diff --git a/CHANGELOG.md b/CHANGELOG.md index 23a31fb6c..b4a598e73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- (bump) Use go 1.22.3 - (bump) Use cosmos-sdk package v0.47.11 / ibc-go v7.4.0 - (bump) replace github.com/tendermint/tendermint by github.com/cometbft/cometbft v0.37.5 - (bump) migrated from gogo/protobuf to cosmos/gogoproto @@ -17,12 +18,15 @@ - (chain) Migrate REST Endpoint to GRPC - (chain) update oracle params to support cosmos-sdk 0.47 - (chain) Add consensus module to handle managing Tendermint consensus parameters +- (chain) Support tss feature +- (chain) Add tss (threshold signature scheme) feature for signing an oracle data. +- (cylinder) provide a new service for supporting tss process ## [v2.5.3](https://github.com/bandprotocol/chain/releases/tag/v2.5.3) - (bump) Use cometbft v0.34.29 - (yoda) Get information of requests through endpoint instead of events - + ## [v2.5.2](https://github.com/bandprotocol/chain/releases/tag/v2.5.2) - (bump) Use cosmos-sdk v0.45.16 / ibc-go v4.3.1 / cometbft v0.34.28 diff --git a/Dockerfile b/Dockerfile index fc49ae633..471a67a14 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.21-bullseye +FROM golang:1.22.3-bullseye WORKDIR /chain COPY . /chain diff --git a/Dockerfile.static b/Dockerfile.static index 2d3a88417..92360f12d 100644 --- a/Dockerfile.static +++ b/Dockerfile.static @@ -1,4 +1,4 @@ -FROM golang:1.21-alpine as go-builder +FROM golang:1.22.3-alpine as go-builder SHELL ["/bin/sh", "-ecuxo", "pipefail"] RUN apk add --no-cache ca-certificates build-base linux-headers git gmp gmp-dev diff --git a/Makefile b/Makefile index 3690bc7b8..b38840a44 100644 --- a/Makefile +++ b/Makefile @@ -3,6 +3,7 @@ VERSION := $(shell echo $(shell git describe --tags) | sed 's/^v//') COMMIT := $(shell git log -1 --format='%H') LEDGER_ENABLED ?= true BINDIR ?= $(GOPATH)/bin +MOCKS_DIR = $(CURDIR)/tests/mocks APP = ./app DOCKER := $(shell which docker) @@ -45,6 +46,7 @@ install: go.sum go install -mod=readonly $(BUILD_FLAGS) ./cmd/bandd go install -mod=readonly $(BUILD_FLAGS) ./cmd/yoda go install -mod=readonly $(BUILD_FLAGS) ./cmd/cylinder + go install -mod=readonly $(BUILD_FLAGS) ./cmd/grogu faucet: go.sum go install -mod=readonly $(BUILD_FLAGS) ./cmd/faucet @@ -63,6 +65,10 @@ release: go.sum env GOOS=windows GOARCH=amd64 \ go build -mod=readonly -o ./build/yoda_windows_amd64 $(BUILD_FLAGS) ./cmd/yoda +mocks: + @go install go.uber.org/mock/mockgen@latest + sh ./scripts/mockgen.sh + go.sum: go.mod @echo "--> Ensure dependencies have not been modified" GO111MODULE=on go mod verify @@ -119,5 +125,5 @@ test-sim-deterministic: runsim @echo "Running application deterministic simulation. This may take awhile!" @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(APP) -ExitOnFail 1 1 TestAppStateDeterminism -.PHONY: proto-all proto-gen proto-swagger-gen proto-format proto-lint proto-check-breaking \ +.PHONY: proto-all proto-gen proto-swagger-gen proto-format proto-lint proto-check-breaking mocks \ test-sim-import-export test-sim-multi-seed-short test-sim-after-import test-sim-deterministic diff --git a/app/ante.go b/app/ante.go index d1be54f94..f866f1fcb 100644 --- a/app/ante.go +++ b/app/ante.go @@ -10,6 +10,7 @@ import ( ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper" bandtsskeeper "github.com/bandprotocol/chain/v2/x/bandtss/keeper" + feedskeeper "github.com/bandprotocol/chain/v2/x/feeds/keeper" "github.com/bandprotocol/chain/v2/x/globalfee/feechecker" globalfeekeeper "github.com/bandprotocol/chain/v2/x/globalfee/keeper" oraclekeeper "github.com/bandprotocol/chain/v2/x/oracle/keeper" @@ -23,10 +24,11 @@ type HandlerOptions struct { AuthzKeeper *authzkeeper.Keeper OracleKeeper *oraclekeeper.Keeper IBCKeeper *ibckeeper.Keeper - GlobalfeeKeeper *globalfeekeeper.Keeper StakingKeeper *stakingkeeper.Keeper + GlobalfeeKeeper *globalfeekeeper.Keeper TSSKeeper *tsskeeper.Keeper BandtssKeeper *bandtsskeeper.Keeper + FeedsKeeper *feedskeeper.Keeper } func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { @@ -51,6 +53,9 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { if options.BandtssKeeper == nil { return nil, sdkerrors.ErrLogic.Wrap("bandtss keeper is required for AnteHandler") } + if options.FeedsKeeper == nil { + return nil, sdkerrors.ErrLogic.Wrap("feeds keeper is required for AnteHandler") + } if options.IBCKeeper == nil { return nil, sdkerrors.ErrLogic.Wrap("IBC keeper is required for AnteHandler") } @@ -74,8 +79,9 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { options.StakingKeeper, options.TSSKeeper, options.BandtssKeeper, + options.FeedsKeeper, ) - options.TxFeeChecker = feeChecker.CheckTxFeeWithMinGasPrices + options.TxFeeChecker = feeChecker.CheckTxFee } anteDecorators := []sdk.AnteDecorator{ diff --git a/app/app.go b/app/app.go index 36573d18c..e51497de5 100644 --- a/app/app.go +++ b/app/app.go @@ -129,6 +129,9 @@ import ( bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" bandbank "github.com/bandprotocol/chain/v2/x/bank" bandbankkeeper "github.com/bandprotocol/chain/v2/x/bank/keeper" + "github.com/bandprotocol/chain/v2/x/feeds" + feedskeeper "github.com/bandprotocol/chain/v2/x/feeds/keeper" + feedstypes "github.com/bandprotocol/chain/v2/x/feeds/types" "github.com/bandprotocol/chain/v2/x/globalfee" globalfeekeeper "github.com/bandprotocol/chain/v2/x/globalfee/keeper" globalfeetypes "github.com/bandprotocol/chain/v2/x/globalfee/types" @@ -190,7 +193,8 @@ var ( ica.AppModuleBasic{}, oracle.AppModuleBasic{}, tss.AppModuleBasic{}, - bandtss.NewAppModuleBasic(oracleclient.OracleSignatureOrderHandler), + bandtss.NewAppModuleBasic(oracleclient.OracleRequestSignatureHandler), + feeds.AppModuleBasic{}, globalfee.AppModule{}, ) // module account permissions @@ -317,6 +321,7 @@ func NewBandApp( oracletypes.StoreKey, tsstypes.StoreKey, bandtsstypes.StoreKey, + feedstypes.StoreKey, globalfeetypes.StoreKey, ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) @@ -446,10 +451,6 @@ func NewBandApp( authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) - app.StakingKeeper.SetHooks( - stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), - ) - // create IBC Keeper app.IBCKeeper = ibckeeper.NewKeeper( appCodec, @@ -595,12 +596,15 @@ func NewBandApp( app.MintKeeper, app.DistrKeeper, app.GovKeeper, + app.GroupKeeper, app.OracleKeeper, app.TSSKeeper, + app.BandtssKeeper, app.ICAHostKeeper, app.IBCKeeper.ClientKeeper, app.IBCKeeper.ConnectionKeeper, app.IBCKeeper.ChannelKeeper, + keys[group.StoreKey], emitterFlag, false, )) @@ -665,6 +669,21 @@ func NewBandApp( // further handlers to be registered after the keeper is created since this // could create invalid or non-deterministic behavior. tssRouter.Seal() + app.FeedsKeeper = feedskeeper.NewKeeper( + appCodec, + keys[feedstypes.StoreKey], + app.OracleKeeper, + app.StakingKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + app.StakingKeeper.SetHooks( + stakingtypes.NewMultiStakingHooks( + app.DistrKeeper.Hooks(), + app.SlashingKeeper.Hooks(), + app.FeedsKeeper.Hooks(), + ), + ) // Create static IBC router, add transfer route, then set and seal it ibcRouter := porttypes.NewRouter() @@ -758,6 +777,7 @@ func NewBandApp( oracleModule, tssModule, bandtssModule, + feeds.NewAppModule(appCodec, app.FeedsKeeper), globalfee.NewAppModule(app.GlobalfeeKeeper), ) @@ -773,6 +793,7 @@ func NewBandApp( oracletypes.ModuleName, tsstypes.ModuleName, bandtsstypes.ModuleName, + feedstypes.ModuleName, distrtypes.ModuleName, slashingtypes.ModuleName, evidencetypes.ModuleName, @@ -802,6 +823,7 @@ func NewBandApp( oracletypes.ModuleName, tsstypes.ModuleName, bandtsstypes.ModuleName, + feedstypes.ModuleName, ibctransfertypes.ModuleName, ibcexported.ModuleName, icatypes.ModuleName, @@ -855,6 +877,7 @@ func NewBandApp( oracletypes.ModuleName, tsstypes.ModuleName, bandtsstypes.ModuleName, + feedstypes.ModuleName, globalfeetypes.ModuleName, ) @@ -901,9 +924,10 @@ func NewBandApp( OracleKeeper: &app.OracleKeeper, TSSKeeper: app.TSSKeeper, BandtssKeeper: app.BandtssKeeper, + FeedsKeeper: &app.FeedsKeeper, IBCKeeper: app.IBCKeeper, - GlobalfeeKeeper: &app.GlobalfeeKeeper, StakingKeeper: app.StakingKeeper, + GlobalfeeKeeper: &app.GlobalfeeKeeper, }, ) if err != nil { diff --git a/app/genesis.go b/app/genesis.go index 5d5bf199a..8a52b927a 100644 --- a/app/genesis.go +++ b/app/genesis.go @@ -40,6 +40,8 @@ import ( "github.com/bandprotocol/chain/v2/app/upgrades/v2_6" "github.com/bandprotocol/chain/v2/x/bandtss" bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" + "github.com/bandprotocol/chain/v2/x/feeds" + feedstypes "github.com/bandprotocol/chain/v2/x/feeds/types" globalfeetypes "github.com/bandprotocol/chain/v2/x/globalfee/types" "github.com/bandprotocol/chain/v2/x/oracle" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" @@ -115,6 +117,7 @@ func NewDefaultGenesisState() GenesisState { oracletypes.ModuleName: oracle.AppModuleBasic{}.DefaultGenesis(cdc), tsstypes.ModuleName: tss.AppModuleBasic{}.DefaultGenesis(cdc), bandtsstypes.ModuleName: bandtss.AppModuleBasic{}.DefaultGenesis(cdc), + feedstypes.ModuleName: feeds.AppModuleBasic{}.DefaultGenesis(cdc), globalfeetypes.ModuleName: cdc.MustMarshalJSON(globalfeeGenesis), } } diff --git a/app/keepers/keepers.go b/app/keepers/keepers.go index ee328727c..6553118c0 100644 --- a/app/keepers/keepers.go +++ b/app/keepers/keepers.go @@ -22,6 +22,7 @@ import ( bandtsskeeper "github.com/bandprotocol/chain/v2/x/bandtss/keeper" bandbankkeeper "github.com/bandprotocol/chain/v2/x/bank/keeper" + feedskeeper "github.com/bandprotocol/chain/v2/x/feeds/keeper" globalfeekeeper "github.com/bandprotocol/chain/v2/x/globalfee/keeper" oraclekeeper "github.com/bandprotocol/chain/v2/x/oracle/keeper" rollingseedKeeper "github.com/bandprotocol/chain/v2/x/rollingseed/keeper" @@ -53,6 +54,7 @@ type AppKeepers struct { OracleKeeper oraclekeeper.Keeper TSSKeeper *tsskeeper.Keeper BandtssKeeper *bandtsskeeper.Keeper + FeedsKeeper feedskeeper.Keeper ConsensusParamsKeeper consensusparamkeeper.Keeper GlobalfeeKeeper globalfeekeeper.Keeper diff --git a/app/upgrades/v2_6/constants.go b/app/upgrades/v2_6/constants.go index 1eb456643..66f60d6a7 100644 --- a/app/upgrades/v2_6/constants.go +++ b/app/upgrades/v2_6/constants.go @@ -16,6 +16,8 @@ import ( ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" "github.com/bandprotocol/chain/v2/app/upgrades" + bandtsstype "github.com/bandprotocol/chain/v2/x/bandtss/types" + feedstypes "github.com/bandprotocol/chain/v2/x/feeds/types" globalfeetypes "github.com/bandprotocol/chain/v2/x/globalfee/types" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" rollingseedtypes "github.com/bandprotocol/chain/v2/x/rollingseed/types" @@ -33,8 +35,10 @@ var Upgrade = upgrades.Upgrade{ globalfeetypes.StoreKey, consensusparamtypes.StoreKey, crisistypes.StoreKey, - tsstypes.StoreKey, + feedstypes.StoreKey, rollingseedtypes.StoreKey, + tsstypes.StoreKey, + bandtsstype.StoreKey, }, }, } diff --git a/benchmark/app_test.go b/benchmark/app_test.go index 19faa4459..48ff190d5 100644 --- a/benchmark/app_test.go +++ b/benchmark/app_test.go @@ -29,7 +29,6 @@ type BenchmarkApp struct { Validator *Account Oid uint64 Did uint64 - Gid tss.GroupID TxConfig client.TxConfig TxEncoder sdk.TxEncoder TB testing.TB @@ -37,7 +36,8 @@ type BenchmarkApp struct { Querier keeper.Querier TSSMsgSrvr tsstypes.MsgServer BandtssMsgSrvr bandtsstypes.MsgServer - authority sdk.AccAddress + Authority sdk.AccAddress + PrivKeyStore map[string]tss.Scalar } var ( @@ -73,7 +73,7 @@ func InitializeBenchmarkApp(tb testing.TB, maxGasPerBlock int64) *BenchmarkApp { }, TB: tb, } - ba.Ctx = ba.NewUncachedContext(false, tmproto.Header{}) + ba.Ctx = ba.NewUncachedContext(false, tmproto.Header{ChainID: bandtesting.ChainID}) ba.TSSMsgSrvr = tsskeeper.NewMsgServerImpl(ba.TestingApp.TSSKeeper) ba.BandtssMsgSrvr = bandtsskeeper.NewMsgServerImpl(ba.TestingApp.BandtssKeeper) ba.Querier = keeper.Querier{ @@ -96,10 +96,6 @@ func InitializeBenchmarkApp(tb testing.TB, maxGasPerBlock int64) *BenchmarkApp { require.NoError(tb, err) ba.Oid = uint64(oid) - // set group ID - ba.Gid = tss.GroupID(1) - ba.authority = authtypes.NewModuleAddress(govtypes.ModuleName) - // create data source dCode := []byte("hello") _, res, err = ba.DeliverMsg(ba.Sender, GenMsgCreateDataSource(ba.Sender, dCode)) @@ -112,6 +108,10 @@ func InitializeBenchmarkApp(tb testing.TB, maxGasPerBlock int64) *BenchmarkApp { _, _, err = ba.DeliverMsg(ba.Validator, GenMsgActivate(ba.Validator)) require.NoError(tb, err) + // get gov address + ba.Authority = authtypes.NewModuleAddress(govtypes.ModuleName) + ba.PrivKeyStore = make(map[string]tss.Scalar) + ba.CallEndBlock() ba.Commit() @@ -127,8 +127,11 @@ func (ba *BenchmarkApp) DeliverMsg(account *Account, msgs []sdk.Msg) (sdk.GasInf func (ba *BenchmarkApp) CallBeginBlock() abci.ResponseBeginBlock { return ba.BeginBlock( abci.RequestBeginBlock{ - Header: tmproto.Header{Height: ba.LastBlockHeight() + 1}, - Hash: ba.LastCommitID().Hash, + Header: tmproto.Header{ + Height: ba.LastBlockHeight() + 1, + ChainID: bandtesting.ChainID, + }, + Hash: ba.LastCommitID().Hash, }, ) } @@ -225,50 +228,50 @@ func (ba *BenchmarkApp) GenMsgReportData(account *Account, rids []uint64) []sdk. func (ba *BenchmarkApp) SetupTSSGroup() { ctx, msgSrvr := ba.Ctx, ba.TSSMsgSrvr - k, bandtssKeeper := ba.TestingApp.TSSKeeper, ba.TestingApp.BandtssKeeper - - // force address to owner - owner := ba.Sender.Address.String() - - // Create group from testutil - for _, tc := range testutil.TestCases { - // Initialize members - for i, m := range tc.Group.Members { - k.SetMember(ctx, tsstypes.Member{ - ID: tss.MemberID(i + 1), - GroupID: tc.Group.ID, - Address: owner, - PubKey: m.PubKey(), - IsMalicious: false, - }) - - err := bandtssKeeper.AddNewMember(ctx, ba.Sender.Address) - require.NoError(ba.TB, err) - } + tssKeeper, bandtssKeeper := ba.TestingApp.TSSKeeper, ba.TestingApp.BandtssKeeper + + memberPubKey := testutil.TestCases[0].Group.Members[0].PubKey() + memberPrivKey := testutil.TestCases[0].Group.Members[0].PrivKey + groupPubKey := testutil.TestCases[0].Group.PubKey + dkg := testutil.TestCases[0].Group.DKGContext + gid := testutil.TestCases[0].Group.ID + + // Set members and submit DEs + tssKeeper.SetMember(ctx, tsstypes.Member{ + ID: tss.MemberID(1), + GroupID: gid, + Address: ba.Sender.Address.String(), + PubKey: memberPubKey, + IsMalicious: false, + IsActive: true, + }) + _, err := msgSrvr.SubmitDEs(ctx, &tsstypes.MsgSubmitDEs{ + DEs: GetDEs(), + Address: ba.Sender.Address.String(), + }) + require.NoError(ba.TB, err) - k.CreateNewGroup(ctx, tsstypes.Group{ - ID: tc.Group.ID, - Size_: uint64(tc.Group.GetSize()), - Threshold: tc.Group.Threshold, - PubKey: tc.Group.PubKey, - Status: tsstypes.GROUP_STATUS_ACTIVE, - CreatedHeight: 1, - }) - k.SetDKGContext(ctx, tc.Group.ID, tc.Group.DKGContext) + // CreateGroup + tssKeeper.CreateNewGroup(ctx, tsstypes.Group{ + ID: gid, + Size_: 1, + Threshold: 1, + PubKey: groupPubKey, + Status: tsstypes.GROUP_STATUS_ACTIVE, + CreatedHeight: 1, + }) + tssKeeper.SetDKGContext(ctx, gid, dkg) + + // Set active group in bandtss module + bandtssKeeper.SetCurrentGroupID(ctx, gid) + err = bandtssKeeper.AddNewMember(ctx, ba.Sender.Address) + require.NoError(ba.TB, err) - // Submit DEs for each member - _, err := msgSrvr.SubmitDEs(ctx, &tsstypes.MsgSubmitDEs{ - DEs: GetDEs(), - Address: ba.Sender.Address.String(), - }) - require.NoError(ba.TB, err) - } + // Set privKey Store + ba.PrivKeyStore[memberPubKey.String()] = memberPrivKey } -func (ba *BenchmarkApp) GetPendingSignTxs( - gid tss.GroupID, - tcs []testutil.TestCase, -) []sdk.Tx { +func (ba *BenchmarkApp) GetPendingSignTxs(gid tss.GroupID) []sdk.Tx { ctx, k := ba.Ctx, ba.TSSKeeper group := k.MustGetGroup(ctx, gid) @@ -277,17 +280,16 @@ func (ba *BenchmarkApp) GetPendingSignTxs( members := k.MustGetMembers(ctx, gid) for _, m := range members { - addr := sdk.AccAddress(m.PubKey) - sids := k.GetPendingSigningsByPubKey(ctx, m.PubKey) - ownPrivkey := FindPrivateKey(tcs, gid, addr) - require.NotNil(ba.TB, ownPrivkey) + privKey, ok := ba.PrivKeyStore[m.PubKey.String()] + require.True(ba.TB, ok) + require.NotNil(ba.TB, privKey) for _, sid := range sids { signing := k.MustGetSigning(ctx, tss.SigningID(sid)) - sig, err := CreateSignature(m.ID, signing, group.PubKey, ownPrivkey) + sig, err := CreateSignature(m.ID, signing, group.PubKey, privKey) require.NoError(ba.TB, err) tx, err := bandtesting.GenTx( @@ -295,7 +297,7 @@ func (ba *BenchmarkApp) GetPendingSignTxs( GenMsgSubmitSignature(tss.SigningID(sid), m.ID, sig, ba.Sender.Address), sdk.Coins{sdk.NewInt64Coin("uband", 1)}, math.MaxInt64, - "", + bandtesting.ChainID, []uint64{ba.Sender.Num}, []uint64{ba.Sender.Seq}, ba.Sender.PrivKey, @@ -314,17 +316,16 @@ func (ba *BenchmarkApp) HandleGenPendingSignTxs( gid tss.GroupID, content tsstypes.Content, feeLimit sdk.Coins, - tcs []testutil.TestCase, ) []sdk.Tx { - txs := ba.GetPendingSignTxs(gid, tcs) + txs := ba.GetPendingSignTxs(gid) if len(txs) > 0 { return txs } ba.RequestSignature(ba.Sender, content, feeLimit) - ba.AddDEs(ba.Gid) + ba.AddDEs(ba.Sender.Address) - return ba.GetPendingSignTxs(gid, tcs) + return ba.GetPendingSignTxs(gid) } func (ba *BenchmarkApp) RequestSignature( @@ -341,16 +342,14 @@ func (ba *BenchmarkApp) RequestSignature( require.NoError(ba.TB, err) } -func (ba *BenchmarkApp) AddDEs( - gid tss.GroupID, -) { +func (ba *BenchmarkApp) AddDEs(addr sdk.AccAddress) { ctx, msgSrvr, k := ba.Ctx, ba.TSSMsgSrvr, ba.TSSKeeper - count := k.GetDECount(ctx, ba.Sender.Address) + count := k.GetDECount(ctx, addr) if count < uint64(DELen) { _, err := msgSrvr.SubmitDEs(ctx, &tsstypes.MsgSubmitDEs{ DEs: GetDEs(), - Address: ba.Sender.Address.String(), + Address: addr.String(), }) require.NoError(ba.TB, err) } diff --git a/benchmark/helper_test.go b/benchmark/helper_test.go index d2bd9ec70..d661af9c0 100644 --- a/benchmark/helper_test.go +++ b/benchmark/helper_test.go @@ -20,7 +20,6 @@ import ( "github.com/bandprotocol/chain/v2/pkg/obi" "github.com/bandprotocol/chain/v2/pkg/tss" - "github.com/bandprotocol/chain/v2/pkg/tss/testutil" bandtesting "github.com/bandprotocol/chain/v2/testing" bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" @@ -67,7 +66,6 @@ func GenMsgRequestData( MinCount: 1, ClientID: "", FeeLimit: sdk.Coins{sdk.NewInt64Coin("uband", 1)}, - TSSGroupID: 0, PrepareGas: prepareGas, ExecuteGas: executeGas, Sender: sender.Address.String(), @@ -156,20 +154,6 @@ func GenMsgSubmitSignature(sid tss.SigningID, mid tss.MemberID, sig tss.Signatur return []sdk.Msg{&msg} } -func FindPrivateKey(tcs []testutil.TestCase, gid tss.GroupID, member sdk.AccAddress) tss.Scalar { - for _, tc := range tcs { - if tc.Group.ID == gid { - for _, m := range tc.Group.Members { - a := sdk.AccAddress(m.PubKey()) - if a.Equals(member) { - return m.PrivKey - } - } - } - } - return nil -} - func CreateSignature( mid tss.MemberID, signing tsstypes.Signing, @@ -202,7 +186,6 @@ func CreateSignature( } } - // Sign the message return nil, fmt.Errorf("this member is not assigned members") } @@ -220,7 +203,7 @@ func GenSequenceOfTxs( msgs, sdk.Coins{sdk.NewInt64Coin("uband", 1)}, math.MaxInt64, - "", + bandtesting.ChainID, []uint64{account.Num}, []uint64{account.Seq}, account.PrivKey, @@ -285,7 +268,7 @@ func InitOwasmTestEnv( Value: parameter, Text: strings.Repeat("#", stringLength), }), []sdk.ValAddress{[]byte{}}, 1, - 1, time.Now(), "", nil, nil, ExecuteGasLimit, 0, 0, + 1, time.Now(), "", nil, nil, ExecuteGasLimit, 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ) diff --git a/benchmark/tss_bench_test.go b/benchmark/tss_bench_test.go index 7da9056a3..589a47941 100644 --- a/benchmark/tss_bench_test.go +++ b/benchmark/tss_bench_test.go @@ -7,7 +7,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/pkg/tss/testutil" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) @@ -26,17 +25,11 @@ var RequestSignCases = map[string]struct { func BenchmarkRequestSignatureDeliver(b *testing.B) { for name, tc := range RequestSignCases { for _, blen := range tc.byteLength { - b.Run(fmt.Sprintf( - "%s (byte_length: %d)", - name, - blen, - ), func(b *testing.B) { + b.Run(fmt.Sprintf("%s (byte_length: %d)", name, blen), func(b *testing.B) { ba := InitializeBenchmarkApp(b, -1) - ba.SetupTSSGroup() msg := MockByte(blen) - txs := GenSequenceOfTxs( ba.TxConfig, GenMsgRequestSignature( @@ -73,13 +66,8 @@ func BenchmarkRequestSignatureDeliver(b *testing.B) { func BenchmarkSubmitSignatureDeliver(b *testing.B) { for name, tc := range RequestSignCases { for _, blen := range tc.byteLength { - b.Run(fmt.Sprintf( - "%s (byte_length: %d)", - name, - blen, - ), func(b *testing.B) { + b.Run(fmt.Sprintf("%s (byte_length: %d)", name, blen), func(b *testing.B) { ba := InitializeBenchmarkApp(b, -1) - ba.SetupTSSGroup() ba.CallBeginBlock() @@ -90,12 +78,14 @@ func BenchmarkSubmitSignatureDeliver(b *testing.B) { // deliver MsgSubmitSignature to the block for i := 0; i < b.N; i++ { + gid := ba.BandtssKeeper.GetCurrentGroupID(ba.Ctx) + require.NotZero(b, gid) + // generate tx txs := ba.HandleGenPendingSignTxs( - ba.Gid, + gid, tsstypes.NewTextSignatureOrder(msg), tc.feeLimit, - testutil.TestCases, ) b.StartTimer() @@ -117,13 +107,8 @@ func BenchmarkSubmitSignatureDeliver(b *testing.B) { func BenchmarkEndBlockHandleProcessSigning(b *testing.B) { for name, tc := range RequestSignCases { for _, blen := range tc.byteLength { - b.Run(fmt.Sprintf( - "%s (byte_length: %d)", - name, - blen, - ), func(b *testing.B) { + b.Run(fmt.Sprintf("%s (byte_length: %d)", name, blen), func(b *testing.B) { ba := InitializeBenchmarkApp(b, -1) - ba.SetupTSSGroup() b.ResetTimer() @@ -135,16 +120,23 @@ func BenchmarkEndBlockHandleProcessSigning(b *testing.B) { for i := 0; i < b.N; i++ { ba.CallBeginBlock() + gid := ba.BandtssKeeper.GetCurrentGroupID(ba.Ctx) + require.NotZero(b, gid) + // generate tx ba.RequestSignature(ba.Sender, tsstypes.NewTextSignatureOrder(msg), tc.feeLimit) // everyone submit signature - txs := ba.GetPendingSignTxs(ba.Gid, testutil.TestCases) + txs := ba.GetPendingSignTxs(gid) for _, tx := range txs { _, _, err := ba.CallDeliver(tx) require.NoError(b, err) } - ba.AddDEs(ba.Gid) + + members := ba.TSSKeeper.MustGetMembers(ba.Ctx, gid) + for _, m := range members { + ba.AddDEs(sdk.MustAccAddressFromBech32(m.Address)) + } b.StartTimer() ba.CallEndBlock() diff --git a/client/grpc/oracle/proof/abi.go b/client/grpc/oracle/proof/abi.go index c85b5c366..ff17cfc51 100644 --- a/client/grpc/oracle/proof/abi.go +++ b/client/grpc/oracle/proof/abi.go @@ -16,22 +16,22 @@ var relayFormat = []byte(` }, { "internalType": "bytes32", - "name": "ibcToIcahostStoresMerkleHash", + "name": "paramsToRollingseedStoresMerkleHash", "type": "bytes32" }, { "internalType": "bytes32", - "name": "feegrantToGroupStoresMerkleHash", + "name": "slashingToTssStoresMerkleHash", "type": "bytes32" }, { "internalType": "bytes32", - "name": "authToEvidenceStoresMerkleHash", + "name": "upgradeStoreMerkleHash", "type": "bytes32" }, { "internalType": "bytes32", - "name": "paramsToUpgradeStoresMerkleHash", + "name": "authToIcahostStoresMerkleHash", "type": "bytes32" } ], diff --git a/client/grpc/oracle/proof/multi_store.go b/client/grpc/oracle/proof/multi_store.go index 8d1efc380..cec902454 100644 --- a/client/grpc/oracle/proof/multi_store.go +++ b/client/grpc/oracle/proof/multi_store.go @@ -8,33 +8,33 @@ import ( // MultiStoreProofEthereum is an Ethereum version of MultiStoreProof for solidity ABI-encoding. type MultiStoreProofEthereum struct { - OracleIAVLStateHash common.Hash - MintStoreMerkleHash common.Hash - IbcToIcahostStoresMerkleHash common.Hash - FeegrantToGroupStoresMerkleHash common.Hash - AuthToEvidenceStoresMerkleHash common.Hash - ParamsToUpgradeStoresMerkleHash common.Hash + OracleIAVLStateHash common.Hash + MintStoreMerkleHash common.Hash + ParamsToRollingseedStoresMerkleHash common.Hash + SlashingToTssStoresMerkleHash common.Hash + UpgradeStoreMerkleHash common.Hash + AuthToIcahostStoresMerkleHash common.Hash } func (m *MultiStoreProof) encodeToEthFormat() MultiStoreProofEthereum { return MultiStoreProofEthereum{ - OracleIAVLStateHash: common.BytesToHash(m.OracleIAVLStateHash), - MintStoreMerkleHash: common.BytesToHash(m.MintStoreMerkleHash), - IbcToIcahostStoresMerkleHash: common.BytesToHash(m.IbcToIcahostStoresMerkleHash), - FeegrantToGroupStoresMerkleHash: common.BytesToHash(m.FeegrantToGroupStoresMerkleHash), - AuthToEvidenceStoresMerkleHash: common.BytesToHash(m.AuthToEvidenceStoresMerkleHash), - ParamsToUpgradeStoresMerkleHash: common.BytesToHash(m.ParamsToUpgradeStoresMerkleHash), + OracleIAVLStateHash: common.BytesToHash(m.OracleIAVLStateHash), + MintStoreMerkleHash: common.BytesToHash(m.MintStoreMerkleHash), + ParamsToRollingseedStoresMerkleHash: common.BytesToHash(m.ParamsToRollingseedStoresMerkleHash), + SlashingToTssStoresMerkleHash: common.BytesToHash(m.SlashingToTssStoresMerkleHash), + UpgradeStoreMerkleHash: common.BytesToHash(m.UpgradeStoreMerkleHash), + AuthToIcahostStoresMerkleHash: common.BytesToHash(m.AuthToIcahostStoresMerkleHash), } } // GetMultiStoreProof compacts Multi store proof from Tendermint to MultiStoreProof version. func GetMultiStoreProof(multiStoreEp *ics23.ExistenceProof) MultiStoreProof { return MultiStoreProof{ - OracleIAVLStateHash: tmbytes.HexBytes(multiStoreEp.Value), - MintStoreMerkleHash: tmbytes.HexBytes(multiStoreEp.Path[0].Prefix[1:]), - IbcToIcahostStoresMerkleHash: tmbytes.HexBytes(multiStoreEp.Path[1].Prefix[1:]), - FeegrantToGroupStoresMerkleHash: tmbytes.HexBytes(multiStoreEp.Path[2].Prefix[1:]), - AuthToEvidenceStoresMerkleHash: tmbytes.HexBytes(multiStoreEp.Path[3].Prefix[1:]), - ParamsToUpgradeStoresMerkleHash: tmbytes.HexBytes(multiStoreEp.Path[4].Suffix), + OracleIAVLStateHash: tmbytes.HexBytes(multiStoreEp.Value), + MintStoreMerkleHash: tmbytes.HexBytes(multiStoreEp.Path[0].Prefix[1:]), + ParamsToRollingseedStoresMerkleHash: tmbytes.HexBytes(multiStoreEp.Path[1].Suffix), + SlashingToTssStoresMerkleHash: tmbytes.HexBytes(multiStoreEp.Path[2].Suffix), + UpgradeStoreMerkleHash: tmbytes.HexBytes(multiStoreEp.Path[3].Suffix), + AuthToIcahostStoresMerkleHash: tmbytes.HexBytes(multiStoreEp.Path[4].Prefix[1:]), } } diff --git a/client/grpc/oracle/proof/multi_store_test.go b/client/grpc/oracle/proof/multi_store_test.go index bc6eb4faa..eb60f4b19 100644 --- a/client/grpc/oracle/proof/multi_store_test.go +++ b/client/grpc/oracle/proof/multi_store_test.go @@ -12,41 +12,41 @@ import ( /* query at localhost:26657/abci_query?path="/store/oracle/key"&data=0xc000000000000000&prove=true { - "jsonrpc": "2.0", - "id": -1, - "result": { - "response": { - "code": 0, - "log": "", - "info": "", - "index": "0", + "jsonrpc": "2.0", + "id": -1, + "result": { + "response": { + "code": 0, + "log": "", + "info": "", + "index": "0", + "key": "wAAAAAAAAAA=", + "value": null, + "proofOps": { + "ops": [ + { + "type": "ics23:iavl", "key": "wAAAAAAAAAA=", - "value": null, - "proofOps": { - "ops": [ - { - "type": "ics23:iavl", - "key": "wAAAAAAAAAA=", - "data": "EtsCCgjAAAAAAAAAABKyAQoBBhIdCBAQEBiAAiCABChkMNCGA0ADSChQgOCllrsRWAEaCwgBGAEgASoDAAICIisIARIEAgQCIBohIOtzm7IvSLfzBTqQuiuk/gf6smLK34ZkSJVlxQ/1Bbi9IikIARIlBAYCIDj1W5djJSu7VMElKi6joXfpQCF9Wk/aOzZIKpCY6Ra2ICIpCAESJQYOBCCKaIo830SxbCL1Qk0rvRoWDuKiCxVidDRpX7yqJwZ6YCAamQEKAfASBm9yYWNsZRoLCAEYASABKgMAAgIiKQgBEiUCBAIgdi5vAneYh9+6Qc3ngEMlnwHOKVsdj3MA1Y18Q0Sfv1ggIikIARIlBAYCIDj1W5djJSu7VMElKi6joXfpQCF9Wk/aOzZIKpCY6Ra2ICIpCAESJQYOBCCKaIo830SxbCL1Qk0rvRoWDuKiCxVidDRpX7yqJwZ6YCA=" - }, - { - "type": "ics23:simple", - "key": "b3JhY2xl", - "data": "CvoBCgZvcmFjbGUSIKOu1UEe8Quc2EL/1+wv12JvlreYOeYIttnz9IEULBF5GgkIARgBIAEqAQAiJQgBEiEBszziiEyGhp8/QWWNpdXqtweFbE6u087DWf5LXq0L+TIiJQgBEiEB3e3II3T8dhCPmDUxvJ1pJX5rydODMevJMyFcgoCkKOoiJQgBEiEB8sFioDJU8QbQ8eoWJa4ohiwrc28YRUAmyvF9anblxgAiJQgBEiEBXRVe5Pdw6aqG0QqzJ4R7u9yNwbcffW/0DrPxR6fSMMQiJwgBEgEBGiCRUnPfxybN1OikJ39IxNDtLuhkE5ECBhk0Y7pLsCJcLQ==" - } - ] - }, - "height": "2813", - "codespace": "" - } + "data": "EtsCCgjAAAAAAAAAABKyAQoBBhIdCBAQEBiAAiCABChkMNCGA0ADSChQgOCllrsRWAEaCwgBGAEgASoDAAICIisIARIEAgQCIBohIOtzm7IvSLfzBTqQuiuk/gf6smLK34ZkSJVlxQ/1Bbi9IikIARIlBAYCIDj1W5djJSu7VMElKi6joXfpQCF9Wk/aOzZIKpCY6Ra2ICIpCAESJQYOCCCtJh9hnFH+nCXUc/vv3W7QfQEwx0Ubf2Lxg+N9C127iCAamQEKAfASBm9yYWNsZRoLCAEYASABKgMAAgIiKQgBEiUCBAIgdi5vAneYh9+6Qc3ngEMlnwHOKVsdj3MA1Y18Q0Sfv1ggIikIARIlBAYCIDj1W5djJSu7VMElKi6joXfpQCF9Wk/aOzZIKpCY6Ra2ICIpCAESJQYOCCCtJh9hnFH+nCXUc/vv3W7QfQEwx0Ubf2Lxg+N9C127iCA=" + }, + { + "type": "ics23:simple", + "key": "b3JhY2xl", + "data": "Cv4BCgZvcmFjbGUSIKXZZIz6tibuBT/XZFlzvARMvAYUk9E9+irQmktTAc7TGgkIARgBIAEqAQAiJQgBEiEBBTl35L9FDWYOYAUJrkHLr8meoEluSU1g2NfAFCU8a3YiJwgBEgEBGiBV7R+2oGZxTGgzi2R7nTnYoaOt3XoszZUxlOmUxW4YCyInCAESAQEaIOzLegRHxMW0Unv0rFaJyJMuGuReOkAl0zrnevlu2LQ+IicIARIBARog35ba8pwX7BvU9VCfJzDMfY/V9uM4X7KOGVmjRaQvfCEiJQgBEiEBmk6jPft10k6/2duBuAdRbAGsRYdAoafrTV4fKNydPoA=" + } + ] + }, + "height": "4", + "codespace": "" } + } } */ func TestGetMultiStoreProof(t *testing.T) { key := []byte("oracle") data := base64ToBytes( - "CvoBCgZvcmFjbGUSIKOu1UEe8Quc2EL/1+wv12JvlreYOeYIttnz9IEULBF5GgkIARgBIAEqAQAiJQgBEiEBszziiEyGhp8/QWWNpdXqtweFbE6u087DWf5LXq0L+TIiJQgBEiEB3e3II3T8dhCPmDUxvJ1pJX5rydODMevJMyFcgoCkKOoiJQgBEiEB8sFioDJU8QbQ8eoWJa4ohiwrc28YRUAmyvF9anblxgAiJQgBEiEBXRVe5Pdw6aqG0QqzJ4R7u9yNwbcffW/0DrPxR6fSMMQiJwgBEgEBGiCRUnPfxybN1OikJ39IxNDtLuhkE5ECBhk0Y7pLsCJcLQ==", + "Cv4BCgZvcmFjbGUSIKXZZIz6tibuBT/XZFlzvARMvAYUk9E9+irQmktTAc7TGgkIARgBIAEqAQAiJQgBEiEBBTl35L9FDWYOYAUJrkHLr8meoEluSU1g2NfAFCU8a3YiJwgBEgEBGiBV7R+2oGZxTGgzi2R7nTnYoaOt3XoszZUxlOmUxW4YCyInCAESAQEaIOzLegRHxMW0Unv0rFaJyJMuGuReOkAl0zrnevlu2LQ+IicIARIBARog35ba8pwX7BvU9VCfJzDMfY/V9uM4X7KOGVmjRaQvfCEiJQgBEiEBmk6jPft10k6/2duBuAdRbAGsRYdAoafrTV4fKNydPoA=", ) var multistoreOps storetypes.CommitmentOp @@ -71,20 +71,20 @@ func TestGetMultiStoreProof(t *testing.T) { prefix = append(prefix, 32) // size of result hash must be 32 apphash := innerHash( + m.AuthToIcahostStoresMerkleHash, innerHash( - m.AuthToEvidenceStoresMerkleHash, innerHash( - m.FeegrantToGroupStoresMerkleHash, innerHash( - m.IbcToIcahostStoresMerkleHash, innerHash( m.MintStoreMerkleHash, leafHash(append(prefix, tmhash.Sum(m.OracleIAVLStateHash)...)), ), + m.ParamsToRollingseedStoresMerkleHash, ), + m.SlashingToTssStoresMerkleHash, ), + m.UpgradeStoreMerkleHash, ), - m.ParamsToUpgradeStoresMerkleHash, ) require.Equal(t, expectAppHash, apphash) diff --git a/client/grpc/oracle/proof/proof.pb.go b/client/grpc/oracle/proof/proof.pb.go index 826b01b83..2d0e4a093 100644 --- a/client/grpc/oracle/proof/proof.pb.go +++ b/client/grpc/oracle/proof/proof.pb.go @@ -882,33 +882,34 @@ func (m *BlockRelayProof) GetSignatures() []TMSignature { // MultiStoreProof stores a compact of other Cosmos-SDK modules' storage hash in multistore to // compute (in combination with oracle store hash) Tendermint's application state hash at a given block. // -// ___________________[AppHash]_________________ -// / \ -// ___________[N19]____________ ____[N20]______ -// / \ / \ -// ____[N15]____ ____[N16]______ _[N17]__ _[N18]_ -// / \ / \ / \ / \ -// __[N8]_ __[N9]_ _[N10]_ _[N11]_ [N12] [N13] [N14] [M] -// / \ / \ / \ / \ / \ / \ / \ -// [N0] [N1] [N2] [N3] [N4] [N5] [N6] [N7] [G] [H] [I] [J] [K] [L] -// / \ / \ / \ / \ / \ / \ / \ / \ -// [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [A] [B] [C] [D] [E] [F] +// __________________________[AppHash]__________________________ +// / \ +// ___________[N21]____________ ___________[N22]____________ +// / \ / \ +// _____[N18]_____ ____[N19]______ ____[N20]______ [O] +// / \ / \ / \ +// _[N12]_ _[N13]_ _[N14]_ _[N15]_ _[N16]_ _[N17]_ +// / \ / \ / \ / \ / \ / \ +// [N0] [N1] [N2] [N3] [N4] [N5] [N6] [N7] [N8] [N9] [N10] [N11] +// / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ +// [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] // -// [0] - acc (auth) [1] - authz [2] - bank [3] - capability [4] - consensus [5] - crisis -// [6] - dist [7] - evidence [8] - feegrant [9] - globalfee [A] - gov [B] - group -// [C] - ibccore [D] - icahost [E] - mint [F] - oracle [G] - params [H] - rollingseed -// [I] - slashing [J] - staking [K] - transfer [L] - tss [M] - upgrade +// [0] - acc (auth) [1] - authz [2] - bandtss [3] - bank [4] - capability [5] - consensus +// [6] - crisis [7] - dist [8] - evidence [9] - feeds [A] - feegrant [B] - globalfee +// [C] - gov [D] - group [E] - ibccore [F] - icahost [G] - mint [H] - oracle +// [I] - params [J] - rollingseed [K] - slashing [L] - staking [M] - transfer [N] - tss +// [O] - upgrade // // Notice that NOT all leaves of the Merkle tree are needed in order to compute the Merkle -// root hash, since we only want to validate the correctness of [F] In fact, only -// [E], [N6], [N10], [N15], and [N20] are needed in order to compute [AppHash]. +// root hash, since we only want to validate the correctness of [H] In fact, only +// [G], [N9], [N17], [O], and [N21] are needed in order to compute [AppHash]. type MultiStoreProof struct { - OracleIAVLStateHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,1,opt,name=oracle_iavl_state_hash,json=oracleIavlStateHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"oracle_iavl_state_hash,omitempty"` - MintStoreMerkleHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,2,opt,name=mint_store_merkle_hash,json=mintStoreMerkleHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"mint_store_merkle_hash,omitempty"` - IbcToIcahostStoresMerkleHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,3,opt,name=ibc_to_icahost_stores_merkle_hash,json=ibcToIcahostStoresMerkleHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"ibc_to_icahost_stores_merkle_hash,omitempty"` - FeegrantToGroupStoresMerkleHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,4,opt,name=feegrant_to_group_stores_merkle_hash,json=feegrantToGroupStoresMerkleHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"feegrant_to_group_stores_merkle_hash,omitempty"` - AuthToEvidenceStoresMerkleHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,5,opt,name=auth_to_evidence_stores_merkle_hash,json=authToEvidenceStoresMerkleHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"auth_to_evidence_stores_merkle_hash,omitempty"` - ParamsToUpgradeStoresMerkleHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,6,opt,name=params_to_upgrade_stores_merkle_hash,json=paramsToUpgradeStoresMerkleHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"params_to_upgrade_stores_merkle_hash,omitempty"` + OracleIAVLStateHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,1,opt,name=oracle_iavl_state_hash,json=oracleIavlStateHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"oracle_iavl_state_hash,omitempty"` + MintStoreMerkleHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,2,opt,name=mint_store_merkle_hash,json=mintStoreMerkleHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"mint_store_merkle_hash,omitempty"` + ParamsToRollingseedStoresMerkleHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,3,opt,name=params_to_rollingseed_stores_merkle_hash,json=paramsToRollingseedStoresMerkleHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"params_to_rollingseed_stores_merkle_hash,omitempty"` + SlashingToTssStoresMerkleHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,4,opt,name=slashing_to_tss_stores_merkle_hash,json=slashingToTssStoresMerkleHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"slashing_to_tss_stores_merkle_hash,omitempty"` + UpgradeStoreMerkleHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,5,opt,name=upgrade_store_merkle_hash,json=upgradeStoreMerkleHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"upgrade_store_merkle_hash,omitempty"` + AuthToIcahostStoresMerkleHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,6,opt,name=auth_to_icahost_stores_merkle_hash,json=authToIcahostStoresMerkleHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"auth_to_icahost_stores_merkle_hash,omitempty"` } func (m *MultiStoreProof) Reset() { *m = MultiStoreProof{} } @@ -958,30 +959,30 @@ func (m *MultiStoreProof) GetMintStoreMerkleHash() github_com_cometbft_cometbft_ return nil } -func (m *MultiStoreProof) GetIbcToIcahostStoresMerkleHash() github_com_cometbft_cometbft_libs_bytes.HexBytes { +func (m *MultiStoreProof) GetParamsToRollingseedStoresMerkleHash() github_com_cometbft_cometbft_libs_bytes.HexBytes { if m != nil { - return m.IbcToIcahostStoresMerkleHash + return m.ParamsToRollingseedStoresMerkleHash } return nil } -func (m *MultiStoreProof) GetFeegrantToGroupStoresMerkleHash() github_com_cometbft_cometbft_libs_bytes.HexBytes { +func (m *MultiStoreProof) GetSlashingToTssStoresMerkleHash() github_com_cometbft_cometbft_libs_bytes.HexBytes { if m != nil { - return m.FeegrantToGroupStoresMerkleHash + return m.SlashingToTssStoresMerkleHash } return nil } -func (m *MultiStoreProof) GetAuthToEvidenceStoresMerkleHash() github_com_cometbft_cometbft_libs_bytes.HexBytes { +func (m *MultiStoreProof) GetUpgradeStoreMerkleHash() github_com_cometbft_cometbft_libs_bytes.HexBytes { if m != nil { - return m.AuthToEvidenceStoresMerkleHash + return m.UpgradeStoreMerkleHash } return nil } -func (m *MultiStoreProof) GetParamsToUpgradeStoresMerkleHash() github_com_cometbft_cometbft_libs_bytes.HexBytes { +func (m *MultiStoreProof) GetAuthToIcahostStoresMerkleHash() github_com_cometbft_cometbft_libs_bytes.HexBytes { if m != nil { - return m.ParamsToUpgradeStoresMerkleHash + return m.AuthToIcahostStoresMerkleHash } return nil } @@ -1325,105 +1326,104 @@ func init() { func init() { proto.RegisterFile("bandchain/v1/oracle/proof.proto", fileDescriptor_ae72765f9c902173) } var fileDescriptor_ae72765f9c902173 = []byte{ - // 1553 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x58, 0xcb, 0x6e, 0x1b, 0x47, - 0x16, 0x55, 0x8b, 0x94, 0xec, 0xb9, 0x94, 0x2c, 0xa9, 0x64, 0x4b, 0xb4, 0x60, 0x93, 0x12, 0xed, - 0xb1, 0xe4, 0xf1, 0x80, 0x1c, 0xc9, 0xb3, 0x31, 0x66, 0x36, 0x92, 0xc7, 0x1e, 0x69, 0xc6, 0xaf, - 0x90, 0x8a, 0x02, 0x04, 0x01, 0x3a, 0xc5, 0xee, 0x12, 0x59, 0x71, 0xb3, 0x8b, 0xee, 0x2a, 0x12, - 0xb2, 0x03, 0x23, 0x2f, 0x24, 0x41, 0xb2, 0x08, 0xf2, 0xf8, 0x8b, 0x6c, 0x8c, 0x6c, 0xf2, 0x0d, - 0x5e, 0x1a, 0xc8, 0x22, 0x01, 0x02, 0x38, 0x86, 0x9c, 0x55, 0x3e, 0x21, 0xab, 0xa0, 0x1e, 0x4d, - 0x76, 0x93, 0xcd, 0x48, 0x36, 0x6d, 0xaf, 0xd8, 0x5d, 0xbc, 0x75, 0xce, 0xb9, 0x8f, 0xba, 0x55, - 0x5d, 0x90, 0xaf, 0x62, 0xdf, 0x75, 0xea, 0x98, 0xfa, 0xa5, 0xf6, 0x6a, 0x89, 0x05, 0xd8, 0xf1, - 0x48, 0xa9, 0x19, 0x30, 0xb6, 0x5b, 0x6c, 0x06, 0x4c, 0x30, 0x34, 0xdb, 0x31, 0x28, 0xb6, 0x57, - 0x8b, 0xda, 0x60, 0xe1, 0x54, 0x8d, 0xb1, 0x9a, 0x47, 0x4a, 0xb8, 0x49, 0x4b, 0xd8, 0xf7, 0x99, - 0xc0, 0x82, 0x32, 0x9f, 0xeb, 0x29, 0x0b, 0xc7, 0x6b, 0xac, 0xc6, 0xd4, 0x63, 0x49, 0x3e, 0x99, - 0xd1, 0x39, 0x03, 0xde, 0xa1, 0xd1, 0xe3, 0x85, 0xff, 0xc1, 0xcc, 0x6b, 0x2d, 0x12, 0xdc, 0xbd, - 0x25, 0x49, 0xcb, 0xe4, 0x4e, 0x8b, 0x70, 0x81, 0x4e, 0x03, 0x04, 0xfa, 0xd1, 0xa6, 0x6e, 0xd6, - 0x5a, 0xb4, 0x56, 0xd2, 0xe5, 0xbf, 0x98, 0x91, 0x2d, 0x17, 0xcd, 0xc1, 0x78, 0x9d, 0xd0, 0x5a, - 0x5d, 0x64, 0x47, 0x17, 0xad, 0x95, 0x54, 0xd9, 0xbc, 0x15, 0x04, 0xa0, 0x28, 0x16, 0x6f, 0x32, - 0x9f, 0x93, 0x88, 0xb5, 0x15, 0xb5, 0x46, 0x57, 0x61, 0x3c, 0x20, 0xbc, 0xe5, 0x69, 0x94, 0xcc, - 0xda, 0x4a, 0x31, 0xc1, 0xd7, 0x62, 0x85, 0xfa, 0x35, 0x8f, 0xc4, 0x10, 0x37, 0xd2, 0x0f, 0x1f, - 0xe7, 0x47, 0xca, 0x66, 0x76, 0xe1, 0x12, 0xcc, 0x29, 0xd6, 0xeb, 0x2d, 0x4f, 0xd0, 0x98, 0x1b, - 0x79, 0xc8, 0x74, 0xdd, 0xe0, 0x59, 0x6b, 0x31, 0xb5, 0x92, 0x2e, 0x43, 0xc7, 0x0f, 0x5e, 0xd8, - 0x83, 0xf9, 0xbe, 0xa9, 0x07, 0xa8, 0xbe, 0xd2, 0xa3, 0x7a, 0x39, 0x51, 0x75, 0x3f, 0x60, 0x8f, - 0xe8, 0x3c, 0x9c, 0x56, 0xcc, 0x46, 0xea, 0x65, 0xd6, 0xf2, 0x45, 0x54, 0x7b, 0xe1, 0x3d, 0xc8, - 0x0d, 0x32, 0x78, 0x21, 0x0a, 0xfb, 0x01, 0x7b, 0x14, 0x7e, 0x67, 0xc1, 0x6c, 0x42, 0xf0, 0xd1, - 0xbf, 0x61, 0x4c, 0x15, 0xa8, 0x62, 0xcd, 0xac, 0x2d, 0x1e, 0x94, 0x35, 0x03, 0xab, 0x27, 0xa1, - 0xb7, 0x60, 0x8a, 0xb4, 0x1b, 0xb6, 0x7a, 0xb1, 0xab, 0x77, 0x05, 0xe1, 0x4a, 0xe5, 0xc4, 0xc6, - 0x3f, 0x7f, 0x7f, 0x9c, 0xff, 0x47, 0x8d, 0x8a, 0x7a, 0xab, 0x5a, 0x74, 0x58, 0xa3, 0xe4, 0xb0, - 0x06, 0x11, 0xd5, 0x5d, 0xd1, 0x7d, 0xf0, 0x68, 0x95, 0x97, 0xd4, 0x94, 0xe2, 0x26, 0xd9, 0xdb, - 0x90, 0x0f, 0xe5, 0x49, 0xd2, 0x6e, 0x68, 0x16, 0xf9, 0x5a, 0x78, 0x60, 0x01, 0x4a, 0xc8, 0xe5, - 0xbf, 0xe2, 0x92, 0xf3, 0x07, 0xa4, 0xec, 0x55, 0x2b, 0x4e, 0xc8, 0xed, 0xa1, 0x14, 0x77, 0xe7, - 0xbd, 0x4a, 0xc5, 0x4f, 0x2c, 0xc8, 0x44, 0xd2, 0x8b, 0x96, 0x60, 0xa2, 0xea, 0x31, 0xe7, 0xb6, - 0x1d, 0x29, 0xc6, 0x74, 0x39, 0xa3, 0xc6, 0x36, 0x75, 0x45, 0xee, 0xc0, 0x8c, 0x96, 0x6c, 0xbb, - 0x58, 0x60, 0x2d, 0xcc, 0x14, 0xe7, 0xd9, 0x44, 0xcf, 0x6e, 0xaa, 0x9f, 0xff, 0x60, 0x81, 0xa3, - 0xee, 0x4d, 0xb1, 0xf8, 0xb0, 0xc4, 0xd5, 0xd4, 0x01, 0xf1, 0xf0, 0x5d, 0x83, 0x9b, 0xfa, 0x13, - 0xdc, 0x0d, 0x69, 0x5d, 0x96, 0xc6, 0x31, 0xdc, 0x6a, 0x7c, 0xb8, 0xf0, 0x9b, 0x05, 0xd0, 0x2d, - 0x87, 0xc3, 0x78, 0x88, 0x61, 0x3e, 0xea, 0x61, 0x43, 0x4e, 0xee, 0xf8, 0x99, 0x7a, 0x46, 0x3f, - 0x8f, 0x77, 0xfd, 0x8c, 0xa8, 0x78, 0x59, 0xce, 0xfe, 0x68, 0x01, 0x74, 0x2b, 0xe9, 0x30, 0xce, - 0xde, 0x80, 0x8c, 0x23, 0x27, 0xc4, 0x12, 0x99, 0xdc, 0x65, 0x4c, 0xf7, 0xe2, 0x7d, 0xa5, 0x0a, - 0x4e, 0x97, 0xf2, 0x65, 0x79, 0xf6, 0xad, 0x05, 0x53, 0x3d, 0x11, 0x46, 0xa5, 0x4e, 0x73, 0xd4, - 0x2b, 0x6b, 0x26, 0xc4, 0x6c, 0xaf, 0x16, 0xcb, 0xea, 0x8f, 0x78, 0x1b, 0x44, 0x59, 0x38, 0xd2, - 0x26, 0x01, 0xa7, 0xcc, 0x57, 0x8e, 0xa6, 0xcb, 0xe1, 0x2b, 0xba, 0x06, 0x13, 0x0d, 0x12, 0xdc, - 0xf6, 0x88, 0xdd, 0xc4, 0xa2, 0xce, 0xb3, 0x29, 0x95, 0xe8, 0x33, 0x89, 0x8a, 0xb7, 0xd6, 0x77, - 0xae, 0x5d, 0x57, 0xc6, 0xb7, 0xb0, 0xa8, 0x1b, 0x8a, 0x4c, 0xa3, 0x33, 0xc2, 0x0b, 0x1f, 0x8f, - 0xc2, 0xb1, 0xb8, 0x15, 0x5a, 0x86, 0x69, 0xca, 0x75, 0x41, 0x31, 0xdf, 0x0e, 0x3a, 0xe9, 0x38, - 0x5a, 0x9e, 0xa4, 0x5c, 0xba, 0x74, 0xd3, 0x2f, 0xab, 0x84, 0xfc, 0x15, 0x8e, 0xf1, 0x56, 0x55, - 0x04, 0x84, 0xd8, 0x91, 0x7d, 0x79, 0xb2, 0x3c, 0x69, 0x46, 0x4d, 0xde, 0x96, 0x60, 0x22, 0x34, - 0xe3, 0xf4, 0x1e, 0x51, 0x21, 0x4e, 0x97, 0x33, 0x66, 0xac, 0x42, 0xef, 0x11, 0xb4, 0x0c, 0x53, - 0xa1, 0x49, 0xe8, 0x75, 0x5a, 0x59, 0x85, 0x04, 0x3b, 0xc6, 0xf9, 0x37, 0x60, 0x82, 0xd3, 0xaa, - 0x47, 0xfd, 0x9a, 0x5d, 0xc7, 0xbc, 0x9e, 0x1d, 0x1b, 0xa2, 0xc1, 0x64, 0x0c, 0xd2, 0x26, 0xe6, - 0xf5, 0xc2, 0xe7, 0x29, 0x98, 0xea, 0xc9, 0xaf, 0x2c, 0x10, 0xbd, 0xa2, 0xb8, 0x60, 0x01, 0xb1, - 0xa3, 0x9d, 0xf1, 0xec, 0xe0, 0x5e, 0x5e, 0x91, 0xc6, 0xb1, 0x02, 0x69, 0xc4, 0x87, 0x91, 0x07, - 0x27, 0xc3, 0x5a, 0xc7, 0x2e, 0x09, 0xec, 0x4e, 0x3a, 0x03, 0xc1, 0x4d, 0x59, 0x5f, 0x18, 0x5c, - 0x80, 0x9b, 0x6a, 0x52, 0x98, 0xaf, 0x40, 0x70, 0x43, 0x33, 0x57, 0x4d, 0xfc, 0x17, 0x51, 0xc8, - 0x3a, 0xac, 0xd1, 0x60, 0xbe, 0x4d, 0x7c, 0x87, 0xb9, 0xc4, 0xb5, 0xdb, 0x4c, 0x68, 0x36, 0x53, - 0xed, 0x7f, 0x1b, 0xd0, 0xe6, 0xe5, 0xa4, 0x2b, 0x7a, 0xce, 0x0e, 0x13, 0x0a, 0xce, 0x70, 0x9d, - 0x70, 0x92, 0xfe, 0x44, 0x57, 0x01, 0x38, 0xad, 0xf9, 0x58, 0xb4, 0x02, 0xc2, 0xb3, 0x69, 0x55, - 0x98, 0xc9, 0x1b, 0xf5, 0xf6, 0xf5, 0x4a, 0x68, 0x18, 0xae, 0xcc, 0xee, 0xcc, 0xc2, 0x17, 0xe3, - 0x30, 0xd5, 0x13, 0x4b, 0xf4, 0xbe, 0x05, 0xe6, 0x2c, 0x69, 0x53, 0xdc, 0xf6, 0x6c, 0x2e, 0xb0, - 0x20, 0xba, 0x08, 0x2c, 0x55, 0x04, 0xff, 0xdf, 0x7f, 0x9c, 0x9f, 0xd5, 0xeb, 0x4e, 0x16, 0x74, - 0x45, 0xfe, 0x2f, 0x53, 0xfb, 0x5c, 0xb5, 0x31, 0xab, 0xa9, 0xb6, 0x70, 0xdb, 0xeb, 0x00, 0x21, - 0x0a, 0x73, 0x0d, 0xea, 0x0b, 0x53, 0x0e, 0x26, 0x6b, 0x4a, 0xc1, 0x30, 0xfb, 0xdc, 0xac, 0xc4, - 0x54, 0x8e, 0xea, 0xac, 0x29, 0xaa, 0xfb, 0xb0, 0x44, 0xab, 0x8e, 0x2d, 0x98, 0x4d, 0x1d, 0x5c, - 0x67, 0xdc, 0x90, 0xf2, 0x18, 0x6b, 0x6a, 0x08, 0xd6, 0x53, 0xb4, 0xea, 0x6c, 0xb3, 0x2d, 0x0d, - 0xae, 0xd8, 0x79, 0x84, 0xfe, 0x23, 0x0b, 0xce, 0xee, 0x12, 0x52, 0x0b, 0xb0, 0x2f, 0xa4, 0x88, - 0x5a, 0xc0, 0x5a, 0xcd, 0x24, 0x09, 0xe9, 0x21, 0x24, 0xe4, 0x43, 0x86, 0x6d, 0xf6, 0x5f, 0x89, - 0xdf, 0xa7, 0xe2, 0x03, 0x0b, 0xce, 0xe0, 0x96, 0xa8, 0x4b, 0x05, 0xa4, 0x4d, 0x5d, 0xe2, 0x3b, - 0x24, 0x49, 0xc4, 0x30, 0x4d, 0x20, 0x27, 0x09, 0xb6, 0xd9, 0x15, 0x03, 0x9f, 0x18, 0x89, 0x26, - 0x0e, 0x70, 0x83, 0x4b, 0x15, 0xad, 0x66, 0x2d, 0xc0, 0x6e, 0xa2, 0x88, 0xf1, 0x61, 0x22, 0xa1, - 0x19, 0xb6, 0xd9, 0xeb, 0x1a, 0xbf, 0x57, 0x45, 0xe1, 0xfb, 0x31, 0x98, 0x4b, 0x5e, 0xfc, 0xc8, - 0x87, 0x93, 0xa6, 0x65, 0xda, 0xd8, 0x77, 0x6d, 0xb5, 0xd0, 0x6c, 0xea, 0x46, 0x57, 0xc6, 0xf3, - 0x89, 0x3a, 0x61, 0x60, 0xd7, 0x7d, 0xf7, 0xb2, 0x04, 0xdd, 0x72, 0x55, 0x40, 0xe2, 0x1f, 0x61, - 0xe9, 0xce, 0xf1, 0x3f, 0x0f, 0x19, 0x41, 0x1b, 0xc4, 0xe6, 0xc4, 0x61, 0xbe, 0x6b, 0x9a, 0x3c, - 0xc8, 0xa1, 0x8a, 0x1a, 0x41, 0x2b, 0x30, 0xad, 0x0c, 0x7c, 0xec, 0xb3, 0xd0, 0x2a, 0xad, 0xf6, - 0x8b, 0x63, 0x72, 0xfc, 0x06, 0xf6, 0x99, 0xb1, 0x7c, 0x07, 0xe6, 0x3d, 0xcc, 0x85, 0xad, 0x9b, - 0x24, 0x75, 0x95, 0x63, 0x4c, 0xd4, 0x49, 0x30, 0x54, 0xaa, 0x67, 0x25, 0xa8, 0x8a, 0xe2, 0x96, - 0xbb, 0xee, 0xbb, 0x37, 0x25, 0x20, 0xfa, 0xd4, 0x82, 0x73, 0x3e, 0xd9, 0x13, 0x76, 0x1b, 0x7b, - 0xd4, 0xc5, 0x82, 0x05, 0x2a, 0x72, 0x3a, 0x96, 0xf2, 0x4c, 0xec, 0xf3, 0x16, 0x1f, 0x3e, 0xc3, - 0x4b, 0x92, 0x63, 0x27, 0xa4, 0x90, 0x81, 0x94, 0x61, 0x0d, 0xf1, 0x55, 0x60, 0xdf, 0x86, 0x19, - 0xe5, 0xb5, 0x3e, 0x00, 0x18, 0xce, 0x23, 0x43, 0x70, 0x4e, 0x49, 0x38, 0x7d, 0xb8, 0xd0, 0x0c, - 0x77, 0x60, 0xa1, 0xb3, 0x8c, 0xa4, 0x7f, 0xcd, 0x80, 0x35, 0x19, 0x27, 0xda, 0xe3, 0xec, 0xd1, - 0x21, 0xa8, 0xe6, 0x43, 0xdc, 0x75, 0xdf, 0xbd, 0x65, 0x50, 0x55, 0xe1, 0xfe, 0x62, 0xc1, 0x89, - 0xc4, 0x8d, 0x04, 0x55, 0x01, 0xc9, 0x8e, 0x4f, 0xdc, 0xf0, 0x70, 0x4e, 0x76, 0xe9, 0xde, 0x50, - 0x05, 0x3b, 0xad, 0xf1, 0xf4, 0xa1, 0x4b, 0xa2, 0xf5, 0x72, 0xf0, 0xd6, 0xae, 0xe4, 0x18, 0x7d, - 0x31, 0x1c, 0x15, 0x85, 0x56, 0xf8, 0x64, 0x14, 0x32, 0x91, 0xdd, 0x0c, 0x6d, 0x80, 0x15, 0x0c, - 0xe5, 0x86, 0x15, 0x48, 0x8c, 0xe1, 0xbe, 0x9d, 0x2c, 0x8e, 0x26, 0xc0, 0x6a, 0xab, 0x55, 0x38, - 0x59, 0xb6, 0xda, 0x08, 0xc3, 0x4c, 0xb8, 0xfb, 0xcb, 0xc5, 0xc6, 0x05, 0x6e, 0x34, 0x87, 0x6a, - 0xde, 0xd3, 0x06, 0x6e, 0x3b, 0x44, 0x2b, 0x7c, 0x6d, 0x01, 0xea, 0x3f, 0x77, 0xa3, 0xe3, 0x30, - 0xa6, 0xce, 0xdc, 0xe6, 0x44, 0xaf, 0x5f, 0x5e, 0xd5, 0xf1, 0x76, 0xed, 0xe7, 0x14, 0x1c, 0xa9, - 0x90, 0xa0, 0x4d, 0x1d, 0x82, 0x3e, 0xb3, 0x60, 0x4c, 0x6b, 0x3a, 0x97, 0x88, 0xd6, 0x77, 0x1f, - 0xb5, 0xb0, 0x7c, 0xa0, 0x9d, 0xfe, 0x6e, 0x2e, 0x94, 0x3e, 0xfc, 0xe1, 0xd7, 0x6f, 0x46, 0xcf, - 0xa3, 0xe5, 0xd2, 0xc0, 0x8b, 0xb5, 0xd2, 0xbb, 0xdd, 0x3b, 0xa1, 0xfb, 0xe8, 0xab, 0xf8, 0xa7, - 0xde, 0x85, 0xc1, 0x44, 0x7d, 0xd7, 0x4b, 0x0b, 0x7f, 0x3f, 0x9c, 0xb1, 0x91, 0xb6, 0xa2, 0xa4, - 0x15, 0xd0, 0x62, 0xa2, 0xb4, 0xc8, 0x17, 0x23, 0x7a, 0x60, 0xc1, 0x4c, 0xdf, 0xb5, 0x0f, 0x5a, - 0x1b, 0xcc, 0x36, 0xe8, 0x12, 0x69, 0xe1, 0xe2, 0x33, 0xcd, 0x31, 0x42, 0x57, 0x95, 0xd0, 0x0b, - 0xe8, 0x7c, 0xa2, 0x50, 0x13, 0x3c, 0x6e, 0x47, 0x3e, 0x01, 0x37, 0x2a, 0x0f, 0xf7, 0x73, 0xd6, - 0xa3, 0xfd, 0x9c, 0xf5, 0x64, 0x3f, 0x67, 0x7d, 0xf9, 0x34, 0x37, 0xf2, 0xe8, 0x69, 0x6e, 0xe4, - 0xa7, 0xa7, 0xb9, 0x91, 0x37, 0x2f, 0x45, 0x0a, 0x5a, 0xc2, 0xa9, 0x4b, 0x47, 0x87, 0x79, 0x25, - 0x83, 0xbb, 0x56, 0x72, 0x3c, 0x4a, 0x7c, 0x51, 0xaa, 0x05, 0x4d, 0x27, 0x96, 0xa7, 0xea, 0xb8, - 0xb2, 0xbd, 0xf8, 0x47, 0x00, 0x00, 0x00, 0xff, 0xff, 0xe9, 0x6f, 0x30, 0x2a, 0x24, 0x15, 0x00, - 0x00, + // 1545 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x58, 0xdb, 0x6f, 0x13, 0xc7, + 0x1a, 0xcf, 0xc6, 0x4e, 0xe0, 0x7c, 0x4e, 0x48, 0x32, 0x81, 0xc4, 0x44, 0x87, 0x38, 0x2c, 0x1c, + 0x12, 0x0e, 0x47, 0xf6, 0x49, 0x38, 0x2f, 0xe8, 0xf4, 0x25, 0xa1, 0xa0, 0xa4, 0xe5, 0xd6, 0x75, + 0x94, 0x4a, 0x55, 0xa5, 0xed, 0x78, 0x77, 0x62, 0x4f, 0x59, 0xef, 0x98, 0x9d, 0xb1, 0x15, 0xa8, + 0x2a, 0x50, 0xa5, 0xb6, 0x6a, 0xfb, 0xd2, 0xcb, 0x7f, 0xd1, 0x17, 0xd4, 0x97, 0xfe, 0x0d, 0x3c, + 0x22, 0xf5, 0xa1, 0x95, 0x2a, 0x51, 0x14, 0xfa, 0xd4, 0x3f, 0xa1, 0x4f, 0xd5, 0x5c, 0xd6, 0x5e, + 0xdb, 0xeb, 0x26, 0x60, 0xe0, 0xc9, 0xbb, 0xe3, 0x6f, 0x7e, 0x97, 0xf9, 0xbe, 0xb9, 0xec, 0x40, + 0xa1, 0x82, 0x43, 0xdf, 0xab, 0x61, 0x1a, 0x96, 0x5a, 0xab, 0x25, 0x16, 0x61, 0x2f, 0x20, 0xa5, + 0x46, 0xc4, 0xd8, 0x6e, 0xb1, 0x11, 0x31, 0xc1, 0xd0, 0x6c, 0x3b, 0xa0, 0xd8, 0x5a, 0x2d, 0xea, + 0x80, 0x85, 0x7f, 0x56, 0x19, 0xab, 0x06, 0xa4, 0x84, 0x1b, 0xb4, 0x84, 0xc3, 0x90, 0x09, 0x2c, + 0x28, 0x0b, 0xb9, 0xee, 0xb2, 0x70, 0xbc, 0xca, 0xaa, 0x4c, 0x3d, 0x96, 0xe4, 0x93, 0x69, 0x9d, + 0x33, 0xe0, 0x6d, 0x1a, 0xdd, 0x6e, 0xbf, 0x05, 0x33, 0xef, 0x34, 0x49, 0x74, 0xf7, 0x96, 0x24, + 0x75, 0xc8, 0x9d, 0x26, 0xe1, 0x02, 0x9d, 0x02, 0x88, 0xf4, 0xa3, 0x4b, 0xfd, 0xbc, 0xb5, 0x64, + 0xad, 0x64, 0x9d, 0x7f, 0x98, 0x96, 0x2d, 0x1f, 0xcd, 0xc1, 0x78, 0x8d, 0xd0, 0x6a, 0x4d, 0xe4, + 0x47, 0x97, 0xac, 0x95, 0x8c, 0x63, 0xde, 0x6c, 0x01, 0x28, 0x89, 0xc5, 0x1b, 0x2c, 0xe4, 0x24, + 0x11, 0x6d, 0x25, 0xa3, 0xd1, 0x55, 0x18, 0x8f, 0x08, 0x6f, 0x06, 0x1a, 0x25, 0xb7, 0xb6, 0x52, + 0x4c, 0xf1, 0x5a, 0x2c, 0xd3, 0xb0, 0x1a, 0x90, 0x2e, 0xc4, 0x8d, 0xec, 0xa3, 0x27, 0x85, 0x11, + 0xc7, 0xf4, 0xb6, 0x2f, 0xc1, 0x9c, 0x62, 0xbd, 0xde, 0x0c, 0x04, 0xed, 0xb2, 0x51, 0x80, 0x5c, + 0xc7, 0x06, 0xcf, 0x5b, 0x4b, 0x99, 0x95, 0xac, 0x03, 0x6d, 0x1f, 0xdc, 0xde, 0x83, 0xf9, 0xbe, + 0xae, 0x07, 0xa8, 0xbe, 0xd2, 0xa3, 0x7a, 0x39, 0x55, 0x75, 0x3f, 0x60, 0x8f, 0xe8, 0x02, 0x9c, + 0x52, 0xcc, 0x46, 0xea, 0x65, 0xd6, 0x0c, 0x45, 0x52, 0xbb, 0x7d, 0x1f, 0x16, 0x07, 0x05, 0xbc, + 0x14, 0x85, 0xfd, 0x80, 0x3d, 0x0a, 0x7f, 0xb0, 0x60, 0x36, 0x65, 0xf0, 0xd1, 0x1b, 0x30, 0xa6, + 0x0a, 0x54, 0xb1, 0xe6, 0xd6, 0x96, 0x0e, 0xca, 0x9a, 0x81, 0xd5, 0x9d, 0xd0, 0xfb, 0x30, 0x45, + 0x5a, 0x75, 0x57, 0xbd, 0xb8, 0x95, 0xbb, 0x82, 0x70, 0xa5, 0x72, 0x62, 0xe3, 0x7f, 0x7f, 0x3e, + 0x29, 0xfc, 0xb7, 0x4a, 0x45, 0xad, 0x59, 0x29, 0x7a, 0xac, 0x5e, 0xf2, 0x58, 0x9d, 0x88, 0xca, + 0xae, 0xe8, 0x3c, 0x04, 0xb4, 0xc2, 0x4b, 0xaa, 0x4b, 0x71, 0x93, 0xec, 0x6d, 0xc8, 0x07, 0x67, + 0x92, 0xb4, 0xea, 0x9a, 0x45, 0xbe, 0xda, 0x0f, 0x2d, 0x40, 0x29, 0xb9, 0xfc, 0x7f, 0xb7, 0xe4, + 0xc2, 0x01, 0x29, 0x7b, 0xdd, 0x8a, 0x53, 0x72, 0x7b, 0x28, 0xc5, 0x9d, 0x7e, 0xaf, 0x53, 0xf1, + 0x53, 0x0b, 0x72, 0x89, 0xf4, 0xa2, 0xd3, 0x30, 0x51, 0x09, 0x98, 0x77, 0xdb, 0x4d, 0x14, 0x63, + 0xd6, 0xc9, 0xa9, 0xb6, 0x4d, 0x5d, 0x91, 0x3b, 0x30, 0xa3, 0x25, 0xbb, 0x3e, 0x16, 0x58, 0x0b, + 0x33, 0xc5, 0x79, 0x36, 0xd5, 0xd9, 0x4d, 0xf5, 0xf3, 0x26, 0x16, 0x38, 0x69, 0x6f, 0x8a, 0x75, + 0x37, 0x4b, 0x5c, 0x4d, 0x1d, 0x91, 0x00, 0xdf, 0x35, 0xb8, 0x99, 0xbf, 0xc1, 0xdd, 0x90, 0xd1, + 0x8e, 0x0c, 0xee, 0xc2, 0xad, 0x74, 0x37, 0xdb, 0x7f, 0x58, 0x00, 0x9d, 0x72, 0x38, 0x8c, 0x43, + 0x0c, 0xf3, 0x49, 0x87, 0x75, 0xd9, 0xb9, 0xed, 0x33, 0xf3, 0x9c, 0x3e, 0x8f, 0x77, 0x7c, 0x26, + 0x54, 0xbc, 0x2a, 0xb3, 0x3f, 0x5b, 0x00, 0x9d, 0x4a, 0x3a, 0x8c, 0xd9, 0x1b, 0x90, 0xf3, 0x64, + 0x87, 0xae, 0x44, 0xa6, 0xaf, 0x32, 0x66, 0xf5, 0xe2, 0x7d, 0xa5, 0x0a, 0x5e, 0x87, 0xf2, 0x55, + 0x39, 0xfb, 0xde, 0x82, 0xa9, 0x9e, 0x11, 0x46, 0xa5, 0xf6, 0xe2, 0xa8, 0x67, 0xd6, 0x4c, 0x8c, + 0xd9, 0x5a, 0x2d, 0x3a, 0xea, 0x8f, 0xee, 0x65, 0x10, 0xe5, 0xe1, 0x48, 0x8b, 0x44, 0x9c, 0xb2, + 0x50, 0x19, 0xcd, 0x3a, 0xf1, 0x2b, 0xba, 0x06, 0x13, 0x75, 0x12, 0xdd, 0x0e, 0x88, 0xdb, 0xc0, + 0xa2, 0xc6, 0xf3, 0x19, 0x95, 0xe8, 0x33, 0xa9, 0x8a, 0xb7, 0xd6, 0x77, 0xae, 0x5d, 0x57, 0xc1, + 0xb7, 0xb0, 0xa8, 0x19, 0x8a, 0x5c, 0xbd, 0xdd, 0xc2, 0xed, 0x4f, 0x47, 0xe1, 0x58, 0x77, 0x14, + 0x5a, 0x86, 0x69, 0xca, 0x75, 0x41, 0xb1, 0xd0, 0x8d, 0xda, 0xe9, 0x38, 0xea, 0x4c, 0x52, 0x2e, + 0x2d, 0xdd, 0x0c, 0x1d, 0x95, 0x90, 0x7f, 0xc1, 0x31, 0xde, 0xac, 0x88, 0x88, 0x10, 0x37, 0xb1, + 0x2f, 0x4f, 0x3a, 0x93, 0xa6, 0xd5, 0xe4, 0xed, 0x34, 0x4c, 0xc4, 0x61, 0x9c, 0xde, 0x23, 0x6a, + 0x88, 0xb3, 0x4e, 0xce, 0xb4, 0x95, 0xe9, 0x3d, 0x82, 0x96, 0x61, 0x2a, 0x0e, 0x89, 0x5d, 0x67, + 0x55, 0x54, 0x4c, 0xb0, 0x63, 0xcc, 0xbf, 0x0b, 0x13, 0x9c, 0x56, 0x02, 0x1a, 0x56, 0xdd, 0x1a, + 0xe6, 0xb5, 0xfc, 0xd8, 0x10, 0x0b, 0x4c, 0xce, 0x20, 0x6d, 0x62, 0x5e, 0xb3, 0xbf, 0xcc, 0xc0, + 0x54, 0x4f, 0x7e, 0x65, 0x81, 0xe8, 0x19, 0xc5, 0x05, 0x8b, 0x88, 0x9b, 0x5c, 0x19, 0xcf, 0x0e, + 0x5e, 0xcb, 0xcb, 0x32, 0xb8, 0xab, 0x40, 0xea, 0xdd, 0xcd, 0x28, 0x80, 0x93, 0x71, 0xad, 0x63, + 0x9f, 0x44, 0x6e, 0x3b, 0x9d, 0x91, 0xe0, 0xa6, 0xac, 0x2f, 0x0c, 0x2e, 0xc0, 0x4d, 0xd5, 0x29, + 0xce, 0x57, 0x24, 0xb8, 0xa1, 0x99, 0xab, 0xa4, 0xfe, 0x8b, 0x28, 0xe4, 0x3d, 0x56, 0xaf, 0xb3, + 0xd0, 0x25, 0xa1, 0xc7, 0x7c, 0xe2, 0xbb, 0x2d, 0x26, 0x34, 0x9b, 0xa9, 0xf6, 0x7f, 0x0f, 0x58, + 0xe6, 0x65, 0xa7, 0x2b, 0xba, 0xcf, 0x0e, 0x13, 0x0a, 0xce, 0x70, 0x9d, 0xf0, 0xd2, 0xfe, 0x44, + 0x57, 0x01, 0x38, 0xad, 0x86, 0x58, 0x34, 0x23, 0xc2, 0xf3, 0x59, 0x55, 0x98, 0xe9, 0x1b, 0xf5, + 0xf6, 0xf5, 0x72, 0x1c, 0x18, 0xcf, 0xcc, 0x4e, 0x4f, 0xfb, 0xc1, 0x38, 0x4c, 0xf5, 0x8c, 0x25, + 0x7a, 0x60, 0x81, 0x39, 0x4b, 0xba, 0x14, 0xb7, 0x02, 0x97, 0x0b, 0x2c, 0x88, 0x2e, 0x02, 0x4b, + 0x15, 0xc1, 0xdb, 0xfb, 0x4f, 0x0a, 0xb3, 0x7a, 0xde, 0xc9, 0x82, 0x2e, 0xcb, 0xff, 0x65, 0x6a, + 0x5f, 0xa8, 0x36, 0x66, 0x35, 0xd5, 0x16, 0x6e, 0x05, 0x6d, 0x20, 0x44, 0x61, 0xae, 0x4e, 0x43, + 0x61, 0xca, 0xc1, 0x64, 0x4d, 0x29, 0x18, 0x66, 0x9f, 0x9b, 0x95, 0x98, 0xca, 0xa8, 0xce, 0x9a, + 0xa2, 0xfa, 0xca, 0x82, 0x95, 0x06, 0x8e, 0x70, 0x9d, 0xbb, 0x82, 0xb9, 0x11, 0x0b, 0x64, 0xa1, + 0x72, 0x42, 0x7c, 0x4d, 0xce, 0xbb, 0xd8, 0x33, 0x43, 0xb0, 0x9f, 0xd1, 0x2c, 0xdb, 0xcc, 0xe9, + 0x70, 0x28, 0x31, 0x3c, 0xa1, 0xe6, 0x3e, 0xd8, 0x3c, 0xc0, 0xbc, 0x26, 0xa7, 0x9d, 0x60, 0xae, + 0xe0, 0x3c, 0x4d, 0x46, 0x76, 0x08, 0x19, 0xa7, 0x62, 0xfc, 0x6d, 0xb6, 0xcd, 0x79, 0x9f, 0x00, + 0x06, 0x27, 0x9b, 0x8d, 0x6a, 0x84, 0x7d, 0x92, 0x32, 0xf8, 0xc3, 0xac, 0x01, 0x73, 0x06, 0xb6, + 0x77, 0xfc, 0xef, 0x83, 0x8d, 0x9b, 0xa2, 0x26, 0xdd, 0x52, 0x0f, 0xd7, 0x18, 0x17, 0x69, 0x8e, + 0xc7, 0x87, 0x71, 0x2c, 0xf1, 0xb7, 0xd9, 0x96, 0x46, 0xef, 0x75, 0x6c, 0xff, 0x38, 0x06, 0x73, + 0xe9, 0xd3, 0x1d, 0x85, 0x70, 0xd2, 0x2c, 0x92, 0x2e, 0x0e, 0x7d, 0x57, 0x4d, 0x2d, 0x97, 0xfa, + 0xc9, 0xb9, 0xf0, 0x62, 0x92, 0x4e, 0x18, 0xd8, 0xf5, 0xd0, 0xbf, 0x2c, 0x41, 0xb7, 0x7c, 0x35, + 0x16, 0xdd, 0x9f, 0x5d, 0xd9, 0xf6, 0x81, 0xbf, 0x00, 0x39, 0x41, 0xeb, 0xc4, 0xe5, 0xc4, 0x63, + 0xa1, 0x6f, 0x96, 0x75, 0x90, 0x4d, 0x65, 0xd5, 0x82, 0x56, 0x60, 0x5a, 0x05, 0x84, 0x38, 0x64, + 0x71, 0x54, 0x56, 0xed, 0x10, 0xc7, 0x64, 0xfb, 0x0d, 0x1c, 0x32, 0x13, 0xf9, 0x21, 0xcc, 0x07, + 0x98, 0x0b, 0x57, 0x2f, 0x8b, 0xd4, 0x57, 0xc6, 0x98, 0xa8, 0x91, 0x68, 0xa8, 0xec, 0xce, 0x4a, + 0x50, 0x35, 0x8a, 0x5b, 0xfe, 0x7a, 0xe8, 0xdf, 0x94, 0x80, 0xe8, 0x73, 0x0b, 0xce, 0x85, 0x64, + 0x4f, 0xb8, 0x2d, 0x1c, 0x50, 0x1f, 0x0b, 0x16, 0xa9, 0x91, 0xd3, 0x63, 0x29, 0x4f, 0xc1, 0x21, + 0x6f, 0xf2, 0xe1, 0xf3, 0x7b, 0x5a, 0x72, 0xec, 0xc4, 0x14, 0x72, 0x20, 0xe5, 0xb0, 0xc6, 0xf8, + 0x6a, 0x60, 0x3f, 0x80, 0x19, 0xe5, 0x5a, 0x6f, 0xf9, 0x86, 0xf3, 0xc8, 0x10, 0x9c, 0x53, 0x12, + 0x4e, 0x1f, 0x27, 0x34, 0xc3, 0x1d, 0x58, 0x20, 0x2d, 0xea, 0x93, 0xd0, 0x23, 0xca, 0x5f, 0x23, + 0x62, 0x0d, 0xc6, 0x89, 0x76, 0x9c, 0x3f, 0x3a, 0x04, 0xd5, 0x7c, 0x8c, 0xbb, 0x1e, 0xfa, 0xb7, + 0x0c, 0xaa, 0x2a, 0xdc, 0xdf, 0x2c, 0x38, 0x91, 0xba, 0x75, 0xa0, 0x0a, 0x20, 0xb9, 0xc6, 0x13, + 0x3f, 0x3e, 0x8e, 0x93, 0x5d, 0xba, 0x37, 0x54, 0xc1, 0x4e, 0x6b, 0x3c, 0x7d, 0xcc, 0x92, 0x68, + 0xbd, 0x1c, 0xbc, 0xb9, 0x2b, 0x39, 0x46, 0x5f, 0x0e, 0x47, 0x59, 0xa1, 0xd9, 0x9f, 0x8d, 0x42, + 0x2e, 0xb1, 0x7f, 0xa1, 0x0d, 0xb0, 0xa2, 0xa1, 0x6c, 0x58, 0x91, 0xc4, 0x18, 0xee, 0x6b, 0xc9, + 0xe2, 0x68, 0x02, 0xac, 0x96, 0x9a, 0x85, 0x93, 0x8e, 0xd5, 0x42, 0x18, 0x66, 0xe2, 0xfd, 0x5e, + 0x4e, 0x36, 0x2e, 0x70, 0xbd, 0x31, 0xd4, 0x12, 0x3d, 0x6d, 0xe0, 0xb6, 0x63, 0x34, 0xfb, 0x5b, + 0x0b, 0x50, 0xff, 0x49, 0x1b, 0x1d, 0x87, 0x31, 0x75, 0xca, 0x36, 0x67, 0x78, 0xfd, 0xf2, 0xba, + 0x0e, 0xb4, 0x6b, 0xbf, 0x66, 0xe0, 0x48, 0x99, 0x44, 0x2d, 0xea, 0x11, 0xf4, 0x85, 0x05, 0x63, + 0x5a, 0xd3, 0xb9, 0x54, 0xb4, 0xbe, 0x1b, 0xa8, 0x85, 0xe5, 0x03, 0xe3, 0xf4, 0x97, 0xb2, 0x5d, + 0xfa, 0xe4, 0xa7, 0xdf, 0xbf, 0x1b, 0x3d, 0x8f, 0x96, 0x4b, 0x03, 0xaf, 0xd2, 0x4a, 0x1f, 0x75, + 0x6e, 0x81, 0x3e, 0x46, 0xdf, 0x74, 0x7f, 0xdc, 0x5d, 0x18, 0x4c, 0xd4, 0x77, 0xa1, 0xb4, 0xf0, + 0x9f, 0xc3, 0x05, 0x1b, 0x69, 0x2b, 0x4a, 0x9a, 0x8d, 0x96, 0x52, 0xa5, 0x25, 0xbe, 0x11, 0xd1, + 0x43, 0x0b, 0x66, 0xfa, 0x2e, 0x7a, 0xd0, 0xda, 0x60, 0xb6, 0x41, 0xd7, 0x46, 0x0b, 0x17, 0x9f, + 0xab, 0x8f, 0x11, 0xba, 0xaa, 0x84, 0x5e, 0x40, 0xe7, 0x53, 0x85, 0x9a, 0xc1, 0xe3, 0x6e, 0xe2, + 0xa3, 0x6f, 0xa3, 0xfc, 0x68, 0x7f, 0xd1, 0x7a, 0xbc, 0xbf, 0x68, 0x3d, 0xdd, 0x5f, 0xb4, 0xbe, + 0x7e, 0xb6, 0x38, 0xf2, 0xf8, 0xd9, 0xe2, 0xc8, 0x2f, 0xcf, 0x16, 0x47, 0xde, 0xbb, 0x94, 0x28, + 0x68, 0x09, 0xa7, 0xae, 0x19, 0x3d, 0x16, 0x94, 0x0c, 0xee, 0x5a, 0xc9, 0x0b, 0x28, 0x09, 0x45, + 0xa9, 0x1a, 0x35, 0xbc, 0xae, 0x3c, 0x55, 0xc6, 0x55, 0xec, 0xc5, 0xbf, 0x02, 0x00, 0x00, 0xff, + 0xff, 0xfb, 0x10, 0x36, 0x69, 0x16, 0x15, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -2257,31 +2257,31 @@ func (m *MultiStoreProof) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.ParamsToUpgradeStoresMerkleHash) > 0 { - i -= len(m.ParamsToUpgradeStoresMerkleHash) - copy(dAtA[i:], m.ParamsToUpgradeStoresMerkleHash) - i = encodeVarintProof(dAtA, i, uint64(len(m.ParamsToUpgradeStoresMerkleHash))) + if len(m.AuthToIcahostStoresMerkleHash) > 0 { + i -= len(m.AuthToIcahostStoresMerkleHash) + copy(dAtA[i:], m.AuthToIcahostStoresMerkleHash) + i = encodeVarintProof(dAtA, i, uint64(len(m.AuthToIcahostStoresMerkleHash))) i-- dAtA[i] = 0x32 } - if len(m.AuthToEvidenceStoresMerkleHash) > 0 { - i -= len(m.AuthToEvidenceStoresMerkleHash) - copy(dAtA[i:], m.AuthToEvidenceStoresMerkleHash) - i = encodeVarintProof(dAtA, i, uint64(len(m.AuthToEvidenceStoresMerkleHash))) + if len(m.UpgradeStoreMerkleHash) > 0 { + i -= len(m.UpgradeStoreMerkleHash) + copy(dAtA[i:], m.UpgradeStoreMerkleHash) + i = encodeVarintProof(dAtA, i, uint64(len(m.UpgradeStoreMerkleHash))) i-- dAtA[i] = 0x2a } - if len(m.FeegrantToGroupStoresMerkleHash) > 0 { - i -= len(m.FeegrantToGroupStoresMerkleHash) - copy(dAtA[i:], m.FeegrantToGroupStoresMerkleHash) - i = encodeVarintProof(dAtA, i, uint64(len(m.FeegrantToGroupStoresMerkleHash))) + if len(m.SlashingToTssStoresMerkleHash) > 0 { + i -= len(m.SlashingToTssStoresMerkleHash) + copy(dAtA[i:], m.SlashingToTssStoresMerkleHash) + i = encodeVarintProof(dAtA, i, uint64(len(m.SlashingToTssStoresMerkleHash))) i-- dAtA[i] = 0x22 } - if len(m.IbcToIcahostStoresMerkleHash) > 0 { - i -= len(m.IbcToIcahostStoresMerkleHash) - copy(dAtA[i:], m.IbcToIcahostStoresMerkleHash) - i = encodeVarintProof(dAtA, i, uint64(len(m.IbcToIcahostStoresMerkleHash))) + if len(m.ParamsToRollingseedStoresMerkleHash) > 0 { + i -= len(m.ParamsToRollingseedStoresMerkleHash) + copy(dAtA[i:], m.ParamsToRollingseedStoresMerkleHash) + i = encodeVarintProof(dAtA, i, uint64(len(m.ParamsToRollingseedStoresMerkleHash))) i-- dAtA[i] = 0x1a } @@ -2778,19 +2778,19 @@ func (m *MultiStoreProof) Size() (n int) { if l > 0 { n += 1 + l + sovProof(uint64(l)) } - l = len(m.IbcToIcahostStoresMerkleHash) + l = len(m.ParamsToRollingseedStoresMerkleHash) if l > 0 { n += 1 + l + sovProof(uint64(l)) } - l = len(m.FeegrantToGroupStoresMerkleHash) + l = len(m.SlashingToTssStoresMerkleHash) if l > 0 { n += 1 + l + sovProof(uint64(l)) } - l = len(m.AuthToEvidenceStoresMerkleHash) + l = len(m.UpgradeStoreMerkleHash) if l > 0 { n += 1 + l + sovProof(uint64(l)) } - l = len(m.ParamsToUpgradeStoresMerkleHash) + l = len(m.AuthToIcahostStoresMerkleHash) if l > 0 { n += 1 + l + sovProof(uint64(l)) } @@ -4809,7 +4809,7 @@ func (m *MultiStoreProof) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IbcToIcahostStoresMerkleHash", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ParamsToRollingseedStoresMerkleHash", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { @@ -4836,14 +4836,14 @@ func (m *MultiStoreProof) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.IbcToIcahostStoresMerkleHash = append(m.IbcToIcahostStoresMerkleHash[:0], dAtA[iNdEx:postIndex]...) - if m.IbcToIcahostStoresMerkleHash == nil { - m.IbcToIcahostStoresMerkleHash = []byte{} + m.ParamsToRollingseedStoresMerkleHash = append(m.ParamsToRollingseedStoresMerkleHash[:0], dAtA[iNdEx:postIndex]...) + if m.ParamsToRollingseedStoresMerkleHash == nil { + m.ParamsToRollingseedStoresMerkleHash = []byte{} } iNdEx = postIndex case 4: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FeegrantToGroupStoresMerkleHash", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field SlashingToTssStoresMerkleHash", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { @@ -4870,14 +4870,14 @@ func (m *MultiStoreProof) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.FeegrantToGroupStoresMerkleHash = append(m.FeegrantToGroupStoresMerkleHash[:0], dAtA[iNdEx:postIndex]...) - if m.FeegrantToGroupStoresMerkleHash == nil { - m.FeegrantToGroupStoresMerkleHash = []byte{} + m.SlashingToTssStoresMerkleHash = append(m.SlashingToTssStoresMerkleHash[:0], dAtA[iNdEx:postIndex]...) + if m.SlashingToTssStoresMerkleHash == nil { + m.SlashingToTssStoresMerkleHash = []byte{} } iNdEx = postIndex case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AuthToEvidenceStoresMerkleHash", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field UpgradeStoreMerkleHash", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { @@ -4904,14 +4904,14 @@ func (m *MultiStoreProof) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.AuthToEvidenceStoresMerkleHash = append(m.AuthToEvidenceStoresMerkleHash[:0], dAtA[iNdEx:postIndex]...) - if m.AuthToEvidenceStoresMerkleHash == nil { - m.AuthToEvidenceStoresMerkleHash = []byte{} + m.UpgradeStoreMerkleHash = append(m.UpgradeStoreMerkleHash[:0], dAtA[iNdEx:postIndex]...) + if m.UpgradeStoreMerkleHash == nil { + m.UpgradeStoreMerkleHash = []byte{} } iNdEx = postIndex case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ParamsToUpgradeStoresMerkleHash", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field AuthToIcahostStoresMerkleHash", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { @@ -4938,9 +4938,9 @@ func (m *MultiStoreProof) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ParamsToUpgradeStoresMerkleHash = append(m.ParamsToUpgradeStoresMerkleHash[:0], dAtA[iNdEx:postIndex]...) - if m.ParamsToUpgradeStoresMerkleHash == nil { - m.ParamsToUpgradeStoresMerkleHash = []byte{} + m.AuthToIcahostStoresMerkleHash = append(m.AuthToIcahostStoresMerkleHash[:0], dAtA[iNdEx:postIndex]...) + if m.AuthToIcahostStoresMerkleHash == nil { + m.AuthToIcahostStoresMerkleHash = []byte{} } iNdEx = postIndex default: diff --git a/client/grpc/oracle/proof/proof_test.go b/client/grpc/oracle/proof/proof_test.go index 38ac53a65..2704c130c 100644 --- a/client/grpc/oracle/proof/proof_test.go +++ b/client/grpc/oracle/proof/proof_test.go @@ -37,16 +37,16 @@ func TestEncodeRelay(t *testing.T) { MintStoreMerkleHash: hexToBytes( "7FD5F5C7C2920C187618542901CDC5717BE8204F24BE856E80902A1BB04737E4", ), - IbcToIcahostStoresMerkleHash: hexToBytes( + ParamsToRollingseedStoresMerkleHash: hexToBytes( "F981716562A49DE06E3DCAFBFB6388C294BAA4FA9D45777E25740A92F81CF65E", ), - FeegrantToGroupStoresMerkleHash: hexToBytes( + SlashingToTssStoresMerkleHash: hexToBytes( "E8E27CBB44BB654F64EEEF4667868AD48667CEB28E3DB5C4DF7A4B4B87F0C04B", ), - AuthToEvidenceStoresMerkleHash: hexToBytes( + UpgradeStoreMerkleHash: hexToBytes( "FC96CFFD30E5B8979EA66F9D0DA1CBAB16F69669E8B2A1FB2E1BEB457C9726E8", ), - ParamsToUpgradeStoresMerkleHash: hexToBytes( + AuthToIcahostStoresMerkleHash: hexToBytes( "C9C8849ED125CC7681329C4D27B83B1FC8ACF7A865C9D1D1DF575CCA56F48DBE", ), }, diff --git a/cmd/grogu/main.go b/cmd/grogu/main.go new file mode 100644 index 000000000..16b55de27 --- /dev/null +++ b/cmd/grogu/main.go @@ -0,0 +1,7 @@ +package main + +import "github.com/bandprotocol/chain/v2/grogu" + +func main() { + grogu.Main() +} diff --git a/contrib/devtools/Dockerfile b/contrib/devtools/Dockerfile index dc4d8fe58..b78cb9682 100644 --- a/contrib/devtools/Dockerfile +++ b/contrib/devtools/Dockerfile @@ -3,7 +3,7 @@ # docker run --rm -v $(pwd):/workspace --workdir /workspace cosmossdk-proto sh ./scripts/protocgen.sh FROM bufbuild/buf:1.9.0 as BUILDER -FROM golang:1.21-alpine +FROM golang:1.22.3-alpine RUN apk add --no-cache \ nodejs \ diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index 9ab2700c3..ebe7255de 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -562,6 +562,78 @@ def Column(*args, **kwargs): Column("last_update", CustomDateTime, index=True), ) + +""" +This section is mainly for tables of Group module +""" + +groups = sa.Table( + "groups", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("version", sa.Integer, index=True), + Column("admin", sa.String, sa.ForeignKey("accounts.address")), + Column("metadata", sa.String), + Column("total_weight", sa.BigInteger), + Column("created_at", CustomDateTime), +) + +group_members = sa.Table( + "group_members", + metadata, + Column("group_id", sa.Integer, sa.ForeignKey("groups.id"), primary_key=True), + Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), + Column("weight", sa.BigInteger), + Column("metadata", sa.String), + Column("added_at", CustomDateTime), +) + +group_policies = sa.Table( + "group_policies", + metadata, + Column("address", sa.String, primary_key=True), + Column("type", sa.String), + Column("group_id", sa.Integer, sa.ForeignKey("groups.id")), + Column("admin", sa.String, sa.ForeignKey("accounts.address")), + Column("metadata", sa.String), + Column("version", sa.Integer), + Column("decision_policy", sa.JSON), + Column("created_at", CustomDateTime), +) + +group_proposals = sa.Table( + "group_proposals", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("group_policy_address", sa.String, sa.ForeignKey("group_policies.address")), + Column("metadata", sa.String), + Column("proposers", sa.String), + Column("submit_time", CustomDateTime), + Column("group_id", sa.Integer, sa.ForeignKey("groups.id")), + Column("group_version", sa.Integer, index=True), + Column("group_policy_version", sa.Integer, index=True), + Column("status", sa.String), + Column("yes_vote", sa.BigInteger, nullable=True), + Column("no_vote", sa.BigInteger, nullable=True), + Column("no_with_veto_vote", sa.BigInteger, nullable=True), + Column("abstain_vote", sa.BigInteger, nullable=True), + Column("voting_period_end", CustomDateTime), + Column("executor_result", sa.String), + Column("messages", sa.JSON), + Column("title", sa.String), + Column("summary", sa.String), +) + +group_votes = sa.Table( + "group_votes", + metadata, + Column("group_proposal_id", sa.Integer, sa.ForeignKey("group_proposals.id"), primary_key=True), + Column("voter_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), + Column("option", sa.String), + Column("metadata", sa.String), + Column("submit_time", CustomDateTime), +) + relayer_tx_stat_days = sa.Table( "relayer_tx_stat_days", metadata, diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 1df0e9fd5..f33dd158a 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -38,6 +38,11 @@ counterparty_chains, connections, channels, + groups, + group_members, + group_policies, + group_proposals, + group_votes, relayer_tx_stat_days, ) @@ -131,6 +136,9 @@ def get_oracle_script_id(self, id): select([oracle_scripts.c.id]).where(oracle_scripts.c.id == id) ).scalar() + def get_group_id_from_policy_address(self, address): + return self.conn.execute(select([group_policies.c.group_id]).where(group_policies.c.address == address)).scalar() + def get_ibc_received_txs(self, date, port, channel, address): msg = {"date": date, "port": port, "channel": channel, "address": address} condition = True @@ -197,6 +205,47 @@ def handle_new_data_source(self, msg): self.conn.execute(data_sources.insert(), msg) self.init_data_source_request_count(msg["id"]) + def handle_new_group(self, msg): + self.conn.execute(groups.insert(), msg) + + def handle_new_group_member(self, msg): + msg["account_id"] = self.get_account_id(msg["address"]) + del msg["address"] + self.conn.execute(group_members.insert(), msg) + + def handle_new_group_policy(self, msg): + self.get_account_id(msg["address"]) + self.conn.execute(group_policies.insert(), msg) + + def handle_new_group_proposal(self, msg): + msg["group_id"] = self.get_group_id_from_policy_address(msg["group_policy_address"]) + self.conn.execute(group_proposals.insert(), msg) + + def handle_new_group_vote(self, msg): + msg["voter_id"] = self.get_account_id(msg["voter_address"]) + del msg["voter_address"] + self.conn.execute(group_votes.insert(), msg) + + def handle_update_group(self, msg): + self.conn.execute(groups.update().where(groups.c.id == msg["id"]).values(**msg)) + + def handle_remove_group_member(self, msg): + account_id = self.get_account_id(msg["address"]) + self.conn.execute(group_members.delete().where((group_members.c.group_id == msg["group_id"]) & (group_members.c.account_id == account_id))) + + def handle_remove_group_members_by_group_id(self, msg): + self.conn.execute(group_members.delete().where(group_members.c.group_id == msg["group_id"])) + + def handle_update_group_policy(self, msg): + self.conn.execute(group_policies.update().where(group_policies.c.address == msg["address"]).values(**msg)) + + def handle_update_group_proposal(self, msg): + msg["group_id"] = self.get_group_id_from_policy_address(msg["group_policy_address"]) + self.conn.execute(group_proposals.update().where(group_proposals.c.id == msg["id"]).values(**msg)) + + def handle_update_group_proposal_by_id(self, msg): + self.conn.execute(group_proposals.update().where(group_proposals.c.id == msg["id"]).values(**msg)) + def handle_set_data_source(self, msg): msg["transaction_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] diff --git a/go.mod b/go.mod index c64d1f7fe..f0a2709a7 100644 --- a/go.mod +++ b/go.mod @@ -1,13 +1,12 @@ module github.com/bandprotocol/chain/v2 -go 1.21 - -toolchain go1.21.7 +go 1.22.3 require ( cosmossdk.io/api v0.3.1 cosmossdk.io/errors v1.0.1 cosmossdk.io/math v1.3.0 + github.com/bandprotocol/bothan/bothan-api/client/go-client v0.0.1 github.com/bandprotocol/go-owasm v0.3.1 github.com/bytecodealliance/wasmtime-go/v20 v20.0.0 github.com/cometbft/cometbft v0.37.5 @@ -46,9 +45,10 @@ require ( golang.org/x/crypto v0.21.0 golang.org/x/exp v0.0.0-20230905200255-921286631fa9 golang.org/x/time v0.5.0 - google.golang.org/genproto/googleapis/api v0.0.0-20240227224415-6ceb2ff114de + google.golang.org/genproto/googleapis/api v0.0.0-20240506185236-b8a5c65736ae google.golang.org/grpc v1.63.2 - google.golang.org/protobuf v1.34.0 + google.golang.org/protobuf v1.34.1 + gopkg.in/yaml.v2 v2.4.0 gorm.io/driver/mysql v1.5.6 gorm.io/driver/postgres v1.5.7 gorm.io/driver/sqlite v1.5.5 @@ -135,6 +135,7 @@ require ( github.com/gorilla/handlers v1.5.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/gtank/merlin v0.1.1 // indirect github.com/gtank/ristretto255 v0.1.2 // indirect @@ -210,8 +211,7 @@ require ( go.opentelemetry.io/otel v1.22.0 // indirect go.opentelemetry.io/otel/metric v1.22.0 // indirect go.opentelemetry.io/otel/trace v1.22.0 // indirect - go.uber.org/atomic v1.10.0 // indirect - go.uber.org/multierr v1.9.0 // indirect + go.uber.org/multierr v1.11.0 // indirect golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect golang.org/x/net v0.23.0 // indirect golang.org/x/oauth2 v0.17.0 // indirect @@ -222,9 +222,8 @@ require ( google.golang.org/api v0.162.0 // indirect google.golang.org/appengine v1.6.8 // indirect google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240429193739-8cf5692501f6 // indirect gopkg.in/ini.v1 v1.67.0 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect nhooyr.io/websocket v1.8.6 // indirect pgregory.net/rapid v1.1.0 // indirect diff --git a/go.sum b/go.sum index eabfee7fe..501aa1d74 100644 --- a/go.sum +++ b/go.sum @@ -245,6 +245,8 @@ github.com/aws/aws-sdk-go v1.44.122/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX github.com/aws/aws-sdk-go v1.44.203 h1:pcsP805b9acL3wUqa4JR2vg1k2wnItkDYNvfmcy6F+U= github.com/aws/aws-sdk-go v1.44.203/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= +github.com/bandprotocol/bothan/bothan-api/client/go-client v0.0.1 h1:HN9170voxmCgJFiQ+H55IWRvMAU00J4Ru1MUw6WnmVQ= +github.com/bandprotocol/bothan/bothan-api/client/go-client v0.0.1/go.mod h1:F2bQczJ5iqEJ8IEG8u/TbVz4PXgHGc3oWjNQv5S9z0A= github.com/bandprotocol/go-owasm v0.3.1 h1:L38qAEmb0KyTICHBHJaBoo6yy5+BlbOzQeQ+ioUV5Uw= github.com/bandprotocol/go-owasm v0.3.1/go.mod h1:SAzGihlBl8eZDXA1dO2aeAZLm8J2QkNd+KvnA2Dw9Kg= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= @@ -637,6 +639,8 @@ github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgf github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1 h1:/c3QmbOGMGTOumP2iT/rCwB7b0QDGLKzqOmktBjT+Is= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1/go.mod h1:5SN9VR2LTsRFsrEC6FHgRbTWrTHu6tqPeKxEQv15giM= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= @@ -1093,14 +1097,12 @@ go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqe go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= -go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= -go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU= go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= -go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= -go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= @@ -1631,10 +1633,10 @@ google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a/go.mod h1:1vXfmgAz google.golang.org/genproto v0.0.0-20221025140454-527a21cfbd71/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de h1:F6qOa9AZTYJXOUEr4jDysRDLrm4PHePlge4v4TGAlxY= google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:VUhTRKeHn9wwcdrk73nvdC9gF178Tzhmt/qyaFcPLSo= -google.golang.org/genproto/googleapis/api v0.0.0-20240227224415-6ceb2ff114de h1:jFNzHPIeuzhdRwVhbZdiym9q0ory/xY3sA+v2wPg8I0= -google.golang.org/genproto/googleapis/api v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:5iCWqnniDlqZHrd3neWVTOwvh/v6s3232omMecelax8= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de h1:cZGRis4/ot9uVm639a+rHCUaG0JJHEsdyzSQTMX+suY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:H4O17MA/PE9BsGx3w+a+W2VOLLD1Qf7oJneAoU6WktY= +google.golang.org/genproto/googleapis/api v0.0.0-20240506185236-b8a5c65736ae h1:AH34z6WAGVNkllnKs5raNq3yRq93VnjBG6rpfub/jYk= +google.golang.org/genproto/googleapis/api v0.0.0-20240506185236-b8a5c65736ae/go.mod h1:FfiGhwUm6CJviekPrc0oJ+7h29e+DmWU6UtjX0ZvI7Y= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240429193739-8cf5692501f6 h1:DujSIu+2tC9Ht0aPNA7jgj23Iq8Ewi5sgkQ++wdvonE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240429193739-8cf5692501f6/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= @@ -1694,8 +1696,8 @@ google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -google.golang.org/protobuf v1.34.0 h1:Qo/qEd2RZPCf2nKuorzksSknv0d3ERwp1vFG38gSmH4= -google.golang.org/protobuf v1.34.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= +google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/grogu/README.md b/grogu/README.md new file mode 100644 index 000000000..f6d1b3dfe --- /dev/null +++ b/grogu/README.md @@ -0,0 +1,20 @@ +### Grogu + +## Prepare environment + +1. Install Golang +2. Install Docker +3. `make install` in chain directory + +### How to run BandChain in development mode + +1. Go to chain directory +2. run `chmod +x scripts/generate_genesis.sh` to generate genesis.json file +3. run `bandd start` to start BandChain + +### How to run Grogu in development mode + +1. Go to chain directory +2. run `chmod +x ./scripts/start_grogu.sh` to change the access permission of start_grogu.script +3. run `./scripts/start_grogu.sh` to start Grogu + diff --git a/grogu/cmd/config.go b/grogu/cmd/config.go new file mode 100644 index 000000000..34e03f0f3 --- /dev/null +++ b/grogu/cmd/config.go @@ -0,0 +1,20 @@ +package cmd + +import ( + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +func ConfigCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "config [key] [value]", + Aliases: []string{"c"}, + Short: "Set grogu configuration environment", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + viper.Set(args[0], args[1]) + return viper.WriteConfig() + }, + } + return cmd +} diff --git a/grogu/cmd/keys.go b/grogu/cmd/keys.go new file mode 100644 index 000000000..d45c57011 --- /dev/null +++ b/grogu/cmd/keys.go @@ -0,0 +1,220 @@ +package cmd + +import ( + "bufio" + "context" + "fmt" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/input" + "github.com/cosmos/cosmos-sdk/crypto/hd" + bip39 "github.com/cosmos/go-bip39" + "github.com/kyokomi/emoji" + "github.com/spf13/cobra" + "github.com/spf13/viper" + + band "github.com/bandprotocol/chain/v2/app" + grogucontext "github.com/bandprotocol/chain/v2/grogu/context" + "github.com/bandprotocol/chain/v2/x/oracle/types" +) + +const ( + flagAccount = "account" + flagIndex = "index" + flagCoinType = "coin-type" + flagRecover = "recover" + flagAddress = "address" +) + +func KeysCmd(c *grogucontext.Context) *cobra.Command { + cmd := &cobra.Command{ + Use: "keys", + Aliases: []string{"k"}, + Short: "Manage key held by the grogu process", + } + cmd.AddCommand( + keysAddCmd(c), + keysDeleteCmd(c), + keysListCmd(c), + keysShowCmd(c), + ) + return cmd +} + +func keysAddCmd(c *grogucontext.Context) *cobra.Command { + cmd := &cobra.Command{ + Use: "add [name]", + Aliases: []string{"a"}, + Short: "Add a new key to the keychain", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + var mnemonic string + recover, err := cmd.Flags().GetBool(flagRecover) + if err != nil { + return err + } + if recover { + inBuf := bufio.NewReader(cmd.InOrStdin()) + var err error + mnemonic, err = input.GetString("Enter your bip39 mnemonic", inBuf) + if err != nil { + return err + } + } else { + seed, err := bip39.NewEntropy(256) + if err != nil { + return err + } + mnemonic, err = bip39.NewMnemonic(seed) + if err != nil { + return err + } + fmt.Printf("Mnemonic: %s\n", mnemonic) + } + + if err != nil { + return err + } + account, err := cmd.Flags().GetUint32(flagAccount) + if err != nil { + return err + } + index, err := cmd.Flags().GetUint32(flagIndex) + if err != nil { + return err + } + hdPath := hd.CreateHDPath(band.Bip44CoinType, account, index) + info, err := grogucontext.Kb.NewAccount(args[0], mnemonic, "", hdPath.String(), hd.Secp256k1) + if err != nil { + return err + } + + address, err := info.GetAddress() + if err != nil { + return err + } + + fmt.Printf("Address: %s\n", address.String()) + return nil + }, + } + cmd.Flags().Bool(flagRecover, false, "Provide seed phrase to recover existing key instead of creating") + cmd.Flags().Uint32(flagAccount, 0, "Account number for HD derivation") + cmd.Flags().Uint32(flagIndex, 0, "Address index number for HD derivation") + return cmd +} + +func keysDeleteCmd(c *grogucontext.Context) *cobra.Command { + cmd := &cobra.Command{ + Use: "delete [name]", + Aliases: []string{"d"}, + Short: "Delete a key from the keychain", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + name := args[0] + + _, err := grogucontext.Kb.Key(name) + if err != nil { + return err + } + + inBuf := bufio.NewReader(cmd.InOrStdin()) + confirmInput, err := input.GetString("Key will be deleted. Continue?[y/N]", inBuf) + if err != nil { + return err + } + + if confirmInput != "y" { + fmt.Println("Cancel") + return nil + } + + if err := grogucontext.Kb.Delete(name); err != nil { + return err + } + + fmt.Printf("Deleted key: %s\n", name) + return nil + }, + } + return cmd +} + +func keysListCmd(c *grogucontext.Context) *cobra.Command { + cmd := &cobra.Command{ + Use: "list", + Aliases: []string{"l"}, + Short: "List all the keys in the keychain", + Args: cobra.ExactArgs(0), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + keys, err := grogucontext.Kb.List() + if err != nil { + return err + } + isShowAddr := viper.GetBool(flagAddress) + for _, key := range keys { + address, err := key.GetAddress() + if err != nil { + return err + } + + if isShowAddr { + fmt.Printf("%s ", address.String()) + } else { + queryClient := types.NewQueryClient(clientCtx) + r, err := queryClient.IsReporter( + context.Background(), + &types.QueryIsReporterRequest{ValidatorAddress: grogucontext.Cfg.Validator, ReporterAddress: address.String()}, + ) + s := ":question:" + if err == nil { + if r.IsReporter { + s = ":white_check_mark:" + } else { + s = ":x:" + } + } + emoji.Printf("%s%s => %s\n", s, key.Name, address.String()) + } + } + + return nil + }, + } + cmd.Flags().BoolP(flagAddress, "a", false, "Output the address only") + _ = viper.BindPFlag(flagAddress, cmd.Flags().Lookup(flagAddress)) + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +func keysShowCmd(c *grogucontext.Context) *cobra.Command { + cmd := &cobra.Command{ + Use: "show [name]", + Aliases: []string{"s"}, + Short: "Show address from name in the keychain", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + name := args[0] + + key, err := grogucontext.Kb.Key(name) + if err != nil { + return err + } + + address, err := key.GetAddress() + if err != nil { + return err + } + fmt.Println(address.String()) + return nil + }, + } + return cmd +} diff --git a/grogu/cmd/run.go b/grogu/cmd/run.go new file mode 100644 index 000000000..2eb99334d --- /dev/null +++ b/grogu/cmd/run.go @@ -0,0 +1,150 @@ +package cmd + +import ( + "errors" + "sync" + "time" + + "github.com/cometbft/cometbft/libs/log" + httpclient "github.com/cometbft/cometbft/rpc/client/http" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/spf13/cobra" + "github.com/spf13/viper" + + band "github.com/bandprotocol/chain/v2/app" + grogucontext "github.com/bandprotocol/chain/v2/grogu/context" + "github.com/bandprotocol/chain/v2/grogu/feed" + "github.com/bandprotocol/chain/v2/grogu/priceservice" + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +const ( + flagValidator = "validator" + flagLogLevel = "log-level" + flagPriceService = "price-service" + flagBroadcastTimeout = "broadcast-timeout" + flagRPCPollInterval = "rpc-poll-interval" + flagMaxTry = "max-try" + flagDistributionStartPercentage = "distribution-start" + flagDistributionPercentageRange = "distribution-range" +) + +func runImpl(c *grogucontext.Context, l *grogucontext.Logger) error { + l.Info(":rocket: Starting WebSocket subscriber") + err := c.Client.Start() + if err != nil { + return err + } + defer c.Client.Stop() //nolint:errcheck + + for i := int64(0); i < int64(len(c.Keys)); i++ { + c.FreeKeys <- i + } + + l.Info(":rocket: Starting Prices submitter") + go feed.StartSubmitPrices(c, l) + + l.Info(":rocket: Starting Prices querier") + go feed.StartQuerySignalIDs(c, l) + + l.Info(":rocket: Starting Feed checker") + feed.StartCheckFeeds(c, l) + + return nil +} + +func RunCmd(c *grogucontext.Context) *cobra.Command { + cmd := &cobra.Command{ + Use: "run", + Aliases: []string{"r"}, + Short: "Run the grogu process", + Args: cobra.ExactArgs(0), + RunE: func(cmd *cobra.Command, args []string) error { + if grogucontext.Cfg.ChainID == "" { + return errors.New("chain ID must not be empty") + } + keys, err := grogucontext.Kb.List() + if err != nil { + return err + } + if len(keys) == 0 { + return errors.New("no key available") + } + c.Keys = keys + c.Validator, err = sdk.ValAddressFromBech32(grogucontext.Cfg.Validator) + if err != nil { + return err + } + err = sdk.VerifyAddressFormat(c.Validator) + if err != nil { + return err + } + + c.GasPrices = grogucontext.Cfg.GasPrices + + allowLevel, err := log.AllowLevel(grogucontext.Cfg.LogLevel) + if err != nil { + return err + } + l := grogucontext.NewLogger(allowLevel) + c.PriceService, err = priceservice.PriceServiceFromUrl(grogucontext.Cfg.PriceService) + if err != nil { + return err + } + l.Info(":star: Creating HTTP client with node URI: %s", grogucontext.Cfg.NodeURI) + c.Client, err = httpclient.New(grogucontext.Cfg.NodeURI, "/websocket") + if err != nil { + return err + } + clientCtx := client.Context{ + Client: c.Client, + Codec: grogucontext.Cdc, + TxConfig: band.MakeEncodingConfig().TxConfig, + BroadcastMode: flags.BroadcastSync, + InterfaceRegistry: band.MakeEncodingConfig().InterfaceRegistry, + } + c.QueryClient = types.NewQueryClient(clientCtx) + c.BroadcastTimeout, err = time.ParseDuration(grogucontext.Cfg.BroadcastTimeout) + if err != nil { + return err + } + c.MaxTry = grogucontext.Cfg.MaxTry + c.RPCPollInterval, err = time.ParseDuration(grogucontext.Cfg.RPCPollInterval) + if err != nil { + return err + } + c.FreeKeys = make(chan int64, len(keys)) + c.InProgressSignalIDs = &sync.Map{} + c.PendingSignalIDs = make(chan map[string]time.Time, 100) + c.PendingPrices = make(chan []types.SubmitPrice, 30) + return runImpl(c, l) + }, + } + cmd.Flags().String(flags.FlagChainID, "", "chain ID of BandChain network") + cmd.Flags().String(flags.FlagNode, "tcp://localhost:26657", "RPC url to BandChain node") + cmd.Flags().String(flagValidator, "", "validator address") + cmd.Flags().String(flagPriceService, "", "price-service name and url for getting prices") + cmd.Flags().String(flags.FlagGasPrices, "", "gas prices for a transaction") + cmd.Flags().String(flagLogLevel, "info", "set the logger level") + cmd.Flags().String(flagBroadcastTimeout, "5m", "The time that Grogu will wait for tx commit") + cmd.Flags().String(flagRPCPollInterval, "1s", "The duration of rpc poll interval") + cmd.Flags().Uint64(flagMaxTry, 5, "The maximum number of tries to submit a transaction") + cmd.Flags(). + Uint64(flagDistributionStartPercentage, 50, "The starting percentage of the distribution range of price sending") + cmd.Flags(). + Uint64(flagDistributionPercentageRange, 30, "The ending percentage of the distribution range of price sending") + _ = viper.BindPFlag(flags.FlagChainID, cmd.Flags().Lookup(flags.FlagChainID)) + _ = viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode)) + _ = viper.BindPFlag(flagValidator, cmd.Flags().Lookup(flagValidator)) + _ = viper.BindPFlag(flags.FlagGasPrices, cmd.Flags().Lookup(flags.FlagGasPrices)) + _ = viper.BindPFlag(flagLogLevel, cmd.Flags().Lookup(flagLogLevel)) + _ = viper.BindPFlag(flagPriceService, cmd.Flags().Lookup(flagPriceService)) + _ = viper.BindPFlag(flagBroadcastTimeout, cmd.Flags().Lookup(flagBroadcastTimeout)) + _ = viper.BindPFlag(flagRPCPollInterval, cmd.Flags().Lookup(flagRPCPollInterval)) + _ = viper.BindPFlag(flagMaxTry, cmd.Flags().Lookup(flagMaxTry)) + _ = viper.BindPFlag(flagDistributionStartPercentage, cmd.Flags().Lookup(flagDistributionStartPercentage)) + _ = viper.BindPFlag(flagDistributionPercentageRange, cmd.Flags().Lookup(flagDistributionPercentageRange)) + return cmd +} diff --git a/grogu/context/context.go b/grogu/context/context.go new file mode 100644 index 000000000..7ac24a2e4 --- /dev/null +++ b/grogu/context/context.go @@ -0,0 +1,57 @@ +package context + +import ( + "sync" + "time" + + rpcclient "github.com/cometbft/cometbft/rpc/client" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" + + band "github.com/bandprotocol/chain/v2/app" + "github.com/bandprotocol/chain/v2/grogu/priceservice" + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// Config data structure for grogu daemon. +type Config struct { + ChainID string `mapstructure:"chain-id"` // ChainID of the target chain + NodeURI string `mapstructure:"node"` // Remote RPC URI of BandChain node to connect to + Validator string `mapstructure:"validator"` // The validator address that I'm responsible for + GasPrices string `mapstructure:"gas-prices"` // Gas prices of the transaction + LogLevel string `mapstructure:"log-level"` // Log level of the logger + PriceService string `mapstructure:"price-service"` // PriceService name and URL (example: "PriceService name:URL") + BroadcastTimeout string `mapstructure:"broadcast-timeout"` // The time that Grogu will wait for tx commit + RPCPollInterval string `mapstructure:"rpc-poll-interval"` // The duration of rpc poll interval + MaxTry uint64 `mapstructure:"max-try"` // The maximum number of tries to submit a report transaction + DistributionStartPercentage uint64 `mapstructure:"distribution-start"` // The starting percentage of the distribution range of price sending + DistributionPercentageRange uint64 `mapstructure:"distribution-range"` // The range of percentage of the distribution range of price sending +} + +// Global instances. +var ( + Cfg Config + Kb keyring.Keyring + DefaultGroguHome string + // Proto codec for encoding/decoding proto message + Cdc = band.MakeEncodingConfig().Marshaler +) + +type Context struct { + Client rpcclient.Client + QueryClient types.QueryClient + Validator sdk.ValAddress + GasPrices string + Keys []*keyring.Record + PriceService priceservice.PriceService + BroadcastTimeout time.Duration + MaxTry uint64 + RPCPollInterval time.Duration + + PendingSignalIDs chan map[string]time.Time + PendingPrices chan []types.SubmitPrice + InProgressSignalIDs *sync.Map + FreeKeys chan int64 + + Home string +} diff --git a/grogu/context/logger.go b/grogu/context/logger.go new file mode 100644 index 000000000..d8825e83a --- /dev/null +++ b/grogu/context/logger.go @@ -0,0 +1,32 @@ +package context + +import ( + "os" + + "github.com/cometbft/cometbft/libs/log" + "github.com/kyokomi/emoji" +) + +type Logger struct { + logger log.Logger +} + +func NewLogger(level log.Option) *Logger { + return &Logger{logger: log.NewFilter(log.NewTMLogger(os.Stdout), level)} +} + +func (l *Logger) Debug(format string, args ...interface{}) { + l.logger.Debug(emoji.Sprintf(format, args...)) +} + +func (l *Logger) Info(format string, args ...interface{}) { + l.logger.Info(emoji.Sprintf(format, args...)) +} + +func (l *Logger) Error(format string, c *Context, args ...interface{}) { + l.logger.Error(emoji.Sprintf(format, args...)) +} + +func (l *Logger) With(keyvals ...interface{}) *Logger { + return &Logger{logger: l.logger.With(keyvals...)} +} diff --git a/grogu/event/event.go b/grogu/event/event.go new file mode 100644 index 000000000..5ab96b2ff --- /dev/null +++ b/grogu/event/event.go @@ -0,0 +1,35 @@ +package event + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// GetEventValues returns the list of all values in the given log with the given type and key. +func GetEventValues(log sdk.ABCIMessageLog, evType string, evKey string) (res []string) { + for _, ev := range log.Events { + if ev.Type != evType { + continue + } + + for _, attr := range ev.Attributes { + if attr.Key == evKey { + res = append(res, attr.Value) + } + } + } + return res +} + +// GetEventValue checks and returns the exact value in the given log with the given type and key. +func GetEventValue(log sdk.ABCIMessageLog, evType string, evKey string) (string, error) { + values := GetEventValues(log, evType, evKey) + if len(values) == 0 { + return "", fmt.Errorf("cannot find event with type: %s, key: %s", evType, evKey) + } + if len(values) > 1 { + return "", fmt.Errorf("found more than one event with type: %s, key: %s", evType, evKey) + } + return values[0], nil +} diff --git a/grogu/feed/check.go b/grogu/feed/check.go new file mode 100644 index 000000000..1dce1bcb2 --- /dev/null +++ b/grogu/feed/check.go @@ -0,0 +1,203 @@ +package feed + +import ( + "context" + "crypto/sha256" + "fmt" + "math" + "strconv" + "strings" + "time" + + bothanproto "github.com/bandprotocol/bothan/bothan-api/client/go-client/query" + sdk "github.com/cosmos/cosmos-sdk/types" + "golang.org/x/exp/maps" + + grogucontext "github.com/bandprotocol/chain/v2/grogu/context" + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func checkFeeds(c *grogucontext.Context, l *grogucontext.Logger) { + // Fetch parameters, supported feeds, validator prices, and prices + params, feeds, validatorPrices, prices, err := fetchData(c) + if err != nil { + return + } + + signalIDTimestampMap := convertToSignalIDTimestampMap(validatorPrices) + signalIDChainPriceMap := convertToSignalIDChainPriceMap(prices) + + requestedSignalIDs := make(map[string]time.Time) + now := time.Now() + + for _, feed := range feeds { + // Skip feeds in progress + if _, inProgress := c.InProgressSignalIDs.Load(feed.SignalID); inProgress { + continue + } + + // Get latest timestamp of the feed + timestamp, ok := signalIDTimestampMap[feed.SignalID] + // If there is no timestamp yet, then puts it in requested signal id list + if !ok { + updateRequestedSignalID(c, requestedSignalIDs, feed, timestamp, params) + continue + } + + // Skip if it's in cooldown + if time.Unix(timestamp+2, 0). + Add(time.Duration(params.CooldownTime) * time.Second). + After(now) { + continue + } + + // Calculate assigned time for the feed + assignedTime := calculateAssignedTime(c.Validator, feed.Interval, timestamp) + + if assignedTime.Before(now) || isDeviate(c, feed, signalIDChainPriceMap) { + updateRequestedSignalID(c, requestedSignalIDs, feed, timestamp, params) + } + } + + if len(requestedSignalIDs) != 0 { + l.Info("found signal ids to send: %v", maps.Keys(requestedSignalIDs)) + c.PendingSignalIDs <- requestedSignalIDs + } +} + +func fetchData( + c *grogucontext.Context, +) (params types.Params, feeds []types.Feed, validatorPrices []types.ValidatorPrice, prices []*types.Price, err error) { + // Fetch validator data + validValidator, err := c.QueryClient.ValidValidator(context.Background(), &types.QueryValidValidatorRequest{ + Validator: c.Validator.String(), + }) + if err != nil { + return types.Params{}, nil, nil, nil, err + } + if !validValidator.Valid { + return types.Params{}, nil, nil, nil, fmt.Errorf("validator is not valid or not required to send price") + } + + // Fetch params + paramsResponse, err := c.QueryClient.Params(context.Background(), &types.QueryParamsRequest{}) + if err != nil { + return types.Params{}, nil, nil, nil, err + } + params = paramsResponse.Params + + // Fetch supported feeds + feedsResponse, err := c.QueryClient.SupportedFeeds(context.Background(), &types.QuerySupportedFeedsRequest{}) + if err != nil { + return types.Params{}, nil, nil, nil, err + } + feeds = feedsResponse.Feeds + + // Fetch validator prices + validatorPricesResponse, err := c.QueryClient.ValidatorPrices( + context.Background(), + &types.QueryValidatorPricesRequest{ + Validator: c.Validator.String(), + }, + ) + if err != nil { + return types.Params{}, nil, nil, nil, err + } + validatorPrices = validatorPricesResponse.ValidatorPrices + + // Fetch prices + pricesResponse, err := c.QueryClient.Prices( + context.Background(), + &types.QueryPricesRequest{}, + ) + if err != nil { + return types.Params{}, nil, nil, nil, err + } + prices = pricesResponse.Prices + + return params, feeds, validatorPrices, prices, nil +} + +// calculateAssignedTime calculates the assigned time for the feed +func calculateAssignedTime(valAddr sdk.ValAddress, interval int64, timestamp int64) time.Time { + hashed := sha256.Sum256(append(valAddr.Bytes(), sdk.Uint64ToBigEndian(uint64(timestamp))...)) + offset := sdk.BigEndianToUint64( + hashed[:], + )%grogucontext.Cfg.DistributionPercentageRange + grogucontext.Cfg.DistributionStartPercentage + timeOffset := interval * int64(offset) / 100 + // add 2 seconds to prevent too fast case + return time.Unix(timestamp+2, 0).Add(time.Duration(timeOffset) * time.Second) +} + +// isDeviate checks if the current price is deviated from the on-chain price +func isDeviate( + c *grogucontext.Context, + feed types.Feed, + signalIDChainPriceMap map[string]uint64, +) bool { + currentPrices, err := c.PriceService.Query([]string{feed.SignalID}) + if err != nil || len(currentPrices) == 0 || + currentPrices[0].PriceStatus != bothanproto.PriceStatus_PRICE_STATUS_AVAILABLE { + return false + } + + price, err := strconv.ParseFloat(strings.TrimSpace(currentPrices[0].Price), 64) + if err != nil { + return false + } + + return feed.DeviationInThousandth <= deviationInThousandth( + signalIDChainPriceMap[feed.SignalID], + uint64(price*math.Pow10(9)), + ) +} + +// updateRequestedSignalID updates the requestedSignalIDs map and stores the timestamp in InProgressSignalIDs for a feed +func updateRequestedSignalID( + c *grogucontext.Context, + requestedSignalIDs map[string]time.Time, + feed types.Feed, + timestamp int64, + params types.Params, +) { + requestedSignalIDs[feed.SignalID] = time.Unix(timestamp, 0). + Add(time.Duration(feed.Interval) * time.Second). + Add(-time.Duration(params.TransitionTime) * time.Second / 2) + c.InProgressSignalIDs.Store(feed.SignalID, time.Now()) +} + +// convertToSignalIDTimestampMap converts an array of ValidatorPrice to a map of signal id to timestamp. +func convertToSignalIDTimestampMap(data []types.ValidatorPrice) map[string]int64 { + signalIDTimestampMap := make(map[string]int64) + + for _, entry := range data { + signalIDTimestampMap[entry.SignalID] = entry.Timestamp + } + + return signalIDTimestampMap +} + +// convertToSignalIDChainPriceMap converts an array of Prices to a map of signal id to its on-chain prices. +func convertToSignalIDChainPriceMap(data []*types.Price) map[string]uint64 { + signalIDChainPriceMap := make(map[string]uint64) + + for _, entry := range data { + signalIDChainPriceMap[entry.SignalID] = entry.Price + } + + return signalIDChainPriceMap +} + +// deviationInThousandth calculates the deviation in thousandth between two values. +func deviationInThousandth(originalValue, newValue uint64) int64 { + diff := math.Abs(float64(newValue) - float64(originalValue)) + deviation := (diff / float64(originalValue)) * 1000 + return int64(deviation) +} + +func StartCheckFeeds(c *grogucontext.Context, l *grogucontext.Logger) { + for { + checkFeeds(c, l) + time.Sleep(time.Second) + } +} diff --git a/grogu/feed/query.go b/grogu/feed/query.go new file mode 100644 index 000000000..cf292b89d --- /dev/null +++ b/grogu/feed/query.go @@ -0,0 +1,106 @@ +package feed + +import ( + "math" + "strconv" + "strings" + "time" + + bothanproto "github.com/bandprotocol/bothan/bothan-api/client/go-client/query" + "golang.org/x/exp/maps" + + grogucontext "github.com/bandprotocol/chain/v2/grogu/context" + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func StartQuerySignalIDs(c *grogucontext.Context, l *grogucontext.Logger) { + for { + QuerySignalIDs(c, l) + } +} + +func QuerySignalIDs(c *grogucontext.Context, l *grogucontext.Logger) { + signalIDsWithTimeLimit := <-c.PendingSignalIDs + +GetAllSignalIDs: + for { + select { + case nextSignalIDs := <-c.PendingSignalIDs: + maps.Copy(signalIDsWithTimeLimit, nextSignalIDs) + default: + break GetAllSignalIDs + } + } + + signalIDs := maps.Keys(signalIDsWithTimeLimit) + + l.Info("Try to get prices for signal ids: %+v", signalIDs) + prices, err := c.PriceService.Query(signalIDs) + if err != nil { + l.Error(":exploding_head: Failed to get prices from price-service with error: %s", c, err.Error()) + } + + maxSafePrice := math.MaxUint64 / uint64(math.Pow10(9)) + now := time.Now() + submitPrices := []types.SubmitPrice{} + for _, priceData := range prices { + switch priceData.PriceStatus { + case bothanproto.PriceStatus_PRICE_STATUS_UNSUPPORTED: + submitPrices = append(submitPrices, types.SubmitPrice{ + PriceStatus: types.PriceStatusUnsupported, + SignalID: priceData.SignalId, + Price: 0, + }) + continue + + case bothanproto.PriceStatus_PRICE_STATUS_AVAILABLE: + price, err := strconv.ParseFloat(strings.TrimSpace(priceData.Price), 64) + if err != nil || price > float64(maxSafePrice) || price < 0 { + l.Error(":exploding_head: Failed to parse price from singal id:", c, priceData.SignalId, err) + priceData.PriceStatus = bothanproto.PriceStatus_PRICE_STATUS_UNAVAILABLE + priceData.Price = "" + } else { + submitPrices = append(submitPrices, types.SubmitPrice{ + PriceStatus: types.PriceStatusAvailable, + SignalID: priceData.SignalId, + Price: uint64(price * math.Pow10(9)), + }) + continue + } + } + + if signalIDsWithTimeLimit[priceData.SignalId].Before(now) { + submitPrices = append(submitPrices, types.SubmitPrice{ + PriceStatus: types.PriceStatusUnavailable, + SignalID: priceData.SignalId, + Price: 0, + }) + } + } + + // delete signal id from in progress map if its price is not found + signalIDPriceMap := convertToSignalIDPriceMap(submitPrices) + for _, signalID := range signalIDs { + if _, found := signalIDPriceMap[signalID]; !found { + c.InProgressSignalIDs.Delete(signalID) + } + } + + if len(submitPrices) == 0 { + l.Debug(":exploding_head: query signal got no prices with signal ids: %+v", signalIDs) + return + } + l.Info("got prices for signal ids: %+v", maps.Keys(signalIDPriceMap)) + c.PendingPrices <- submitPrices +} + +// convertToSignalIDPriceMap converts an array of SubmitPrice to a map of signal id to price. +func convertToSignalIDPriceMap(data []types.SubmitPrice) map[string]uint64 { + signalIDPriceMap := make(map[string]uint64) + + for _, entry := range data { + signalIDPriceMap[entry.SignalID] = entry.Price + } + + return signalIDPriceMap +} diff --git a/grogu/feed/query_test.go b/grogu/feed/query_test.go new file mode 100644 index 000000000..349ffbf3b --- /dev/null +++ b/grogu/feed/query_test.go @@ -0,0 +1,158 @@ +package feed_test + +import ( + "math" + "strconv" + "strings" + "sync" + "testing" + "time" + + bothanproto "github.com/bandprotocol/bothan/bothan-api/client/go-client/query" + "github.com/cometbft/cometbft/libs/log" + "github.com/stretchr/testify/require" + + grogucontext "github.com/bandprotocol/chain/v2/grogu/context" + "github.com/bandprotocol/chain/v2/grogu/feed" + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +var mockData = map[string]*bothanproto.PriceData{ + "BTC": {SignalId: "BTC", PriceStatus: bothanproto.PriceStatus_PRICE_STATUS_AVAILABLE, Price: "50000"}, + "ETH": {SignalId: "ETH", PriceStatus: bothanproto.PriceStatus_PRICE_STATUS_UNAVAILABLE, Price: ""}, + "BAND": {SignalId: "BAND", PriceStatus: bothanproto.PriceStatus_PRICE_STATUS_AVAILABLE, Price: "18446744074"}, +} + +// MockPriceService is a mock implementation of the price service for testing. +type MockPriceService struct{} + +// Query is a mock implementation of the Query method in the PriceService interface. +func (mps *MockPriceService) Query(signalIDs []string) ([]*bothanproto.PriceData, error) { + var priceData []*bothanproto.PriceData + for _, id := range signalIDs { + data, ok := mockData[id] + if ok { + priceData = append(priceData, data) + } else { + priceData = append(priceData, &bothanproto.PriceData{ + SignalId: id, + PriceStatus: bothanproto.PriceStatus_PRICE_STATUS_UNSUPPORTED, + }) + } + } + + return priceData, nil +} + +func TestQuerySignalIDs(t *testing.T) { + // Create a mock context and logger for testing. + mockContext := grogucontext.Context{} + mockLogger := grogucontext.NewLogger(log.AllowAll()) + + // Mock the pending signalIDs channel. + mockContext.PendingSignalIDs = make(chan map[string]time.Time, 10) + mockContext.PendingPrices = make(chan []types.SubmitPrice, 10) + + // Test cases: price available and price not supported + signalIDsWithTimeLimit := make(map[string]time.Time) + mockContext.InProgressSignalIDs = &sync.Map{} + + signalIDsWithTimeLimit["BTC"] = time.Now(). + Add(time.Minute) + mockContext.InProgressSignalIDs.Load("BTC") + + signalIDsWithTimeLimit["DOGE"] = time.Now(). + Add(time.Minute) + mockContext.InProgressSignalIDs.Load("DOGE") + + mockContext.PendingSignalIDs <- signalIDsWithTimeLimit + + // Set up a mock price service. + mockContext.PriceService = &MockPriceService{} + + // Call the function being tested. + feed.QuerySignalIDs(&mockContext, mockLogger) + + // Check if the correct prices were sent to the pending prices channel. + select { + case submitPrices := <-mockContext.PendingPrices: + // Check the number of prices received. + require.Equal(t, 2, len(submitPrices)) + + // Check if BTC price is correct. + btcPrice := getPrice(submitPrices, "BTC") + require.Equal(t, types.PriceStatusAvailable, btcPrice.PriceStatus) + mockBTCPrice, _ := strconv.ParseFloat(strings.TrimSpace(mockData["BTC"].Price), 64) + require.Equal(t, uint64(mockBTCPrice*math.Pow10(9)), btcPrice.Price) + + dogePrice := getPrice(submitPrices, "DOGE") + require.Equal(t, types.PriceStatusUnsupported, dogePrice.PriceStatus) + require.Equal(t, uint64(0), dogePrice.Price) + + default: + t.Error("No prices received") + } + + // Test cases: price out of range, price unavailable with time limit not reached + mockContext.InProgressSignalIDs.Delete("BTC") + mockContext.InProgressSignalIDs.Delete("DOGE") + + signalIDsWithTimeLimit = make(map[string]time.Time) + signalIDsWithTimeLimit["ETH"] = time.Now(). + Add(time.Minute) + mockContext.InProgressSignalIDs.Load("ETH") + signalIDsWithTimeLimit["BAND"] = time.Now(). + Add(time.Minute) + mockContext.InProgressSignalIDs.Load("BAND") + mockContext.PendingSignalIDs <- signalIDsWithTimeLimit + + // Call the function being tested. + feed.QuerySignalIDs(&mockContext, mockLogger) + + // Check if the correct prices were sent to the pending prices channel. + select { + case submitPrices := <-mockContext.PendingPrices: + t.Error("Should receive no prices but receive:", submitPrices) + default: + } + + // Test cases: price out of range, price unavailable with time limit reached + signalIDsWithTimeLimit = make(map[string]time.Time) + signalIDsWithTimeLimit["ETH"] = time.Now(). + Add(-time.Minute) + mockContext.InProgressSignalIDs.Load("ETH") + signalIDsWithTimeLimit["BAND"] = time.Now(). + Add(-time.Minute) + mockContext.InProgressSignalIDs.Load("BAND") + mockContext.PendingSignalIDs <- signalIDsWithTimeLimit + + // Call the function being tested. + feed.QuerySignalIDs(&mockContext, mockLogger) + + // Check if the correct prices were sent to the pending prices channel. + select { + case submitPrices := <-mockContext.PendingPrices: + // Check the number of prices received. + require.Equal(t, 2, len(submitPrices)) + + ethPrice := getPrice(submitPrices, "ETH") + require.Equal(t, types.PriceStatusUnavailable, ethPrice.PriceStatus) + require.Equal(t, uint64(0), ethPrice.Price) + + bandPrice := getPrice(submitPrices, "BAND") + require.Equal(t, types.PriceStatusUnavailable, bandPrice.PriceStatus) + require.Equal(t, uint64(0), bandPrice.Price) + default: + t.Error("No prices received") + } +} + +// getPrice retrieves the price data for a specific signalID from the submit prices array. +func getPrice(submitPrices []types.SubmitPrice, signalID string) types.SubmitPrice { + for _, price := range submitPrices { + if price.SignalID == signalID { + return price + } + } + return types.SubmitPrice{} +} diff --git a/grogu/feed/submit.go b/grogu/feed/submit.go new file mode 100644 index 000000000..5ec1170d3 --- /dev/null +++ b/grogu/feed/submit.go @@ -0,0 +1,217 @@ +package feed + +import ( + "fmt" + "time" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/authz" + + band "github.com/bandprotocol/chain/v2/app" + grogucontext "github.com/bandprotocol/chain/v2/grogu/context" + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func StartSubmitPrices(c *grogucontext.Context, l *grogucontext.Logger) { + for { + SubmitPrices(c, l) + } +} + +func SubmitPrices(c *grogucontext.Context, l *grogucontext.Logger) { + // Return key and update pending metric when done with SubmitReport whether successfully or not. + keyIndex := <-c.FreeKeys + defer func() { + c.FreeKeys <- keyIndex + }() + + prices := <-c.PendingPrices + +GetAllPrices: + for { + select { + case nextPrices := <-c.PendingPrices: + prices = append(prices, nextPrices...) + default: + break GetAllPrices + } + } + + defer func() { + for _, price := range prices { + c.InProgressSignalIDs.Delete(price.SignalID) + } + }() + + msg := types.MsgSubmitPrices{ + Validator: c.Validator.String(), + Timestamp: time.Now().Unix(), + Prices: prices, + } + + msgs := []sdk.Msg{&msg} + key := c.Keys[keyIndex] + + clientCtx := client.Context{ + Client: c.Client, + TxConfig: band.MakeEncodingConfig().TxConfig, + InterfaceRegistry: band.MakeEncodingConfig().InterfaceRegistry, + } + + gasAdjustment := float64(2.0) + + for sendAttempt := uint64(1); sendAttempt <= c.MaxTry; sendAttempt++ { + var txHash string + l.Info(":e-mail: Sending report transaction attempt: (%d/%d)", sendAttempt, c.MaxTry) + for broadcastTry := uint64(1); broadcastTry <= c.MaxTry; broadcastTry++ { + l.Info(":writing_hand: Try to sign and broadcast report transaction(%d/%d)", broadcastTry, c.MaxTry) + res, err := signAndBroadcast(c, key, msgs, gasAdjustment) + if err != nil { + // Use info level because this error can happen and retry process can solve this error. + l.Info(":warning: %s", err.Error()) + time.Sleep(c.RPCPollInterval) + continue + } + if res.Codespace == sdkerrors.RootCodespace && res.Code == sdkerrors.ErrOutOfGas.ABCICode() { + gasAdjustment += 0.1 + l.Info( + ":fuel_pump: Tx(%s) is out of gas and will be rebroadcasted with gas adjustment(%f)", + txHash, + gasAdjustment, + ) + continue + } + // Transaction passed CheckTx process and wait to include in block. + txHash = res.TxHash + break + } + if txHash == "" { + l.Error(":exploding_head: Cannot try to broadcast more than %d try", c, c.MaxTry) + return + } + txFound := false + FindTx: + for start := time.Now(); time.Since(start) < c.BroadcastTimeout; { + time.Sleep(c.RPCPollInterval) + txRes, err := authtx.QueryTx(clientCtx, txHash) + if err != nil { + l.Debug(":warning: Failed to query tx with error: %s", err.Error()) + continue + } + + if txRes.Code == 0 { + l.Info(":smiling_face_with_sunglasses: Successfully broadcast tx with hash: %s", txHash) + return + } + if txRes.Codespace == sdkerrors.RootCodespace && + txRes.Code == sdkerrors.ErrOutOfGas.ABCICode() { + // Increase gas adjustment and try to broadcast again + gasAdjustment += 0.1 + l.Info(":fuel_pump: Tx(%s) is out of gas and will be rebroadcasted with gas adjustment(%f)", txHash, gasAdjustment) + txFound = true + break FindTx + } else { + l.Error(":exploding_head: Tx returned nonzero code %d with log %s, tx hash: %s", c, txRes.Code, txRes.RawLog, txRes.TxHash) + return + } + } + if !txFound { + l.Error( + ":question_mark: Cannot get transaction response from hash: %s transaction might be included in the next few blocks or check your node's health.", + c, + txHash, + ) + return + } + } + l.Error(":anxious_face_with_sweat: Cannot send price with adjusted gas: %d", c, gasAdjustment) +} + +func signAndBroadcast( + c *grogucontext.Context, key *keyring.Record, msgs []sdk.Msg, gasAdjustment float64, +) (*sdk.TxResponse, error) { + clientCtx := client.Context{ + Client: c.Client, + Codec: grogucontext.Cdc, + TxConfig: band.MakeEncodingConfig().TxConfig, + BroadcastMode: flags.BroadcastSync, + InterfaceRegistry: band.MakeEncodingConfig().InterfaceRegistry, + } + acc, err := queryAccount(clientCtx, key) + if err != nil { + return nil, fmt.Errorf("unable to get account: %w", err) + } + + txf := tx.Factory{}. + WithAccountNumber(acc.GetAccountNumber()). + WithSequence(acc.GetSequence()). + WithTxConfig(band.MakeEncodingConfig().TxConfig). + WithSimulateAndExecute(true). + WithGasAdjustment(gasAdjustment). + WithChainID(grogucontext.Cfg.ChainID). + WithGasPrices(c.GasPrices). + WithKeybase(grogucontext.Kb). + WithFromName(key.Name). + WithAccountRetriever(clientCtx.AccountRetriever) + + address, err := key.GetAddress() + if err != nil { + return nil, err + } + + execMsg := authz.NewMsgExec(address, msgs) + + _, adjusted, err := tx.CalculateGas(clientCtx, txf, &execMsg) + if err != nil { + return nil, err + } + + // Set the gas amount on the transaction factory + txf = txf.WithGas(adjusted) + + txb, err := txf.BuildUnsignedTx(&execMsg) + if err != nil { + return nil, err + } + + err = tx.Sign(txf, key.Name, txb, true) + if err != nil { + return nil, err + } + + txBytes, err := clientCtx.TxConfig.TxEncoder()(txb.GetTx()) + if err != nil { + return nil, err + } + + // broadcast to a Tendermint node + res, err := clientCtx.BroadcastTx(txBytes) + if err != nil { + return nil, err + } + + return res, nil +} + +func queryAccount(clientCtx client.Context, key *keyring.Record) (client.Account, error) { + accountRetriever := authtypes.AccountRetriever{} + + address, err := key.GetAddress() + if err != nil { + return nil, err + } + + acc, err := accountRetriever.GetAccount(clientCtx, address) + if err != nil { + return nil, err + } + + return acc, nil +} diff --git a/grogu/main.go b/grogu/main.go new file mode 100644 index 000000000..2b46f97f7 --- /dev/null +++ b/grogu/main.go @@ -0,0 +1,75 @@ +package grogu + +import ( + "fmt" + "os" + "path" + "path/filepath" + + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" + "github.com/spf13/viper" + + band "github.com/bandprotocol/chain/v2/app" + "github.com/bandprotocol/chain/v2/grogu/cmd" + grogucontext "github.com/bandprotocol/chain/v2/grogu/context" +) + +func initConfig(c *grogucontext.Context, cmd *cobra.Command) error { + viper.SetConfigFile(path.Join(c.Home, "config.yaml")) + _ = viper.ReadInConfig() // If we fail to read config file, we'll just rely on cmd flags. + if err := viper.Unmarshal(&grogucontext.Cfg); err != nil { + return err + } + return nil +} + +func init() { + userHomeDir, err := os.UserHomeDir() + if err != nil { + panic(err) + } + + grogucontext.DefaultGroguHome = filepath.Join(userHomeDir, ".grogu") +} + +func Main() { + appConfig := sdk.GetConfig() + band.SetBech32AddressPrefixesAndBip44CoinTypeAndSeal(appConfig) + + ctx := &grogucontext.Context{} + rootCmd := &cobra.Command{ + Use: "grogu", + Short: "BandChain daemon to submit prices for feeds module", + } + + rootCmd.AddCommand( + cmd.ConfigCmd(), + cmd.KeysCmd(ctx), + cmd.RunCmd(ctx), + version.NewVersionCommand(), + ) + rootCmd.PersistentPreRunE = func(_ *cobra.Command, _ []string) error { + home, err := rootCmd.PersistentFlags().GetString(flags.FlagHome) + if err != nil { + return err + } + ctx.Home = home + if err := os.MkdirAll(home, os.ModePerm); err != nil { + return err + } + grogucontext.Kb, err = keyring.New("band", keyring.BackendTest, home, nil, grogucontext.Cdc) + if err != nil { + return err + } + return initConfig(ctx, rootCmd) + } + rootCmd.PersistentFlags().String(flags.FlagHome, grogucontext.DefaultGroguHome, "home directory") + if err := rootCmd.Execute(); err != nil { + fmt.Println(err) + os.Exit(1) + } +} diff --git a/grogu/priceservice/grpc.go b/grogu/priceservice/grpc.go new file mode 100644 index 000000000..b96368c04 --- /dev/null +++ b/grogu/priceservice/grpc.go @@ -0,0 +1,37 @@ +package priceservice + +import ( + "context" + "time" + + bothanproto "github.com/bandprotocol/bothan/bothan-api/client/go-client/query" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +type GRPCService struct { + connection *grpc.ClientConn + timeout time.Duration +} + +func NewGRPCService(url string, timeout time.Duration) (*GRPCService, error) { + conn, err := grpc.Dial(url, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return nil, err + } + return &GRPCService{connection: conn, timeout: timeout}, nil +} + +func (gs *GRPCService) Query(signalIds []string) ([]*bothanproto.PriceData, error) { + // Create a client instance using the connection. + client := bothanproto.NewQueryClient(gs.connection) + ctx, cancel := context.WithTimeout(context.Background(), gs.timeout) + defer cancel() + + response, err := client.Prices(ctx, &bothanproto.QueryPricesRequest{SignalIds: signalIds}) + if err != nil { + return nil, err + } + + return response.Prices, nil +} diff --git a/grogu/priceservice/priceservice.go b/grogu/priceservice/priceservice.go new file mode 100644 index 000000000..1f3117181 --- /dev/null +++ b/grogu/priceservice/priceservice.go @@ -0,0 +1,82 @@ +package priceservice + +import ( + "errors" + "fmt" + "net/url" + "strings" + "time" + + bothanproto "github.com/bandprotocol/bothan/bothan-api/client/go-client/query" +) + +const ( + flagQueryTimeout = "timeout" +) + +var ( + ErrExecutionimeout = errors.New("execution timeout") + ErrRestNotOk = errors.New("rest return non 2XX response") +) + +type PriceService interface { + Query(signalIds []string) ([]*bothanproto.PriceData, error) +} + +// NewPriceService returns priceService by name and priceService URL +func PriceServiceFromUrl(priceService string) (exec PriceService, err error) { + name, base, timeout, err := parsePriceServiceURL(priceService) + if err != nil { + return nil, err + } + switch name { + case "rest": + exec = NewRestService(base.String(), timeout) + case "grpc": + exec, err = NewGRPCService(base.Host, timeout) + if err != nil { + return nil, err + } + default: + return nil, fmt.Errorf("invalid priceService name: %s, base: %s", name, base) + } + + // TODO: Remove hardcode in test execution + _, err = exec.Query([]string{"crypto_price.ethusd"}) + if err != nil { + return nil, fmt.Errorf("failed to run test program: %s", err.Error()) + } + + return exec, nil +} + +// parsePriceService splits the priceService string in the form of "name:base?timeout=" into parts. +func parsePriceServiceURL(priceServiceStr string) (name string, base *url.URL, timeout time.Duration, err error) { + priceService := strings.SplitN(priceServiceStr, ":", 2) + if len(priceService) != 2 { + return "", nil, 0, fmt.Errorf("invalid priceService, cannot parse priceService: %s", priceServiceStr) + } + u, err := url.Parse(priceService[1]) + if err != nil { + return "", nil, 0, fmt.Errorf( + "invalid url, cannot parse %s to url with error: %s", + priceService[1], + err.Error(), + ) + } + + query := u.Query() + timeoutStr := query.Get(flagQueryTimeout) + if timeoutStr == "" { + return "", nil, 0, fmt.Errorf("invalid timeout, priceService requires query timeout") + } + // Remove timeout from query because we need to return `base` + query.Del(flagQueryTimeout) + u.RawQuery = query.Encode() + + timeout, err = time.ParseDuration(timeoutStr) + if err != nil { + return "", nil, 0, fmt.Errorf("invalid timeout, cannot parse duration with error: %s", err.Error()) + } + return priceService[0], u, timeout, nil +} diff --git a/grogu/priceservice/rest.go b/grogu/priceservice/rest.go new file mode 100644 index 000000000..4564875f9 --- /dev/null +++ b/grogu/priceservice/rest.go @@ -0,0 +1,48 @@ +package priceservice + +import ( + "encoding/json" + "net/url" + "path" + "strings" + "time" + + bothanproto "github.com/bandprotocol/bothan/bothan-api/client/go-client/query" + "github.com/levigross/grequests" +) + +type RestService struct { + url string + timeout time.Duration +} + +func NewRestService(url string, timeout time.Duration) *RestService { + return &RestService{url: url, timeout: timeout} +} + +func (rs *RestService) Query(signalIds []string) ([]*bothanproto.PriceData, error) { + concatSignalIds := strings.Join(signalIds, ",") + u, err := url.Parse(rs.url) + if err != nil { + return nil, err + } + u.Path = path.Join(u.Path, concatSignalIds) + + resp, err := grequests.Get( + u.String(), + &grequests.RequestOptions{ + RequestTimeout: rs.timeout, + }, + ) + if err != nil { + return nil, err + } + + var priceResp bothanproto.QueryPricesResponse + err = json.Unmarshal(resp.Bytes(), &priceResp) + if err != nil { + return nil, err + } + + return priceResp.Prices, nil +} diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index 784ced95b..810f17a4d 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -48,6 +48,34 @@ table: name: deposits schema: public + - name: group_members + using: + foreign_key_constraint_on: + column: account_id + table: + name: group_members + schema: public + - name: group_policies + using: + foreign_key_constraint_on: + column: admin + table: + name: group_policies + schema: public + - name: group_votes + using: + foreign_key_constraint_on: + column: voter_id + table: + name: group_votes + schema: public + - name: groups + using: + foreign_key_constraint_on: + column: admin + table: + name: groups + schema: public - name: proposals using: foreign_key_constraint_on: @@ -304,6 +332,98 @@ - name: transaction using: foreign_key_constraint_on: tx_id +- table: + name: group_members + schema: public + object_relationships: + - name: account + using: + foreign_key_constraint_on: account_id + - name: group + using: + foreign_key_constraint_on: group_id +- table: + name: group_policies + schema: public + object_relationships: + - name: account + using: + foreign_key_constraint_on: admin + - name: group + using: + foreign_key_constraint_on: group_id + array_relationships: + - name: group_proposals + using: + foreign_key_constraint_on: + column: group_policy_address + table: + name: group_proposals + schema: public +- table: + name: group_proposals + schema: public + object_relationships: + - name: group + using: + foreign_key_constraint_on: group_id + - name: group_policy + using: + foreign_key_constraint_on: group_policy_address + - name: group_vote + using: + foreign_key_constraint_on: + column: group_proposal_id + table: + name: group_votes + schema: public + array_relationships: + - name: group_votes + using: + foreign_key_constraint_on: + column: group_proposal_id + table: + name: group_votes + schema: public +- table: + name: group_votes + schema: public + object_relationships: + - name: account + using: + foreign_key_constraint_on: voter_id + - name: group_proposal + using: + foreign_key_constraint_on: group_proposal_id +- table: + name: groups + schema: public + object_relationships: + - name: account + using: + foreign_key_constraint_on: admin + array_relationships: + - name: group_members + using: + foreign_key_constraint_on: + column: group_id + table: + name: group_members + schema: public + - name: group_policies + using: + foreign_key_constraint_on: + column: group_id + table: + name: group_policies + schema: public + - name: group_proposals + using: + foreign_key_constraint_on: + column: group_id + table: + name: group_proposals + schema: public - table: name: historical_bonded_token_on_validators schema: public diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go new file mode 100644 index 000000000..99a8078a5 --- /dev/null +++ b/hooks/emitter/bandtss.go @@ -0,0 +1,84 @@ +package emitter + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/hooks/common" + "github.com/bandprotocol/chain/v2/x/bandtss/types" +) + +func (h *Hook) emitSetBandtssStatus(member types.Member) { + h.Write("SET_BANDTSS_STATUS", common.JsDict{ + "address": member.Address, + "is_active": member.IsActive, + "since": member.Since.UnixNano(), + "last_active": member.LastActive.UnixNano(), + }) +} + +func (h *Hook) emitNewBandtssReplacement(replacement types.Replacement) { + h.Write("NEW_BANDTSS_REPLACEMENT", common.JsDict{ + "tss_signing_id": replacement.SigningID, + "new_group_id": replacement.NewGroupID, + "new_pub_key": parseBytes(replacement.NewPubKey), + "current_group_id": replacement.CurrentGroupID, + "current_pub_key": parseBytes(replacement.CurrentPubKey), + "exec_time": replacement.ExecTime.UnixNano(), + "status": int(replacement.Status), + }) +} + +func (h *Hook) emitUpdateBandtssReplacementStatus(status types.ReplacementStatus) { + h.Write("UPDATE_BANDTSS_REPLACEMENT_STATUS", common.JsDict{ + "status": int(status), + }) +} + +// handleUpdateBandtssStatus implements emitter handler for update bandtss status. +func (h *Hook) handleUpdateBandtssStatus(ctx sdk.Context, address sdk.AccAddress) { + member, err := h.bandtssKeeper.GetMember(ctx, address) + if err != nil { + panic(err) + } + h.emitSetBandtssStatus(member) +} + +// handleBandtssMsgActivate implements emitter handler for MsgActivate of bandtss. +func (h *Hook) handleBandtssMsgActivate( + ctx sdk.Context, msg *types.MsgActivate, +) { + acc, err := sdk.AccAddressFromBech32(msg.Address) + if err != nil { + panic(err) + } + + h.handleUpdateBandtssStatus(ctx, acc) +} + +// handleBandtssMsgHealthCheck implements emitter handler for MsgHealthCheck of bandtss. +func (h *Hook) handleBandtssMsgHealthCheck( + ctx sdk.Context, msg *types.MsgHealthCheck, +) { + acc, err := sdk.AccAddressFromBech32(msg.Address) + if err != nil { + panic(err) + } + + h.handleUpdateBandtssStatus(ctx, acc) +} + +// handleUpdateBandtssReplacementStatus implements emitter handler events related to replacements. +func (h *Hook) handleUpdateBandtssReplacementStatus(ctx sdk.Context) { + r := h.bandtssKeeper.GetReplacement(ctx) + if r.Status == types.REPLACEMENT_STATUS_SUCCESS { + h.handleSetTSSGroup(ctx, r.CurrentGroupID) + } + + h.emitUpdateBandtssReplacementStatus(r.Status) +} + +// handleInitTSSReplacement implements emitter handler for init replacement event. +func (h *Hook) handleInitBandtssReplacement(ctx sdk.Context) { + r := h.bandtssKeeper.GetReplacement(ctx) + h.emitNewBandtssReplacement(r) +} diff --git a/hooks/emitter/decoder.go b/hooks/emitter/decoder.go index bf5e79751..ba3cb6e44 100644 --- a/hooks/emitter/decoder.go +++ b/hooks/emitter/decoder.go @@ -11,6 +11,7 @@ import ( feegranttypes "github.com/cosmos/cosmos-sdk/x/feegrant" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + "github.com/cosmos/cosmos-sdk/x/group" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" transfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" @@ -124,6 +125,34 @@ func DecodeMsg(msg sdk.Msg, detail common.JsDict) { DecodeMsgGrantAllowance(msg, detail) case *feegranttypes.MsgRevokeAllowance: DecodeMsgRevokeAllowance(msg, detail) + case *group.MsgCreateGroup: + DecodeGroupMsgCreateGroup(msg, detail) + case *group.MsgCreateGroupPolicy: + DecodeGroupMsgCreateGroupPolicy(msg, detail) + case *group.MsgCreateGroupWithPolicy: + DecodeGroupMsgCreateGroupWithPolicy(msg, detail) + case *group.MsgExec: + DecodeGroupMsgExec(msg, detail) + case *group.MsgLeaveGroup: + DecodeGroupMsgLeaveGroup(msg, detail) + case *group.MsgSubmitProposal: + DecodeGroupMsgSubmitProposal(msg, detail) + case *group.MsgUpdateGroupAdmin: + DecodeGroupMsgUpdateGroupAdmin(msg, detail) + case *group.MsgUpdateGroupMembers: + DecodeGroupMsgUpdateGroupMembers(msg, detail) + case *group.MsgUpdateGroupMetadata: + DecodeGroupMsgUpdateGroupMetadata(msg, detail) + case *group.MsgUpdateGroupPolicyAdmin: + DecodeGroupMsgUpdateGroupPolicyAdmin(msg, detail) + case *group.MsgUpdateGroupPolicyDecisionPolicy: + DecodeGroupMsgUpdateGroupPolicyDecisionPolicy(msg, detail) + case *group.MsgUpdateGroupPolicyMetadata: + DecodeGroupMsgUpdateGroupPolicyMetadata(msg, detail) + case *group.MsgVote: + DecodeGroupMsgVote(msg, detail) + case *group.MsgWithdrawProposal: + DecodeGroupMsgWithdrawProposal(msg, detail) default: break } @@ -251,7 +280,6 @@ func DecodeMsgRequestData(msg *oracletypes.MsgRequestData, detail common.JsDict) detail["min_count"] = msg.GetMinCount() detail["client_id"] = msg.GetClientID() detail["fee_limit"] = msg.GetFeeLimit() - detail["tss_group_id"] = msg.GetTSSGroupID() detail["prepare_gas"] = msg.GetPrepareGas() detail["execute_gas"] = msg.GetExecuteGas() detail["sender"] = msg.GetSender() @@ -619,3 +647,108 @@ func DecodeDescription(des stakingtypes.Description) common.JsDict { "website": des.GetWebsite(), } } + +func DecodeGroupMsgCreateGroup(msg *group.MsgCreateGroup, detail common.JsDict) { + detail["admin"] = msg.Admin + detail["members"] = msg.Members + detail["metadata"] = msg.Metadata +} + +func DecodeGroupMsgCreateGroupPolicy(msg *group.MsgCreateGroupPolicy, detail common.JsDict) { + detail["admin"] = msg.Admin + detail["group_id"] = msg.GroupId + detail["metadata"] = msg.Metadata + detail["decision_policy"] = msg.DecisionPolicy.GetCachedValue() +} + +func DecodeGroupMsgCreateGroupWithPolicy(msg *group.MsgCreateGroupWithPolicy, detail common.JsDict) { + detail["admin"] = msg.Admin + detail["members"] = msg.Members + detail["group_metadata"] = msg.GroupMetadata + detail["group_policy_metadata"] = msg.GroupPolicyMetadata + detail["group_policy_as_admin"] = msg.GroupPolicyAsAdmin + detail["decision_policy"] = msg.DecisionPolicy.GetCachedValue() +} + +func DecodeGroupMsgExec(msg *group.MsgExec, detail common.JsDict) { + detail["proposal_id"] = msg.ProposalId + detail["executor"] = msg.Executor +} + +func DecodeGroupMsgLeaveGroup(msg *group.MsgLeaveGroup, detail common.JsDict) { + detail["address"] = msg.Address + detail["group_id"] = msg.GroupId +} + +func DecodeGroupMsgSubmitProposal(msg *group.MsgSubmitProposal, detail common.JsDict) { + detail["group_policy_address"] = msg.GroupPolicyAddress + detail["proposers"] = msg.Proposers + detail["metadata"] = msg.Metadata + + msgs, _ := msg.GetMsgs() + messages := make([]common.JsDict, len(msgs)) + for i, m := range msgs { + detail := make(common.JsDict) + DecodeMsg(m, detail) + messages[i] = common.JsDict{ + "msg": detail, + "type": sdk.MsgTypeURL(m), + } + } + detail["msgs"] = messages + + detail["exec"] = msg.Exec.String() + detail["summary"] = msg.Summary +} + +func DecodeGroupMsgUpdateGroupAdmin(msg *group.MsgUpdateGroupAdmin, detail common.JsDict) { + detail["admin"] = msg.Admin + detail["group_id"] = msg.GroupId + detail["new_admin"] = msg.NewAdmin +} + +func DecodeGroupMsgUpdateGroupMembers(msg *group.MsgUpdateGroupMembers, detail common.JsDict) { + detail["admin"] = msg.Admin + detail["group_id"] = msg.GroupId + detail["members"] = msg.MemberUpdates +} + +func DecodeGroupMsgUpdateGroupMetadata(msg *group.MsgUpdateGroupMetadata, detail common.JsDict) { + detail["admin"] = msg.Admin + detail["group_id"] = msg.GroupId + detail["metadata"] = msg.Metadata +} + +func DecodeGroupMsgUpdateGroupPolicyAdmin(msg *group.MsgUpdateGroupPolicyAdmin, detail common.JsDict) { + detail["admin"] = msg.Admin + detail["group_policy_address"] = msg.GroupPolicyAddress + detail["new_admin"] = msg.NewAdmin +} + +func DecodeGroupMsgUpdateGroupPolicyDecisionPolicy( + msg *group.MsgUpdateGroupPolicyDecisionPolicy, + detail common.JsDict, +) { + detail["admin"] = msg.Admin + detail["group_policy_address"] = msg.GroupPolicyAddress + detail["decision_policy"] = msg.DecisionPolicy.GetCachedValue() +} + +func DecodeGroupMsgUpdateGroupPolicyMetadata(msg *group.MsgUpdateGroupPolicyMetadata, detail common.JsDict) { + detail["admin"] = msg.Admin + detail["group_policy_address"] = msg.GroupPolicyAddress + detail["metadata"] = msg.Metadata +} + +func DecodeGroupMsgVote(msg *group.MsgVote, detail common.JsDict) { + detail["proposal_id"] = msg.ProposalId + detail["voter"] = msg.Voter + detail["option"] = msg.Option + detail["metadata"] = msg.Metadata + detail["exec"] = msg.Exec.String() +} + +func DecodeGroupMsgWithdrawProposal(msg *group.MsgWithdrawProposal, detail common.JsDict) { + detail["proposal_id"] = msg.ProposalId + detail["address"] = msg.Address +} diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index 10f9ef7d5..0a64431ef 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -195,12 +195,11 @@ func (suite *DecoderTestSuite) TestDecodeMsgRequestData() { bandtesting.TestDefaultExecuteGas, SenderAddress, 0, - 0, ) emitter.DecodeMsgRequestData(msg, detail) suite.testCompareJson( detail, - "{\"ask_count\":1,\"calldata\":\"Y2FsbGRhdGE=\",\"client_id\":\"cleint_id\",\"execute_gas\":300000,\"fee_limit\":[{\"denom\":\"uband\",\"amount\":\"100000000\"}],\"min_count\":1,\"oracle_script_id\":1,\"prepare_gas\":40000,\"sender\":\"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0\",\"tss_group_id\":0}", + "{\"ask_count\":1,\"calldata\":\"Y2FsbGRhdGE=\",\"client_id\":\"cleint_id\",\"execute_gas\":300000,\"fee_limit\":[{\"denom\":\"uband\",\"amount\":\"100000000\"}],\"min_count\":1,\"oracle_script_id\":1,\"prepare_gas\":40000,\"sender\":\"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0\"}", ) } diff --git a/hooks/emitter/emitter.go b/hooks/emitter/emitter.go index 120f8b22d..f302c486f 100644 --- a/hooks/emitter/emitter.go +++ b/hooks/emitter/emitter.go @@ -10,6 +10,7 @@ import ( "github.com/cometbft/cometbft/crypto/tmhash" tmjson "github.com/cometbft/cometbft/libs/json" "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/authz" @@ -21,6 +22,7 @@ import ( govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + groupkeeper "github.com/cosmos/cosmos-sdk/x/group/keeper" mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -32,6 +34,7 @@ import ( "github.com/bandprotocol/chain/v2/app/params" "github.com/bandprotocol/chain/v2/hooks/common" + bandtsskeeper "github.com/bandprotocol/chain/v2/x/bandtss/keeper" oraclekeeper "github.com/bandprotocol/chain/v2/x/oracle/keeper" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" tsskeeper "github.com/bandprotocol/chain/v2/x/tss/keeper" @@ -56,14 +59,18 @@ type Hook struct { mintKeeper mintkeeper.Keeper distrKeeper distrkeeper.Keeper govKeeper govkeeper.Keeper + groupKeeper groupkeeper.Keeper oracleKeeper oraclekeeper.Keeper - tssKeeper tsskeeper.Keeper + tssKeeper *tsskeeper.Keeper + bandtssKeeper *bandtsskeeper.Keeper icahostKeeper icahostkeeper.Keeper // ibc keeper clientKeeper clientkeeper.Keeper connectionKeeper connectionkeeper.Keeper channelKeeper channelkeeper.Keeper + + groupStoreKey storetypes.StoreKey } // NewHook creates an emitter hook instance that will be added in Band App. @@ -77,12 +84,15 @@ func NewHook( mintKeeper mintkeeper.Keeper, distrKeeper distrkeeper.Keeper, govKeeper govkeeper.Keeper, + groupKeeper groupkeeper.Keeper, oracleKeeper oraclekeeper.Keeper, - tssKeeper tsskeeper.Keeper, + tssKeeper *tsskeeper.Keeper, + bandtssKeeper *bandtsskeeper.Keeper, icahostKeeper icahostkeeper.Keeper, clientKeeper clientkeeper.Keeper, connectionKeeper connectionkeeper.Keeper, channelKeeper channelkeeper.Keeper, + groupStorekey storetypes.StoreKey, kafkaURI string, emitStartState bool, ) *Hook { @@ -104,12 +114,15 @@ func NewHook( mintKeeper: mintKeeper, distrKeeper: distrKeeper, govKeeper: govKeeper, + groupKeeper: groupKeeper, oracleKeeper: oracleKeeper, tssKeeper: tssKeeper, + bandtssKeeper: bandtssKeeper, icahostKeeper: icahostKeeper, clientKeeper: clientKeeper, connectionKeeper: connectionKeeper, channelKeeper: channelKeeper, + groupStoreKey: groupStorekey, emitStartState: emitStartState, } } @@ -428,6 +441,19 @@ func (h *Hook) AfterDeliverTx(ctx sdk.Context, req abci.RequestDeliverTx, res ab // AfterEndBlock specify actions need to do after end block period (app.Hook interface). func (h *Hook) AfterEndBlock(ctx sdk.Context, req abci.RequestEndBlock, res abci.ResponseEndBlock) { + // update group proposals when voting period is end + timeBytes := sdk.FormatTimeBytes(ctx.BlockTime().UTC()) + lenTimeByte := byte(len(timeBytes)) + prefix := []byte{groupkeeper.ProposalsByVotingPeriodEndPrefix} + + iterator := ctx.KVStore(h.groupStoreKey). + Iterator(prefix, sdk.PrefixEndBytes(append(append(prefix, lenTimeByte), timeBytes...))) + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + proposalID, _ := splitKeyWithTime(iterator.Key()) + h.doUpdateGroupProposal(ctx, proposalID) + } + for _, event := range res.Events { h.handleBeginBlockEndBlockEvent(ctx, event) } diff --git a/hooks/emitter/group.go b/hooks/emitter/group.go new file mode 100644 index 000000000..bb1f79cc9 --- /dev/null +++ b/hooks/emitter/group.go @@ -0,0 +1,412 @@ +package emitter + +import ( + "encoding/json" + "strings" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" + "github.com/cosmos/cosmos-sdk/x/group" + proto "github.com/cosmos/gogoproto/proto" + + "github.com/bandprotocol/chain/v2/hooks/common" +) + +func extractStringFromEventMap(evMap common.EvMap, event string, topic string) string { + return strings.Trim(evMap[event+"."+topic][0], `"`) +} + +// handleGroupMsgCreateGroup implements emitter handler for Group's MsgCreateGroup. +func (h *Hook) handleGroupMsgCreateGroup( + ctx sdk.Context, evMap common.EvMap, +) { + groupId := uint64( + common.Atoi(extractStringFromEventMap(evMap, proto.MessageName(&group.EventCreateGroup{}), "group_id")), + ) + groupInfoResponse, _ := h.groupKeeper.GroupInfo( + sdk.WrapSDKContext(ctx), + &group.QueryGroupInfoRequest{GroupId: groupId}, + ) + groupInfo := groupInfoResponse.Info + h.Write("NEW_GROUP", common.JsDict{ + "id": groupId, + "version": groupInfo.Version, + "admin": groupInfo.Admin, + "metadata": groupInfo.Metadata, + "total_weight": groupInfo.TotalWeight, + "created_at": common.TimeToNano(&groupInfo.CreatedAt), + }) + h.doAddGroupMembers(ctx, groupId) +} + +// handleGroupMsgCreateGroup implements emitter handler for Group's MsgCreateGroupPolicy. +func (h *Hook) handleGroupMsgCreateGroupPolicy( + ctx sdk.Context, evMap common.EvMap, +) { + policyAddress := extractStringFromEventMap(evMap, proto.MessageName(&group.EventCreateGroupPolicy{}), "address") + groupPolicyResponse, _ := h.groupKeeper.GroupPolicyInfo( + sdk.WrapSDKContext(ctx), + &group.QueryGroupPolicyInfoRequest{ + Address: policyAddress, + }, + ) + groupPolicyInfo := groupPolicyResponse.Info + decisionPolicy, _ := groupPolicyInfo.GetDecisionPolicy() + h.Write("NEW_GROUP_POLICY", common.JsDict{ + "address": policyAddress, + "type": proto.MessageName(decisionPolicy), + "group_id": groupPolicyInfo.GroupId, + "admin": groupPolicyInfo.Admin, + "metadata": groupPolicyInfo.Metadata, + "version": groupPolicyInfo.Version, + "decision_policy": decisionPolicy, + "created_at": common.TimeToNano(&groupPolicyInfo.CreatedAt), + }) +} + +// handleGroupMsgCreateGroupWithPolicy implements emitter handler for Group's MsgCreateGroupWithPolicy. +func (h *Hook) handleGroupMsgCreateGroupWithPolicy( + ctx sdk.Context, evMap common.EvMap, +) { + h.handleGroupMsgCreateGroup(ctx, evMap) + h.handleGroupMsgCreateGroupPolicy(ctx, evMap) +} + +// handleGroupMsgSubmitProposal implements emitter handler for Group's MsgSubmitProposal. +func (h *Hook) handleGroupMsgSubmitProposal( + ctx sdk.Context, evMap common.EvMap, +) { + proposalId := uint64( + common.Atoi(extractStringFromEventMap(evMap, proto.MessageName(&group.EventSubmitProposal{}), "proposal_id")), + ) + proposalResponse, _ := h.groupKeeper.Proposal( + sdk.WrapSDKContext(ctx), + &group.QueryProposalRequest{ProposalId: proposalId}, + ) + proposal := proposalResponse.Proposal + msgs, _ := proposal.GetMsgs() + messages := make([]common.JsDict, len(msgs)) + for i, m := range msgs { + messages[i] = common.JsDict{ + "msg": m, + "type": sdk.MsgTypeURL(m), + } + } + + h.Write("NEW_GROUP_PROPOSAL", common.JsDict{ + "id": proposal.Id, + "group_policy_address": proposal.GroupPolicyAddress, + "metadata": proposal.Metadata, + "proposers": strings.Join(proposal.Proposers, ","), + "submit_time": common.TimeToNano(&proposal.SubmitTime), + "group_version": proposal.GroupVersion, + "group_policy_version": proposal.GroupPolicyVersion, + "status": proposal.Status.String(), + "yes_vote": proposal.FinalTallyResult.YesCount, + "no_vote": proposal.FinalTallyResult.NoCount, + "no_with_veto_vote": proposal.FinalTallyResult.NoWithVetoCount, + "abstain_vote": proposal.FinalTallyResult.AbstainCount, + "voting_period_end": common.TimeToNano(&proposal.VotingPeriodEnd), + "executor_result": proposal.ExecutorResult.String(), + "messages": messages, + "title": proposal.Title, + "summary": proposal.Summary, + }) +} + +// handleGroupMsgVote implements emitter handler for Group's MsgVote. +func (h *Hook) handleGroupMsgVote( + ctx sdk.Context, msg *group.MsgVote, evMap common.EvMap, +) { + proposalId := uint64( + common.Atoi(extractStringFromEventMap(evMap, proto.MessageName(&group.EventVote{}), "proposal_id")), + ) + voteResponse, err := h.groupKeeper.VoteByProposalVoter( + sdk.WrapSDKContext(ctx), + &group.QueryVoteByProposalVoterRequest{ + ProposalId: proposalId, + Voter: msg.Voter, + }, + ) + if err != nil { + return + } + vote := voteResponse.Vote + h.Write("NEW_GROUP_VOTE", common.JsDict{ + "group_proposal_id": proposalId, + "voter_address": vote.Voter, + "option": vote.Option.String(), + "metadata": vote.Metadata, + "submit_time": common.TimeToNano(&vote.SubmitTime), + }) +} + +// handleGroupMsgLeaveGroup implements emitter handler for Group's MsgLeaveGroup. +func (h *Hook) handleGroupMsgLeaveGroup( + ctx sdk.Context, evMap common.EvMap, +) { + groupId := uint64( + common.Atoi(extractStringFromEventMap(evMap, proto.MessageName(&group.EventLeaveGroup{}), "group_id")), + ) + address := extractStringFromEventMap(evMap, proto.MessageName(&group.EventLeaveGroup{}), "address") + h.doUpdateGroup(ctx, groupId) + h.Write("REMOVE_GROUP_MEMBER", common.JsDict{ + "group_id": groupId, + "address": address, + }) +} + +// handleGroupMsgUpdateGroupAdmin implements emitter handler for Group's MsgUpdateGroupAdmin. +func (h *Hook) handleGroupMsgUpdateGroupAdmin( + ctx sdk.Context, evMap common.EvMap, +) { + groupId := uint64( + common.Atoi(extractStringFromEventMap(evMap, proto.MessageName(&group.EventUpdateGroup{}), "group_id")), + ) + h.doUpdateGroup(ctx, groupId) +} + +// handleGroupMsgUpdateGroupMembers implements emitter handler for Group's MsgUpdateGroupMembers. +func (h *Hook) handleGroupMsgUpdateGroupMembers( + ctx sdk.Context, msg *group.MsgUpdateGroupMembers, evMap common.EvMap, +) { + h.Write("REMOVE_GROUP_MEMBERS_BY_GROUP_ID", common.JsDict{ + "group_id": msg.GroupId, + }) + h.doAddGroupMembers(ctx, msg.GroupId) + h.doUpdateGroup(ctx, msg.GroupId) +} + +// handleGroupMsgUpdateGroupMetadata implements emitter handler for Group's MsgUpdateGroupMetadata. +func (h *Hook) handleGroupMsgUpdateGroupMetadata( + ctx sdk.Context, evMap common.EvMap, +) { + groupId := uint64( + common.Atoi(extractStringFromEventMap(evMap, proto.MessageName(&group.EventUpdateGroup{}), "group_id")), + ) + h.doUpdateGroup(ctx, groupId) +} + +// handleGroupMsgUpdateGroupPolicyAdmin implements emitter handler for Group's MsgUpdateGroupPolicyAdmin. +func (h *Hook) handleGroupMsgUpdateGroupPolicyAdmin( + ctx sdk.Context, evMap common.EvMap, +) { + groupPolicyAddress := extractStringFromEventMap( + evMap, + proto.MessageName(&group.EventUpdateGroupPolicy{}), + "address", + ) + h.doUpdateGroupPolicy(ctx, groupPolicyAddress) +} + +// handleGroupMsgUpdateGroupPolicyDecisionPolicy implements emitter handler for Group's MsgUpdateGroupPolicyDecisionPolicy. +func (h *Hook) handleGroupMsgUpdateGroupPolicyDecisionPolicy( + ctx sdk.Context, evMap common.EvMap, +) { + groupPolicyAddress := extractStringFromEventMap( + evMap, + proto.MessageName(&group.EventUpdateGroupPolicy{}), + "address", + ) + h.doUpdateGroupPolicy(ctx, groupPolicyAddress) +} + +// handleGroupMsgUpdateGroupPolicyMetadata implements emitter handler for Group's MsgUpdateGroupPolicyMetadata. +func (h *Hook) handleGroupMsgUpdateGroupPolicyMetadata( + ctx sdk.Context, evMap common.EvMap, +) { + groupPolicyAddress := extractStringFromEventMap( + evMap, + proto.MessageName(&group.EventUpdateGroupPolicy{}), + "address", + ) + h.doUpdateGroupPolicy(ctx, groupPolicyAddress) +} + +// handleGroupMsgWithdrawProposal implements emitter handler for Group's MsgWithdrawProposal. +func (h *Hook) handleGroupMsgWithdrawProposal( + ctx sdk.Context, evMap common.EvMap, +) { + proposalId := uint64( + common.Atoi( + extractStringFromEventMap(evMap, proto.MessageName(&group.EventWithdrawProposal{}), "proposal_id"), + ), + ) + h.doUpdateGroupProposal(ctx, proposalId) +} + +// handleGroupEventExec implements emitter handler for Group's EventExec. +func (h *Hook) handleGroupEventExec( + ctx sdk.Context, evMap common.EvMap, +) { + if len(evMap[proto.MessageName(&group.EventExec{})+".proposal_id"]) == 0 { + return + } + proposalId := uint64( + common.Atoi(extractStringFromEventMap(evMap, proto.MessageName(&group.EventExec{}), "proposal_id")), + ) + executorResult := extractStringFromEventMap(evMap, proto.MessageName(&group.EventExec{}), "result") + h.Write("UPDATE_GROUP_PROPOSAL_BY_ID", common.JsDict{ + "id": proposalId, + "executor_result": executorResult, + }) + + h.handleGroupEventProposalPruned(ctx, evMap) +} + +// handleGroupEventProposalPruned implements emitter handler for Group's EventProposalPruned. +func (h *Hook) handleGroupEventProposalPruned( + ctx sdk.Context, evMap common.EvMap, +) { + if len(evMap[proto.MessageName(&group.EventProposalPruned{})+".proposal_id"]) == 0 { + return + } + proposalId := uint64( + common.Atoi(extractStringFromEventMap(evMap, proto.MessageName(&group.EventProposalPruned{}), "proposal_id")), + ) + proposalStatus := extractStringFromEventMap(evMap, proto.MessageName(&group.EventProposalPruned{}), "status") + tallyResult := group.DefaultTallyResult() + _ = json.Unmarshal([]byte(evMap[proto.MessageName(&group.EventProposalPruned{})+".tally_result"][0]), &tallyResult) + h.Write("UPDATE_GROUP_PROPOSAL_BY_ID", common.JsDict{ + "id": proposalId, + "status": proposalStatus, + "yes_vote": tallyResult.YesCount, + "no_vote": tallyResult.NoCount, + "no_with_veto_vote": tallyResult.NoWithVetoCount, + "abstain_vote": tallyResult.AbstainCount, + }) +} + +func (h *Hook) doUpdateGroup(ctx sdk.Context, groupId uint64) { + groupInfoResponse, _ := h.groupKeeper.GroupInfo( + sdk.WrapSDKContext(ctx), + &group.QueryGroupInfoRequest{GroupId: groupId}, + ) + groupInfo := groupInfoResponse.Info + h.Write("UPDATE_GROUP", common.JsDict{ + "id": groupId, + "version": groupInfo.Version, + "admin": groupInfo.Admin, + "metadata": groupInfo.Metadata, + "total_weight": groupInfo.TotalWeight, + "created_at": common.TimeToNano(&groupInfo.CreatedAt), + }) +} + +func (h *Hook) doUpdateGroupPolicy(ctx sdk.Context, policyAddress string) { + groupPolicyResponse, _ := h.groupKeeper.GroupPolicyInfo( + sdk.WrapSDKContext(ctx), + &group.QueryGroupPolicyInfoRequest{ + Address: policyAddress, + }, + ) + groupPolicyInfo := groupPolicyResponse.Info + decisionPolicy, _ := groupPolicyInfo.GetDecisionPolicy() + h.Write("UPDATE_GROUP_POLICY", common.JsDict{ + "address": policyAddress, + "group_id": groupPolicyInfo.GroupId, + "admin": groupPolicyInfo.Admin, + "metadata": groupPolicyInfo.Metadata, + "version": groupPolicyInfo.Version, + "decision_policy": decisionPolicy, + "created_at": common.TimeToNano(&groupPolicyInfo.CreatedAt), + }) + + h.doAbortProposals(ctx, policyAddress) +} + +func (h *Hook) doAbortProposals(ctx sdk.Context, policyAddress string) { + groupProposalsResponse, _ := h.groupKeeper.ProposalsByGroupPolicy( + sdk.WrapSDKContext(ctx), + &group.QueryProposalsByGroupPolicyRequest{ + Address: policyAddress, + }, + ) + for { + groupProposals := groupProposalsResponse.Proposals + for _, groupProposal := range groupProposals { + if groupProposal.Status == group.PROPOSAL_STATUS_ABORTED { + h.doUpdateGroupProposal(ctx, groupProposal.Id) + } + } + if len(groupProposalsResponse.Pagination.NextKey) == 0 { + break + } + groupProposalsResponse, _ = h.groupKeeper.ProposalsByGroupPolicy( + sdk.WrapSDKContext(ctx), + &group.QueryProposalsByGroupPolicyRequest{ + Address: policyAddress, + Pagination: &query.PageRequest{ + Key: groupProposalsResponse.Pagination.NextKey, + }, + }, + ) + } +} + +func (h *Hook) doUpdateGroupProposal(ctx sdk.Context, proposalId uint64) { + proposalResponse, _ := h.groupKeeper.Proposal( + sdk.WrapSDKContext(ctx), + &group.QueryProposalRequest{ProposalId: proposalId}, + ) + proposal := proposalResponse.Proposal + msgs, _ := proposal.GetMsgs() + messages := make([]common.JsDict, len(msgs)) + for i, m := range msgs { + messages[i] = common.JsDict{ + "msg": m, + "type": sdk.MsgTypeURL(m), + } + } + + h.Write("UPDATE_GROUP_PROPOSAL", common.JsDict{ + "id": proposal.Id, + "group_policy_address": proposal.GroupPolicyAddress, + "metadata": proposal.Metadata, + "proposers": strings.Join(proposal.Proposers, ","), + "submit_time": common.TimeToNano(&proposal.SubmitTime), + "group_version": proposal.GroupVersion, + "group_policy_version": proposal.GroupPolicyVersion, + "status": proposal.Status.String(), + "yes_vote": proposal.FinalTallyResult.YesCount, + "no_vote": proposal.FinalTallyResult.NoCount, + "no_with_veto_vote": proposal.FinalTallyResult.NoWithVetoCount, + "abstain_vote": proposal.FinalTallyResult.AbstainCount, + "voting_period_end": common.TimeToNano(&proposal.VotingPeriodEnd), + "executor_result": proposal.ExecutorResult.String(), + "messages": messages, + "title": proposal.Title, + "summary": proposal.Summary, + }) +} + +func (h *Hook) doAddGroupMembers(ctx sdk.Context, groupId uint64) { + groupMembersResponse, _ := h.groupKeeper.GroupMembers( + sdk.WrapSDKContext(ctx), + &group.QueryGroupMembersRequest{GroupId: groupId}, + ) + for { + groupMembers := groupMembersResponse.Members + for _, groupMember := range groupMembers { + h.Write("NEW_GROUP_MEMBER", common.JsDict{ + "group_id": groupId, + "address": groupMember.Member.Address, + "weight": groupMember.Member.Weight, + "metadata": groupMember.Member.Metadata, + "added_at": common.TimeToNano(&groupMember.Member.AddedAt), + }) + } + if len(groupMembersResponse.Pagination.NextKey) == 0 { + break + } + groupMembersResponse, _ = h.groupKeeper.GroupMembers( + sdk.WrapSDKContext(ctx), + &group.QueryGroupMembersRequest{ + GroupId: groupId, + Pagination: &query.PageRequest{ + Key: groupMembersResponse.Pagination.NextKey, + }, + }, + ) + } +} diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index f95939357..9ef8ff8d9 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -1,16 +1,21 @@ package emitter import ( + "time" + abci "github.com/cometbft/cometbft/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/kv" "github.com/cosmos/cosmos-sdk/x/authz" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + "github.com/cosmos/cosmos-sdk/x/group" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + proto "github.com/cosmos/gogoproto/proto" transfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" connectiontypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types" @@ -18,6 +23,7 @@ import ( "github.com/bandprotocol/chain/v2/hooks/common" "github.com/bandprotocol/chain/v2/pkg/tss" + bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) @@ -120,14 +126,43 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, log sdk.AB h.handleMsgRevoke(msg, detail) case *authz.MsgExec: h.handleMsgExec(ctx, txHash, msg, log, detail) - case *tsstypes.MsgActivate: - h.handleTSSMsgActivate(ctx, msg) - case *tsstypes.MsgHealthCheck: - h.handleTSSMsgHealthCheck(ctx, msg) + case *bandtsstypes.MsgActivate: + h.handleBandtssMsgActivate(ctx, msg) + case *bandtsstypes.MsgHealthCheck: + h.handleBandtssMsgHealthCheck(ctx, msg) + case *bandtsstypes.MsgRequestSignature: + h.handleEventRequestSignature(ctx, evMap) case *tsstypes.MsgSubmitDEs: h.handleTSSMsgSubmitDEs(ctx, msg) - case *tsstypes.MsgRequestSignature: - h.handleEventRequestSignature(ctx, evMap) + case *group.MsgCreateGroup: + h.handleGroupMsgCreateGroup(ctx, evMap) + case *group.MsgCreateGroupPolicy: + h.handleGroupMsgCreateGroupPolicy(ctx, evMap) + case *group.MsgCreateGroupWithPolicy: + h.handleGroupMsgCreateGroupWithPolicy(ctx, evMap) + case *group.MsgExec: + h.handleGroupEventExec(ctx, evMap) + case *group.MsgLeaveGroup: + h.handleGroupMsgLeaveGroup(ctx, evMap) + case *group.MsgSubmitProposal: + h.handleGroupMsgSubmitProposal(ctx, evMap) + case *group.MsgUpdateGroupAdmin: + h.handleGroupMsgUpdateGroupAdmin(ctx, evMap) + case *group.MsgUpdateGroupMembers: + h.handleGroupMsgUpdateGroupMembers(ctx, msg, evMap) + case *group.MsgUpdateGroupMetadata: + h.handleGroupMsgUpdateGroupMetadata(ctx, evMap) + case *group.MsgUpdateGroupPolicyAdmin: + h.handleGroupMsgUpdateGroupPolicyAdmin(ctx, evMap) + case *group.MsgUpdateGroupPolicyDecisionPolicy: + h.handleGroupMsgUpdateGroupPolicyDecisionPolicy(ctx, evMap) + case *group.MsgUpdateGroupPolicyMetadata: + h.handleGroupMsgUpdateGroupPolicyMetadata(ctx, evMap) + case *group.MsgVote: + h.handleGroupMsgVote(ctx, msg, evMap) + h.handleGroupEventExec(ctx, evMap) + case *group.MsgWithdrawProposal: + h.handleGroupMsgWithdrawProposal(ctx, evMap) default: break } @@ -163,34 +198,43 @@ func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) h.handleEventSigningFailed(ctx, evMap) case tsstypes.EventTypeExpiredSigning: h.handleEventExpiredSigning(ctx, evMap) - case tsstypes.EventTypeInactiveStatus: + case bandtsstypes.EventTypeInactiveStatus: address := sdk.MustAccAddressFromBech32( - evMap[tsstypes.EventTypeInactiveStatus+"."+tsstypes.AttributeKeyAddress][0], + evMap[bandtsstypes.EventTypeInactiveStatus+"."+tsstypes.AttributeKeyAddress][0], ) - h.handleUpdateTSSStatus(ctx, address) + h.handleUpdateBandtssStatus(ctx, address) case tsstypes.EventTypeCreateGroup, tsstypes.EventTypeRound2Success, tsstypes.EventTypeRound3Success, tsstypes.EventTypeComplainSuccess, tsstypes.EventTypeComplainFailed, - tsstypes.EventTypeExpiredGroup, - tsstypes.EventTypeUpdateGroupFee: + tsstypes.EventTypeExpiredGroup: gid := tss.GroupID(common.Atoi(evMap[event.Type+"."+tsstypes.AttributeKeyGroupID][0])) h.handleSetTSSGroup(ctx, gid) - case tsstypes.EventTypeReplacement: - h.handleInitTSSReplacement(ctx, evMap) - case tsstypes.EventTypeReplacementSuccess: - rid := uint64( - common.Atoi(evMap[tsstypes.EventTypeReplacementSuccess+"."+tsstypes.AttributeKeyReplacementID][0]), - ) - h.handleUpdateTSSReplacementStatus(ctx, rid) - case tsstypes.EventTypeReplacementFailed: - rid := uint64( - common.Atoi(evMap[tsstypes.EventTypeReplacementFailed+"."+tsstypes.AttributeKeyReplacementID][0]), - ) - h.handleUpdateTSSReplacementStatus(ctx, rid) + case bandtsstypes.EventTypeReplacement: + if evMap[bandtsstypes.EventTypeReplacement+"."+bandtsstypes.AttributeKeyReplacementStatus][0] == "1" { + h.handleInitBandtssReplacement(ctx) + } else { + // TODO: check EventTypeNewGroupActivate + h.handleUpdateBandtssReplacementStatus(ctx) + } + case proto.MessageName(&group.EventProposalPruned{}): + h.handleGroupEventProposalPruned(ctx, evMap) default: break } } + +func splitKeyWithTime(key []byte) (proposalID uint64, endTime time.Time) { + lenTime := len(sdk.FormatTimeBytes(time.Now())) + kv.AssertKeyLength(key[2:], 8+lenTime) + + endTime, err := sdk.ParseTimeBytes(key[2 : 2+lenTime]) + if err != nil { + panic(err) + } + + proposalID = sdk.BigEndianToUint64(key[2+lenTime:]) + return +} diff --git a/hooks/emitter/oracle.go b/hooks/emitter/oracle.go index 8243c7bf1..a1291fc35 100644 --- a/hooks/emitter/oracle.go +++ b/hooks/emitter/oracle.go @@ -172,7 +172,6 @@ func (h *Hook) handleMsgRequestData( "ask_count": msg.AskCount, "min_count": msg.MinCount, "sender": msg.Sender, - "tss_group_id": msg.TSSGroupID, "client_id": msg.ClientID, "resolve_status": types.RESOLVE_STATUS_OPEN, "timestamp": ctx.BlockTime().UnixNano(), diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index b3340565c..80973f0e8 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -15,10 +15,8 @@ func (h *Hook) emitNewTSSSigning(signing types.Signing) { "group_pub_key": parseBytes(signing.GroupPubKey), "msg": parseBytes(signing.Message), "group_pub_nonce": parseBytes(signing.GroupPubNonce), - "fee": signing.Fee.String(), "status": int(signing.Status), "created_height": signing.CreatedHeight, - "requester": signing.Requester, }) } @@ -45,26 +43,15 @@ func (h *Hook) emitUpdateTSSSigningStatus(signing types.Signing) { }) } -func (h *Hook) emitSetTSSStatus(status types.Status) { - h.Write("SET_TSS_STATUS", common.JsDict{ - "address": status.Address, - "status": int(status.Status), - "since": status.Since.UnixNano(), - "last_active": status.LastActive.UnixNano(), - }) -} - func (h *Hook) emitSetTSSGroup(group types.Group, dkgContext []byte) { h.Write("SET_TSS_GROUP", common.JsDict{ - "id": group.ID, - "size": group.Size_, - "threshold": group.Threshold, - "dkg_context": parseBytes(dkgContext), - "pub_key": parseBytes(group.PubKey), - "status": int(group.Status), - "fee": group.Fee.String(), - "latest_replacement_id": group.LatestReplacementID, - "created_height": group.CreatedHeight, + "id": group.ID, + "size": group.Size_, + "threshold": group.Threshold, + "dkg_context": parseBytes(dkgContext), + "pub_key": parseBytes(group.PubKey), + "status": int(group.Status), + "created_height": group.CreatedHeight, }) } @@ -90,26 +77,6 @@ func (h *Hook) emitNewTSSAssignedMember(sid tss.SigningID, gid tss.GroupID, am t }) } -func (h *Hook) emitNewTSSReplacement(replacement types.Replacement) { - h.Write("NEW_TSS_REPLACEMENT", common.JsDict{ - "id": replacement.ID, - "tss_signing_id": replacement.SigningID, - "new_group_id": replacement.NewGroupID, - "new_pub_key": parseBytes(replacement.NewPubKey), - "current_group_id": replacement.CurrentGroupID, - "current_pub_key": parseBytes(replacement.CurrentPubKey), - "exec_time": replacement.ExecTime.UnixNano(), - "status": int(replacement.Status), - }) -} - -func (h *Hook) emitUpdateTSSReplacementStatus(ctx sdk.Context, id uint64, status types.ReplacementStatus) { - h.Write("UPDATE_TSS_REPLACEMENT_STATUS", common.JsDict{ - "id": id, - "status": int(status), - }) -} - // handleInitTSSModule implements emitter handler for initializing tss module. func (h *Hook) handleInitTSSModule(ctx sdk.Context) { for _, signing := range h.tssKeeper.GetSignings(ctx) { @@ -120,10 +87,8 @@ func (h *Hook) handleInitTSSModule(ctx sdk.Context) { "msg": parseBytes(signing.Message), "group_pub_nonce": parseBytes(signing.GroupPubNonce), "signature": parseBytes(signing.Signature), - "fee": signing.Fee.String(), "status": int(signing.Status), "created_height": signing.CreatedHeight, - "requester": signing.Requester, }) } } @@ -186,12 +151,6 @@ func (h *Hook) handleEventExpiredSigning(ctx sdk.Context, evMap common.EvMap) { } } -// handleUpdateTSSStatus implements emitter handler for update tss status. -func (h *Hook) handleUpdateTSSStatus(ctx sdk.Context, address sdk.AccAddress) { - status := h.tssKeeper.GetStatus(ctx, address) - h.emitSetTSSStatus(status) -} - // handleSetTSSGroup implements emitter handler events related to group. func (h *Hook) handleSetTSSGroup(ctx sdk.Context, gid tss.GroupID) { group := h.tssKeeper.MustGetGroup(ctx, gid) @@ -208,57 +167,6 @@ func (h *Hook) handleSetTSSGroup(ctx sdk.Context, gid tss.GroupID) { } } -// handleInitTSSReplacement implements emitter handler for init replacement event. -func (h *Hook) handleInitTSSReplacement(ctx sdk.Context, evMap common.EvMap) { - rids := evMap[types.EventTypeReplacement+"."+types.AttributeKeyReplacementID] - for _, rid := range rids { - id := uint64(common.Atoi(rid)) - r, err := h.tssKeeper.GetReplacement(ctx, id) - if err != nil { - panic(err) - } - - h.emitNewTSSReplacement(r) - } -} - -// handleUpdateTSSReplacementStatus implements emitter handler events related to replacements. -func (h *Hook) handleUpdateTSSReplacementStatus(ctx sdk.Context, rid uint64) { - r, err := h.tssKeeper.GetReplacement(ctx, rid) - if err != nil { - panic(err) - } - if r.Status == types.REPLACEMENT_STATUS_SUCCESS { - h.handleSetTSSGroup(ctx, r.CurrentGroupID) - } - - h.emitUpdateTSSReplacementStatus(ctx, rid, r.Status) -} - -// handleTSSMsgActivate implements emitter handler for MsgActivate of TSS. -func (h *Hook) handleTSSMsgActivate( - ctx sdk.Context, msg *types.MsgActivate, -) { - acc, err := sdk.AccAddressFromBech32(msg.Address) - if err != nil { - panic(err) - } - - h.handleUpdateTSSStatus(ctx, acc) -} - -// handleTSSMsgHealthCheck implements emitter handler for MsgHealthCheck of TSS. -func (h *Hook) handleTSSMsgHealthCheck( - ctx sdk.Context, msg *types.MsgHealthCheck, -) { - acc, err := sdk.AccAddressFromBech32(msg.Address) - if err != nil { - panic(err) - } - - h.handleUpdateTSSStatus(ctx, acc) -} - // handleTSSMsgSubmitDEs implements emitter handler for MsgSubmitDEs of TSS. func (h *Hook) handleTSSMsgSubmitDEs( ctx sdk.Context, msg *types.MsgSubmitDEs, @@ -268,5 +176,5 @@ func (h *Hook) handleTSSMsgSubmitDEs( panic(err) } - h.handleUpdateTSSStatus(ctx, acc) + h.handleUpdateBandtssStatus(ctx, acc) } diff --git a/hooks/request/types.go b/hooks/request/types.go index 59dda3cdf..7e4ade7a6 100644 --- a/hooks/request/types.go +++ b/hooks/request/types.go @@ -245,7 +245,6 @@ func (r Request) QueryRequestResponse() types.QueryRequestResponse { ibcChannel, r.ExecuteGas, 0, - 0, "", nil, ) diff --git a/proto/bandchain/v1/oracle/proof.proto b/proto/bandchain/v1/oracle/proof.proto index 3951061b2..8f736f177 100644 --- a/proto/bandchain/v1/oracle/proof.proto +++ b/proto/bandchain/v1/oracle/proof.proto @@ -128,40 +128,39 @@ message BlockRelayProof { // MultiStoreProof stores a compact of other Cosmos-SDK modules' storage hash in multistore to // compute (in combination with oracle store hash) Tendermint's application state hash at a given block. // -// ___________________[AppHash]_________________ -// / \ -// ___________[N19]____________ ____[N20]______ -// / \ / \ -// ____[N15]____ ____[N16]______ _[N17]__ _[N18]_ -// / \ / \ / \ / \ -// __[N8]_ __[N9]_ _[N10]_ _[N11]_ [N12] [N13] [N14] [M] -// / \ / \ / \ / \ / \ / \ / \ -// [N0] [N1] [N2] [N3] [N4] [N5] [N6] [N7] [G] [H] [I] [J] [K] [L] -// / \ / \ / \ / \ / \ / \ / \ / \ -// [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [A] [B] [C] [D] [E] [F] +// __________________________[AppHash]__________________________ +// / \ +// ___________[N21]____________ ___________[N22]____________ +// / \ / \ +// _____[N18]_____ ____[N19]______ ____[N20]______ [O] +// / \ / \ / \ +// _[N12]_ _[N13]_ _[N14]_ _[N15]_ _[N16]_ _[N17]_ +// / \ / \ / \ / \ / \ / \ +// [N0] [N1] [N2] [N3] [N4] [N5] [N6] [N7] [N8] [N9] [N10] [N11] +// / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ +// [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] // -// [0] - acc (auth) [1] - authz [2] - bank [3] - capability [4] - consensus [5] - crisis -// [6] - dist [7] - evidence [8] - feegrant [9] - globalfee [A] - gov [B] - group -// [C] - ibccore [D] - icahost [E] - mint [F] - oracle [G] - params [H] - rollingseed -// [I] - slashing [J] - staking [K] - transfer [L] - tss [M] - upgrade +// [0] - acc (auth) [1] - authz [2] - bandtss [3] - bank [4] - capability [5] - consensus +// [6] - crisis [7] - dist [8] - evidence [9] - feeds [A] - feegrant [B] - globalfee +// [C] - gov [D] - group [E] - ibccore [F] - icahost [G] - mint [H] - oracle +// [I] - params [J] - rollingseed [K] - slashing [L] - staking [M] - transfer [N] - tss +// [O] - upgrade // // Notice that NOT all leaves of the Merkle tree are needed in order to compute the Merkle -// root hash, since we only want to validate the correctness of [F] In fact, only -// [E], [N6], [N10], [N15], and [N20] are needed in order to compute [AppHash]. +// root hash, since we only want to validate the correctness of [H] In fact, only +// [G], [N9], [N17], [O], and [N21] are needed in order to compute [AppHash]. message MultiStoreProof { bytes oracle_iavl_state_hash = 1 [ (gogoproto.customname) = "OracleIAVLStateHash", (gogoproto.casttype) = "github.com/cometbft/cometbft/libs/bytes.HexBytes" ]; bytes mint_store_merkle_hash = 2 [(gogoproto.casttype) = "github.com/cometbft/cometbft/libs/bytes.HexBytes"]; - bytes ibc_to_icahost_stores_merkle_hash = 3 + bytes params_to_rollingseed_stores_merkle_hash = 3 [(gogoproto.casttype) = "github.com/cometbft/cometbft/libs/bytes.HexBytes"]; - bytes feegrant_to_group_stores_merkle_hash = 4 - [(gogoproto.casttype) = "github.com/cometbft/cometbft/libs/bytes.HexBytes"]; - bytes auth_to_evidence_stores_merkle_hash = 5 - [(gogoproto.casttype) = "github.com/cometbft/cometbft/libs/bytes.HexBytes"]; - bytes params_to_upgrade_stores_merkle_hash = 6 + bytes slashing_to_tss_stores_merkle_hash = 4 [(gogoproto.casttype) = "github.com/cometbft/cometbft/libs/bytes.HexBytes"]; + bytes upgrade_store_merkle_hash = 5 [(gogoproto.casttype) = "github.com/cometbft/cometbft/libs/bytes.HexBytes"]; + bytes auth_to_icahost_stores_merkle_hash = 6 [(gogoproto.casttype) = "github.com/cometbft/cometbft/libs/bytes.HexBytes"]; } // BlockHeaderMerkleParts stores a group of hashes using for computing Tendermint's block diff --git a/proto/bandtss/v1beta1/bandtss.proto b/proto/bandtss/v1beta1/bandtss.proto index a80e59499..823ac58bd 100644 --- a/proto/bandtss/v1beta1/bandtss.proto +++ b/proto/bandtss/v1beta1/bandtss.proto @@ -17,7 +17,7 @@ message Member { string address = 1; // is_active is a flag to indicate whether a member is active or not. bool is_active = 2; - // since is a block timestamp when a member has been activated/deactivated/jailed + // since is a block timestamp when a member is deactivated google.protobuf.Timestamp since = 3 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; // last_active is a latest block timestamp when a member is active google.protobuf.Timestamp last_active = 4 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; @@ -32,14 +32,14 @@ message Signing { // fee is the tokens that will be paid per signer for this bandtss signing. repeated cosmos.base.v1beta1.Coin fee = 2 [(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; - // requester is the address of requester who paid for the Bandtss signing. + // requester is the address who pays the Bandtss signing. string requester = 3; // current_group_signing_id is a tss signing ID of a current group. uint64 current_group_signing_id = 4 [ (gogoproto.customname) = "CurrentGroupSigningID", (gogoproto.casttype) = "github.com/bandprotocol/chain/v2/pkg/tss.SigningID" ]; - // replacing_group_signing_id is a tss signing ID of the replacing group. + // replacing_group_signing_id is a tss signing ID of a replacing group, if any. uint64 replacing_group_signing_id = 5 [ (gogoproto.customname) = "ReplacingGroupSigningID", (gogoproto.casttype) = "github.com/bandprotocol/chain/v2/pkg/tss.SigningID" @@ -78,11 +78,11 @@ enum ReplacementStatus { // REPLACEMENT_STATUS_UNSPECIFIED is the status of a group replacement that has not been specified. REPLACEMENT_STATUS_UNSPECIFIED = 0; - // REPLACEMENT_STATUS_WAITING_SIGNING is the status of a group replacement that is waiting - // current group to sign the replacement message. - REPLACEMENT_STATUS_WAITING_SIGNING = 1; - // REPLACEMENT_STATUS_WAITING_REPLACE is the status of a group replacement that is waiting - // to be replaced in the protocol. + // REPLACEMENT_STATUS_WAITING_SIGN is the status of a group replacement that waits members in + // a current group to sign the replacement message. + REPLACEMENT_STATUS_WAITING_SIGN = 1; + // REPLACEMENT_STATUS_WAITING_REPLACE is the status of a group replacement that a current group + // approved to be replaced but waits for the replacement to be executed. REPLACEMENT_STATUS_WAITING_REPLACE = 2; // REPLACEMENT_STATUS_SUCCESS is the status of a group replacement that has success in the protocol. REPLACEMENT_STATUS_SUCCESS = 3; diff --git a/proto/bandtss/v1beta1/genesis.proto b/proto/bandtss/v1beta1/genesis.proto index af4ef5b7e..f6300599f 100644 --- a/proto/bandtss/v1beta1/genesis.proto +++ b/proto/bandtss/v1beta1/genesis.proto @@ -13,7 +13,7 @@ option go_package = "github.com/bandprotocol/chain/v2/x/bandtss/types"; message GenesisState { // params defines all the paramiters of the module. Params params = 1 [(gogoproto.nullable) = false]; - // members is an array containing member information. + // members is an array containing members information. repeated Member members = 2 [(gogoproto.nullable) = false]; // current_group_id is the current group id of the module. uint64 current_group_id = 3 [ @@ -24,7 +24,7 @@ message GenesisState { uint64 signing_count = 4; // signings is the bandtss signing info. repeated Signing signings = 5 [(gogoproto.nullable) = false]; - // signing_request_mappings is the list of mapping between tss signing id and bandtss signing id. + // signing_id_mappings is the list of mapping between tss signing id and bandtss signing id. repeated SigningIDMappingGenesis signing_id_mappings = 6 [(gogoproto.nullable) = false, (gogoproto.customname) = "SigningIDMappings"]; // replacement is the replacement information of the current group and new group. @@ -33,14 +33,14 @@ message GenesisState { // Params defines the set of module parameters. message Params { - // active_duration is the duration where a member can be active without interaction. + // active_duration is the duration where a member is active without interaction. google.protobuf.Duration active_duration = 1 [(gogoproto.stdduration) = true, (gogoproto.nullable) = false]; - // reward_percentage is the percentage of block rewards allocated to active TSS validators after being allocated to - // oracle rewards. + // reward_percentage is the percentage of block rewards allocated to active TSS members. + // The reward proportion is calculated after being allocated to oracle rewards. uint64 reward_percentage = 2 [(gogoproto.customname) = "RewardPercentage"]; - // inactive_penalty_duration is the duration where a member cannot activate back after inactive. + // inactive_penalty_duration is the duration where a member cannot activate back after being set to inactive. google.protobuf.Duration inactive_penalty_duration = 3 [(gogoproto.stdduration) = true, (gogoproto.nullable) = false]; - // fee is the tokens that will be paid per signing. + // fee is the tokens that will be paid per signer. repeated cosmos.base.v1beta1.Coin fee = 4 [(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; } diff --git a/proto/bandtss/v1beta1/query.proto b/proto/bandtss/v1beta1/query.proto index bd49376ec..c538a087b 100644 --- a/proto/bandtss/v1beta1/query.proto +++ b/proto/bandtss/v1beta1/query.proto @@ -13,12 +13,12 @@ option go_package = "github.com/bandprotocol/chain/v2/x/bandtss/types"; // Query defines the gRPC querier service. service Query { - // Params queries parameters of Bandtss module + // Params queries parameters of bandtss module rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { option (google.api.http).get = "/bandtss/v1beta1/params"; } - // IsGrantee queries grant of account on this granter. + // IsGrantee queries whether granter grants the grantee. rpc IsGrantee(QueryIsGranteeRequest) returns (QueryIsGranteeResponse) { option (google.api.http).get = "/bandtss/v1beta1/is_grantee/{granter}/{grantee}"; } @@ -28,7 +28,7 @@ service Query { option (google.api.http).get = "/bandtss/v1beta1/members"; } - // Member queries the member information of the address. + // Member queries the member information of the given address. rpc Member(QueryMemberRequest) returns (QueryMemberResponse) { option (google.api.http).get = "/bandtss/v1beta1/members/{address}"; } @@ -38,7 +38,7 @@ service Query { option (google.api.http).get = "/bandtss/v1beta1/current_group"; } - // Signing queries the signing result of the signing request. + // Signing queries the signing result of the given signing request ID. rpc Signing(QuerySigningRequest) returns (QuerySigningResponse) { option (google.api.http).get = "/bandtss/v1beta1/signings/{signing_id}"; } @@ -131,7 +131,7 @@ message QuerySigningResponse { // fee is the total tokens that will be paid for this bandtss signing. repeated cosmos.base.v1beta1.Coin fee = 1 [(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; - // requester is the address of requester who paid for the Bandtss signing. + // requester is the address of requester who paid for bandtss signing. string requester = 2; // current_group_signing_result is the signing result from the current group. .tss.v1beta1.SigningResult current_group_signing_result = 3; diff --git a/proto/bandtss/v1beta1/tx.proto b/proto/bandtss/v1beta1/tx.proto index c2645734a..6c57cab4d 100644 --- a/proto/bandtss/v1beta1/tx.proto +++ b/proto/bandtss/v1beta1/tx.proto @@ -18,16 +18,16 @@ service Msg { // CreateGroup creates a new group with a list of members. rpc CreateGroup(MsgCreateGroup) returns (MsgCreateGroupResponse); - // ReplaceGroup replaces the group with another group. + // ReplaceGroup replaces the current group with another group. rpc ReplaceGroup(MsgReplaceGroup) returns (MsgReplaceGroupResponse); // RequestSignature submits a general message to be signed by a specific group. rpc RequestSignature(MsgRequestSignature) returns (MsgRequestSignatureResponse); - // Activate activates the status of the group's member. + // Activate activates the status of the sender. rpc Activate(MsgActivate) returns (MsgActivateResponse); - // HealthCheck marks last active of the mebmer. + // HealthCheck marks last active of the sender. rpc HealthCheck(MsgHealthCheck) returns (MsgHealthCheckResponse); // UpdateParams updates the x/bandtss parameters. @@ -55,7 +55,7 @@ message MsgReplaceGroup { option (cosmos.msg.v1.signer) = "authority"; option (amino.name) = "bandtss/MsgReplaceGroup"; - // new_group_id is the ID of the group that want to replace, and subsequently remove this group. + // new_group_id is the ID of the group that want to replace. uint64 new_group_id = 1 [ (gogoproto.customname) = "NewGroupID", (gogoproto.casttype) = "github.com/bandprotocol/chain/v2/pkg/tss.GroupID" @@ -87,7 +87,7 @@ message MsgRequestSignature { // MsgRequestSignatureResponse is response data for MsgRequestSignature message message MsgRequestSignatureResponse {} -// MsgActivate is a message used to activate the status of the group's address. +// MsgActivate is a message used to activate the status of the sender. message MsgActivate { option (cosmos.msg.v1.signer) = "address"; option (amino.name) = "bandtss/MsgActivate"; @@ -99,7 +99,7 @@ message MsgActivate { // MsgActivateResponse is response data for MsgActivate message message MsgActivateResponse {} -// MsgHealthCheck is a message used to show active status if the address is still active. +// MsgHealthCheck is a message used to show if the address is still active. message MsgHealthCheck { option (cosmos.msg.v1.signer) = "address"; option (amino.name) = "bandtss/MsgHealthCheck"; @@ -118,10 +118,9 @@ message MsgUpdateParams { // params defines the x/tss parameters to update. Params params = 1 [(gogoproto.nullable) = false]; - // authority is the address of the governance account. + // authority is the address that controls the module (defaults to x/gov unless overwritten). string authority = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; } -// MsgUpdateParamsResponse defines the response structure for executing a -// MsgUpdateParams message. +// MsgUpdateParamsResponse defines the response structure for executing a MsgUpdateParams message. message MsgUpdateParamsResponse {} diff --git a/proto/feeds/v1beta1/feeds.proto b/proto/feeds/v1beta1/feeds.proto new file mode 100644 index 000000000..b8a50c21c --- /dev/null +++ b/proto/feeds/v1beta1/feeds.proto @@ -0,0 +1,129 @@ +syntax = "proto3"; +package feeds.v1beta1; + +option go_package = "github.com/bandprotocol/chain/v2/x/feeds/types"; + +import "cosmos_proto/cosmos.proto"; +import "gogoproto/gogo.proto"; + +// Signal is the data structure that contains signal id and power of that signal. +message Signal { + option (gogoproto.equal) = true; + + // ID is the id of the signal. + string id = 1 [(gogoproto.customname) = "ID"]; + + // Power is the power of the corresponding signal id. + int64 power = 2; +} + +// DelegatorSignals is the data structure that contains array of signals of a delegator. +message DelegatorSignals { + // Delegator is the address of the delegator of this signals. + string delegator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // Signals is a list of signals submit by the delegator. + repeated Signal signals = 2 [(gogoproto.nullable) = false]; +} + +// Feed is a structure that holds a signal id, its total power, and its calculated interval. +message Feed { + option (gogoproto.equal) = true; + + // SignalID is the unique string that identifies the unit of feed. + string signal_id = 1 [(gogoproto.customname) = "SignalID"]; + + // Power is the power of the corresponding feed. + int64 power = 2; + + // Interval is the interval of the price feed. + int64 interval = 3; + + // LastIntervalUpdateTimestamp is the timestamp of the last time interval is updated. + int64 last_interval_update_timestamp = 4; + + // DeviationInThousandth is the maximum deviation value the feed can tolerate, expressed in thousandths. + int64 deviation_in_thousandth = 5; +} + +// PriceStatus is a structure that defines the price status of a price. +enum PriceStatus { + option (gogoproto.goproto_enum_prefix) = false; + + // PRICE_STATUS_UNSPECIFIED is an unspecified price status. + PRICE_STATUS_UNSPECIFIED = 0 [(gogoproto.enumvalue_customname) = "PriceStatusUnspecified"]; + + // PRICE_STATUS_UNSUPPORTED is an unsupported price status. + PRICE_STATUS_UNSUPPORTED = 1 [(gogoproto.enumvalue_customname) = "PriceStatusUnsupported"]; + + // PRICE_STATUS_UNAVAILABLE is an unavailable price status. + PRICE_STATUS_UNAVAILABLE = 2 [(gogoproto.enumvalue_customname) = "PriceStatusUnavailable"]; + + // PRICE_STATUS_AVAILABLE is an available price status. + PRICE_STATUS_AVAILABLE = 3 [(gogoproto.enumvalue_customname) = "PriceStatusAvailable"]; +} + +// Price is a structure that defines the price of a signal id. +message Price { + option (gogoproto.equal) = true; + + // PriceStatus is the price status of a signal id. + PriceStatus price_status = 1; + + // SignalID is the signal id of the price. + string signal_id = 2 [(gogoproto.customname) = "SignalID"]; + + // Price is the price of the signal id. + uint64 price = 3; + + // Timestamp is the timestamp at which the price was aggregated. + int64 timestamp = 4; +} + +// SubmitPrice is a structure that defines the submit price of a signal id. +message SubmitPrice { + option (gogoproto.equal) = true; + + // PriceStatus is the price status of a signal id. + PriceStatus price_status = 1; + + // SignalID is the signal id of the price. + string signal_id = 2 [(gogoproto.customname) = "SignalID"]; + + // Price is the price submitted by the validator. + uint64 price = 3; +} + +// ValidatorPrice is a structure that defines the price submitted by a validator for a signal id. +message ValidatorPrice { + option (gogoproto.equal) = true; + + // PriceStatus is the price status of a price submitted. + PriceStatus price_status = 1; + + // Validator is the validator address. + string validator = 2; + + // SignalID is the signal id of the price. + string signal_id = 3 [(gogoproto.customname) = "SignalID"]; + + // Price is the price submitted by the validator. + uint64 price = 4; + + // Timestamp is the timestamp at which the price was submitted. + int64 timestamp = 5; +} + +// PriceService is a structure that defines the information of price service. +message PriceService { + option (gogoproto.equal) = true; + + // Hash is the hash of the price service. + string hash = 1; + + // Version is the version of the price service. + string version = 2; + + // Url is the URL of the price service. + string url = 3; +} diff --git a/proto/feeds/v1beta1/genesis.proto b/proto/feeds/v1beta1/genesis.proto new file mode 100644 index 000000000..195cb8588 --- /dev/null +++ b/proto/feeds/v1beta1/genesis.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; +package feeds.v1beta1; + +option go_package = "github.com/bandprotocol/chain/v2/x/feeds/types"; + +import "gogoproto/gogo.proto"; +import "feeds/v1beta1/params.proto"; +import "feeds/v1beta1/feeds.proto"; + +// GenesisState is a structure that defines the feeds module's genesis state. +message GenesisState { + // Params is all parameters of the module. + Params params = 1 [(gogoproto.nullable) = false]; + + // Feeds is a list of feeds that requires validators to submit the price. + repeated Feed feeds = 2 [(gogoproto.nullable) = false]; + + // PriceService is the information about price service. + PriceService price_service = 3 [(gogoproto.nullable) = false]; + + // DelegatorSignals is a list of delegator signals submitted by delegators. + repeated DelegatorSignals delegator_signals = 4 [(gogoproto.nullable) = false]; +} diff --git a/proto/feeds/v1beta1/params.proto b/proto/feeds/v1beta1/params.proto new file mode 100644 index 000000000..60a3df0a6 --- /dev/null +++ b/proto/feeds/v1beta1/params.proto @@ -0,0 +1,46 @@ +syntax = "proto3"; +package feeds.v1beta1; + +option go_package = "github.com/bandprotocol/chain/v2/x/feeds/types"; + +import "gogoproto/gogo.proto"; +import "cosmos_proto/cosmos.proto"; + +// Params is the data structure that keeps the parameters of the feeds module. +message Params { + option (gogoproto.equal) = true; // Use gogoproto.equal for proto3 message equality checks + option (gogoproto.goproto_stringer) = false; // Disable stringer generation for better control + + // Admin is the address of the admin that is allowed to perform operations on modules. + string admin = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // AllowableBlockTimeDiscrepancy is the allowed discrepancy (in seconds) between validator price timestamp and + // block_time. + int64 allowable_block_time_discrepancy = 2; + + // TransitionTime is the time (in seconds) given for validators to adapt to changing in feed's interval. + int64 transition_time = 3; + + // MinInterval is the minimum limit of every feeds' interval (in seconds). + // If the calculated interval is lower than this, it will be capped at this value. + int64 min_interval = 4; + + // MaxInterval is the maximum limit of every feeds' interval (in seconds). + // If the calculated interval of a feed is higher than this, it will not be recognized as a supported feed. + int64 max_interval = 5; + + // PowerThreshold is the amount of minimum power required to put feed in the supported list. + int64 power_threshold = 6; + + // MaxSupportedFeeds is the maximum number of feeds supported at a time. + int64 max_supported_feeds = 7; + + // CooldownTime represents the duration (in seconds) during which validators are prohibited from sending new prices. + int64 cooldown_time = 8; + + // MinDeviationInThousandth is the minimum limit of every feeds' deviation (in thousandth). + int64 min_deviation_in_thousandth = 9; + + // MaxDeviationInThousandth is the maximum limit of every feeds' deviation (in thousandth). + int64 max_deviation_in_thousandth = 10; +} diff --git a/proto/feeds/v1beta1/query.proto b/proto/feeds/v1beta1/query.proto new file mode 100644 index 000000000..9e0cd7c89 --- /dev/null +++ b/proto/feeds/v1beta1/query.proto @@ -0,0 +1,192 @@ +syntax = "proto3"; +package feeds.v1beta1; + +option go_package = "github.com/bandprotocol/chain/v2/x/feeds/types"; + +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "cosmos_proto/cosmos.proto"; +import "cosmos/base/query/v1beta1/pagination.proto"; +import "feeds/v1beta1/feeds.proto"; +import "feeds/v1beta1/params.proto"; + +// Query defines the gRPC querier service. +service Query { + // Prices is a RPC method that returns all prices. + rpc Prices(QueryPricesRequest) returns (QueryPricesResponse) { + option (google.api.http).get = "/feeds/v1beta1/prices"; + } + + // Price is a RPC method that returns price by signal id. + rpc Price(QueryPriceRequest) returns (QueryPriceResponse) { + option (google.api.http).get = "/feeds/v1beta1/prices/{signal_id}"; + } + + // ValidatorPrices is a RPC method that returns prices of a validator. + rpc ValidatorPrices(QueryValidatorPricesRequest) returns (QueryValidatorPricesResponse) { + option (google.api.http).get = "/feeds/v1beta1/validators/{validator}/prices"; + } + + // ValidatorPrice is a RPC method that returns price of validator by signal id. + rpc ValidatorPrice(QueryValidatorPriceRequest) returns (QueryValidatorPriceResponse) { + option (google.api.http).get = "/feeds/v1beta1/prices/{signal_id}/validators/{validator}"; + } + + // ValidValidator is a RPC method that returns flag to show if the validator is required to send prices. + rpc ValidValidator(QueryValidValidatorRequest) returns (QueryValidValidatorResponse) { + option (google.api.http).get = "/feeds/v1beta1/validators/{validator}"; + } + + // Feeds is a RPC method that returns all feeds. + rpc Feeds(QueryFeedsRequest) returns (QueryFeedsResponse) { + option (google.api.http).get = "/feeds/v1beta1/feeds"; + } + + // Params is a RPC method that returns all parameters of the module. + rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { + option (google.api.http).get = "/feeds/v1beta1/params"; + } + + // PriceService is a RPC method that returns information of price service. + rpc PriceService(QueryPriceServiceRequest) returns (QueryPriceServiceResponse) { + option (google.api.http).get = "/feeds/v1beta1/price-service"; + } + + // DelegatorSignals is a RPC method that returns signals of a delegator + rpc DelegatorSignals(QueryDelegatorSignalsRequest) returns (QueryDelegatorSignalsResponse) { + option (google.api.http).get = "/feeds/v1beta1/delegators/{delegator}/signals"; + } + + // SupportedFeeds is a RPC method that return list of currect supported feeds + rpc SupportedFeeds(QuerySupportedFeedsRequest) returns (QuerySupportedFeedsResponse) { + option (google.api.http).get = "/feeds/v1beta1/supported-feeds"; + } +} + +// QueryPricesRequest is the request type for the Query/Prices RPC method. +message QueryPricesRequest { + // SignalIDs is a List of signal ids to query prices for. + repeated string signal_ids = 1; + + // Pagination is the pagination for the request. + cosmos.base.query.v1beta1.PageRequest pagination = 2; +} + +// QueryPricesResponse is the response type for the Query/Prices RPC method. +message QueryPricesResponse { + // Prices is a list of prices. + repeated Price prices = 1; + + // Pagination is the pagination information in the response. + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + +// QueryPriceRequest is the request type for the Query/Price RPC method. +message QueryPriceRequest { + // SignalID is the signal id to query the price for. + string signal_id = 1; +} + +// QueryPriceResponse is the response type for the Query/Price RPC method. +message QueryPriceResponse { + // Price is the aggregated price of the signal id. + Price price = 1 [(gogoproto.nullable) = false]; + + // ValidatorPrices is a list of prices from each validator. + repeated ValidatorPrice validator_prices = 2 [(gogoproto.nullable) = false]; +} + +// QueryValidatorPricesRequest is the request type for the Query/ValidatorPrices RPC method. +message QueryValidatorPricesRequest { + // Validator is the validator address to query prices for. + string validator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; +} + +// QueryValidatorPricesResponse is the response type for the Query/ValidatorPrices RPC method. +message QueryValidatorPricesResponse { + // ValidatorPrices is a list of prices submitted by the validator. + repeated ValidatorPrice validator_prices = 1 [(gogoproto.nullable) = false]; +} + +// QueryValidatorPriceRequest is the request type for the Query/ValidatorPrice RPC method. +message QueryValidatorPriceRequest { + // SignalID is the signal id to query the price for. + string signal_id = 1; + + // Validator is the validator address to query the price for. + string validator = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; +} + +// QueryValidatorPriceResponse is the response type for the Query/ValidatorPrice RPC method. +message QueryValidatorPriceResponse { + // ValidatorPrice is the requested price submitted by the validator. + ValidatorPrice validator_price = 1 [(gogoproto.nullable) = false]; +} + +// QueryValidValidatorRequest is the request type for the Query/ValidValidator RPC method. +message QueryValidValidatorRequest { + // Validator is the validator address to query the flag. + string validator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; +} + +// QueryValidValidatorResponse is the response type for the Query/ValidValidator RPC method. +message QueryValidValidatorResponse { + // Valid is a valid flag. + bool valid = 1; +} + +// QueryFeedsRequest is the request type for the Query/Feeds RPC method. +message QueryFeedsRequest { + // SignalIDs is a list of signal ids to query. + repeated string signal_ids = 1; + + // Pagination is the pagination for the request. + cosmos.base.query.v1beta1.PageRequest pagination = 2; +} + +// QueryFeedsResponse is the response type for the Query/Feeds RPC method. +message QueryFeedsResponse { + // Feeds is a list of feeds. + repeated Feed feeds = 1; + + // Pagination is the pagination information in the response. + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + +// QueryParamsRequest is the request type for the Query/Params RPC method. +message QueryParamsRequest {} + +// QueryParamsResponse is the response type for the Query/Params RPC method. +message QueryParamsResponse { + // Params is the parameters of the module. + Params params = 1 [(gogoproto.nullable) = false]; +} + +// QueryPriceServiceRequest is the request type for the Query/PriceService RPC method. +message QueryPriceServiceRequest {} + +// QueryPriceServiceResponse is the response type for the Query/PriceService RPC method. +message QueryPriceServiceResponse { + // PriceService is the information about price service. + PriceService price_service = 1 [(gogoproto.nullable) = false]; +} + +// QueryDelegatorSignalsRequest is the request type for the Query/DelegatorSignals RPC method +message QueryDelegatorSignalsRequest { + // Delegator is the delegator address to query signal for. + string delegator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; +} + +// QueryDelegatorSignalsResponse is the response type for the Query/DelegatorSignals RPC method +message QueryDelegatorSignalsResponse { + repeated Signal signals = 1 [(gogoproto.nullable) = false]; +} + +// QuerySupportedFeedsRequest is the request type for the Query/SupportedFeeds RPC method +message QuerySupportedFeedsRequest {} + +// QuerySupportedFeedsResponse is the response type for the Query/SupportedFeeds RPC method +message QuerySupportedFeedsResponse { + // Feeds is a list of feeds. + repeated Feed feeds = 1 [(gogoproto.nullable) = false]; +} diff --git a/proto/feeds/v1beta1/tx.proto b/proto/feeds/v1beta1/tx.proto new file mode 100644 index 000000000..b408127af --- /dev/null +++ b/proto/feeds/v1beta1/tx.proto @@ -0,0 +1,88 @@ +syntax = "proto3"; +package feeds.v1beta1; + +option go_package = "github.com/bandprotocol/chain/v2/x/feeds/types"; + +import "gogoproto/gogo.proto"; +import "feeds/v1beta1/feeds.proto"; +import "feeds/v1beta1/params.proto"; +import "cosmos_proto/cosmos.proto"; +import "cosmos/msg/v1/msg.proto"; +import "amino/amino.proto"; + +// Msg defines the feeds Msg service. +service Msg { + // SubmitPrices is a RPC method to submit prices + rpc SubmitPrices(MsgSubmitPrices) returns (MsgSubmitPricesResponse); + + // UpdatePriceService is a RPC method to update price service information + rpc UpdatePriceService(MsgUpdatePriceService) returns (MsgUpdatePriceServiceResponse); + + // UpdateParams is a RPC method to update parameters + rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); + + // SubmitSignals is a RPC method to signal ids and their powers + rpc SubmitSignals(MsgSubmitSignals) returns (MsgSubmitSignalsResponse); +} + +// MsgSubmitSignals is the transaction message to submit signals +message MsgSubmitSignals { + option (cosmos.msg.v1.signer) = "delegator"; + option (amino.name) = "feeds/MsgSubmitSignals"; + + // Delegator is the address of the delegator that want to submit signals + string delegator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + // Signals is a list of submitted signal + repeated Signal signals = 2 [(gogoproto.nullable) = false]; +} + +// MsgSubmitPricesResponse is the response type for the Msg/SubmitSignals RPC method. +message MsgSubmitSignalsResponse {} + +// MsgSubmitPrices is the transaction message to submit multiple prices. +message MsgSubmitPrices { + option (cosmos.msg.v1.signer) = "validator"; + option (amino.name) = "feeds/MsgSubmitPrices"; + + // Validator is the address of the validator that is performing the operation. + string validator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // Timestamp is the timestamp use as reference of the data. + int64 timestamp = 2; + + // Prices is a list of prices to submit. + repeated SubmitPrice prices = 3 [(gogoproto.nullable) = false]; +} + +// MsgSubmitPricesResponse is the response type for the Msg/SubmitPrices RPC method. +message MsgSubmitPricesResponse {} + +// MsgUpdatePriceService is the transaction message to update price service's information. +message MsgUpdatePriceService { + option (cosmos.msg.v1.signer) = "authority"; + option (amino.name) = "feeds/MsgUpdateParams"; + + // Admin is the address of the admin that is performing the operation. + string admin = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // PriceService is the information of price service. + PriceService price_service = 2 [(gogoproto.nullable) = false]; +} + +// MsgUpdatePriceServiceResponse is the response type for the Msg/UpdatePriceService RPC method. +message MsgUpdatePriceServiceResponse {} + +// MsgUpdateParams is the transaction message to update parameters. +message MsgUpdateParams { + option (cosmos.msg.v1.signer) = "authority"; + option (amino.name) = "feeds/MsgUpdateParams"; + + // Authority is the address of the governance account. + string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // Params is the x/feeds parameters to update. + Params params = 2 [(gogoproto.nullable) = false]; +} + +// MsgUpdateParamsResponse is the response type for the Msg/UpdateParams RPC method. +message MsgUpdateParamsResponse {} diff --git a/proto/oracle/v1/oracle.proto b/proto/oracle/v1/oracle.proto index c4afd522b..4dc6a912e 100644 --- a/proto/oracle/v1/oracle.proto +++ b/proto/oracle/v1/oracle.proto @@ -105,17 +105,12 @@ message Request { IBCChannel ibc_channel = 9 [(gogoproto.customname) = "IBCChannel"]; // ExecuteGas is amount of gas to reserve for executing uint64 execute_gas = 10; - // TSSGroupID is ID of the group that assign for sign the result data on tss module. - uint64 tss_group_id = 11 [ - (gogoproto.customname) = "TSSGroupID", - (gogoproto.casttype) = "github.com/bandprotocol/chain/v2/pkg/tss.GroupID" - ]; // TSSEncodeType is the encode type of oracle result that will be sent to TSS. - EncodeType tss_encode_type = 12 [(gogoproto.customname) = "TSSEncodeType"]; - // request is the address of requester - string requester = 13; - // fee_limit is the fee left for paying fee in this request. - repeated cosmos.base.v1beta1.Coin fee_limit = 14 + EncodeType tss_encode_type = 11 [(gogoproto.customname) = "TSSEncodeType"]; + // Requester is the address of person who requests the data. + string requester = 12; + // FeeLimit is the maximum tokens that will be paid for this request. + repeated cosmos.base.v1beta1.Coin fee_limit = 13 [(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; } @@ -176,13 +171,8 @@ message OracleRequestPacketData { uint64 prepare_gas = 7; // ExecuteGas is amount of gas to reserve for executing uint64 execute_gas = 8; - // TSSGroupID is ID of the group that assign for sign the result data on tss module. - uint64 tss_group_id = 9 [ - (gogoproto.customname) = "TSSGroupID", - (gogoproto.casttype) = "github.com/bandprotocol/chain/v2/pkg/tss.GroupID" - ]; // TSSEncodeType is the encode type of oracle result that will be sent to TSS. - EncodeType tss_encode_type = 10 [(gogoproto.customname) = "TSSEncodeType"]; + EncodeType tss_encode_type = 9 [(gogoproto.customname) = "TSSEncodeType"]; } // OracleRequestPacketAcknowledgement encodes an oracle request acknowledgement @@ -261,7 +251,7 @@ message Result { // SigningResult encodes a result of signing of request message SigningResult { option (gogoproto.equal) = true; - // signing_id is the id of the signing + // signing_id is the id of the bandtss signing uint64 signing_id = 1 [ (gogoproto.customname) = "SigningID", (gogoproto.casttype) = "github.com/bandprotocol/chain/v2/x/bandtss/types.SigningID" @@ -381,18 +371,18 @@ message PriceResult { int64 resolve_time = 5; } -// OracleResultSignatureOrder defines a request id to request TSS signature from the oracle result. +// OracleResultSignatureOrder defines a request id to request bandtss signature from the oracle result. message OracleResultSignatureOrder { option (gogoproto.goproto_getters) = false; - // RequestID is BandChain's unique identifier for this oracle request. + // RequestID is oracle's unique identifier for this oracle request. uint64 request_id = 1 [(gogoproto.customname) = "RequestID", (gogoproto.casttype) = "RequestID"]; - // EncodeType is encoding type of the oracle result when it's sent to TSS + // EncodeType is encoding type of the oracle result when it's sent to bandtss EncodeType encode_type = 2; } -// EncodeType represent encode type of oracle result when using in TSS +// EncodeType represent encode type of oracle result when using in bandtss enum EncodeType { option (gogoproto.goproto_enum_prefix) = false; diff --git a/proto/oracle/v1/query.proto b/proto/oracle/v1/query.proto index be2de475b..47ef7e8b6 100644 --- a/proto/oracle/v1/query.proto +++ b/proto/oracle/v1/query.proto @@ -152,7 +152,7 @@ message QueryRequestResponse { repeated Report reports = 2 [(gogoproto.nullable) = false]; // Result is a final form of result data Result result = 3; - // Signing is the signing detail in the TSS module. + // Signing is the signing detail in the bandtss module. SigningResult signing = 4; } diff --git a/proto/oracle/v1/tx.proto b/proto/oracle/v1/tx.proto index 8ca775d01..942e0fb5c 100644 --- a/proto/oracle/v1/tx.proto +++ b/proto/oracle/v1/tx.proto @@ -67,13 +67,8 @@ message MsgRequestData { uint64 execute_gas = 8; // Sender is an account address of message sender. string sender = 9 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // TSSGroupID is ID of the group that assign for sign the result data on tss module. - uint64 tss_group_id = 10 [ - (gogoproto.customname) = "TSSGroupID", - (gogoproto.casttype) = "github.com/bandprotocol/chain/v2/pkg/tss.GroupID" - ]; - // TSSEncodeType is the encode type of oracle result that will be sent to TSS. - EncodeType tss_encode_type = 11 [(gogoproto.customname) = "TSSEncodeType"]; + // TSSEncodeType is the encode type of oracle result that will be sent to bandtss. + EncodeType tss_encode_type = 10 [(gogoproto.customname) = "TSSEncodeType"]; } // MsgRequestDataResponse is response data for MsgRequestData message diff --git a/proto/tss/v1beta1/genesis.proto b/proto/tss/v1beta1/genesis.proto index 59627930f..d7216632c 100644 --- a/proto/tss/v1beta1/genesis.proto +++ b/proto/tss/v1beta1/genesis.proto @@ -22,10 +22,8 @@ message GenesisState { uint64 signing_count = 5; // signings is an array containing information about each signing. repeated Signing signings = 6 [(gogoproto.nullable) = false]; - // de_queues is an array containing the de queues of all the addressres. - repeated DEQueue de_queues = 7 [(gogoproto.customname) = "DEQueues", (gogoproto.nullable) = false]; // des_genesis is an array containing the des of all the addressres. - repeated DEGenesis des_genesis = 8 [(gogoproto.customname) = "DEsGenesis", (gogoproto.nullable) = false]; + repeated DEGenesis des_genesis = 7 [(gogoproto.customname) = "DEsGenesis", (gogoproto.nullable) = false]; } // Params defines the set of module parameters. @@ -44,8 +42,6 @@ message Params { message DEGenesis { // address is the address of the de holder. string address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // index is the index for store de of the address - uint64 index = 2; // de defines the difference de this balance holds. - DE de = 3 [(gogoproto.customname) = "DE", (gogoproto.nullable) = false]; + DE de = 2 [(gogoproto.customname) = "DE", (gogoproto.nullable) = false]; } diff --git a/proto/tss/v1beta1/query.proto b/proto/tss/v1beta1/query.proto index a0e91f435..6616b66ed 100644 --- a/proto/tss/v1beta1/query.proto +++ b/proto/tss/v1beta1/query.proto @@ -25,7 +25,7 @@ service Query { option (google.api.http).get = "/tss/v1beta1/groups/{group_id}/members"; } - // IsGrantee queries grant of account on this granter. + // IsGrantee queries whether granter grants the grantee. rpc IsGrantee(QueryIsGranteeRequest) returns (QueryIsGranteeResponse) { option (google.api.http).get = "/tss/v1beta1/is_grantee/{granter}/{grantee}"; } @@ -35,17 +35,17 @@ service Query { option (google.api.http).get = "/tss/v1beta1/de_list/{address}"; } - // PendingGroups queries all pending groups for this address. + // PendingGroups queries all pending groups that waits the given address to submit a message. rpc PendingGroups(QueryPendingGroupsRequest) returns (QueryPendingGroupsResponse) { option (google.api.http).get = "/tss/v1beta1/pending_groups/{address}"; } - // PendingSignings queries all pending signs for this address. + // PendingSignings queries all pending requests that waits the given address to sign a message. rpc PendingSignings(QueryPendingSigningsRequest) returns (QueryPendingSigningsResponse) { option (google.api.http).get = "/tss/v1beta1/pending_signings/{address}"; } - // Signing queries signing details. + // Signing queries signing details from the given id. rpc Signing(QuerySigningRequest) returns (QuerySigningResponse) { option (google.api.http).get = "/tss/v1beta1/signings/{signing_id}"; } @@ -133,7 +133,7 @@ message QueryDEResponse { // QueryPendingGroupsRequest is the request type for the Query/PendingGroups RPC method. message QueryPendingGroupsRequest { - // address is the address for the request. + // address is the address of the member. string address = 1; } @@ -145,7 +145,7 @@ message QueryPendingGroupsResponse { // QueryPendingSigningsRequest is the request type for the Query/PendingSignings RPC method. message QueryPendingSigningsRequest { - // address is the address for the request. + // address is the address of the member. string address = 1; } diff --git a/scripts/bandtss/proposal_create_group.json b/scripts/bandtss/proposal_create_group.json index 3133e3e4c..b811a7f32 100755 --- a/scripts/bandtss/proposal_create_group.json +++ b/scripts/bandtss/proposal_create_group.json @@ -3,9 +3,9 @@ { "@type": "/bandtss.v1beta1.MsgCreateGroup", "members": [ - "band1nx0xkpnytk35wvflsg7gszf9smw3vaeauk248q", - "band1a22hgwm4tz8gj82y6zad3de2dcg5dpymtj20m5", - "band1t5x8hrmht463eq4m0xhfgz95h62dyvkq049eek" + "band1w8yurh6naeqg4mjx4zcs7hsu3fppwu0f4q4l7f", + "band1ph8tcg7ncxxx5vndfc9h6ffsn4st4whq3rn260", + "band1nx0xkpnytk35wvflsg7gszf9smw3vaeauk248q" ], "threshold": "2", "authority": "band10d07y265gmmuvt4z0w9aw880jnsr700jrdn8wm" diff --git a/scripts/bandtss/request_signature_oracle.sh b/scripts/bandtss/request_signature_oracle.sh index b372f4276..907b1143f 100755 --- a/scripts/bandtss/request_signature_oracle.sh +++ b/scripts/bandtss/request_signature_oracle.sh @@ -2,7 +2,6 @@ export WALLET_NAME=requester export REQUEST_ID=1 -export GROUP_ID=1 export ENCODE_TYPE=1 bandd tx bandtss request-signature oracle-result $REQUEST_ID $ENCODE_TYPE \ diff --git a/scripts/bandtss/request_signature_text.sh b/scripts/bandtss/request_signature_text.sh index f9800d61a..796a48f35 100755 --- a/scripts/bandtss/request_signature_text.sh +++ b/scripts/bandtss/request_signature_text.sh @@ -2,7 +2,6 @@ export WALLET_NAME=requester export TEXT=62616e6470726f746f636f6c -export GROUP_ID=1 bandd tx bandtss request-signature text $TEXT \ --from requester --keyring-backend test \ diff --git a/scripts/feeds/submit_signals.sh b/scripts/feeds/submit_signals.sh new file mode 100755 index 000000000..27c0ea57f --- /dev/null +++ b/scripts/feeds/submit_signals.sh @@ -0,0 +1,8 @@ +# delegate +bandd tx staking delegate bandvaloper1p40yh3zkmhcv0ecqp3mcazy83sa57rgjde6wec 1000000000000uband --from validator --keyring-backend test --gas-prices 0.0025uband -y --chain-id bandchain +bandd tx staking delegate bandvaloper1p40yh3zkmhcv0ecqp3mcazy83sa57rgjde6wec 1000000000000uband --from requester --keyring-backend test --gas-prices 0.0025uband -y --chain-id bandchain +sleep 3 + +# signal +bandd tx feeds signal crypto_price.ethusd:30000000000 crypto_price.usdtusd:30000000000 --from validator --keyring-backend test --gas-prices 0.0025uband -y --chain-id bandchain +bandd tx feeds signal crypto_price.ethusd:30000000000 crypto_price.usdtusd:29000000000 --from requester --keyring-backend test --gas-prices 0.0025uband -y --chain-id bandchain diff --git a/scripts/generate_genesis.sh b/scripts/generate_genesis.sh index 51859ce45..f0456ab80 100755 --- a/scripts/generate_genesis.sh +++ b/scripts/generate_genesis.sh @@ -8,22 +8,19 @@ echo "lock nasty suffer dirt dream fine fall deal curtain plate husband sound to | bandd keys add validator --recover --keyring-backend test echo "smile stem oven genius cave resource better lunar nasty moon company ridge brass rather supply used horn three panic put venue analyst leader comic" \ | bandd keys add requester --recover --keyring-backend test +echo "erase relief tree tobacco around knee concert toast diesel melody rule sight forum camera oil sick leopard valid furnace casino post dumb tag young" \ + | bandd keys add account1 --recover --keyring-backend test +echo "thought insane behind cool expand clarify strategy occur arrive broccoli middle despair foot cake genuine dawn goose abuse curve identify dinner derive genre effort" \ + | bandd keys add account2 --recover --keyring-backend test echo "drop video mention casual soldier ostrich resemble harvest casual step design gasp grunt lab meadow buzz envelope today spy cliff column habit fall eyebrow" \ - | bandd keys add tss1 --recover --keyring-backend test -echo "enlist electric thumb valve inherit visa ecology trust cake argue forward hidden thing analyst science treat ice lend pumpkin today ticket purchase process pioneer" \ - | bandd keys add tss2 --recover --keyring-backend test -echo "measure fence mail fluid olive cute empower fossil ahead manage snow marble dash citizen tourist skate assist solution bonus spend tip negative try eyebrow" \ - | bandd keys add tss3 --recover --keyring-backend test - + | bandd keys add account3 --recover --keyring-backend test # add accounts to genesis bandd genesis add-genesis-account validator 10000000000000uband --keyring-backend test bandd genesis add-genesis-account requester 10000000000000uband --keyring-backend test - -## add tss accounts to genesis -bandd genesis add-genesis-account tss1 10000000000000uband --keyring-backend test -bandd genesis add-genesis-account tss2 10000000000000uband --keyring-backend test -bandd genesis add-genesis-account tss3 10000000000000uband --keyring-backend test +bandd genesis add-genesis-account account1 10000000000000uband --keyring-backend test +bandd genesis add-genesis-account account2 10000000000000uband --keyring-backend test +bandd genesis add-genesis-account account3 10000000000000uband --keyring-backend test # register initial validators bandd genesis gentx validator 100000000uband \ diff --git a/scripts/group/create_group.sh b/scripts/group/create_group.sh new file mode 100755 index 000000000..78d3d8ecd --- /dev/null +++ b/scripts/group/create_group.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +export WALLET_NAME=account1 +export ENDPOINT=http://localhost:26657 + +BASEDIR=$(dirname "$0") + +TX_HASH=$(bandd tx group create-group $(bandd keys show $WALLET_NAME --address --keyring-backend test) "ipfs://" $BASEDIR/group_members.json \ + --from $WALLET_NAME \ + --node $ENDPOINT \ + -y --keyring-backend test --gas-prices 0.0025uband -b sync --output json | jq '.txhash'| tr -d '"') +echo "TX_HASH: $TX_HASH" + +sleep 3 + +GROUP_ID=$(bandd query tx $TX_HASH --node $ENDPOINT --output json | jq '.events' | jq -r '.[] | select(.type == "cosmos.group.v1.EventCreateGroup") | .attributes[0].value' | jq -r '.') +echo "GROUP_ID: $GROUP_ID" + diff --git a/scripts/group/create_policy.sh b/scripts/group/create_policy.sh new file mode 100755 index 000000000..88c58489a --- /dev/null +++ b/scripts/group/create_policy.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +export WALLET_NAME=account1 +export GROUP_ID=1 +export ENDPOINT=http://localhost:26657 + +BASEDIR=$(dirname "$0") + +TX_HASH=$(bandd tx group create-group-policy $(bandd keys show $WALLET_NAME --address --keyring-backend test) $GROUP_ID "{\"name\":\"policy 1\",\"description\":\"\"}" $BASEDIR/threshold_policy.json \ + --from $WALLET_NAME \ + --node $ENDPOINT \ + -y --keyring-backend test --gas-prices 0.0025uband -b sync --output json | jq '.txhash'| tr -d '"') +echo "TX_HASH: $TX_HASH" + +sleep 3 + +GROUP_POLICY_ADDRESS=$(bandd query tx $TX_HASH --node $ENDPOINT --output json | jq '.events' | jq -r '.[] | select(.type == "cosmos.group.v1.EventCreateGroupPolicy") | .attributes[0].value' | jq -r '.') +echo "GROUP_POLICY_ADDRESS: $GROUP_POLICY_ADDRESS" diff --git a/scripts/group/group_members.json b/scripts/group/group_members.json new file mode 100644 index 000000000..9b8b15560 --- /dev/null +++ b/scripts/group/group_members.json @@ -0,0 +1,14 @@ +{ + "members": [ + { + "address": "band1w8yurh6naeqg4mjx4zcs7hsu3fppwu0f4q4l7f", + "weight": "1", + "metadata": "account1" + }, + { + "address": "band1ph8tcg7ncxxx5vndfc9h6ffsn4st4whq3rn260", + "weight": "1", + "metadata": "account2" + } + ] +} diff --git a/scripts/group/threshold_policy.json b/scripts/group/threshold_policy.json new file mode 100644 index 000000000..570c10ecb --- /dev/null +++ b/scripts/group/threshold_policy.json @@ -0,0 +1,8 @@ +{ + "@type": "/cosmos.group.v1.ThresholdDecisionPolicy", + "threshold": "2", + "windows": { + "voting_period": "1m", + "min_execution_period": "0s" + } +} diff --git a/scripts/mockgen.sh b/scripts/mockgen.sh new file mode 100755 index 000000000..568846057 --- /dev/null +++ b/scripts/mockgen.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +mockgen_cmd="mockgen" +$mockgen_cmd -source=x/feeds/types/expected_keepers.go -package testutil -destination x/feeds/testutil/mock_expected_keepers.go +$mockgen_cmd -source x/bandtss/types/expected_keepers.go -package testutil -destination x/bandtss/testutil/mock_expected_keepers.go +$mockgen_cmd -source x/tss/types/expected_keepers.go -package testutil -destination x/tss/testutil/mock_expected_keepers.go diff --git a/scripts/start_grogu.sh b/scripts/start_grogu.sh new file mode 100755 index 000000000..d33b161c6 --- /dev/null +++ b/scripts/start_grogu.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +rm -rf ~/.grogu + +# config chain id +grogu config chain-id bandchain + +# add validator to grogu config +grogu config validator $(bandd keys show validator -a --bech val --keyring-backend test) + +# setup execution endpoint +grogu config price-service "rest:$PRICE_SERVICE_URL?timeout=10s" + +# setup broadcast-timeout to grogu config +grogu config broadcast-timeout "5m" + +# setup rpc-poll-interval to grogu config +grogu config rpc-poll-interval "1s" + +# setup max-try to grogu config +grogu config max-try 5 + +echo "y" | bandd tx oracle activate --from validator --gas-prices 0.0025uband --keyring-backend test --chain-id bandchain + +# wait for activation transaction success +sleep 2 + +for i in $(eval echo {1..1}) +do + # add reporter key + grogu keys add reporter$i +done + +# send band tokens to reporters +echo "y" | bandd tx bank send validator $(grogu keys list -a) 1000000uband --gas-prices 0.0025uband --keyring-backend test --chain-id bandchain + +# wait for sending band tokens transaction success +sleep 2 + +# add reporter to bandchain +echo "y" | bandd tx feeds add-grantees $(grogu keys list -a) --from validator --gas-prices 0.0025uband --keyring-backend test --chain-id bandchain + +# wait for addding reporter transaction success +sleep 2 + +# run grogu +grogu run diff --git a/x/bandtss/abci_test.go b/x/bandtss/abci_test.go index be3266845..edbbd7289 100644 --- a/x/bandtss/abci_test.go +++ b/x/bandtss/abci_test.go @@ -49,7 +49,6 @@ func TestReplaceGroups(t *testing.T) { initialSigning := tsstypes.Signing{ ID: signingID, Status: tsstypes.SIGNING_STATUS_SUCCESS, - // ... other fields ... } tssKeeper.SetGroup(ctx, initialCurrentGroup) diff --git a/x/bandtss/client/cli/query.go b/x/bandtss/client/cli/query.go index b2b3b0090..9d5d79de2 100644 --- a/x/bandtss/client/cli/query.go +++ b/x/bandtss/client/cli/query.go @@ -10,7 +10,7 @@ import ( "github.com/bandprotocol/chain/v2/x/bandtss/types" ) -// GetQueryCmd returns the cli query commands for the bandtss module. +// GetQueryCmd returns the cli query commands for this module func GetQueryCmd() *cobra.Command { cmd := &cobra.Command{ Use: types.ModuleName, @@ -32,7 +32,7 @@ func GetQueryCmd() *cobra.Command { return cmd } -// GetQueryCmdMember creates a CLI command for Query/Member. +// GetQueryCmdMember creates a CLI command for querying member information. func GetQueryCmdMember() *cobra.Command { cmd := &cobra.Command{ Use: "member [address]", @@ -89,6 +89,7 @@ func GetQueryCmdCurrentGroup() *cobra.Command { return cmd } +// GetQueryCmdParams creates a CLI command for querying module's parameter. func GetQueryCmdParams() *cobra.Command { cmd := &cobra.Command{ Use: "params", @@ -113,7 +114,7 @@ func GetQueryCmdParams() *cobra.Command { return cmd } -// GetQueryCmdSigning creates a CLI command for Query/Signing. +// GetQueryCmdSigning creates a CLI command for querying signing information. func GetQueryCmdSigning() *cobra.Command { cmd := &cobra.Command{ Use: "signing [id]", @@ -175,7 +176,7 @@ func GetQueryCmdReplacement() *cobra.Command { return cmd } -// GetQueryCmdIsGrantee creates a CLI command for Query/IsGrantee. +// GetQueryCmdIsGrantee creates a CLI command for querying whether a grantee is granted by a granter. func GetQueryCmdIsGrantee() *cobra.Command { cmd := &cobra.Command{ Use: "is-grantee [granter_address] [grantee_address]", diff --git a/x/bandtss/client/cli/tx.go b/x/bandtss/client/cli/tx.go index 4df0a1378..2d34511f5 100644 --- a/x/bandtss/client/cli/tx.go +++ b/x/bandtss/client/cli/tx.go @@ -23,7 +23,7 @@ const ( flagFeeLimit = "fee-limit" ) -// GetTxCmd returns a root CLI command handler for all x/bandtss transaction commands. +// NewTxCmd returns the transaction commands for this module func GetTxCmd(requestSignatureCmds []*cobra.Command) *cobra.Command { txCmd := &cobra.Command{ Use: types.ModuleName, @@ -60,7 +60,7 @@ func GetTxCmd(requestSignatureCmds []*cobra.Command) *cobra.Command { return txCmd } -// GetTxCmdRequestSignature creates a CLI command for CLI command for Msg/RequestSignature. +// GetTxCmdRequestSignature creates a CLI command for create a signature request. func GetTxCmdRequestSignature() *cobra.Command { cmd := &cobra.Command{ Use: "request-signature", @@ -74,7 +74,7 @@ func GetTxCmdRequestSignature() *cobra.Command { return cmd } -// GetTxCmdTextRequestSignature creates a CLI command for CLI command for Msg/TextRequestSignature. +// GetTxCmdTextRequestSignature creates a CLI command for create a signature on text message. func GetTxCmdTextRequestSignature() *cobra.Command { return &cobra.Command{ Use: "text [message]", @@ -121,7 +121,7 @@ func GetTxCmdTextRequestSignature() *cobra.Command { } } -// GetTxCmdActivate creates a CLI command for CLI command for Msg/Activate. +// GetTxCmdActivate creates a CLI command for activate the sender. func GetTxCmdActivate() *cobra.Command { cmd := &cobra.Command{ Use: "activate", @@ -150,7 +150,7 @@ func GetTxCmdActivate() *cobra.Command { return cmd } -// GetTxCmdHealthCheck creates a CLI command for CLI command for Msg/HealthCheck. +// GetTxCmdHealthCheck creates a CLI command for keep sender's status to be active. func GetTxCmdHealthCheck() *cobra.Command { cmd := &cobra.Command{ Use: "health-check", @@ -193,7 +193,7 @@ $ %s tx bandtss add-grantees band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun band1m5 version.AppName, ), ), - RunE: grant.AddGranteeCmd(types.GetBandtssGrantMsgTypes(), flagExpiration), + RunE: grant.AddGranteeCmd(types.BandtssGrantMsgTypes, flagExpiration), } cmd.Flags(). @@ -217,7 +217,7 @@ $ %s tx bandtss remove-grantees band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun band version.AppName, ), ), - RunE: grant.RemoveGranteeCmd(types.GetBandtssGrantMsgTypes()), + RunE: grant.RemoveGranteeCmd(types.BandtssGrantMsgTypes), } flags.AddTxFlagsToCmd(cmd) diff --git a/x/bandtss/client/request_signature_handler.go b/x/bandtss/client/request_signature_handler.go new file mode 100644 index 000000000..5b6ebda6d --- /dev/null +++ b/x/bandtss/client/request_signature_handler.go @@ -0,0 +1,20 @@ +package client + +import ( + "github.com/spf13/cobra" +) + +// function to create the cli handler +type CLIHandlerFn func() *cobra.Command + +// RequestSignatureHandler wraps CLIHandlerFn +type RequestSignatureHandler struct { + CLIHandler CLIHandlerFn +} + +// NewRequestSignatureHandler creates a new SignatureOrderHandler object +func NewRequestSignatureHandler(cliHandler CLIHandlerFn) RequestSignatureHandler { + return RequestSignatureHandler{ + CLIHandler: cliHandler, + } +} diff --git a/x/bandtss/genesis.go b/x/bandtss/genesis.go index a085cf74e..2ddfc91f8 100644 --- a/x/bandtss/genesis.go +++ b/x/bandtss/genesis.go @@ -7,7 +7,7 @@ import ( "github.com/bandprotocol/chain/v2/x/bandtss/types" ) -// InitGenesis performs genesis initialization for the bandtss module. +// InitGenesis performs genesis initialization for this module. func InitGenesis(ctx sdk.Context, k *keeper.Keeper, data *types.GenesisState) { if err := k.SetParams(ctx, data.Params); err != nil { panic(err) diff --git a/x/bandtss/genesis_test.go b/x/bandtss/genesis_test.go index 98acdd1c8..2e2641dd9 100644 --- a/x/bandtss/genesis_test.go +++ b/x/bandtss/genesis_test.go @@ -33,7 +33,7 @@ func TestExportGenesis(t *testing.T) { SigningID: tss.SigningID(1), CurrentGroupID: tss.GroupID(1), NewGroupID: tss.GroupID(2), - Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + Status: types.REPLACEMENT_STATUS_WAITING_SIGN, }, } diff --git a/x/bandtss/keeper/group.go b/x/bandtss/keeper/group.go index 59d8575db..f531120a2 100644 --- a/x/bandtss/keeper/group.go +++ b/x/bandtss/keeper/group.go @@ -33,7 +33,7 @@ func (k Keeper) CreateGroupReplacement( } replacement := k.GetReplacement(ctx) - if replacement.Status == types.REPLACEMENT_STATUS_WAITING_SIGNING || + if replacement.Status == types.REPLACEMENT_STATUS_WAITING_SIGN || replacement.Status == types.REPLACEMENT_STATUS_WAITING_REPLACE { return 0, types.ErrReplacementInProgress } @@ -48,7 +48,7 @@ func (k Keeper) CreateGroupReplacement( } // Execute the handler to process the replacement request. - msg, err := k.tssKeeper.HandleSigningContent(ctx, types.NewReplaceGroupSignatureOrder(newGroup.PubKey)) + msg, err := k.tssKeeper.ConvertContentToBytes(ctx, types.NewReplaceGroupSignatureOrder(newGroup.PubKey)) if err != nil { return 0, err } @@ -63,7 +63,7 @@ func (k Keeper) CreateGroupReplacement( CurrentPubKey: currentGroup.PubKey, NewGroupID: newGroupID, NewPubKey: newGroup.PubKey, - Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + Status: types.REPLACEMENT_STATUS_WAITING_SIGN, ExecTime: execTime, }) @@ -73,7 +73,8 @@ func (k Keeper) CreateGroupReplacement( sdk.NewAttribute(tsstypes.AttributeKeySigningID, fmt.Sprintf("%d", signing.ID)), sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", currentGroupID)), sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", newGroupID)), - sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_WAITING_SIGNING.String()), + sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_WAITING_SIGN.String()), + sdk.NewAttribute(types.AttributeKeyExecTime, replacement.ExecTime.Format(time.RFC3339)), ), ) @@ -86,13 +87,14 @@ func (k Keeper) HandleReplaceGroup(ctx sdk.Context, endBlockTime time.Time) erro replacement := k.GetReplacement(ctx) // check signing status and update replacement status. - if replacement.Status == types.REPLACEMENT_STATUS_WAITING_SIGNING { + if replacement.Status == types.REPLACEMENT_STATUS_WAITING_SIGN { signing, err := k.tssKeeper.GetSigning(ctx, replacement.SigningID) if err != nil { return err } - if signing.IsFailed() || + if signing.Status == tsstypes.SIGNING_STATUS_EXPIRED || + signing.Status == tsstypes.SIGNING_STATUS_FALLEN || (signing.Status == tsstypes.SIGNING_STATUS_WAITING && endBlockTime.After(replacement.ExecTime)) { return k.HandleFailReplacementSigning(ctx, replacement) } @@ -107,6 +109,7 @@ func (k Keeper) HandleReplaceGroup(ctx sdk.Context, endBlockTime time.Time) erro sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", replacement.CurrentGroupID)), sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", replacement.NewGroupID)), sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_WAITING_REPLACE.String()), + sdk.NewAttribute(types.AttributeKeyExecTime, replacement.ExecTime.Format(time.RFC3339)), ), ) } @@ -131,6 +134,7 @@ func (k Keeper) HandleFailReplacementSigning(ctx sdk.Context, replacement types. sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", replacement.CurrentGroupID)), sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", replacement.NewGroupID)), sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_FALLEN.String()), + sdk.NewAttribute(types.AttributeKeyExecTime, replacement.ExecTime.Format(time.RFC3339)), ), ) return nil @@ -157,13 +161,16 @@ func (k Keeper) ReplaceGroup(ctx sdk.Context, replacement types.Replacement) err // update replacement status and emit an event. replacement.Status = types.REPLACEMENT_STATUS_SUCCESS k.SetReplacement(ctx, replacement) + + newGroup, err := k.tssKeeper.GetGroup(ctx, replacement.NewGroupID) + if err != nil { + return err + } ctx.EventManager().EmitEvent( sdk.NewEvent( - types.EventTypeReplacement, - sdk.NewAttribute(tsstypes.AttributeKeySigningID, fmt.Sprintf("%d", replacement.SigningID)), - sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", replacement.CurrentGroupID)), - sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", replacement.NewGroupID)), - sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_SUCCESS.String()), + types.EventTypeNewGroupActivate, + sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", newGroup.ID)), + sdk.NewAttribute(types.AttributeKeyGroupPubKey, fmt.Sprintf("%v", newGroup.PubKey.String())), ), ) diff --git a/x/bandtss/keeper/group_test.go b/x/bandtss/keeper/group_test.go index f8e090ede..8ef6ca78c 100644 --- a/x/bandtss/keeper/group_test.go +++ b/x/bandtss/keeper/group_test.go @@ -36,7 +36,7 @@ func TestSuccessCreateGroupReplacement(t *testing.T) { k.SetCurrentGroupID(ctx, currentGroupID) s.MockTSSKeeper.EXPECT().GetGroup(ctx, currentGroupID).Return(currentGroup, nil).AnyTimes() s.MockTSSKeeper.EXPECT().GetGroup(ctx, newGroupID).Return(newGroup, nil).AnyTimes() - s.MockTSSKeeper.EXPECT().HandleSigningContent(ctx, types.NewReplaceGroupSignatureOrder(newGroup.PubKey)).Return([]byte("test-msg"), nil) + s.MockTSSKeeper.EXPECT().ConvertContentToBytes(ctx, types.NewReplaceGroupSignatureOrder(newGroup.PubKey)).Return([]byte("test-msg"), nil) s.MockTSSKeeper.EXPECT().CreateSigning(ctx, currentGroup, []byte("test-msg")).Return(expectSigning, nil) signingID, err := k.CreateGroupReplacement(ctx, newGroupID, execTime) @@ -49,7 +49,7 @@ func TestSuccessCreateGroupReplacement(t *testing.T) { NewGroupID: newGroupID, CurrentPubKey: currentGroup.PubKey, NewPubKey: newGroup.PubKey, - Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + Status: types.REPLACEMENT_STATUS_WAITING_SIGN, ExecTime: execTime, } actualReplacement := k.GetReplacement(ctx) @@ -78,7 +78,7 @@ func TestFailCreateGroupReplacement(t *testing.T) { name: "replacement in progress - waiting signing", preProcess: func(s *testutil.TestSuite) { s.Keeper.SetReplacement(s.Ctx, types.Replacement{ - Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + Status: types.REPLACEMENT_STATUS_WAITING_SIGN, }) }, input: input{ @@ -181,7 +181,7 @@ func TestHandleReplaceGroup(t *testing.T) { preProcess: func(s *testutil.TestSuite) { s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), - Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + Status: types.REPLACEMENT_STATUS_WAITING_SIGN, ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), }) s.MockTSSKeeper.EXPECT().GetSigning(s.Ctx, tss.SigningID(1)).Return(tsstypes.Signing{ @@ -190,7 +190,7 @@ func TestHandleReplaceGroup(t *testing.T) { }, nil) }, expectOut: expectOut{ - replacementStatus: types.REPLACEMENT_STATUS_WAITING_SIGNING, + replacementStatus: types.REPLACEMENT_STATUS_WAITING_SIGN, currentGroupID: currentGroupID, }, }, @@ -199,7 +199,7 @@ func TestHandleReplaceGroup(t *testing.T) { preProcess: func(s *testutil.TestSuite) { s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), - Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + Status: types.REPLACEMENT_STATUS_WAITING_SIGN, ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), }) s.MockTSSKeeper.EXPECT().GetSigning(s.Ctx, tss.SigningID(1)).Return(tsstypes.Signing{ @@ -217,7 +217,7 @@ func TestHandleReplaceGroup(t *testing.T) { preProcess: func(s *testutil.TestSuite) { s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), - Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + Status: types.REPLACEMENT_STATUS_WAITING_SIGN, ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), }) s.MockTSSKeeper.EXPECT().GetSigning(s.Ctx, tss.SigningID(1)).Return(tsstypes.Signing{ @@ -235,7 +235,7 @@ func TestHandleReplaceGroup(t *testing.T) { preProcess: func(s *testutil.TestSuite) { s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), - Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + Status: types.REPLACEMENT_STATUS_WAITING_SIGN, ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), }) s.MockTSSKeeper.EXPECT().GetSigning(s.Ctx, tss.SigningID(1)).Return(tsstypes.Signing{ @@ -253,7 +253,7 @@ func TestHandleReplaceGroup(t *testing.T) { preProcess: func(s *testutil.TestSuite) { s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), - Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + Status: types.REPLACEMENT_STATUS_WAITING_SIGN, ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), }) @@ -273,7 +273,7 @@ func TestHandleReplaceGroup(t *testing.T) { preProcess: func(s *testutil.TestSuite) { s.Keeper.SetReplacement(s.Ctx, types.Replacement{ SigningID: tss.SigningID(1), - Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + Status: types.REPLACEMENT_STATUS_WAITING_SIGN, ExecTime: s.Ctx.BlockTime().Add(10 * time.Minute), CurrentGroupID: currentGroupID, NewGroupID: tss.GroupID(2), @@ -290,6 +290,9 @@ func TestHandleReplaceGroup(t *testing.T) { s.MockTSSKeeper.EXPECT().MustGetMembers(s.Ctx, tss.GroupID(2)).Return([]tsstypes.Member{ {ID: 1, Address: "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun"}, }) + s.MockTSSKeeper.EXPECT().GetGroup(s.Ctx, tss.GroupID(2)).Return(tsstypes.Group{ + ID: tss.GroupID(2), + }, nil) }, expectOut: expectOut{ replacementStatus: types.REPLACEMENT_STATUS_SUCCESS, diff --git a/x/bandtss/keeper/grpc_query.go b/x/bandtss/keeper/grpc_query.go index 63eb4b977..c9cb04c5d 100644 --- a/x/bandtss/keeper/grpc_query.go +++ b/x/bandtss/keeper/grpc_query.go @@ -5,6 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -21,22 +22,21 @@ func NewQueryServer(k *Keeper) types.QueryServer { return queryServer{k: k} } -// IsGrantee function handles the request to check if a specific address is a grantee of another. +// IsGrantee queries if a specific address is a grantee of another. func (q queryServer) IsGrantee( goCtx context.Context, req *types.QueryIsGranteeRequest, ) (*types.QueryIsGranteeResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - // Convert granter and grantee addresses from Bech32 to AccAddress granter, err := sdk.AccAddressFromBech32(req.Granter) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid granter address: %s", err) } grantee, err := sdk.AccAddressFromBech32(req.Grantee) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", err) } return &types.QueryIsGranteeResponse{ @@ -44,20 +44,18 @@ func (q queryServer) IsGrantee( }, nil } -// Member function handles the request to get the member of a given account address. +// Member queries the member information of a given account address. func (q queryServer) Member( goCtx context.Context, req *types.QueryMemberRequest, ) (*types.QueryMemberResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - // Convert the address from Bech32 format to AccAddress format address, err := sdk.AccAddressFromBech32(req.Address) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", err) } - // Get member of the address member, err := q.k.GetMember(ctx, address) if err != nil { return nil, err @@ -68,7 +66,7 @@ func (q queryServer) Member( }, nil } -// Members function handles the request to get filtered members based on criteria. +// Members queries filtered members information based on criteria. func (q queryServer) Members( goCtx context.Context, req *types.QueryMembersRequest, @@ -100,7 +98,7 @@ func (q queryServer) Members( }, nil } -// CurrentGroup function handles the request to get the current group information. +// CurrentGroup queries the current group information. func (q queryServer) CurrentGroup( goCtx context.Context, req *types.QueryCurrentGroupRequest, @@ -126,7 +124,7 @@ func (q queryServer) CurrentGroup( }, nil } -// Replacement function handles the request to get the group replacement information. +// Replacement queries group replacement information. func (q queryServer) Replacement( goCtx context.Context, req *types.QueryReplacementRequest, @@ -140,7 +138,7 @@ func (q queryServer) Replacement( }, nil } -// Signing function handles the request to get the bandtss signing information. +// Signing queries the bandtss signing information. func (q queryServer) Signing( goCtx context.Context, req *types.QuerySigningRequest, @@ -174,7 +172,7 @@ func (q queryServer) Signing( }, nil } -// Params return parameters of bandtss module +// Params queries parameters of bandtss module func (q queryServer) Params(stdCtx context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { ctx := sdk.UnwrapSDKContext(stdCtx) diff --git a/x/bandtss/keeper/hooks.go b/x/bandtss/keeper/hooks.go index 202f45db1..35f9bc399 100644 --- a/x/bandtss/keeper/hooks.go +++ b/x/bandtss/keeper/hooks.go @@ -39,8 +39,9 @@ func (h Hooks) AfterCreatingGroupCompleted(ctx sdk.Context, group tsstypes.Group ctx.EventManager().EmitEvent( sdk.NewEvent( - types.EventTypeFirstGroupCreated, - sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", group.ID)), + types.EventTypeNewGroupActivate, + sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", group.ID)), + sdk.NewAttribute(types.AttributeKeyGroupPubKey, fmt.Sprintf("%v", group.PubKey.String())), ), ) diff --git a/x/bandtss/keeper/keeper.go b/x/bandtss/keeper/keeper.go index 40769b09c..7a55fa90c 100644 --- a/x/bandtss/keeper/keeper.go +++ b/x/bandtss/keeper/keeper.go @@ -43,7 +43,7 @@ func NewKeeper( authority string, feeCollectorName string, ) *Keeper { - // ensure Bandtss module account is set + // ensure bandtss module account is set if addr := authKeeper.GetModuleAddress(types.ModuleName); addr == nil { panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) } @@ -150,14 +150,8 @@ func (k Keeper) GetReplacement(ctx sdk.Context) types.Replacement { // CheckIsGrantee checks if the granter granted permissions to the grantee. func (k Keeper) CheckIsGrantee(ctx sdk.Context, granter sdk.AccAddress, grantee sdk.AccAddress) bool { - for _, msg := range types.GetBandtssGrantMsgTypes() { - cap, _ := k.authzKeeper.GetAuthorization( - ctx, - grantee, - granter, - msg, - ) - + for _, msg := range types.BandtssGrantMsgTypes { + cap, _ := k.authzKeeper.GetAuthorization(ctx, grantee, granter, msg) if cap == nil { return false } diff --git a/x/bandtss/keeper/keeper_test.go b/x/bandtss/keeper/keeper_test.go index ed42c67b5..1cdb51c2b 100644 --- a/x/bandtss/keeper/keeper_test.go +++ b/x/bandtss/keeper/keeper_test.go @@ -245,7 +245,7 @@ func (s *KeeperTestSuite) TestIsGrantee() { granter, _ := sdk.AccAddressFromBech32("band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun") // Save grant msgs to grantee - for _, m := range types.GetBandtssGrantMsgTypes() { + for _, m := range types.BandtssGrantMsgTypes { err := s.app.AuthzKeeper.SaveGrant(ctx, grantee, granter, authz.NewGenericAuthorization(m), &expTime) s.Require().NoError(err) } diff --git a/x/bandtss/keeper/msg_server.go b/x/bandtss/keeper/msg_server.go index 8f6ba5205..99e337001 100644 --- a/x/bandtss/keeper/msg_server.go +++ b/x/bandtss/keeper/msg_server.go @@ -3,8 +3,8 @@ package keeper import ( "context" - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/bandprotocol/chain/v2/x/bandtss/types" @@ -37,7 +37,7 @@ func (k msgServer) CreateGroup( for _, m := range req.Members { address, err := sdk.AccAddressFromBech32(m) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid member address: %s", err) } members = append(members, address) } @@ -76,7 +76,7 @@ func (k msgServer) RequestSignature( feePayer, err := sdk.AccAddressFromBech32(req.Sender) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } // Execute the handler to process the request. @@ -94,7 +94,7 @@ func (k msgServer) Activate(goCtx context.Context, msg *types.MsgActivate) (*typ address, err := sdk.AccAddressFromBech32(msg.Address) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } if err = k.ActivateMember(ctx, address); err != nil { @@ -118,7 +118,7 @@ func (k msgServer) HealthCheck( address, err := sdk.AccAddressFromBech32(msg.Address) if err != nil { - return nil, err + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } if err = k.SetLastActive(ctx, address); err != nil { @@ -139,8 +139,7 @@ func (k Keeper) UpdateParams( req *types.MsgUpdateParams, ) (*types.MsgUpdateParamsResponse, error) { if k.authority != req.Authority { - return nil, errors.Wrapf( - govtypes.ErrInvalidSigner, + return nil, govtypes.ErrInvalidSigner.Wrapf( "invalid authority; expected %s, got %s", k.authority, req.Authority, diff --git a/x/bandtss/keeper/msg_server_test.go b/x/bandtss/keeper/msg_server_test.go index fa53cd044..9fc87e00f 100644 --- a/x/bandtss/keeper/msg_server_test.go +++ b/x/bandtss/keeper/msg_server_test.go @@ -150,7 +150,7 @@ func (s *KeeperTestSuite) TestFailCreateGroup() { }, preProcess: func() {}, postProcess: func() {}, - expectErr: fmt.Errorf("members can not duplicate"), + expectErr: fmt.Errorf("duplicated member found within the list"), }, { name: "threshold more than members length", @@ -253,7 +253,7 @@ func (s *KeeperTestSuite) TestSuccessReplaceGroup() { s.Require().NoError(err) replacement_status := s.app.BandtssKeeper.GetReplacement(ctx).Status - s.Require().Equal(types.REPLACEMENT_STATUS_WAITING_SIGNING, replacement_status) + s.Require().Equal(types.REPLACEMENT_STATUS_WAITING_SIGN, replacement_status) } func (s *KeeperTestSuite) TestFailedRequestSignatureReq() { diff --git a/x/bandtss/keeper/params.go b/x/bandtss/keeper/params.go index 52dee27f3..2804b04dc 100644 --- a/x/bandtss/keeper/params.go +++ b/x/bandtss/keeper/params.go @@ -8,8 +8,7 @@ import ( // GetParams returns the current x/bandtss module parameters. func (k Keeper) GetParams(ctx sdk.Context) (p types.Params) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ParamsKeyPrefix) + bz := ctx.KVStore(k.storeKey).Get(types.ParamsKeyPrefix) if bz == nil { return p } @@ -24,9 +23,7 @@ func (k Keeper) SetParams(ctx sdk.Context, p types.Params) error { return err } - store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshal(&p) - store.Set(types.ParamsKeyPrefix, bz) + ctx.KVStore(k.storeKey).Set(types.ParamsKeyPrefix, k.cdc.MustMarshal(&p)) return nil } diff --git a/x/bandtss/keeper/signing.go b/x/bandtss/keeper/signing.go index 611778078..c05d21693 100644 --- a/x/bandtss/keeper/signing.go +++ b/x/bandtss/keeper/signing.go @@ -28,12 +28,12 @@ func (k Keeper) GetNextSigningID(ctx sdk.Context) types.SigningID { return types.SigningID(signingNumber) } -// SetSigning sets a signing of the Bandtss module. +// SetSigning sets a signing of the bandtss module. func (k Keeper) SetSigning(ctx sdk.Context, signing types.Signing) { - ctx.KVStore(k.storeKey).Set(types.SigningStoreKey(signing.ID), k.cdc.MustMarshal(&signing)) + ctx.KVStore(k.storeKey).Set(types.SigningInfoStoreKey(signing.ID), k.cdc.MustMarshal(&signing)) } -// AddSigning adds the Signing data to the store and returns the new Signing ID. +// AddSigning adds the signing data to the store and returns the new Signing ID. func (k Keeper) AddSigning(ctx sdk.Context, signing types.Signing) types.SigningID { signing.ID = k.GetNextSigningID(ctx) k.SetSigning(ctx, signing) @@ -50,7 +50,7 @@ func (k Keeper) AddSigning(ctx sdk.Context, signing types.Signing) types.Signing // GetSigning retrieves a bandtss signing info. func (k Keeper) GetSigning(ctx sdk.Context, id types.SigningID) (types.Signing, error) { - bz := ctx.KVStore(k.storeKey).Get(types.SigningStoreKey(id)) + bz := ctx.KVStore(k.storeKey).Get(types.SigningInfoStoreKey(id)) if bz == nil { return types.Signing{}, types.ErrSigningNotFound.Wrapf("signingID: %d", id) } @@ -133,7 +133,7 @@ func (k Keeper) HandleCreateSigning( feeLimit sdk.Coins, ) (types.SigningID, error) { // Execute the handler to process the request. - msg, err := k.tssKeeper.HandleSigningContent(ctx, content) + msg, err := k.tssKeeper.ConvertContentToBytes(ctx, content) if err != nil { return 0, err } @@ -197,7 +197,7 @@ func (k Keeper) HandleCreateSigning( } } - // save signingInfo + // save signing info bandtssSigningID := k.AddSigning(ctx, types.Signing{ Fee: feePerSigner, Requester: sender.String(), diff --git a/x/bandtss/keeper/signing_test.go b/x/bandtss/keeper/signing_test.go index 912424df9..1bb609f26 100644 --- a/x/bandtss/keeper/signing_test.go +++ b/x/bandtss/keeper/signing_test.go @@ -32,7 +32,7 @@ func TestHandleCreateSigning(t *testing.T) { err := k.SetParams(ctx, params) require.NoError(t, err) - s.MockTSSKeeper.EXPECT().HandleSigningContent(ctx, content).Return([]byte("test"), nil).AnyTimes() + s.MockTSSKeeper.EXPECT().ConvertContentToBytes(ctx, content).Return([]byte("test"), nil).AnyTimes() s.MockTSSKeeper.EXPECT().GetGroup(ctx, currentGroupID).Return(currentGroup, nil).AnyTimes() type input struct { @@ -209,7 +209,7 @@ func TestHandleCreateSigning(t *testing.T) { replaceGroupID := tss.GroupID(2) replacement := types.Replacement{ SigningID: tss.SigningID(1), - Status: types.REPLACEMENT_STATUS_WAITING_SIGNING, + Status: types.REPLACEMENT_STATUS_WAITING_SIGN, CurrentGroupID: currentGroupID, NewGroupID: replaceGroupID, } diff --git a/x/bandtss/keeper/validator.go b/x/bandtss/keeper/validator.go index a156b1b08..74c825434 100644 --- a/x/bandtss/keeper/validator.go +++ b/x/bandtss/keeper/validator.go @@ -50,7 +50,7 @@ func (k Keeper) AllocateTokens(ctx sdk.Context, previousVotes []abci.VoteInfo) { tssRewardRatio := sdk.NewDecWithPrec(int64(k.GetParams(ctx).RewardPercentage), 2) tssRewardInt, _ := totalFee.MulDecTruncate(tssRewardRatio).TruncateDecimal() - // Transfer the tss reward portion from fee collector to distr module. + // Transfer the reward from fee collector to distr module. err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, k.feeCollectorName, distrtypes.ModuleName, tssRewardInt) if err != nil { panic(err) diff --git a/x/bandtss/module.go b/x/bandtss/module.go index 4e8d646e2..f59a02e61 100644 --- a/x/bandtss/module.go +++ b/x/bandtss/module.go @@ -13,10 +13,10 @@ import ( "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" + bandtssclient "github.com/bandprotocol/chain/v2/x/bandtss/client" "github.com/bandprotocol/chain/v2/x/bandtss/client/cli" "github.com/bandprotocol/chain/v2/x/bandtss/keeper" "github.com/bandprotocol/chain/v2/x/bandtss/types" - tssclient "github.com/bandprotocol/chain/v2/x/tss/client" ) var ( @@ -26,11 +26,11 @@ var ( // AppModuleBasic defines the basic application module used by the bandtss module. type AppModuleBasic struct { - signatureOrderHandlers []tssclient.SignatureOrderHandler + signatureOrderHandlers []bandtssclient.RequestSignatureHandler } // NewAppModuleBasic creates a new AppModuleBasic object -func NewAppModuleBasic(signatureOrderHandlers ...tssclient.SignatureOrderHandler) AppModuleBasic { +func NewAppModuleBasic(signatureOrderHandlers ...bandtssclient.RequestSignatureHandler) AppModuleBasic { return AppModuleBasic{ signatureOrderHandlers: signatureOrderHandlers, } @@ -63,7 +63,7 @@ func (a AppModuleBasic) GetTxCmd() *cobra.Command { return cli.GetTxCmd(signatureOrderHandlers) } -func getSignatureOrderCLIHandlers(handlers []tssclient.SignatureOrderHandler) []*cobra.Command { +func getSignatureOrderCLIHandlers(handlers []bandtssclient.RequestSignatureHandler) []*cobra.Command { signatureOrderHandlers := make([]*cobra.Command, 0, len(handlers)) for _, handler := range handlers { signatureOrderHandlers = append(signatureOrderHandlers, handler.CLIHandler()) diff --git a/x/bandtss/testutil/mock_expected_keepers.go b/x/bandtss/testutil/mock_expected_keepers.go index 89a815f39..4a4716e1b 100644 --- a/x/bandtss/testutil/mock_expected_keepers.go +++ b/x/bandtss/testutil/mock_expected_keepers.go @@ -98,20 +98,6 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { return m.recorder } -// GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types0.Context, addr types0.AccAddress) types1.AccountI { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAccount", ctx, addr) - ret0, _ := ret[0].(types1.AccountI) - return ret0 -} - -// GetAccount indicates an expected call of GetAccount. -func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccount", reflect.TypeOf((*MockAccountKeeper)(nil).GetAccount), ctx, addr) -} - // GetModuleAccount mocks base method. func (m *MockAccountKeeper) GetModuleAccount(ctx types0.Context, name string) types1.ModuleAccountI { m.ctrl.T.Helper() @@ -177,20 +163,6 @@ func (mr *MockBankKeeperMockRecorder) GetAllBalances(ctx, addr any) *gomock.Call return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllBalances", reflect.TypeOf((*MockBankKeeper)(nil).GetAllBalances), ctx, addr) } -// GetBalance mocks base method. -func (m *MockBankKeeper) GetBalance(ctx types0.Context, addr types0.AccAddress, denom string) types0.Coin { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetBalance", ctx, addr, denom) - ret0, _ := ret[0].(types0.Coin) - return ret0 -} - -// GetBalance indicates an expected call of GetBalance. -func (mr *MockBankKeeperMockRecorder) GetBalance(ctx, addr, denom any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBalance", reflect.TypeOf((*MockBankKeeper)(nil).GetBalance), ctx, addr, denom) -} - // SendCoinsFromAccountToModule mocks base method. func (m *MockBankKeeper) SendCoinsFromAccountToModule(ctx types0.Context, senderAddr types0.AccAddress, recipientModule string, amt types0.Coins) error { m.ctrl.T.Helper() @@ -445,6 +417,21 @@ func (mr *MockTSSKeeperMockRecorder) ActivateMember(ctx, groupID, address any) * return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ActivateMember", reflect.TypeOf((*MockTSSKeeper)(nil).ActivateMember), ctx, groupID, address) } +// ConvertContentToBytes mocks base method. +func (m *MockTSSKeeper) ConvertContentToBytes(ctx types0.Context, content types.Content) ([]byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ConvertContentToBytes", ctx, content) + ret0, _ := ret[0].([]byte) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ConvertContentToBytes indicates an expected call of ConvertContentToBytes. +func (mr *MockTSSKeeperMockRecorder) ConvertContentToBytes(ctx, content any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConvertContentToBytes", reflect.TypeOf((*MockTSSKeeper)(nil).ConvertContentToBytes), ctx, content) +} + // CreateGroup mocks base method. func (m *MockTSSKeeper) CreateGroup(ctx types0.Context, members []types0.AccAddress, threshold uint64, moduleOwner string) (tss.GroupID, error) { m.ctrl.T.Helper() @@ -533,21 +520,6 @@ func (mr *MockTSSKeeperMockRecorder) GetMemberByAddress(ctx, groupID, address an return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMemberByAddress", reflect.TypeOf((*MockTSSKeeper)(nil).GetMemberByAddress), ctx, groupID, address) } -// GetPenalizedMembersExpiredGroup mocks base method. -func (m *MockTSSKeeper) GetPenalizedMembersExpiredGroup(ctx types0.Context, group types.Group) ([]types0.AccAddress, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPenalizedMembersExpiredGroup", ctx, group) - ret0, _ := ret[0].([]types0.AccAddress) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPenalizedMembersExpiredGroup indicates an expected call of GetPenalizedMembersExpiredGroup. -func (mr *MockTSSKeeperMockRecorder) GetPenalizedMembersExpiredGroup(ctx, group any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPenalizedMembersExpiredGroup", reflect.TypeOf((*MockTSSKeeper)(nil).GetPenalizedMembersExpiredGroup), ctx, group) -} - // GetPenalizedMembersExpiredSigning mocks base method. func (m *MockTSSKeeper) GetPenalizedMembersExpiredSigning(ctx types0.Context, signing types.Signing) ([]types0.AccAddress, error) { m.ctrl.T.Helper() @@ -593,21 +565,6 @@ func (mr *MockTSSKeeperMockRecorder) GetSigningResult(ctx, signingID any) *gomoc return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSigningResult", reflect.TypeOf((*MockTSSKeeper)(nil).GetSigningResult), ctx, signingID) } -// HandleSigningContent mocks base method. -func (m *MockTSSKeeper) HandleSigningContent(ctx types0.Context, content types.Content) ([]byte, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "HandleSigningContent", ctx, content) - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// HandleSigningContent indicates an expected call of HandleSigningContent. -func (mr *MockTSSKeeperMockRecorder) HandleSigningContent(ctx, content any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleSigningContent", reflect.TypeOf((*MockTSSKeeper)(nil).HandleSigningContent), ctx, content) -} - // MustGetMembers mocks base method. func (m *MockTSSKeeper) MustGetMembers(ctx types0.Context, groupID tss.GroupID) []types.Member { m.ctrl.T.Helper() diff --git a/x/bandtss/testutil/mock_keeper.go b/x/bandtss/testutil/mock_keeper.go index 5a99fadd6..6af34895b 100644 --- a/x/bandtss/testutil/mock_keeper.go +++ b/x/bandtss/testutil/mock_keeper.go @@ -19,7 +19,7 @@ import ( "github.com/bandprotocol/chain/v2/x/bandtss/types" ) -// NOTE: cannot put suite.Suite inside this struct, or else the test get timeout. +// TestSuite is a struct that embeds a *testing.T and provides a setup for a mock keeper type TestSuite struct { t *testing.T Keeper *keeper.Keeper @@ -36,6 +36,7 @@ type TestSuite struct { Authority sdk.AccAddress } +// NewTestSuite returns a new TestSuite object func NewTestSuite(t *testing.T) TestSuite { ctrl := gomock.NewController(t) key := sdk.NewKVStoreKey(types.StoreKey) diff --git a/x/bandtss/types/bandtss.pb.go b/x/bandtss/types/bandtss.pb.go index e0e97caf1..6e5f694cf 100644 --- a/x/bandtss/types/bandtss.pb.go +++ b/x/bandtss/types/bandtss.pb.go @@ -39,11 +39,11 @@ type ReplacementStatus int32 const ( // REPLACEMENT_STATUS_UNSPECIFIED is the status of a group replacement that has not been specified. REPLACEMENT_STATUS_UNSPECIFIED ReplacementStatus = 0 - // REPLACEMENT_STATUS_WAITING_SIGNING is the status of a group replacement that is waiting - // current group to sign the replacement message. - REPLACEMENT_STATUS_WAITING_SIGNING ReplacementStatus = 1 - // REPLACEMENT_STATUS_WAITING_REPLACE is the status of a group replacement that is waiting - // to be replaced in the protocol. + // REPLACEMENT_STATUS_WAITING_SIGN is the status of a group replacement that waits members in + // a current group to sign the replacement message. + REPLACEMENT_STATUS_WAITING_SIGN ReplacementStatus = 1 + // REPLACEMENT_STATUS_WAITING_REPLACE is the status of a group replacement that a current group + // approved to be replaced but waits for the replacement to be executed. REPLACEMENT_STATUS_WAITING_REPLACE ReplacementStatus = 2 // REPLACEMENT_STATUS_SUCCESS is the status of a group replacement that has success in the protocol. REPLACEMENT_STATUS_SUCCESS ReplacementStatus = 3 @@ -53,7 +53,7 @@ const ( var ReplacementStatus_name = map[int32]string{ 0: "REPLACEMENT_STATUS_UNSPECIFIED", - 1: "REPLACEMENT_STATUS_WAITING_SIGNING", + 1: "REPLACEMENT_STATUS_WAITING_SIGN", 2: "REPLACEMENT_STATUS_WAITING_REPLACE", 3: "REPLACEMENT_STATUS_SUCCESS", 4: "REPLACEMENT_STATUS_FALLEN", @@ -61,7 +61,7 @@ var ReplacementStatus_name = map[int32]string{ var ReplacementStatus_value = map[string]int32{ "REPLACEMENT_STATUS_UNSPECIFIED": 0, - "REPLACEMENT_STATUS_WAITING_SIGNING": 1, + "REPLACEMENT_STATUS_WAITING_SIGN": 1, "REPLACEMENT_STATUS_WAITING_REPLACE": 2, "REPLACEMENT_STATUS_SUCCESS": 3, "REPLACEMENT_STATUS_FALLEN": 4, @@ -81,7 +81,7 @@ type Member struct { Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` // is_active is a flag to indicate whether a member is active or not. IsActive bool `protobuf:"varint,2,opt,name=is_active,json=isActive,proto3" json:"is_active,omitempty"` - // since is a block timestamp when a member has been activated/deactivated/jailed + // since is a block timestamp when a member is deactivated Since time.Time `protobuf:"bytes,3,opt,name=since,proto3,stdtime" json:"since"` // last_active is a latest block timestamp when a member is active LastActive time.Time `protobuf:"bytes,4,opt,name=last_active,json=lastActive,proto3,stdtime" json:"last_active"` @@ -154,11 +154,11 @@ type Signing struct { ID SigningID `protobuf:"varint,1,opt,name=id,proto3,casttype=SigningID" json:"id,omitempty"` // fee is the tokens that will be paid per signer for this bandtss signing. Fee github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=fee,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"fee"` - // requester is the address of requester who paid for the Bandtss signing. + // requester is the address who pays the Bandtss signing. Requester string `protobuf:"bytes,3,opt,name=requester,proto3" json:"requester,omitempty"` // current_group_signing_id is a tss signing ID of a current group. CurrentGroupSigningID github_com_bandprotocol_chain_v2_pkg_tss.SigningID `protobuf:"varint,4,opt,name=current_group_signing_id,json=currentGroupSigningId,proto3,casttype=github.com/bandprotocol/chain/v2/pkg/tss.SigningID" json:"current_group_signing_id,omitempty"` - // replacing_group_signing_id is a tss signing ID of the replacing group. + // replacing_group_signing_id is a tss signing ID of a replacing group, if any. ReplacingGroupSigningID github_com_bandprotocol_chain_v2_pkg_tss.SigningID `protobuf:"varint,5,opt,name=replacing_group_signing_id,json=replacingGroupSigningId,proto3,casttype=github.com/bandprotocol/chain/v2/pkg/tss.SigningID" json:"replacing_group_signing_id,omitempty"` } @@ -388,59 +388,59 @@ func init() { proto.RegisterFile("bandtss/v1beta1/bandtss.proto", fileDescriptor var fileDescriptor_2effaef066b71284 = []byte{ // 867 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x55, 0xcd, 0x6e, 0xdb, 0x46, - 0x10, 0xd6, 0x4a, 0xb2, 0x64, 0xad, 0x52, 0x47, 0xdd, 0x36, 0x88, 0xac, 0x36, 0xa4, 0xa1, 0x02, - 0x85, 0x50, 0x20, 0x64, 0xa2, 0xf6, 0xe4, 0x9b, 0x28, 0xcb, 0x2e, 0x51, 0x9b, 0x71, 0x49, 0x19, + 0x10, 0xd6, 0x4a, 0xb2, 0x64, 0x8d, 0x52, 0x47, 0xdd, 0x36, 0x88, 0xac, 0x36, 0xa4, 0xa1, 0x00, + 0x85, 0x50, 0x20, 0x64, 0xa2, 0xf6, 0xe4, 0x9b, 0x28, 0xcb, 0xae, 0x50, 0x5b, 0x71, 0x49, 0x19, 0x05, 0x02, 0x14, 0x04, 0x7f, 0xd6, 0xcc, 0xc2, 0x12, 0xc9, 0x72, 0x97, 0xfe, 0x79, 0x83, 0x9c, - 0x8a, 0x3c, 0x42, 0x81, 0x5e, 0x8a, 0x9e, 0xfb, 0x10, 0x46, 0xd1, 0x02, 0x39, 0xf6, 0xc4, 0x14, - 0xf4, 0xa5, 0x8f, 0x50, 0xf8, 0x54, 0x70, 0x49, 0x5a, 0x6a, 0x22, 0x20, 0x3f, 0xed, 0x49, 0x3b, - 0x9a, 0x6f, 0x66, 0xbe, 0x6f, 0x66, 0x30, 0x84, 0xf7, 0x6c, 0xcb, 0x77, 0x19, 0xa5, 0xf2, 0xe9, - 0x43, 0x1b, 0x33, 0xeb, 0xa1, 0x5c, 0xd8, 0x52, 0x18, 0x05, 0x2c, 0x40, 0xb7, 0x4b, 0xb3, 0x70, - 0xf7, 0x3e, 0xf4, 0x02, 0x2f, 0xe0, 0x3e, 0x39, 0x7b, 0xe5, 0xb0, 0x9e, 0xe8, 0x05, 0x81, 0x37, - 0xc3, 0x32, 0xb7, 0xec, 0xf8, 0x58, 0x66, 0x64, 0x8e, 0x29, 0xb3, 0xe6, 0x61, 0x01, 0x10, 0x9c, - 0x80, 0xce, 0x03, 0x2a, 0xdb, 0x16, 0xc5, 0x37, 0xa5, 0x9c, 0x80, 0xf8, 0x85, 0x7f, 0x33, 0xf7, - 0x9b, 0x79, 0xe6, 0xdc, 0xc8, 0x5d, 0xfd, 0x4b, 0x00, 0x1b, 0x07, 0x78, 0x6e, 0xe3, 0x08, 0x75, - 0x61, 0xd3, 0x72, 0xdd, 0x08, 0x53, 0xda, 0x05, 0x5b, 0x60, 0xd0, 0xd2, 0x4b, 0x13, 0x7d, 0x04, - 0x5b, 0x84, 0x9a, 0x96, 0xc3, 0xc8, 0x29, 0xee, 0x56, 0xb7, 0xc0, 0x60, 0x5d, 0x5f, 0x27, 0x74, - 0xc4, 0x6d, 0xb4, 0x0d, 0xd7, 0x28, 0xf1, 0x1d, 0xdc, 0xad, 0x6d, 0x81, 0x41, 0x7b, 0xd8, 0x93, - 0x72, 0xb6, 0x52, 0xc9, 0x56, 0x9a, 0x96, 0x6c, 0x95, 0xf5, 0xcb, 0x44, 0xac, 0x3c, 0x7b, 0x21, - 0x02, 0x3d, 0x0f, 0x41, 0x13, 0xd8, 0x9e, 0x59, 0x94, 0x95, 0xa9, 0xeb, 0x6f, 0x91, 0x01, 0x66, - 0x81, 0x39, 0x85, 0xed, 0xfa, 0x5f, 0x3f, 0x88, 0xa0, 0xff, 0x7b, 0x0d, 0x36, 0x0d, 0xe2, 0xf9, - 0xc4, 0xf7, 0xd0, 0x27, 0xb0, 0x4a, 0x5c, 0x2e, 0xa3, 0xae, 0x7c, 0x90, 0x26, 0x62, 0x55, 0xdd, - 0xb9, 0x4e, 0xc4, 0x56, 0xe1, 0x56, 0x77, 0xf4, 0x2a, 0x71, 0xd1, 0xb7, 0xb0, 0x76, 0x8c, 0x33, - 0x41, 0xb5, 0x41, 0x7b, 0xb8, 0x29, 0x15, 0x7d, 0xc9, 0x9a, 0x58, 0x0e, 0x44, 0x1a, 0x07, 0xc4, - 0x57, 0x1e, 0x64, 0x45, 0x7f, 0x7e, 0x21, 0x0e, 0x3c, 0xc2, 0x9e, 0xc4, 0xb6, 0xe4, 0x04, 0xf3, - 0xa2, 0x89, 0xc5, 0xcf, 0x7d, 0xea, 0x9e, 0xc8, 0xec, 0x22, 0xc4, 0x94, 0x07, 0x50, 0x3d, 0xcb, - 0x8b, 0x3e, 0x86, 0xad, 0x08, 0x7f, 0x17, 0x63, 0xca, 0x70, 0xc4, 0x9b, 0xd3, 0xd2, 0x17, 0x7f, - 0xa0, 0xa7, 0x00, 0x76, 0x9d, 0x38, 0x8a, 0xb0, 0xcf, 0x4c, 0x2f, 0x0a, 0xe2, 0xd0, 0xa4, 0x39, - 0x39, 0x93, 0xb8, 0xbc, 0x11, 0x75, 0xe5, 0x51, 0x9a, 0x88, 0x77, 0xc6, 0x39, 0x66, 0x2f, 0x83, - 0xdc, 0xd0, 0xbf, 0x4e, 0xc4, 0xe1, 0x12, 0x99, 0x6c, 0x8d, 0x78, 0xb3, 0x9c, 0x60, 0x26, 0x3b, - 0x4f, 0x2c, 0xe2, 0xcb, 0xa7, 0x43, 0x39, 0x3c, 0xf1, 0xe4, 0x6c, 0xb9, 0x16, 0xa2, 0xef, 0x38, - 0x2b, 0x92, 0xb9, 0xe8, 0x7b, 0x00, 0x7b, 0x11, 0x0e, 0x67, 0x96, 0x93, 0x95, 0x7f, 0x85, 0xcc, - 0x1a, 0x27, 0xf3, 0x75, 0x9a, 0x88, 0x77, 0xf5, 0x12, 0xf5, 0xbf, 0xd0, 0xb9, 0x1b, 0xad, 0x4c, - 0xe7, 0x16, 0xf3, 0xfc, 0xbb, 0x0e, 0xdb, 0x79, 0x41, 0x3c, 0xc7, 0x3e, 0x43, 0x36, 0x84, 0x4b, - 0xac, 0xf2, 0xd9, 0x8e, 0xd3, 0xe5, 0xa9, 0xbe, 0x23, 0x8f, 0x16, 0xbd, 0x69, 0x45, 0x08, 0x3b, - 0xff, 0x1e, 0x0a, 0x71, 0xf9, 0xc2, 0xd7, 0x95, 0xdd, 0x34, 0x11, 0x37, 0x96, 0x87, 0xc1, 0xcb, - 0x3d, 0x78, 0xe3, 0x72, 0x45, 0x8c, 0xbe, 0xb1, 0x3c, 0x03, 0xd5, 0x45, 0x8f, 0xe1, 0xed, 0xb2, - 0x62, 0x18, 0xdb, 0xe6, 0x09, 0xbe, 0xe0, 0xbb, 0x72, 0x4b, 0x19, 0x5e, 0x27, 0xa2, 0xf4, 0xc6, - 0xe9, 0x0f, 0x03, 0xe2, 0x33, 0xfd, 0xbd, 0x22, 0xd5, 0x61, 0x6c, 0x7f, 0x85, 0x2f, 0x90, 0x0b, - 0x6f, 0xf9, 0xf8, 0x6c, 0xa1, 0x24, 0x5f, 0x2b, 0x25, 0x4d, 0x44, 0xa8, 0xe1, 0xb3, 0xff, 0xa2, - 0x02, 0xfa, 0x65, 0xbc, 0x8b, 0x74, 0xd8, 0xce, 0xaa, 0x94, 0xec, 0xd7, 0xde, 0x99, 0x7d, 0xcb, - 0xc7, 0x67, 0x05, 0xf3, 0x6d, 0xd8, 0xa0, 0xcc, 0x62, 0x31, 0xed, 0x36, 0xb6, 0xc0, 0x60, 0x63, - 0xd8, 0x97, 0x5e, 0x3a, 0x95, 0xd2, 0xd2, 0x66, 0x18, 0x1c, 0xa9, 0x17, 0x11, 0x68, 0x04, 0x5b, - 0xf8, 0x1c, 0x3b, 0x66, 0x76, 0x25, 0xbb, 0xcd, 0xb7, 0x38, 0x29, 0xeb, 0x59, 0x58, 0xe6, 0xe8, - 0x9f, 0xc3, 0x5e, 0x91, 0xff, 0x66, 0x33, 0x2d, 0x16, 0x47, 0xf8, 0x51, 0xe4, 0xe2, 0x08, 0x1d, - 0xc0, 0x66, 0x29, 0x16, 0x70, 0xb1, 0x5f, 0xbc, 0xd4, 0x43, 0x27, 0x98, 0x63, 0x66, 0x1f, 0xb3, - 0xc5, 0x63, 0x46, 0x6c, 0x2a, 0xdb, 0x17, 0x0c, 0x53, 0xe9, 0x4b, 0x7c, 0xae, 0x64, 0x0f, 0xbd, - 0x11, 0x72, 0xad, 0xdb, 0xed, 0x5f, 0x7f, 0xb9, 0xdf, 0x1c, 0x07, 0x3e, 0xc3, 0x3e, 0xfb, 0xec, - 0x37, 0x00, 0xdf, 0x7f, 0x45, 0x1a, 0xea, 0x43, 0x41, 0x9f, 0x1c, 0xee, 0x8f, 0xc6, 0x93, 0x83, - 0x89, 0x36, 0x35, 0x8d, 0xe9, 0x68, 0x7a, 0x64, 0x98, 0x47, 0x9a, 0x71, 0x38, 0x19, 0xab, 0xbb, - 0xea, 0x64, 0xa7, 0x53, 0x41, 0x9f, 0xc2, 0xfe, 0x0a, 0xcc, 0x37, 0x23, 0x75, 0xaa, 0x6a, 0x7b, - 0xa6, 0xa1, 0xee, 0x69, 0xaa, 0xb6, 0xd7, 0x01, 0xaf, 0xc1, 0x15, 0xae, 0x4e, 0x15, 0x09, 0xb0, - 0xb7, 0x02, 0x67, 0x1c, 0x8d, 0xc7, 0x13, 0xc3, 0xe8, 0xd4, 0xd0, 0x3d, 0xb8, 0xb9, 0xc2, 0xbf, - 0x3b, 0xda, 0xdf, 0x9f, 0x68, 0x9d, 0x7a, 0xaf, 0xfe, 0xf4, 0x47, 0xa1, 0xa2, 0x68, 0x3f, 0xa5, - 0x02, 0xb8, 0x4c, 0x05, 0xf0, 0x3c, 0x15, 0xc0, 0x9f, 0xa9, 0x00, 0x9e, 0x5d, 0x09, 0x95, 0xe7, - 0x57, 0x42, 0xe5, 0x8f, 0x2b, 0xa1, 0xf2, 0xf8, 0xf5, 0x7b, 0x77, 0x5e, 0x7e, 0x31, 0xf3, 0xf3, - 0x6a, 0x37, 0x38, 0xe4, 0xf3, 0x7f, 0x02, 0x00, 0x00, 0xff, 0xff, 0xbd, 0xaa, 0x16, 0x35, 0x59, + 0x8a, 0x3c, 0x42, 0x81, 0x5e, 0x8a, 0x9e, 0xfb, 0x10, 0x6e, 0x81, 0x02, 0x39, 0xf6, 0xc4, 0x14, + 0xf4, 0xa5, 0x8f, 0x50, 0xf8, 0x54, 0xf0, 0xcf, 0x56, 0x13, 0xa1, 0x4d, 0xdc, 0x9c, 0xb4, 0xa3, + 0xf9, 0x66, 0xe6, 0xfb, 0x66, 0x06, 0x43, 0xb8, 0x67, 0x1a, 0xae, 0xcd, 0x19, 0x93, 0x8f, 0x1f, + 0x99, 0x84, 0x1b, 0x8f, 0xe4, 0xdc, 0x96, 0xfc, 0xc0, 0xe3, 0x1e, 0xbe, 0x5d, 0x98, 0xb9, 0xbb, + 0xf3, 0xa1, 0xe3, 0x39, 0x5e, 0xea, 0x93, 0x93, 0x57, 0x06, 0xeb, 0x88, 0x8e, 0xe7, 0x39, 0x33, + 0x22, 0xa7, 0x96, 0x19, 0x1e, 0xca, 0x9c, 0xce, 0x09, 0xe3, 0xc6, 0xdc, 0xcf, 0x01, 0x82, 0xe5, + 0xb1, 0xb9, 0xc7, 0x64, 0xd3, 0x60, 0xe4, 0xaa, 0x94, 0xe5, 0x51, 0x37, 0xf7, 0xaf, 0x67, 0x7e, + 0x3d, 0xcb, 0x9c, 0x19, 0x99, 0xab, 0x7b, 0x8e, 0xa0, 0xb6, 0x47, 0xe6, 0x26, 0x09, 0x70, 0x1b, + 0xea, 0x86, 0x6d, 0x07, 0x84, 0xb1, 0x36, 0xda, 0x40, 0xbd, 0x86, 0x5a, 0x98, 0xf8, 0x23, 0x68, + 0x50, 0xa6, 0x1b, 0x16, 0xa7, 0xc7, 0xa4, 0x5d, 0xde, 0x40, 0xbd, 0x55, 0x75, 0x95, 0xb2, 0x41, + 0x6a, 0xe3, 0x4d, 0x58, 0x61, 0xd4, 0xb5, 0x48, 0xbb, 0xb2, 0x81, 0x7a, 0xcd, 0x7e, 0x47, 0xca, + 0xd8, 0x4a, 0x05, 0x5b, 0x69, 0x5a, 0xb0, 0x55, 0x56, 0xcf, 0x23, 0xb1, 0xf4, 0xfc, 0xa5, 0x88, + 0xd4, 0x2c, 0x04, 0x8f, 0xa0, 0x39, 0x33, 0x18, 0x2f, 0x52, 0x57, 0xdf, 0x22, 0x03, 0x24, 0x81, + 0x19, 0x85, 0xcd, 0xea, 0x9f, 0xdf, 0x8b, 0xa8, 0xfb, 0x5b, 0x05, 0xea, 0x1a, 0x75, 0x5c, 0xea, + 0x3a, 0xf8, 0x3e, 0x94, 0xa9, 0x9d, 0xca, 0xa8, 0x2a, 0x1f, 0xc4, 0x91, 0x58, 0x1e, 0x6f, 0x5d, + 0x46, 0x62, 0x23, 0x77, 0x8f, 0xb7, 0xd4, 0x32, 0xb5, 0xf1, 0x37, 0x50, 0x39, 0x24, 0x89, 0xa0, + 0x4a, 0xaf, 0xd9, 0x5f, 0x97, 0xf2, 0xbe, 0x24, 0x4d, 0x2c, 0x06, 0x22, 0x0d, 0x3d, 0xea, 0x2a, + 0x0f, 0x93, 0xa2, 0x3f, 0xbd, 0x14, 0x7b, 0x0e, 0xe5, 0x4f, 0x43, 0x53, 0xb2, 0xbc, 0x79, 0xde, + 0xc4, 0xfc, 0xe7, 0x01, 0xb3, 0x8f, 0x64, 0x7e, 0xe6, 0x13, 0x96, 0x06, 0x30, 0x35, 0xc9, 0x8b, + 0x3f, 0x86, 0x46, 0x40, 0xbe, 0x0d, 0x09, 0xe3, 0x24, 0x48, 0x9b, 0xd3, 0x50, 0xaf, 0xff, 0xc0, + 0xcf, 0x10, 0xb4, 0xad, 0x30, 0x08, 0x88, 0xcb, 0x75, 0x27, 0xf0, 0x42, 0x5f, 0x67, 0x19, 0x39, + 0x9d, 0xda, 0x69, 0x23, 0xaa, 0xca, 0xe3, 0x38, 0x12, 0xef, 0x0c, 0x33, 0xcc, 0x4e, 0x02, 0xb9, + 0xa2, 0x7f, 0x19, 0x89, 0xfd, 0x05, 0x32, 0xc9, 0x1a, 0xa5, 0xcd, 0xb2, 0xbc, 0x99, 0x6c, 0x3d, + 0x35, 0xa8, 0x2b, 0x1f, 0xf7, 0x65, 0xff, 0xc8, 0x91, 0x93, 0xe5, 0xba, 0x16, 0x7d, 0xc7, 0x5a, + 0x92, 0xcc, 0xc6, 0xdf, 0x21, 0xe8, 0x04, 0xc4, 0x9f, 0x19, 0x56, 0x52, 0xfe, 0x35, 0x32, 0x2b, + 0x29, 0x99, 0xaf, 0xe2, 0x48, 0xbc, 0xab, 0x16, 0xa8, 0x77, 0x42, 0xe7, 0x6e, 0xb0, 0x34, 0x9d, + 0x9d, 0xcf, 0xf3, 0xaf, 0x2a, 0x34, 0xb3, 0x82, 0x64, 0x4e, 0x5c, 0x8e, 0x4d, 0x80, 0x05, 0x56, + 0xd9, 0x6c, 0x87, 0xf1, 0xe2, 0x54, 0x6f, 0xc8, 0xa3, 0xc1, 0xae, 0x5a, 0xe1, 0x43, 0xeb, 0x9f, + 0x43, 0xa1, 0x76, 0xba, 0xf0, 0x55, 0x65, 0x3b, 0x8e, 0xc4, 0xb5, 0xc5, 0x61, 0xa4, 0xe5, 0x1e, + 0xbe, 0x71, 0xb9, 0x3c, 0x46, 0x5d, 0x5b, 0x9c, 0xc1, 0xd8, 0xc6, 0x4f, 0xe0, 0x76, 0x51, 0xd1, + 0x0f, 0x4d, 0xfd, 0x88, 0x9c, 0xa5, 0xbb, 0x72, 0x4b, 0xe9, 0x5f, 0x46, 0xa2, 0xf4, 0xc6, 0xe9, + 0xf7, 0x3d, 0xea, 0x72, 0xf5, 0xbd, 0x3c, 0xd5, 0x7e, 0x68, 0x7e, 0x49, 0xce, 0xb0, 0x0d, 0xb7, + 0x5c, 0x72, 0x72, 0xad, 0x24, 0x5b, 0x2b, 0x25, 0x8e, 0x44, 0x98, 0x90, 0x93, 0xff, 0xa3, 0x02, + 0xdc, 0x22, 0xde, 0xc6, 0x2a, 0x34, 0x93, 0x2a, 0x05, 0xfb, 0x95, 0x1b, 0xb3, 0x6f, 0xb8, 0xe4, + 0x24, 0x67, 0xbe, 0x09, 0x35, 0xc6, 0x0d, 0x1e, 0xb2, 0x76, 0x6d, 0x03, 0xf5, 0xd6, 0xfa, 0x5d, + 0xe9, 0x95, 0x53, 0x29, 0x2d, 0x6c, 0x86, 0x96, 0x22, 0xd5, 0x3c, 0x02, 0x0f, 0xa0, 0x41, 0x4e, + 0x89, 0xa5, 0x27, 0x57, 0xb2, 0x5d, 0x7f, 0x8b, 0x93, 0xb2, 0x9a, 0x84, 0x25, 0x8e, 0xee, 0x29, + 0x74, 0xf2, 0xfc, 0x57, 0x9b, 0x69, 0xf0, 0x30, 0x20, 0x8f, 0x03, 0x9b, 0x04, 0x78, 0x0f, 0xea, + 0x85, 0x58, 0x94, 0x8a, 0xfd, 0xfc, 0x95, 0x1e, 0x5a, 0xde, 0x9c, 0x70, 0xf3, 0x90, 0x5f, 0x3f, + 0x66, 0xd4, 0x64, 0xb2, 0x79, 0xc6, 0x09, 0x93, 0xbe, 0x20, 0xa7, 0x4a, 0xf2, 0x50, 0x6b, 0x7e, + 0xaa, 0x75, 0xb3, 0xf9, 0xeb, 0xcf, 0x0f, 0xea, 0x43, 0xcf, 0xe5, 0xc4, 0xe5, 0x9f, 0xfe, 0x82, + 0xe0, 0xfd, 0xd7, 0xa4, 0xe1, 0x2e, 0x08, 0xea, 0x68, 0x7f, 0x77, 0x30, 0x1c, 0xed, 0x8d, 0x26, + 0x53, 0x5d, 0x9b, 0x0e, 0xa6, 0x07, 0x9a, 0x7e, 0x30, 0xd1, 0xf6, 0x47, 0xc3, 0xf1, 0xf6, 0x78, + 0xb4, 0xd5, 0x2a, 0xe1, 0xfb, 0x20, 0x2e, 0xc1, 0x7c, 0x3d, 0x18, 0x4f, 0xc7, 0x93, 0x1d, 0x5d, + 0x1b, 0xef, 0x4c, 0x5a, 0x08, 0x7f, 0x02, 0xdd, 0x7f, 0x01, 0xe5, 0xae, 0x56, 0x19, 0x0b, 0xd0, + 0x59, 0x82, 0xd3, 0x0e, 0x86, 0xc3, 0x91, 0xa6, 0xb5, 0x2a, 0xf8, 0x1e, 0xac, 0x2f, 0xf1, 0x6f, + 0x0f, 0x76, 0x77, 0x47, 0x93, 0x56, 0xb5, 0x53, 0x7d, 0xf6, 0x83, 0x50, 0x52, 0x26, 0x3f, 0xc6, + 0x02, 0x3a, 0x8f, 0x05, 0xf4, 0x22, 0x16, 0xd0, 0x1f, 0xb1, 0x80, 0x9e, 0x5f, 0x08, 0xa5, 0x17, + 0x17, 0x42, 0xe9, 0xf7, 0x0b, 0xa1, 0xf4, 0xe4, 0xbf, 0x97, 0xee, 0xb4, 0xf8, 0x5c, 0x66, 0xb7, + 0xd5, 0xac, 0xa5, 0x90, 0xcf, 0xfe, 0x0e, 0x00, 0x00, 0xff, 0xff, 0x78, 0x52, 0xab, 0x92, 0x56, 0x07, 0x00, 0x00, } diff --git a/x/bandtss/types/codec.go b/x/bandtss/types/codec.go index 0e47339a3..99b65716b 100644 --- a/x/bandtss/types/codec.go +++ b/x/bandtss/types/codec.go @@ -10,12 +10,12 @@ import ( // RegisterLegacyAminoCodec registers the necessary x/bandtss interfaces and concrete types // on the provided LegacyAmino codec. These types are used for Amino JSON serialization. func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - legacy.RegisterAminoMsg(cdc, &MsgCreateGroup{}, "bandtss/CreateGroup") - legacy.RegisterAminoMsg(cdc, &MsgReplaceGroup{}, "bandtss/ReplaceGroup") - legacy.RegisterAminoMsg(cdc, &MsgRequestSignature{}, "bandtss/RequestSignature") - legacy.RegisterAminoMsg(cdc, &MsgActivate{}, "bandtss/Activate") - legacy.RegisterAminoMsg(cdc, &MsgHealthCheck{}, "bandtss/HealthCheck") - legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "bandtss/UpdateParams") + legacy.RegisterAminoMsg(cdc, &MsgCreateGroup{}, "bandtss/MsgCreateGroup") + legacy.RegisterAminoMsg(cdc, &MsgReplaceGroup{}, "bandtss/MsgReplaceGroup") + legacy.RegisterAminoMsg(cdc, &MsgRequestSignature{}, "bandtss/MsgRequestSignature") + legacy.RegisterAminoMsg(cdc, &MsgActivate{}, "bandtss/MsgActivate") + legacy.RegisterAminoMsg(cdc, &MsgHealthCheck{}, "bandtss/MsgHealthCheck") + legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "bandtss/MsgUpdateParams") } // RegisterInterfaces register the bandtss module interfaces to protobuf Any. @@ -30,18 +30,14 @@ func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { ) } -// RegisterRequestSignatureTypeCodec registers an external signature request type defined -// in another module for the internal ModuleCdc. This allows the MsgRequestSignature -// to be correctly Amino encoded and decoded. -// -// NOTE: This should only be used for applications that are still using a concrete -// Amino codec for serialization. -func RegisterSignatureOrderTypeCodec(o interface{}, name string) { - amino.RegisterConcrete(o, name, nil) -} - var ( - amino = codec.NewLegacyAmino() + amino = codec.NewLegacyAmino() + + // ModuleCdc references the global x/bandtss module codec. Note, the codec + // should ONLY be used in certain instances of tests and for JSON encoding. + // + // The actual codec used for serialization should be provided to x/bandtss and + // defined at the application level ModuleCdc = codec.NewAminoCodec(amino) ) diff --git a/x/bandtss/types/constants.go b/x/bandtss/types/constants.go index a504abf0f..b1ed3937f 100644 --- a/x/bandtss/types/constants.go +++ b/x/bandtss/types/constants.go @@ -4,9 +4,4 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// GetBandtssGrantMsgTypes get message types that can be granted. -func GetBandtssGrantMsgTypes() []string { - return []string{ - sdk.MsgTypeURL(&MsgHealthCheck{}), - } -} +var BandtssGrantMsgTypes = []string{sdk.MsgTypeURL(&MsgHealthCheck{})} diff --git a/x/bandtss/types/errors.go b/x/bandtss/types/errors.go index 20c680966..53a7e07c0 100644 --- a/x/bandtss/types/errors.go +++ b/x/bandtss/types/errors.go @@ -1,19 +1,19 @@ package types -import "cosmossdk.io/errors" +import errorsmod "cosmossdk.io/errors" // x/bandtss module sentinel errors var ( - ErrInvalidStatus = errors.Register(ModuleName, 2, "invalid status") - ErrStatusIsNotActive = errors.Register(ModuleName, 3, "status is not active") - ErrTooSoonToActivate = errors.Register(ModuleName, 4, "too soon to activate") - ErrFeeExceedsLimit = errors.Register(ModuleName, 5, "fee exceeds limit") - ErrInvalidGroupID = errors.Register(ModuleName, 6, "invalid groupID") - ErrNoActiveGroup = errors.Register(ModuleName, 7, "no active group") - ErrReplacementInProgress = errors.Register(ModuleName, 8, "group replacement is in progress") - ErrInvalidExecTime = errors.Register(ModuleName, 9, "invalid exec time") - ErrSigningNotFound = errors.Register(ModuleName, 10, "signing not found") - ErrMemberNotFound = errors.Register(ModuleName, 11, "member not found") - ErrMemberAlreadyExists = errors.Register(ModuleName, 12, "member already exists") - ErrMemberAlreadyActive = errors.Register(ModuleName, 13, "member already active") + ErrInvalidStatus = errorsmod.Register(ModuleName, 2, "invalid status") + ErrTooSoonToActivate = errorsmod.Register(ModuleName, 3, "too soon to activate") + ErrFeeExceedsLimit = errorsmod.Register(ModuleName, 4, "fee exceeds limit") + ErrNoActiveGroup = errorsmod.Register(ModuleName, 5, "no active group") + ErrReplacementInProgress = errorsmod.Register(ModuleName, 6, "group replacement is in progress") + ErrInvalidExecTime = errorsmod.Register(ModuleName, 7, "invalid exec time") + ErrSigningNotFound = errorsmod.Register(ModuleName, 8, "signing not found") + ErrMemberNotFound = errorsmod.Register(ModuleName, 9, "member not found") + ErrMemberAlreadyExists = errorsmod.Register(ModuleName, 10, "member already exists") + ErrMemberAlreadyActive = errorsmod.Register(ModuleName, 11, "member already active") + ErrMemberDuplicate = errorsmod.Register(ModuleName, 12, "duplicated member found within the list") + ErrInvalidSigningThreshold = errorsmod.Register(ModuleName, 13, "invalid signing threshold number") ) diff --git a/x/bandtss/types/events.go b/x/bandtss/types/events.go index e7a1437e3..63f333e37 100644 --- a/x/bandtss/types/events.go +++ b/x/bandtss/types/events.go @@ -4,9 +4,9 @@ const ( EventTypeActivate = "activate" EventTypeHealthCheck = "health_check" EventTypeInactiveStatus = "inactive_status" - EventTypeFirstGroupCreated = "first_group_created" EventTypeReplacement = "replacement" EventTypeSigningRequestCreated = "bandtss_signing_request_created" + EventTypeNewGroupActivate = "new_group_activate" AttributeKeyAddress = "address" AttributeKeySigningID = "bandtss_signing_id" @@ -15,4 +15,7 @@ const ( AttributeKeyCurrentGroupSigningID = "current_group_signing_id" AttributeKeyReplacingGroupSigningID = "replacing_group_signing_id" AttributeKeyReplacementStatus = "replacement_status" + AttributeKeyExecTime = "exec_time" + AttributeKeyGroupID = "group_id" + AttributeKeyGroupPubKey = "group_pub_key" ) diff --git a/x/bandtss/types/expected_keepers.go b/x/bandtss/types/expected_keepers.go index 108f08de7..c51a21dec 100644 --- a/x/bandtss/types/expected_keepers.go +++ b/x/bandtss/types/expected_keepers.go @@ -32,8 +32,6 @@ type AuthzKeeper interface { // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - GetModuleAddress(name string) sdk.AccAddress GetModuleAccount(ctx sdk.Context, name string) types.ModuleAccountI } @@ -41,7 +39,6 @@ type AccountKeeper interface { // BankKeeper defines the expected interface needed to retrieve account balances. type BankKeeper interface { GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin SendCoinsFromModuleToAccount( ctx sdk.Context, @@ -104,10 +101,9 @@ type TSSKeeper interface { GetDECount(ctx sdk.Context, address sdk.AccAddress) uint64 GetGroup(ctx sdk.Context, groupID tss.GroupID) (tsstypes.Group, error) - GetPenalizedMembersExpiredGroup(ctx sdk.Context, group tsstypes.Group) ([]sdk.AccAddress, error) GetPenalizedMembersExpiredSigning(ctx sdk.Context, signing tsstypes.Signing) ([]sdk.AccAddress, error) GetSigning(ctx sdk.Context, signingID tss.SigningID) (tsstypes.Signing, error) - HandleSigningContent(ctx sdk.Context, content tsstypes.Content) ([]byte, error) + ConvertContentToBytes(ctx sdk.Context, content tsstypes.Content) ([]byte, error) GetSigningResult(ctx sdk.Context, signingID tss.SigningID) (*tsstypes.SigningResult, error) } diff --git a/x/bandtss/types/genesis.go b/x/bandtss/types/genesis.go index 21e79eb4c..6fbd95740 100644 --- a/x/bandtss/types/genesis.go +++ b/x/bandtss/types/genesis.go @@ -1,13 +1,37 @@ package types +import "github.com/bandprotocol/chain/v2/pkg/tss" + // NewGenesisState - Create a new genesis state -func NewGenesisState(params Params) *GenesisState { +func NewGenesisState( + params Params, + members []Member, + currentGroupID tss.GroupID, + signingCount uint64, + signings []Signing, + signingIDMappings []SigningIDMappingGenesis, + replacement Replacement, +) *GenesisState { return &GenesisState{ - Params: params, + Params: params, + Members: members, + CurrentGroupID: currentGroupID, + SigningCount: signingCount, + Signings: signings, + SigningIDMappings: signingIDMappings, + Replacement: replacement, } } // DefaultGenesisState returns the default bandtss genesis state. func DefaultGenesisState() *GenesisState { - return NewGenesisState(DefaultParams()) + return NewGenesisState( + DefaultParams(), + []Member{}, + 0, + 0, + []Signing{}, + []SigningIDMappingGenesis{}, + Replacement{}, + ) } diff --git a/x/bandtss/types/genesis.pb.go b/x/bandtss/types/genesis.pb.go index 54f5b1611..7d7f88f3c 100644 --- a/x/bandtss/types/genesis.pb.go +++ b/x/bandtss/types/genesis.pb.go @@ -35,7 +35,7 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type GenesisState struct { // params defines all the paramiters of the module. Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // members is an array containing member information. + // members is an array containing members information. Members []Member `protobuf:"bytes,2,rep,name=members,proto3" json:"members"` // current_group_id is the current group id of the module. CurrentGroupID github_com_bandprotocol_chain_v2_pkg_tss.GroupID `protobuf:"varint,3,opt,name=current_group_id,json=currentGroupId,proto3,casttype=github.com/bandprotocol/chain/v2/pkg/tss.GroupID" json:"current_group_id,omitempty"` @@ -43,7 +43,7 @@ type GenesisState struct { SigningCount uint64 `protobuf:"varint,4,opt,name=signing_count,json=signingCount,proto3" json:"signing_count,omitempty"` // signings is the bandtss signing info. Signings []Signing `protobuf:"bytes,5,rep,name=signings,proto3" json:"signings"` - // signing_request_mappings is the list of mapping between tss signing id and bandtss signing id. + // signing_id_mappings is the list of mapping between tss signing id and bandtss signing id. SigningIDMappings []SigningIDMappingGenesis `protobuf:"bytes,6,rep,name=signing_id_mappings,json=signingIdMappings,proto3" json:"signing_id_mappings"` // replacement is the replacement information of the current group and new group. Replacement Replacement `protobuf:"bytes,7,opt,name=replacement,proto3" json:"replacement"` @@ -133,14 +133,14 @@ func (m *GenesisState) GetReplacement() Replacement { // Params defines the set of module parameters. type Params struct { - // active_duration is the duration where a member can be active without interaction. + // active_duration is the duration where a member is active without interaction. ActiveDuration time.Duration `protobuf:"bytes,1,opt,name=active_duration,json=activeDuration,proto3,stdduration" json:"active_duration"` - // reward_percentage is the percentage of block rewards allocated to active TSS validators after being allocated to - // oracle rewards. + // reward_percentage is the percentage of block rewards allocated to active TSS members. + // The reward proportion is calculated after being allocated to oracle rewards. RewardPercentage uint64 `protobuf:"varint,2,opt,name=reward_percentage,json=rewardPercentage,proto3" json:"reward_percentage,omitempty"` - // inactive_penalty_duration is the duration where a member cannot activate back after inactive. + // inactive_penalty_duration is the duration where a member cannot activate back after being set to inactive. InactivePenaltyDuration time.Duration `protobuf:"bytes,3,opt,name=inactive_penalty_duration,json=inactivePenaltyDuration,proto3,stdduration" json:"inactive_penalty_duration"` - // fee is the tokens that will be paid per signing. + // fee is the tokens that will be paid per signer. Fee github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=fee,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"fee"` } diff --git a/x/bandtss/types/helpers.go b/x/bandtss/types/helpers.go deleted file mode 100644 index 304b494f7..000000000 --- a/x/bandtss/types/helpers.go +++ /dev/null @@ -1,14 +0,0 @@ -package types - -// DuplicateInArray checks if there are any duplicates in the given string array. -func DuplicateInArray(arr []string) bool { - visited := make(map[string]bool, 0) - for i := 0; i < len(arr); i++ { - if visited[arr[i]] { - return true - } else { - visited[arr[i]] = true - } - } - return false -} diff --git a/x/bandtss/types/keys.go b/x/bandtss/types/keys.go index d266d12c8..9ecfb1011 100644 --- a/x/bandtss/types/keys.go +++ b/x/bandtss/types/keys.go @@ -37,20 +37,23 @@ var ( // ReplacementStoreKey is the key for storing the group replacement information. ReplacementStoreKey = append(GlobalStoreKeyPrefix, []byte("Replacement")...) - // SigningInfoStoreKeyPrefix is the key for storing the bandtss signing info under SigningStoreKeyPrefix. + // SigningInfoStoreKeyPrefix is the prefix for SigningInfoStoreKey. SigningInfoStoreKeyPrefix = append(SigningStoreKeyPrefix, []byte{0x00}...) - // SigningIDMappingStoreKey is the key for storing the bandtss signing ID under SigningStoreKeyPrefix. + // SigningIDMappingStoreKeyPrefix is the prefix for SigningIDMappingStoreKey. SigningIDMappingStoreKeyPrefix = append(SigningStoreKeyPrefix, []byte{0x01}...) ) +// MemberStoreKey returns the key for storing the member information. func MemberStoreKey(address sdk.AccAddress) []byte { return append(MemberStoreKeyPrefix, address...) } -func SigningStoreKey(id SigningID) []byte { +// SigningInfoStoreKey returns the key for storing the bandtss signing info. +func SigningInfoStoreKey(id SigningID) []byte { return append(SigningInfoStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(id))...) } +// SigningIDMappingStoreKey returns the key for storing the tss signing ID mapping. func SigningIDMappingStoreKey(id tss.SigningID) []byte { return append(SigningIDMappingStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(id))...) } diff --git a/x/bandtss/types/msgs.go b/x/bandtss/types/msgs.go index de40163d3..0c044f27b 100644 --- a/x/bandtss/types/msgs.go +++ b/x/bandtss/types/msgs.go @@ -4,9 +4,9 @@ import ( "fmt" "time" - "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" proto "github.com/cosmos/gogoproto/proto" "github.com/bandprotocol/chain/v2/pkg/tss" @@ -50,35 +50,24 @@ func (m MsgCreateGroup) GetSigners() []sdk.AccAddress { func (m MsgCreateGroup) ValidateBasic() error { // Validate members address for _, member := range m.Members { - _, err := sdk.AccAddressFromBech32(member) - if err != nil { - return errors.Wrap( - err, - fmt.Sprintf("member: %s", member), - ) + if _, err := sdk.AccAddressFromBech32(member); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid member address: %s", err) } } // Check duplicate member - if DuplicateInArray(m.Members) { - return errors.Wrap(fmt.Errorf("members can not duplicate"), "members") + if tsstypes.DuplicateInArray(m.Members) { + return ErrMemberDuplicate } // Validate sender address - _, err := sdk.AccAddressFromBech32(m.Authority) - if err != nil { - return errors.Wrap( - err, - fmt.Sprintf("sender: %s", m.Authority), - ) + if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) } // Validate threshold must be less than or equal to members but more than zero if m.Threshold > uint64(len(m.Members)) || m.Threshold <= 0 { - return errors.Wrap( - fmt.Errorf("threshold must be less than or equal to the members but more than zero"), - "threshold", - ) + return ErrInvalidSigningThreshold.Wrapf("threshold must be less than or equal to the members but more than zero") } return nil @@ -86,7 +75,6 @@ func (m MsgCreateGroup) ValidateBasic() error { // NewMsgReplaceGroup creates a new MsgReplaceGroup instance. func NewMsgReplaceGroup( - currentGroupID tss.GroupID, newGroupID tss.GroupID, execTime time.Time, authority string, @@ -114,12 +102,8 @@ func (m MsgReplaceGroup) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data func (m MsgReplaceGroup) ValidateBasic() error { // Validate sender address - _, err := sdk.AccAddressFromBech32(m.Authority) - if err != nil { - return errors.Wrap( - err, - fmt.Sprintf("sender: %s", m.Authority), - ) + if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) } return nil @@ -167,9 +151,8 @@ func (m MsgRequestSignature) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data func (m MsgRequestSignature) ValidateBasic() error { // Validate sender address - _, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - return errors.Wrap(err, "sender") + if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid sender address: %s", err) } return nil @@ -218,9 +201,8 @@ func (m MsgActivate) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data func (m MsgActivate) ValidateBasic() error { // Validate member address - _, err := sdk.AccAddressFromBech32(m.Address) - if err != nil { - return errors.Wrap(err, "member") + if _, err := sdk.AccAddressFromBech32(m.Address); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } return nil @@ -249,9 +231,8 @@ func (m MsgHealthCheck) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data func (m MsgHealthCheck) ValidateBasic() error { // Validate member address - _, err := sdk.AccAddressFromBech32(m.Address) - if err != nil { - return errors.Wrap(err, "member") + if _, err := sdk.AccAddressFromBech32(m.Address); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } return nil @@ -281,7 +262,7 @@ func (m *MsgUpdateParams) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data. func (m *MsgUpdateParams) ValidateBasic() error { if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { - return errors.Wrap(err, "invalid authority address") + return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) } if err := m.Params.Validate(); err != nil { diff --git a/x/bandtss/types/params.go b/x/bandtss/types/params.go index 21de98986..a24a8c245 100644 --- a/x/bandtss/types/params.go +++ b/x/bandtss/types/params.go @@ -4,7 +4,6 @@ import ( "fmt" "time" - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -60,7 +59,7 @@ func (p Params) Validate() error { // Validate fee if !p.Fee.IsValid() { - return errors.Wrap(sdkerrors.ErrInvalidCoins, p.Fee.String()) + return sdkerrors.ErrInvalidCoins.Wrapf(p.Fee.String()) } return nil diff --git a/x/bandtss/types/query.pb.go b/x/bandtss/types/query.pb.go index 31f11465b..12690aa8c 100644 --- a/x/bandtss/types/query.pb.go +++ b/x/bandtss/types/query.pb.go @@ -589,7 +589,7 @@ func (m *QuerySigningRequest) GetSigningId() uint64 { type QuerySigningResponse struct { // fee is the total tokens that will be paid for this bandtss signing. Fee github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=fee,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"fee"` - // requester is the address of requester who paid for the Bandtss signing. + // requester is the address of requester who paid for bandtss signing. Requester string `protobuf:"bytes,2,opt,name=requester,proto3" json:"requester,omitempty"` // current_group_signing_result is the signing result from the current group. CurrentGroupSigningResult *types.SigningResult `protobuf:"bytes,3,opt,name=current_group_signing_result,json=currentGroupSigningResult,proto3" json:"current_group_signing_result,omitempty"` @@ -841,17 +841,17 @@ const _ = grpc.SupportPackageIsVersion4 // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type QueryClient interface { - // Params queries parameters of Bandtss module + // Params queries parameters of bandtss module Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // IsGrantee queries grant of account on this granter. + // IsGrantee queries whether granter grants the grantee. IsGrantee(ctx context.Context, in *QueryIsGranteeRequest, opts ...grpc.CallOption) (*QueryIsGranteeResponse, error) // Members queries all members. Members(ctx context.Context, in *QueryMembersRequest, opts ...grpc.CallOption) (*QueryMembersResponse, error) - // Member queries the member information of the address. + // Member queries the member information of the given address. Member(ctx context.Context, in *QueryMemberRequest, opts ...grpc.CallOption) (*QueryMemberResponse, error) // CurrentGroup queries the current group information. CurrentGroup(ctx context.Context, in *QueryCurrentGroupRequest, opts ...grpc.CallOption) (*QueryCurrentGroupResponse, error) - // Signing queries the signing result of the signing request. + // Signing queries the signing result of the given signing request ID. Signing(ctx context.Context, in *QuerySigningRequest, opts ...grpc.CallOption) (*QuerySigningResponse, error) // Replacement queries the replacement information. Replacement(ctx context.Context, in *QueryReplacementRequest, opts ...grpc.CallOption) (*QueryReplacementResponse, error) @@ -930,17 +930,17 @@ func (c *queryClient) Replacement(ctx context.Context, in *QueryReplacementReque // QueryServer is the server API for Query service. type QueryServer interface { - // Params queries parameters of Bandtss module + // Params queries parameters of bandtss module Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // IsGrantee queries grant of account on this granter. + // IsGrantee queries whether granter grants the grantee. IsGrantee(context.Context, *QueryIsGranteeRequest) (*QueryIsGranteeResponse, error) // Members queries all members. Members(context.Context, *QueryMembersRequest) (*QueryMembersResponse, error) - // Member queries the member information of the address. + // Member queries the member information of the given address. Member(context.Context, *QueryMemberRequest) (*QueryMemberResponse, error) // CurrentGroup queries the current group information. CurrentGroup(context.Context, *QueryCurrentGroupRequest) (*QueryCurrentGroupResponse, error) - // Signing queries the signing result of the signing request. + // Signing queries the signing result of the given signing request ID. Signing(context.Context, *QuerySigningRequest) (*QuerySigningResponse, error) // Replacement queries the replacement information. Replacement(context.Context, *QueryReplacementRequest) (*QueryReplacementResponse, error) diff --git a/x/bandtss/types/signature_order.go b/x/bandtss/types/signature_order.go index f7989e067..b848bcf47 100644 --- a/x/bandtss/types/signature_order.go +++ b/x/bandtss/types/signature_order.go @@ -1,7 +1,6 @@ package types import ( - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -42,8 +41,7 @@ func NewSignatureOrderHandler() tsstypes.Handler { return append(ReplaceGroupMsgPrefix, c.PubKey...), nil default: - return nil, errors.Wrapf( - sdkerrors.ErrUnknownRequest, + return nil, sdkerrors.ErrUnknownRequest.Wrapf( "unrecognized tss request signature message type: %s", c.OrderType(), ) diff --git a/x/bandtss/types/tx.pb.go b/x/bandtss/types/tx.pb.go index ee565cad0..4688434e1 100644 --- a/x/bandtss/types/tx.pb.go +++ b/x/bandtss/types/tx.pb.go @@ -142,7 +142,7 @@ var xxx_messageInfo_MsgCreateGroupResponse proto.InternalMessageInfo // MsgReplaceGroup is the Msg/ReplaceGroup request type. type MsgReplaceGroup struct { - // new_group_id is the ID of the group that want to replace, and subsequently remove this group. + // new_group_id is the ID of the group that want to replace. NewGroupID github_com_bandprotocol_chain_v2_pkg_tss.GroupID `protobuf:"varint,1,opt,name=new_group_id,json=newGroupId,proto3,casttype=github.com/bandprotocol/chain/v2/pkg/tss.GroupID" json:"new_group_id,omitempty"` // exec_time is the time that will be substituted in place of the group. ExecTime time.Time `protobuf:"bytes,2,opt,name=exec_time,json=execTime,proto3,stdtime" json:"exec_time"` @@ -321,7 +321,7 @@ func (m *MsgRequestSignatureResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgRequestSignatureResponse proto.InternalMessageInfo -// MsgActivate is a message used to activate the status of the group's address. +// MsgActivate is a message used to activate the status of the sender. type MsgActivate struct { // address is the signer of this message, who must be a member of the group. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` @@ -404,7 +404,7 @@ func (m *MsgActivateResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgActivateResponse proto.InternalMessageInfo -// MsgHealthCheck is a message used to show active status if the address is still active. +// MsgHealthCheck is a message used to show if the address is still active. type MsgHealthCheck struct { // address is the signer of this message, who must be a member of the group. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` @@ -491,7 +491,7 @@ var xxx_messageInfo_MsgHealthCheckResponse proto.InternalMessageInfo type MsgUpdateParams struct { // params defines the x/tss parameters to update. Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // authority is the address of the governance account. + // authority is the address that controls the module (defaults to x/gov unless overwritten). Authority string `protobuf:"bytes,2,opt,name=authority,proto3" json:"authority,omitempty"` } @@ -542,8 +542,7 @@ func (m *MsgUpdateParams) GetAuthority() string { return "" } -// MsgUpdateParamsResponse defines the response structure for executing a -// MsgUpdateParams message. +// MsgUpdateParamsResponse defines the response structure for executing a MsgUpdateParams message. type MsgUpdateParamsResponse struct { } @@ -670,13 +669,13 @@ const _ = grpc.SupportPackageIsVersion4 type MsgClient interface { // CreateGroup creates a new group with a list of members. CreateGroup(ctx context.Context, in *MsgCreateGroup, opts ...grpc.CallOption) (*MsgCreateGroupResponse, error) - // ReplaceGroup replaces the group with another group. + // ReplaceGroup replaces the current group with another group. ReplaceGroup(ctx context.Context, in *MsgReplaceGroup, opts ...grpc.CallOption) (*MsgReplaceGroupResponse, error) // RequestSignature submits a general message to be signed by a specific group. RequestSignature(ctx context.Context, in *MsgRequestSignature, opts ...grpc.CallOption) (*MsgRequestSignatureResponse, error) - // Activate activates the status of the group's member. + // Activate activates the status of the sender. Activate(ctx context.Context, in *MsgActivate, opts ...grpc.CallOption) (*MsgActivateResponse, error) - // HealthCheck marks last active of the mebmer. + // HealthCheck marks last active of the sender. HealthCheck(ctx context.Context, in *MsgHealthCheck, opts ...grpc.CallOption) (*MsgHealthCheckResponse, error) // UpdateParams updates the x/bandtss parameters. UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) @@ -748,13 +747,13 @@ func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts type MsgServer interface { // CreateGroup creates a new group with a list of members. CreateGroup(context.Context, *MsgCreateGroup) (*MsgCreateGroupResponse, error) - // ReplaceGroup replaces the group with another group. + // ReplaceGroup replaces the current group with another group. ReplaceGroup(context.Context, *MsgReplaceGroup) (*MsgReplaceGroupResponse, error) // RequestSignature submits a general message to be signed by a specific group. RequestSignature(context.Context, *MsgRequestSignature) (*MsgRequestSignatureResponse, error) - // Activate activates the status of the group's member. + // Activate activates the status of the sender. Activate(context.Context, *MsgActivate) (*MsgActivateResponse, error) - // HealthCheck marks last active of the mebmer. + // HealthCheck marks last active of the sender. HealthCheck(context.Context, *MsgHealthCheck) (*MsgHealthCheckResponse, error) // UpdateParams updates the x/bandtss parameters. UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) diff --git a/x/feeds/README.md b/x/feeds/README.md new file mode 100644 index 000000000..404b99ff7 --- /dev/null +++ b/x/feeds/README.md @@ -0,0 +1,360 @@ +# `x/feeds` + +## Abstract + +This document specifies the Feeds module. + +The Feeds module provides a mechanism for decentralized signal voting, price submission, and price updating within a blockchain. + +This module is used in the BandChain. + +## Contents + +- [`x/feeds`](#xfeeds) + - [Abstract](#abstract) + - [Contents](#contents) + - [Concepts](#concepts) + - [Delegator Signal](#delegator-signal) + - [Feed](#feed) + - [Feed Interval](#feed-interval) + - [Feed Deviation](#feed-deviation) + - [How Feed Interval and Deviation are calculated](#how-feed-interval-and-deviation-are-calculated) + - [Supported Feeds](#supported-feeds) + - [Validator Price](#validator-price) + - [Price](#price) + - [Price Service](#price-service) + - [State](#state) + - [PriceService](#priceservice) + - [Feed](#feed-1) + - [FeedByPowerIndex](#feedbypowerindex) + - [ValidatorPrice](#validatorprice) + - [Price](#price-1) + - [DelegatorSignal](#delegatorsignal) + - [Params](#params) + - [Messages](#messages) + - [MsgSubmitPrices](#msgsubmitprices) + - [MsgUpdatePriceService](#msgupdatepriceservice) + - [MsgUpdateParams](#msgupdateparams) + - [MsgSubmitSignals](#msgsubmitsignals) + - [End-Block](#end-block) + - [Update Prices](#update-prices) + - [Events](#events) + - [EndBlocker](#endblocker) + - [Handlers](#handlers) + - [MsgSubmitPrices](#msgsubmitprices-1) + - [MsgUpdatePriceService](#msgupdatepriceservice-1) + - [MsgUpdateParams](#msgupdateparams-1) + - [MsgSubmitSignals](#msgsubmitsignals-1) + + +## Concepts + +### Delegator Signal + +A Delegator Signal is a sign or vote from a delegator, instructing the chain to provide feed service for the designated ID. + +A Delegator Signal consists of an ID and the power associated with that ID. The feeding interval and deviation are reduced by the sum of the power of the ID. The total power of a delegator cannot exceed their bonded delegation. + +### Feed + +A Feed is a data structure containing a signal ID, its total power, and calculated interval and deviation values. Essentially, it instructs the validator regarding which signal IDs' prices need to be submitted at each specified interval or deviation. + +#### Feed Interval + +The interval is calculated based on the power of its feed; the greater the power, the shorter the interval. The total power of a feed is the sum of the power of its signal IDs received from the delegators. The minimum and maximum intervals are determined by parameters called `MinInterval` and `MaxInterval`, respectively. + +#### Feed Deviation + +Deviation follows a similar logic to interval. On-chain deviation is measured in thousandths, meaning a deviation of 1 indicates a price tolerance within 0.1%. The minimum and maximum deviations are determined by parameters called `MinDeviationInThousandth` and `MaxDeviationInThousandth`, respectively. + +#### How Feed Interval and Deviation are calculated + +- Power is registered after surpassing the `PowerThreshold`. +- Then, the power factor is calculated as the floor(Power / PowerThreshold). +- Subsequently, the interval is calculated as the maximum of MinInterval or the floor(MaxInterval / power factor). +- The deviation is then calculated as the max(`MinDeviationInThousandth`, (`MaxDeviationInThousandth` / power factor). + +You can visualize the interval/deviation as resembling the harmonic series times MaxInterval/MaxDeviationInThousandth, with step of PowerThreshold. + +#### Supported Feeds + +The list of currently supported feeds includes those with power exceeding the PowerThreshold parameter and ranking within the top MaxSupportedFeeds. Feeds outside of this list are considered unsupported, and validators do not need to submit their prices. + +### Validator Price + +The Validator Price refers to the price submitted by each validator before being aggregated into the final Price. + +The module only contains the latest price of each validator and signal id. + +### Price + +A Price is a structure that maintains the current price state for a signal id, including its current price, price status, and the most recent timestamp. + +Once the Validator Price is submitted, it will be weighted median which weight by how latest the price and how much validator power of the owner of the price to get the most accurate and trustworthy price. + +The module only contains the latest price of each signal id. + +### Price Service + +The On-chain Price Service is the agreed-upon version of the price service suggested for validators to use when querying prices for the feeds. + +## State + +### PriceService + +PriceService is stored in the global store `0x00` to hold Price Service information. + +* PriceService: `0x00 | []byte("PriceService") -> ProtocolBuffer(PriceService)` + +### Feed + +The Feed is a space for holding current Feeds information. + +* Feed: `0x01 -> ProtocolBuffer(Feed)` + +#### FeedByPowerIndex + +`FeedByPowerIndex` allow to retrieve Feeds by power: +`0x20| BigEndian(Power) | SignalIDLen (1 byte) | SignalID -> SignalID` + +### ValidatorPrice + +The ValidatorPrice is a space for holding current Validator Price information. + +* ValidatorPrice: `0x02 -> ProtocolBuffer(ValidatorPrice)` + +### Price + +The Price is a space for holding current Priceinformation. + +* Price: `0x03 -> ProtocolBuffer(Price)` + +### DelegatorSignal + +The DelegatorSignal is a space for holding current Delegator Signals information. + +* DelegatorSignal: `0x04 -> ProtocolBuffer(Signal)` + +### Params + +The feeds module stores its params in state with the prefix of `0x10`, +it can be updated with governance or the address with authority. + +* Params: `0x10 | ProtocolBuffer(Params)` + +```protobuf +// Params is the data structure that keeps the parameters of the feeds module. +message Params { + option (gogoproto.equal) = true; // Use gogoproto.equal for proto3 message equality checks + option (gogoproto.goproto_stringer) = false; // Disable stringer generation for better control + + // Admin is the address of the admin that is allowed to perform operations on modules. + string admin = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // AllowableBlockTimeDiscrepancy is the allowed discrepancy (in seconds) between validator price timestamp and + // block_time. + int64 allowable_block_time_discrepancy = 2; + + // TransitionTime is the time (in seconds) given for validators to adapt to changing in feed's interval. + int64 transition_time = 3; + + // MinInterval is the minimum limit of every feeds' interval (in seconds). + // If the calculated interval is lower than this, it will be capped at this value. + int64 min_interval = 4; + + // MaxInterval is the maximum limit of every feeds' interval (in seconds). + // If the calculated interval of a feed is higher than this, it will not be recognized as a supported feed. + int64 max_interval = 5; + + // PowerThreshold is the amount of minimum power required to put feed in the supported list. + int64 power_threshold = 6; + + // MaxSupportedFeeds is the maximum number of feeds supported at a time. + int64 max_supported_feeds = 7; + + // CooldownTime represents the duration (in seconds) during which validators are prohibited from sending new prices. + int64 cooldown_time = 8; + + // MinDeviationInThousandth is the minimum limit of every feeds' deviation (in thousandth). + int64 min_deviation_in_thousandth = 9; + + // MaxDeviationInThousandth is the maximum limit of every feeds' deviation (in thousandth). + int64 max_deviation_in_thousandth = 10; +} +``` + +## Messages + +In this section we describe the processing of the feeds messages and the corresponding updates to the state. All created/modified state objects specified by each message are defined within the [state](#state) section. + +### MsgSubmitPrices + +Validator Prices are submitted using the `MsgSubmitPrices` message. +The Prices will be updated at endblock using this new Validator Prices. + +```protobuf +// MsgSubmitPrices is the transaction message to submit multiple prices. +message MsgSubmitPrices { + option (cosmos.msg.v1.signer) = "validator"; + option (amino.name) = "feeds/MsgSubmitPrices"; + + // Validator is the address of the validator that is performing the operation. + string validator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // Timestamp is the timestamp use as reference of the data. + int64 timestamp = 2; + + // Prices is a list of prices to submit. + repeated SubmitPrice prices = 3 [(gogoproto.nullable) = false]; +} +``` + +This message is expected to fail if: + +* validator address is not correct +* validator status is not bonded +* price is submitted in `CooldownTime` param +* no Feed with the same signalID + +### MsgUpdatePriceService + +Price Service can be updated with the `MsgUpdatePriceService` message. +Only assigned admin can update the Price Service. + +```protobuf +// MsgUpdatePriceService is the transaction message to update price service's information. +message MsgUpdatePriceService { + option (cosmos.msg.v1.signer) = "authority"; + option (amino.name) = "feeds/MsgUpdateParams"; + + // Admin is the address of the admin that is performing the operation. + string admin = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // PriceService is the information of price service. + PriceService price_service = 2 [(gogoproto.nullable) = false]; +} +``` + +This message is expected to fail if: + +* sender address do not match `Admin` param +* Price Service url is not in the correct format of an url + +### MsgUpdateParams + +The `MsgUpdateParams` update the feeds module parameters. +The params are updated through a governance proposal where the signer is the gov module account address or other specified authority addresses. + +```protobuf +// MsgUpdateParams is the transaction message to update parameters. +message MsgUpdateParams { + option (cosmos.msg.v1.signer) = "authority"; + option (amino.name) = "feeds/MsgUpdateParams"; + + // Authority is the address of the governance account. + string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // Params is the x/feeds parameters to update. + Params params = 2 [(gogoproto.nullable) = false]; +} +``` + +The message handling can fail if: + +* signer is not the authority defined in the feeds keeper (usually the gov module account). + +### MsgSubmitSignals + +Delegator Signals are submitted as a batch using the MsgSubmitSignals message. + +Batched Signals replace the previous Signals of the same delegator as a batch. +Signals are registered, and their power is added to the feeds of the same SignalID. +If the Feed's Interval is changed, its LastIntervalUpdateTimestamp will be marked as the block time. +If the updated Feed's Power is zero, it will be deleted from the state. +Every time there is an update to a Feed, `FeedByPowerIndex` will be re-indexed. + +```protobuf +// MsgSubmitSignals is the transaction message to submit signals +message MsgSubmitSignals { + option (cosmos.msg.v1.signer) = "delegator"; + option (amino.name) = "feeds/MsgSubmitSignals"; + + // Delegator is the address of the delegator that want to submit signals + string delegator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + // Signals is a list of submitted signal + repeated Signal signals = 2 [(gogoproto.nullable) = false]; +} +``` + +The message handling can fail if: + +* delegator address is not correct +* delegator do not have less delegation than sum of the Powers +* no Feed with the same signalID + +## End-Block + +Each abci end block call, the operations to update prices. + +### Update Prices + +At every end block, the Validator Price of every Supported Feed will be obtained and checked if it is within the acceptance period (1 interval). +Any validator that does not submit a price within this period is considered to have miss-reported and will be deactivated, unless the Feed is in a transition period (where the interval has just been updated within TransitionTime). +Accepted Validator Prices of the same SignalID will be weighted and medianed based on the recency of the price and the power of the validator who submitted the price. +The medianed price is then set as the Price. + +## Events + +The feeds module emits the following events: + +### EndBlocker + +| Type | Attribute Key | Attribute Value | +| ---------------------- | ------------- | --------------- | +| calculate_price_failed | signal_id | {signalID} | +| calculate_price_failed | error_message | {error} | +| update_price | signal_id | {signalID} | +| update_price | price | {price} | +| update_price | timestamp | {timestamp} | + +### Handlers + +#### MsgSubmitPrices + +| Type | Attribute Key | Attribute Value | +| ------------ | ------------- | ------------------ | +| submit_price | price_status | {priceStatus} | +| submit_price | validator | {validatorAddress} | +| submit_price | signal_id | {signalID} | +| submit_price | price | {price} | +| submit_price | timestamp | {timestamp} | + + +#### MsgUpdatePriceService + +| Type | Attribute Key | Attribute Value | +| -------------------- | ------------- | --------------- | +| update_price_service | hash | {hash} | +| update_price_service | version | {version} | +| update_price_service | url | {url} | + +#### MsgUpdateParams + +| Type | Attribute Key | Attribute Value | +| ------------- | ------------- | --------------- | +| update_params | params | {params} | + +#### MsgSubmitSignals + +| Type | Attribute Key | Attribute Value | +| ------------ | ----------------------- | ----------------------- | +| update_feed | signal_id | {signalID} | +| update_feed | power | {power} | +| update_feed | interval | {interval} | +| update_feed | timestamp | {timestamp} | +| update_feed | deviation_in_thousandth | {deviationInThousandth} | +| deleate_feed | signal_id | {signalID} | +| deleate_feed | power | {power} | +| deleate_feed | interval | {interval} | +| deleate_feed | timestamp | {timestamp} | +| deleate_feed | deviation_in_thousandth | {deviationInThousandth} | diff --git a/x/feeds/abci.go b/x/feeds/abci.go new file mode 100644 index 000000000..c1583b95b --- /dev/null +++ b/x/feeds/abci.go @@ -0,0 +1,39 @@ +package feeds + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/feeds/keeper" + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// HandleEndBlock is a handler function for the EndBlock ABCI request. +func HandleEndBlock(ctx sdk.Context, k keeper.Keeper) { + feeds := k.GetSupportedFeedsByPower(ctx) + for _, feed := range feeds { + price, err := k.CalculatePrice(ctx, feed) + if err != nil { + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeCalculatePriceFailed, + sdk.NewAttribute(types.AttributeKeySignalID, feed.SignalID), + sdk.NewAttribute(types.AttributeKeyErrorMessage, err.Error()), + ), + ) + continue + } + + k.SetPrice(ctx, price) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeUpdatePrice, + sdk.NewAttribute(types.AttributeKeySignalID, price.SignalID), + sdk.NewAttribute(types.AttributeKeyPrice, fmt.Sprintf("%d", price.Price)), + sdk.NewAttribute(types.AttributeKeyTimestamp, fmt.Sprintf("%d", price.Timestamp)), + ), + ) + } +} diff --git a/x/feeds/client/cli/query.go b/x/feeds/client/cli/query.go new file mode 100644 index 000000000..6ba8eadce --- /dev/null +++ b/x/feeds/client/cli/query.go @@ -0,0 +1,275 @@ +package cli + +import ( + "context" + "fmt" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd() *cobra.Command { + queryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + queryCmd.AddCommand( + GetQueryCmdPrices(), + GetQueryCmdPrice(), + GetQueryCmdValidatorPrices(), + GetQueryCmdValidatorPrice(), + GetQueryCmdFeeds(), + GetQueryCmdParams(), + GetQueryCmdDelegatorSignal(), + GetQueryCmdSupportedFeeds(), + ) + + return queryCmd +} + +// GetQueryCmdDelegatorSignal implements the query delegator signal command. +func GetQueryCmdDelegatorSignal() *cobra.Command { + cmd := &cobra.Command{ + Use: "delegator-signal [delegator-addr]", + Short: "Shows delegator's currently active signal", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.DelegatorSignals( + context.Background(), + &types.QueryDelegatorSignalsRequest{Delegator: args[0]}, + ) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetQueryCmdPrices implements the query prices command. +func GetQueryCmdPrices() *cobra.Command { + cmd := &cobra.Command{ + Use: "prices", + Short: "Shows the latest price of all signal ids", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + queryClient := types.NewQueryClient(clientCtx) + + pageReq, err := client.ReadPageRequest(cmd.Flags()) + if err != nil { + return err + } + + res, err := queryClient.Prices(context.Background(), &types.QueryPricesRequest{Pagination: pageReq}) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddPaginationFlagsToCmd(cmd, "prices") + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetQueryCmdPrice implements the query price command. +func GetQueryCmdPrice() *cobra.Command { + cmd := &cobra.Command{ + Use: "price [signal_id]", + Short: "Shows the latest price of a signal id", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.Price(context.Background(), &types.QueryPriceRequest{ + SignalId: args[0], + }) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetQueryCmdSupportedFeeds implements the query supported feeds command. +func GetQueryCmdSupportedFeeds() *cobra.Command { + cmd := &cobra.Command{ + Use: "supported-feeds", + Short: "Shows all currently supported feeds", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.SupportedFeeds(context.Background(), &types.QuerySupportedFeedsRequest{}) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetQueryCmdValidatorPrices implements the query validator prices command. +func GetQueryCmdValidatorPrices() *cobra.Command { + cmd := &cobra.Command{ + Use: "validator-prices [validator]", + Short: "Shows all prices of the validator", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.ValidatorPrices(context.Background(), &types.QueryValidatorPricesRequest{ + Validator: args[0], + }) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetQueryCmdValidatorPrice implements the query validator price command. +func GetQueryCmdValidatorPrice() *cobra.Command { + cmd := &cobra.Command{ + Use: "price-validator [signal_id] [validator]", + Short: "Shows the price of validator of the signal id", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.ValidatorPrice(context.Background(), &types.QueryValidatorPriceRequest{ + SignalId: args[0], + Validator: args[1], + }) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetQueryCmdFeeds implements the query feeds command. +func GetQueryCmdFeeds() *cobra.Command { + cmd := &cobra.Command{ + Use: "feeds", + Short: "Shows all information of all feeds", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + queryClient := types.NewQueryClient(clientCtx) + + pageReq, err := client.ReadPageRequest(cmd.Flags()) + if err != nil { + return err + } + + res, err := queryClient.Feeds(context.Background(), &types.QueryFeedsRequest{Pagination: pageReq}) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddPaginationFlagsToCmd(cmd, "feeds") + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetQueryCmdPriceService implements the query price service command. +func GetQueryCmdPriceService() *cobra.Command { + cmd := &cobra.Command{ + Use: "price-service", + Short: "Shows information of price service", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.PriceService(context.Background(), &types.QueryPriceServiceRequest{}) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetQueryCmdParams implements the query params command. +func GetQueryCmdParams() *cobra.Command { + cmd := &cobra.Command{ + Use: "params", + Short: "Shows the parameters of the module", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/feeds/client/cli/tx.go b/x/feeds/client/cli/tx.go new file mode 100644 index 000000000..df1e80a7b --- /dev/null +++ b/x/feeds/client/cli/tx.go @@ -0,0 +1,246 @@ +package cli + +import ( + "fmt" + "strconv" + "strings" + "time" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/version" + "github.com/spf13/cobra" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +const ( + flagExpiration = "expiration" +) + +// getGrantMsgTypes returns types for GrantMsg. +func getGrantMsgTypes() []string { + return []string{ + sdk.MsgTypeURL(&types.MsgSubmitPrices{}), + } +} + +// GetTxCmd returns the transaction commands for this module +func GetTxCmd() *cobra.Command { + txCmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + txCmd.AddCommand( + GetTxCmdAddGrantees(), + GetTxCmdRemoveGrantees(), + GetTxCmdSubmitSignals(), + GetTxCmdUpdatePriceService(), + ) + + return txCmd +} + +// GetTxCmdSubmitSignals creates a CLI command for submitting signals +func GetTxCmdSubmitSignals() *cobra.Command { + cmd := &cobra.Command{ + Use: "signal [signal_id1]:[power1] [signal_id2]:[power2] ...", + Short: "Signal signal ids and their powers", + Args: cobra.MinimumNArgs(0), + Long: strings.TrimSpace( + fmt.Sprintf( + `Signal signal ids and their power. +Example: +$ %s tx feeds signal BTC:1000000 --from mykey +`, + version.AppName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + delegator := clientCtx.GetFromAddress() + var signals []types.Signal + for i, arg := range args { + idAndPower := strings.SplitN(arg, ":", 2) + if len(idAndPower) != 2 { + return fmt.Errorf("argument %d is not valid", i) + } + power, err := strconv.ParseInt(idAndPower[1], 0, 64) + if err != nil { + return err + } + signals = append( + signals, types.Signal{ + ID: idAndPower[0], + Power: power, + }, + ) + } + + msg := types.MsgSubmitSignals{ + Delegator: delegator.String(), + Signals: signals, + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + flags.AddTxFlagsToCmd(cmd) + + return cmd +} + +// GetTxCmdAddGrantees creates a CLI command for adding new grantees +func GetTxCmdAddGrantees() *cobra.Command { + cmd := &cobra.Command{ + Use: "add-grantees [grantee1] [grantee2] ...", + Short: "Add agents authorized to submit prices transactions.", + Args: cobra.MinimumNArgs(1), + Long: strings.TrimSpace( + fmt.Sprintf( + `Add agents authorized to submit feeds transactions. +Example: +$ %s tx feeds add-grantees band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs --from mykey +`, + version.AppName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + exp, err := cmd.Flags().GetInt64(flagExpiration) + if err != nil { + return err + } + expTime := time.Unix(exp, 0) + + granter := clientCtx.GetFromAddress() + var msgs []sdk.Msg + + for _, arg := range args { + grantee, err := sdk.AccAddressFromBech32(arg) + if err != nil { + return err + } + + gMsgs, err := combineGrantMsgs(granter, grantee, getGrantMsgTypes(), &expTime) + if err != nil { + return err + } + + msgs = append(msgs, gMsgs...) + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msgs...) + }, + } + + cmd.Flags(). + Int64( + flagExpiration, + time.Now().AddDate(2500, 0, 0).Unix(), + "The Unix timestamp. Default is 2500 years(forever).", + ) + flags.AddTxFlagsToCmd(cmd) + + return cmd +} + +// GetTxCmdRemoveGrantees creates a CLI command for removing grantees from granter +func GetTxCmdRemoveGrantees() *cobra.Command { + cmd := &cobra.Command{ + Use: "remove-grantees [grantee1] [grantee2] ...", + Short: "Remove agents from the list of authorized grantees.", + Args: cobra.MinimumNArgs(1), + Long: strings.TrimSpace( + fmt.Sprintf( + `Remove agents from the list of authorized grantees. +Example: +$ %s tx feeds remove-grantees band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs --from mykey +`, + version.AppName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + granter := clientCtx.GetFromAddress() + var msgs []sdk.Msg + + for _, arg := range args { + grantee, err := sdk.AccAddressFromBech32(arg) + if err != nil { + return err + } + + rMsgs, err := combineRevokeMsgs(granter, grantee, getGrantMsgTypes()) + if err != nil { + return err + } + + msgs = append(msgs, rMsgs...) + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msgs...) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} + +// GetTxCmdUpdatePriceService creates a CLI command for updating price service +func GetTxCmdUpdatePriceService() *cobra.Command { + cmd := &cobra.Command{ + Use: "update-price-service [hash] [version] [url]", + Short: "Update reference price service", + Args: cobra.ExactArgs(3), + Long: strings.TrimSpace( + fmt.Sprintf( + `Update reference price service that will be use as the default service for price querying. +Example: +$ %s tx feeds update-price-service 1234abcedf 1.0.0 http://www.example.com --from mykey +`, + version.AppName, + ), + ), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + admin := clientCtx.GetFromAddress() + priceService := types.PriceService{ + Hash: args[0], + Version: args[1], + Url: args[2], + } + + msg := types.MsgUpdatePriceService{ + Admin: admin.String(), + PriceService: priceService, + } + + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) + }, + } + flags.AddTxFlagsToCmd(cmd) + + return cmd +} diff --git a/x/feeds/client/cli/utils.go b/x/feeds/client/cli/utils.go new file mode 100644 index 000000000..8ee6287fe --- /dev/null +++ b/x/feeds/client/cli/utils.go @@ -0,0 +1,59 @@ +package cli + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/authz" +) + +// combineGrantMsgs combines multiple grant messages into a single slice of messages. +func combineGrantMsgs( + granter sdk.AccAddress, + grantee sdk.AccAddress, + msgGrants []string, + expiration *time.Time, +) ([]sdk.Msg, error) { + var msgs []sdk.Msg + + for _, msgGrant := range msgGrants { + msg, err := authz.NewMsgGrant( + granter, + grantee, + authz.NewGenericAuthorization(msgGrant), + expiration, + ) + if err != nil { + return nil, err + } + + if err = msg.ValidateBasic(); err != nil { + return nil, err + } + + msgs = append(msgs, msg) + } + + return msgs, nil +} + +// combineRevokeMsgs combines multiple revoke messages into a single slice of messages. +func combineRevokeMsgs(granter sdk.AccAddress, grantee sdk.AccAddress, msgRevokes []string) ([]sdk.Msg, error) { + var msgs []sdk.Msg + + for _, msgRevoke := range msgRevokes { + msg := authz.NewMsgRevoke( + granter, + grantee, + msgRevoke, + ) + + if err := msg.ValidateBasic(); err != nil { + return nil, err + } + + msgs = append(msgs, &msg) + } + + return msgs, nil +} diff --git a/x/feeds/keeper/calculate.go b/x/feeds/keeper/calculate.go new file mode 100644 index 000000000..13b2167da --- /dev/null +++ b/x/feeds/keeper/calculate.go @@ -0,0 +1,35 @@ +package keeper + +import ( + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// calculateIntervalAndDeviation calculates feed interval and deviation from power +func calculateIntervalAndDeviation(power int64, param types.Params) (interval int64, deviation int64) { + if power < param.PowerThreshold { + return 0, 0 + } + + // divide power by power threshold to create steps + powerFactor := power / param.PowerThreshold + + interval = param.MaxInterval / powerFactor + if interval < param.MinInterval { + interval = param.MinInterval + } + + deviation = param.MaxDeviationInThousandth / powerFactor + if deviation < param.MinDeviationInThousandth { + deviation = param.MinDeviationInThousandth + } + + return +} + +// sumPower sums power from a list of signals +func sumPower(signals []types.Signal) (sum int64) { + for _, signal := range signals { + sum += signal.Power + } + return +} diff --git a/x/feeds/keeper/calculate_test.go b/x/feeds/keeper/calculate_test.go new file mode 100644 index 000000000..b4e5a7d30 --- /dev/null +++ b/x/feeds/keeper/calculate_test.go @@ -0,0 +1,71 @@ +package keeper + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func TestCalculateIntervalAndDeviation(t *testing.T) { + params := types.NewParams("[NOT_SET]", 30, 30, 60, 3600, 1000_000_000, 100, 30, 5, 300) + + testCases := []struct { + name string + power int64 + expInterval int64 + expDeviation int64 + }{ + { + name: "power less than threshold", + power: 10000, + expInterval: 0, + expDeviation: 0, + }, + { + name: "power at the threshold", + power: 1000000000, + expInterval: 3600, + expDeviation: 300, + }, + { + name: "power at minimum interval", + power: 60000000000, + expInterval: 60, + expDeviation: 5, + }, + { + name: "power exceed the minimum interval", + power: 600000000000, + expInterval: 60, + expDeviation: 5, + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(tt *testing.T) { + interval, deviation := calculateIntervalAndDeviation(tc.power, params) + require.Equal(tt, tc.expInterval, interval) + require.Equal(tt, tc.expDeviation, deviation) + }) + } +} + +func TestSumPower(t *testing.T) { + require.Equal(t, int64(300000), sumPower([]types.Signal{ + { + ID: "crypto_price.bandusd", + Power: 100000, + }, + { + ID: "crypto_price.atomusd", + Power: 100000, + }, + { + ID: "crypto_price.osmousd", + Power: 100000, + }, + })) +} diff --git a/x/feeds/keeper/emit.go b/x/feeds/keeper/emit.go new file mode 100644 index 000000000..50fa26050 --- /dev/null +++ b/x/feeds/keeper/emit.go @@ -0,0 +1,78 @@ +package keeper + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func emitEventUpdateFeed(ctx sdk.Context, feed types.Feed) { + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeUpdateFeed, + sdk.NewAttribute(types.AttributeKeySignalID, feed.SignalID), + sdk.NewAttribute(types.AttributeKeyPower, fmt.Sprintf("%d", feed.Power)), + sdk.NewAttribute(types.AttributeKeyInterval, fmt.Sprintf("%d", feed.Interval)), + sdk.NewAttribute( + types.AttributeKeyLastIntervalUpdateTimestamp, + fmt.Sprintf("%d", feed.LastIntervalUpdateTimestamp), + ), + sdk.NewAttribute( + types.AttributeKeyDeviationInThousandth, + fmt.Sprintf("%d", feed.DeviationInThousandth), + ), + ), + ) +} + +func emitEventDeleteFeed(ctx sdk.Context, feed types.Feed) { + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeDeleteFeed, + sdk.NewAttribute(types.AttributeKeySignalID, feed.SignalID), + sdk.NewAttribute(types.AttributeKeyPower, fmt.Sprintf("%d", feed.Power)), + sdk.NewAttribute(types.AttributeKeyInterval, fmt.Sprintf("%d", feed.Interval)), + sdk.NewAttribute( + types.AttributeKeyLastIntervalUpdateTimestamp, + fmt.Sprintf("%d", feed.LastIntervalUpdateTimestamp), + ), + sdk.NewAttribute( + types.AttributeKeyDeviationInThousandth, + fmt.Sprintf("%d", feed.DeviationInThousandth), + ), + ), + ) +} + +func emitEventSubmitPrice(ctx sdk.Context, valPrice types.ValidatorPrice) { + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeSubmitPrice, + sdk.NewAttribute(types.AttributeKeyPriceStatus, valPrice.PriceStatus.String()), + sdk.NewAttribute(types.AttributeKeyValidator, valPrice.Validator), + sdk.NewAttribute(types.AttributeKeySignalID, valPrice.SignalID), + sdk.NewAttribute(types.AttributeKeyPrice, fmt.Sprintf("%d", valPrice.Price)), + sdk.NewAttribute(types.AttributeKeyTimestamp, fmt.Sprintf("%d", valPrice.Timestamp)), + ), + ) +} + +func emitEventUpdatePriceService(ctx sdk.Context, priceService types.PriceService) { + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeUpdatePriceService, + sdk.NewAttribute(types.AttributeKeyHash, priceService.Hash), + sdk.NewAttribute(types.AttributeKeyVersion, priceService.Version), + sdk.NewAttribute(types.AttributeKeyURL, priceService.Url), + ), + ) +} + +func emitEventUpdateParams(ctx sdk.Context, params types.Params) { + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeUpdateParams, + sdk.NewAttribute(types.AttributeKeyParams, params.String()), + )) +} diff --git a/x/feeds/keeper/genesis.go b/x/feeds/keeper/genesis.go new file mode 100644 index 000000000..ba93b6cd8 --- /dev/null +++ b/x/feeds/keeper/genesis.go @@ -0,0 +1,29 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// InitGenesis initializes the module's state from a provided genesis state. +func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { + if err := k.SetParams(ctx, genState.Params); err != nil { + panic(err) + } + k.SetFeeds(ctx, genState.Feeds) + if err := k.SetPriceService(ctx, genState.PriceService); err != nil { + panic(err) + } + k.SetAllDelegatorSignals(ctx, genState.DelegatorSignals) +} + +// ExportGenesis returns the module's exported genesis +func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { + return &types.GenesisState{ + Params: k.GetParams(ctx), + Feeds: k.GetFeeds(ctx), + PriceService: k.GetPriceService(ctx), + DelegatorSignals: k.GetAllDelegatorSignals(ctx), + } +} diff --git a/x/feeds/keeper/genesis_test.go b/x/feeds/keeper/genesis_test.go new file mode 100644 index 000000000..38d0c4ab0 --- /dev/null +++ b/x/feeds/keeper/genesis_test.go @@ -0,0 +1,76 @@ +package keeper_test + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func (suite *KeeperTestSuite) TestExportGenesis() { + ctx := suite.ctx + + err := suite.feedsKeeper.SetParams(ctx, types.DefaultParams()) + suite.Require().NoError(err) + + err = suite.feedsKeeper.SetPriceService(ctx, types.DefaultPriceService()) + suite.Require().NoError(err) + + feeds := []types.Feed{ + { + SignalID: "crypto_price.bandusd", + Power: 10000, + Interval: 60, + LastIntervalUpdateTimestamp: 123456789, + }, + } + suite.feedsKeeper.SetFeeds(ctx, feeds) + + exportGenesis := suite.feedsKeeper.ExportGenesis(ctx) + + suite.Require().Equal(types.DefaultParams(), exportGenesis.Params) + suite.Require().Equal(types.DefaultPriceService(), exportGenesis.PriceService) + suite.Require().Equal(feeds, exportGenesis.Feeds) +} + +func (suite *KeeperTestSuite) TestInitGenesis() { + ctx := suite.ctx + + feeds := []types.Feed{ + { + SignalID: "crypto_price.bandusd", + Power: 10000, + Interval: 60, + LastIntervalUpdateTimestamp: 123456789, + }, + } + + delegatorSignals := []types.DelegatorSignals{ + { + Delegator: ValidDelegator.String(), + Signals: []types.Signal{ + { + ID: "crypto_price.bandusd", + Power: 1e9, + }, + { + ID: "crypto_price.btcusd", + Power: 1e9, + }, + }, + }, + } + + g := types.DefaultGenesisState() + g.Feeds = feeds + g.DelegatorSignals = delegatorSignals + + suite.feedsKeeper.InitGenesis(suite.ctx, *g) + + suite.Require().Equal(feeds, suite.feedsKeeper.GetFeeds(suite.ctx)) + suite.Require().Equal(types.DefaultPriceService(), suite.feedsKeeper.GetPriceService(ctx)) + suite.Require().Equal(types.DefaultParams(), suite.feedsKeeper.GetParams(ctx)) + for _, ds := range delegatorSignals { + suite.Require(). + Equal(ds.Signals, suite.feedsKeeper.GetDelegatorSignals(ctx, sdk.MustAccAddressFromBech32(ds.Delegator))) + } +} diff --git a/x/feeds/keeper/grpc_query.go b/x/feeds/keeper/grpc_query.go new file mode 100644 index 000000000..9caae81da --- /dev/null +++ b/x/feeds/keeper/grpc_query.go @@ -0,0 +1,265 @@ +package keeper + +import ( + "context" + + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +var _ types.QueryServer = queryServer{} + +type queryServer struct { + keeper Keeper +} + +func NewQueryServer(k Keeper) types.QueryServer { + return queryServer{ + keeper: k, + } +} + +// DelegatorSignals queries all signals submitted by a delegator. +func (q queryServer) DelegatorSignals( + goCtx context.Context, req *types.QueryDelegatorSignalsRequest, +) (*types.QueryDelegatorSignalsResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + delegator, err := sdk.AccAddressFromBech32(req.Delegator) + if err != nil { + return nil, err + } + + signals := q.keeper.GetDelegatorSignals(ctx, delegator) + if signals == nil { + return nil, status.Error(codes.NotFound, "no signal") + } + return &types.QueryDelegatorSignalsResponse{Signals: signals}, nil +} + +// Prices queries all current prices. +func (q queryServer) Prices( + goCtx context.Context, req *types.QueryPricesRequest, +) (*types.QueryPricesResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + // convert filter signal ids to map + reqSignalIDs := make(map[string]bool) + for _, s := range req.SignalIds { + reqSignalIDs[s] = true + } + + store := ctx.KVStore(q.keeper.storeKey) + priceStore := prefix.NewStore(store, types.PriceStoreKeyPrefix) + + filteredPrices, pageRes, err := query.GenericFilteredPaginate( + q.keeper.cdc, + priceStore, + req.Pagination, + func(key []byte, p *types.Price) (*types.Price, error) { + matchSignalID := true + + // match signal id + if len(reqSignalIDs) != 0 { + if _, ok := reqSignalIDs[p.SignalID]; !ok { + matchSignalID = false + } + } + + if matchSignalID { + return p, nil + } + + return nil, nil + }, func() *types.Price { + return &types.Price{} + }, + ) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &types.QueryPricesResponse{Prices: filteredPrices, Pagination: pageRes}, nil +} + +// Price queries price of a signal id. +func (q queryServer) Price( + goCtx context.Context, req *types.QueryPriceRequest, +) (*types.QueryPriceResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + f, err := q.keeper.GetFeed(ctx, req.SignalId) + if err != nil { + return nil, err + } + + price, _ := q.keeper.GetPrice(ctx, req.SignalId) + priceVals := q.keeper.GetValidatorPrices(ctx, req.SignalId) + + var filteredPriceVals []types.ValidatorPrice + blockTime := ctx.BlockTime().Unix() + for _, priceVal := range priceVals { + if priceVal.Timestamp > blockTime-f.Interval { + filteredPriceVals = append(filteredPriceVals, priceVal) + } + } + + return &types.QueryPriceResponse{ + Price: price, + ValidatorPrices: filteredPriceVals, + }, nil +} + +// ValidatorPrices queries all price-validator submitted by a validator. +func (q queryServer) ValidatorPrices( + goCtx context.Context, req *types.QueryValidatorPricesRequest, +) (*types.QueryValidatorPricesResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + val, err := sdk.ValAddressFromBech32(req.Validator) + if err != nil { + return nil, err + } + + var priceVals []types.ValidatorPrice + + feeds := q.keeper.GetFeeds(ctx) + for _, feed := range feeds { + priceVal, err := q.keeper.GetValidatorPrice(ctx, feed.SignalID, val) + if err == nil { + priceVals = append(priceVals, priceVal) + } + } + + return &types.QueryValidatorPricesResponse{ + ValidatorPrices: priceVals, + }, nil +} + +// ValidatorPrice queries price-validator of a specified validator and signal id. +func (q queryServer) ValidatorPrice( + goCtx context.Context, req *types.QueryValidatorPriceRequest, +) (*types.QueryValidatorPriceResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + val, err := sdk.ValAddressFromBech32(req.Validator) + if err != nil { + return nil, err + } + + priceVal, err := q.keeper.GetValidatorPrice(ctx, req.SignalId, val) + if err != nil { + return nil, err + } + + return &types.QueryValidatorPriceResponse{ + ValidatorPrice: priceVal, + }, nil +} + +// ValidValidator queries whether a validator is required to send price. +func (q queryServer) ValidValidator( + goCtx context.Context, req *types.QueryValidValidatorRequest, +) (*types.QueryValidValidatorResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + val, err := sdk.ValAddressFromBech32(req.Validator) + if err != nil { + return nil, err + } + + isValid := true + + // check if it's bonded validators. + isBonded := q.keeper.IsBondedValidator(ctx, req.Validator) + if !isBonded { + isValid = false + } + + validatorStatus := q.keeper.oracleKeeper.GetValidatorStatus(ctx, val) + if !validatorStatus.IsActive { + isValid = false + } + + return &types.QueryValidValidatorResponse{Valid: isValid}, nil +} + +// Feeds queries all current feeds. +func (q queryServer) Feeds( + goCtx context.Context, req *types.QueryFeedsRequest, +) (*types.QueryFeedsResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + // convert filter signal ids to map + reqSignalIDs := make(map[string]bool) + for _, s := range req.SignalIds { + reqSignalIDs[s] = true + } + + store := ctx.KVStore(q.keeper.storeKey) + feedStore := prefix.NewStore(store, types.FeedStoreKeyPrefix) + + filteredFeeds, pageRes, err := query.GenericFilteredPaginate( + q.keeper.cdc, + feedStore, + req.Pagination, + func(key []byte, f *types.Feed) (*types.Feed, error) { + matchSignalID := true + + // match signal id + if len(reqSignalIDs) != 0 { + if _, ok := reqSignalIDs[f.SignalID]; !ok { + matchSignalID = false + } + } + + if matchSignalID { + return f, nil + } + + return nil, nil + }, func() *types.Feed { + return &types.Feed{} + }, + ) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &types.QueryFeedsResponse{Feeds: filteredFeeds, Pagination: pageRes}, nil +} + +// SupportedFeeds queries all current supported feeds. +func (q queryServer) SupportedFeeds( + goCtx context.Context, _ *types.QuerySupportedFeedsRequest, +) (*types.QuerySupportedFeedsResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + return &types.QuerySupportedFeedsResponse{ + Feeds: q.keeper.GetSupportedFeedsByPower(ctx), + }, nil +} + +// PriceService queries current price service. +func (q queryServer) PriceService( + goCtx context.Context, _ *types.QueryPriceServiceRequest, +) (*types.QueryPriceServiceResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + return &types.QueryPriceServiceResponse{ + PriceService: q.keeper.GetPriceService(ctx), + }, nil +} + +// Params queries all params of feeds module. +func (q queryServer) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + + return &types.QueryParamsResponse{ + Params: q.keeper.GetParams(ctx), + }, nil +} diff --git a/x/feeds/keeper/grpc_query_test.go b/x/feeds/keeper/grpc_query_test.go new file mode 100644 index 000000000..3205fb35a --- /dev/null +++ b/x/feeds/keeper/grpc_query_test.go @@ -0,0 +1,457 @@ +package keeper_test + +import ( + gocontext "context" + "fmt" + + "github.com/cosmos/cosmos-sdk/types/query" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func (suite *KeeperTestSuite) TestQueryDelegatorSignals() { + ctx, queryClient := suite.ctx, suite.queryClient + + // setup + signals := []types.Signal{ + { + ID: "crypto_price.bandusd", + Power: 1e9, + }, + { + ID: "crypto_price.btcusd", + Power: 1e9, + }, + } + _, err := suite.msgServer.SubmitSignals(ctx, &types.MsgSubmitSignals{ + Delegator: ValidDelegator.String(), + Signals: signals, + }) + suite.Require().NoError(err) + + // query and check + res, err := queryClient.DelegatorSignals(gocontext.Background(), &types.QueryDelegatorSignalsRequest{ + Delegator: ValidDelegator.String(), + }) + suite.Require().NoError(err) + suite.Require().Equal(&types.QueryDelegatorSignalsResponse{ + Signals: signals, + }, res) +} + +func (suite *KeeperTestSuite) TestQueryPrices() { + ctx, queryClient := suite.ctx, suite.queryClient + + // setup + prices := []*types.Price{ + { + SignalID: "crypto_price.atomusd", + Price: 100000000, + Timestamp: 1234567890, + }, + { + SignalID: "crypto_price.bandusd", + Price: 200000000, + Timestamp: 1234567890, + }, + } + + for _, price := range prices { + suite.feedsKeeper.SetPrice(ctx, *price) + } + + // query and check + var ( + req *types.QueryPricesRequest + expRes *types.QueryPricesResponse + ) + + testCases := []struct { + msg string + malleate func() + expPass bool + }{ + { + "all prices", + func() { + req = &types.QueryPricesRequest{} + expRes = &types.QueryPricesResponse{ + Prices: prices, + } + }, + true, + }, + { + "limit 1", + func() { + req = &types.QueryPricesRequest{ + Pagination: &query.PageRequest{Limit: 1}, + } + expRes = &types.QueryPricesResponse{ + Prices: prices[:1], + } + }, + true, + }, + { + "filter", + func() { + req = &types.QueryPricesRequest{ + SignalIds: []string{"crypto_price.bandusd"}, + } + expRes = &types.QueryPricesResponse{ + Prices: prices[1:], + } + }, + true, + }, + } + + for _, testCase := range testCases { + suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { + testCase.malleate() + + res, err := queryClient.Prices(gocontext.Background(), req) + + if testCase.expPass { + suite.Require().NoError(err) + suite.Require().Equal(expRes.GetPrices(), res.GetPrices()) + } else { + suite.Require().Error(err) + suite.Require().Nil(expRes) + } + }) + } +} + +func (suite *KeeperTestSuite) TestQueryPrice() { + ctx, queryClient := suite.ctx, suite.queryClient + + // setup + feed := types.Feed{ + SignalID: "crypto_price.bandusd", + Power: 100000000, + Interval: 100, + LastIntervalUpdateTimestamp: 1234567890, + } + suite.feedsKeeper.SetFeed(ctx, feed) + + price := types.Price{ + SignalID: "crypto_price.bandusd", + Price: 100000000, + Timestamp: 1234567890, + } + suite.feedsKeeper.SetPrice(ctx, price) + + priceVal := types.ValidatorPrice{ + PriceStatus: types.PriceStatusAvailable, + Validator: ValidValidator.String(), + SignalID: "crypto_price.bandusd", + Price: 1e9, + Timestamp: ctx.BlockTime().Unix(), + } + err := suite.feedsKeeper.SetValidatorPrice(ctx, priceVal) + suite.Require().NoError(err) + + // query and check + res, err := queryClient.Price(gocontext.Background(), &types.QueryPriceRequest{ + SignalId: "crypto_price.bandusd", + }) + suite.Require().NoError(err) + suite.Require().Equal(&types.QueryPriceResponse{ + Price: price, + ValidatorPrices: []types.ValidatorPrice{ + priceVal, + }, + }, res) + + res, err = queryClient.Price(gocontext.Background(), &types.QueryPriceRequest{ + SignalId: "crypto_price.atomusd", + }) + suite.Require().ErrorContains(err, "feed not found") + suite.Require().Nil(res) +} + +func (suite *KeeperTestSuite) TestQueryValidatorPrices() { + ctx, queryClient := suite.ctx, suite.queryClient + + // setup + feeds := []types.Feed{ + { + SignalID: "crypto_price.atomusd", + Power: 100000000, + Interval: 100, + LastIntervalUpdateTimestamp: 1234567890, + }, + { + SignalID: "crypto_price.bandusd", + Power: 100000000, + Interval: 100, + LastIntervalUpdateTimestamp: 1234567890, + }, + } + for _, feed := range feeds { + suite.feedsKeeper.SetFeed(ctx, feed) + } + + priceVals := []types.ValidatorPrice{ + { + Validator: ValidValidator.String(), + SignalID: "crypto_price.atomusd", + Price: 1e9, + Timestamp: ctx.BlockTime().Unix(), + }, + { + Validator: ValidValidator.String(), + SignalID: "crypto_price.bandusd", + Price: 1e9, + Timestamp: ctx.BlockTime().Unix(), + }, + } + for _, priceVal := range priceVals { + err := suite.feedsKeeper.SetValidatorPrice(ctx, priceVal) + suite.Require().NoError(err) + } + + // query and check + res, err := queryClient.ValidatorPrices(gocontext.Background(), &types.QueryValidatorPricesRequest{ + Validator: ValidValidator.String(), + }) + suite.Require().NoError(err) + suite.Require().Equal(&types.QueryValidatorPricesResponse{ + ValidatorPrices: priceVals, + }, res) + + res, err = queryClient.ValidatorPrices(gocontext.Background(), &types.QueryValidatorPricesRequest{ + Validator: InvalidValidator.String(), + }) + suite.Require().NoError(err) + suite.Require().Equal(&types.QueryValidatorPricesResponse{ + ValidatorPrices: nil, + }, res) +} + +func (suite *KeeperTestSuite) TestQueryValidatorPrice() { + ctx, queryClient := suite.ctx, suite.queryClient + + // setup + priceVal := types.ValidatorPrice{ + Validator: ValidValidator.String(), + SignalID: "crypto_price.bandusd", + Price: 1e9, + Timestamp: ctx.BlockTime().Unix(), + } + err := suite.feedsKeeper.SetValidatorPrice(ctx, priceVal) + suite.Require().NoError(err) + + // query and check + res, err := queryClient.ValidatorPrice(gocontext.Background(), &types.QueryValidatorPriceRequest{ + SignalId: "crypto_price.bandusd", + Validator: ValidValidator.String(), + }) + suite.Require().NoError(err) + suite.Require().Equal(&types.QueryValidatorPriceResponse{ + ValidatorPrice: priceVal, + }, res) + + res, err = queryClient.ValidatorPrice(gocontext.Background(), &types.QueryValidatorPriceRequest{ + SignalId: "crypto_price.atomusd", + Validator: ValidValidator.String(), + }) + suite.Require().ErrorContains(err, "validator price not found") + suite.Require().Nil(res) +} + +func (suite *KeeperTestSuite) TestQueryValidValidator() { + queryClient := suite.queryClient + + // query and check + res, err := queryClient.ValidValidator(gocontext.Background(), &types.QueryValidValidatorRequest{ + Validator: ValidValidator.String(), + }) + suite.Require().NoError(err) + suite.Require().Equal(&types.QueryValidValidatorResponse{ + Valid: true, + }, res) + + res, err = queryClient.ValidValidator(gocontext.Background(), &types.QueryValidValidatorRequest{ + Validator: InvalidValidator.String(), + }) + suite.Require().NoError(err) + suite.Require().Equal(&types.QueryValidValidatorResponse{ + Valid: false, + }, res) +} + +func (suite *KeeperTestSuite) TestQueryFeeds() { + ctx, queryClient := suite.ctx, suite.queryClient + + // setup + feeds := []*types.Feed{ + { + SignalID: "crypto_price.atomusd", + Power: 100000000, + Interval: 100, + LastIntervalUpdateTimestamp: 1234567890, + }, + { + SignalID: "crypto_price.bandusd", + Power: 100000000, + Interval: 100, + LastIntervalUpdateTimestamp: 1234567890, + }, + } + + for _, feed := range feeds { + suite.feedsKeeper.SetFeed(ctx, *feed) + } + + // query and check + var ( + req *types.QueryFeedsRequest + expRes *types.QueryFeedsResponse + ) + + testCases := []struct { + msg string + malleate func() + expPass bool + }{ + { + "all feeds", + func() { + req = &types.QueryFeedsRequest{} + expRes = &types.QueryFeedsResponse{ + Feeds: feeds, + } + }, + true, + }, + { + "limit 1", + func() { + req = &types.QueryFeedsRequest{ + Pagination: &query.PageRequest{Limit: 1}, + } + expRes = &types.QueryFeedsResponse{ + Feeds: feeds[:1], + } + }, + true, + }, + { + "filter", + func() { + req = &types.QueryFeedsRequest{ + SignalIds: []string{"crypto_price.bandusd"}, + } + expRes = &types.QueryFeedsResponse{ + Feeds: feeds[1:], + } + }, + true, + }, + } + + for _, testCase := range testCases { + suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { + testCase.malleate() + + res, err := queryClient.Feeds(gocontext.Background(), req) + + if testCase.expPass { + suite.Require().NoError(err) + suite.Require().Equal(expRes.GetFeeds(), res.GetFeeds()) + } else { + suite.Require().Error(err) + suite.Require().Nil(expRes) + } + }) + } +} + +func (suite *KeeperTestSuite) TestQuerySupportedFeeds() { + ctx, queryClient := suite.ctx, suite.queryClient + + // query and check + var ( + req *types.QuerySupportedFeedsRequest + expRes *types.QuerySupportedFeedsResponse + ) + + testCases := []struct { + msg string + malleate func() + expPass bool + }{ + { + "no supported feeds", + func() { + req = &types.QuerySupportedFeedsRequest{} + expRes = &types.QuerySupportedFeedsResponse{} + }, + true, + }, + { + "1 supported symbol", + func() { + feeds := []types.Feed{ + { + SignalID: "crypto_price.bandusd", + Power: 100000000, + Interval: 100, + LastIntervalUpdateTimestamp: 1234567890, + }, + } + + for _, feed := range feeds { + suite.feedsKeeper.SetFeed(ctx, feed) + } + + req = &types.QuerySupportedFeedsRequest{} + expRes = &types.QuerySupportedFeedsResponse{ + Feeds: feeds, + } + }, + true, + }, + } + + for _, testCase := range testCases { + suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { + testCase.malleate() + + res, err := queryClient.SupportedFeeds(gocontext.Background(), req) + + if testCase.expPass { + suite.Require().NoError(err) + suite.Require().Equal(expRes, res) + } else { + suite.Require().Error(err) + suite.Require().Nil(expRes) + } + }) + } +} + +func (suite *KeeperTestSuite) TestQueryPriceService() { + ctx, queryClient := suite.ctx, suite.queryClient + + // query and check + res, err := queryClient.PriceService(gocontext.Background(), &types.QueryPriceServiceRequest{}) + suite.Require().NoError(err) + suite.Require().Equal(&types.QueryPriceServiceResponse{ + PriceService: suite.feedsKeeper.GetPriceService(ctx), + }, res) +} + +func (suite *KeeperTestSuite) TestQueryParams() { + ctx, queryClient := suite.ctx, suite.queryClient + + // query and check + res, err := queryClient.Params(gocontext.Background(), &types.QueryParamsRequest{}) + suite.Require().NoError(err) + suite.Require().Equal(&types.QueryParamsResponse{ + Params: suite.feedsKeeper.GetParams(ctx), + }, res) +} diff --git a/x/feeds/keeper/hooks.go b/x/feeds/keeper/hooks.go new file mode 100644 index 000000000..c4a283639 --- /dev/null +++ b/x/feeds/keeper/hooks.go @@ -0,0 +1,88 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +type Hooks struct { + k Keeper +} + +var _ stakingtypes.StakingHooks = Hooks{} + +func (k Keeper) Hooks() Hooks { + return Hooks{k} +} + +func (h Hooks) AfterValidatorCreated(_ sdk.Context, _ sdk.ValAddress) error { + return nil +} + +func (h Hooks) BeforeValidatorModified(_ sdk.Context, _ sdk.ValAddress) error { + return nil +} + +func (h Hooks) AfterValidatorRemoved(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error { + return nil +} + +func (h Hooks) AfterValidatorBonded(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error { + return nil +} + +func (h Hooks) AfterValidatorBeginUnbonding(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error { + return nil +} + +func (h Hooks) BeforeDelegationCreated(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { + return nil +} + +func (h Hooks) BeforeDelegationSharesModified(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { + return nil +} + +func (h Hooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { + delegated := h.k.stakingKeeper.GetDelegatorBonded(ctx, delAddr) + + // remove power of removed delegation from total delegation + removedDelegation, found := h.k.stakingKeeper.GetDelegation(ctx, delAddr, valAddr) + if found { + validatorAddr, err := sdk.ValAddressFromBech32(removedDelegation.ValidatorAddress) + if err != nil { + panic(err) // shouldn't happen + } + validator, found := h.k.stakingKeeper.GetValidator(ctx, validatorAddr) + if found { + shares := removedDelegation.Shares + tokens := validator.TokensFromSharesTruncated(shares) + delegated = delegated.Sub(tokens.RoundInt()) + } + } + + power := sumPower(h.k.GetDelegatorSignals(ctx, delAddr)) + if power > delegated.Int64() { + return types.ErrUnableToUndelegate + } + return nil +} + +func (h Hooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, _ sdk.ValAddress) error { + delegated := h.k.stakingKeeper.GetDelegatorBonded(ctx, delAddr).Int64() + power := sumPower(h.k.GetDelegatorSignals(ctx, delAddr)) + if power > delegated { + return types.ErrUnableToUndelegate + } + return nil +} + +func (h Hooks) BeforeValidatorSlashed(_ sdk.Context, _ sdk.ValAddress, _ sdk.Dec) error { + return nil +} + +func (h Hooks) AfterUnbondingInitiated(_ sdk.Context, _ uint64) error { + return nil +} diff --git a/x/feeds/keeper/keeper.go b/x/feeds/keeper/keeper.go new file mode 100644 index 000000000..435400f31 --- /dev/null +++ b/x/feeds/keeper/keeper.go @@ -0,0 +1,63 @@ +package keeper + +import ( + "fmt" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +type Keeper struct { + storeKey storetypes.StoreKey + cdc codec.BinaryCodec + oracleKeeper types.OracleKeeper + stakingKeeper types.StakingKeeper + + authority string +} + +// NewKeeper creates a new feeds Keeper instance. +func NewKeeper( + cdc codec.BinaryCodec, + storeKey storetypes.StoreKey, + oracleKeeper types.OracleKeeper, + stakingKeeper types.StakingKeeper, + authority string, +) Keeper { + return Keeper{ + cdc: cdc, + storeKey: storeKey, + oracleKeeper: oracleKeeper, + stakingKeeper: stakingKeeper, + authority: authority, + } +} + +// GetAuthority returns the x/feeds module's authority. +func (k Keeper) GetAuthority() string { + return k.authority +} + +// Logger returns a module-specific logger. +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +} + +// IsBondedValidator checks is the validator is in the bonded validators. +func (k Keeper) IsBondedValidator(ctx sdk.Context, valAddr string) bool { + addr, err := sdk.ValAddressFromBech32(valAddr) + if err != nil { + return false + } + + val, found := k.stakingKeeper.GetValidator(ctx, addr) + if !found { + return false + } + + return val.IsBonded() +} diff --git a/x/feeds/keeper/keeper_feed.go b/x/feeds/keeper/keeper_feed.go new file mode 100644 index 000000000..fb0982873 --- /dev/null +++ b/x/feeds/keeper/keeper_feed.go @@ -0,0 +1,118 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// GetFeedsIterator returns an iterator for feeds store. +func (k Keeper) GetFeedsIterator(ctx sdk.Context) sdk.Iterator { + return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.FeedStoreKeyPrefix) +} + +// GetFeeds returns a list of all feeds. +func (k Keeper) GetFeeds(ctx sdk.Context) (feeds []types.Feed) { + iterator := k.GetFeedsIterator(ctx) + defer func(iterator sdk.Iterator) { + _ = iterator.Close() + }(iterator) + + for ; iterator.Valid(); iterator.Next() { + var feed types.Feed + k.cdc.MustUnmarshal(iterator.Value(), &feed) + feeds = append(feeds, feed) + } + + return +} + +// GetFeed returns a feed by signal id. +func (k Keeper) GetFeed(ctx sdk.Context, signalID string) (types.Feed, error) { + bz := ctx.KVStore(k.storeKey).Get(types.FeedStoreKey(signalID)) + if bz == nil { + return types.Feed{}, types.ErrFeedNotFound.Wrapf("failed to get feed detail for signal id: %s", signalID) + } + + var f types.Feed + k.cdc.MustUnmarshal(bz, &f) + + return f, nil +} + +// SetFeeds sets multiple feeds. +func (k Keeper) SetFeeds(ctx sdk.Context, feeds []types.Feed) { + for _, feed := range feeds { + k.SetFeed(ctx, feed) + } +} + +// SetFeed sets a new feed to the feeds store or replace if feed with the same signal id existed. +func (k Keeper) SetFeed(ctx sdk.Context, feed types.Feed) { + // set new timestamp if interval is updated + prevFeed, err := k.GetFeed(ctx, feed.SignalID) + k.deleteFeedByPowerIndex(ctx, prevFeed) + if err == nil { + if prevFeed.Interval != feed.Interval { + feed.LastIntervalUpdateTimestamp = ctx.BlockTime().Unix() + } + } + + if feed.Power > 0 { + ctx.KVStore(k.storeKey).Set(types.FeedStoreKey(feed.SignalID), k.cdc.MustMarshal(&feed)) + k.setFeedByPowerIndex(ctx, feed) + emitEventUpdateFeed(ctx, feed) + } else { + k.DeleteFeed(ctx, feed) + emitEventDeleteFeed(ctx, feed) + } +} + +// DeleteFeed deletes a feed from the feeds store. +func (k Keeper) DeleteFeed(ctx sdk.Context, feed types.Feed) { + k.DeletePrice(ctx, feed.SignalID) + k.deleteFeedByPowerIndex(ctx, feed) + ctx.KVStore(k.storeKey).Delete(types.FeedStoreKey(feed.SignalID)) +} + +// setFeedByPowerIndex sets a feed in feedx by power index store. +func (k Keeper) setFeedByPowerIndex(ctx sdk.Context, feed types.Feed) { + ctx.KVStore(k.storeKey). + Set(types.FeedsByPowerIndexKey(feed.SignalID, feed.Power), []byte(feed.SignalID)) +} + +// DeleteFeedByPowerIndex deletes a feed from feedx by power index store. +func (k Keeper) deleteFeedByPowerIndex(ctx sdk.Context, feed types.Feed) { + ctx.KVStore(k.storeKey).Delete(types.FeedsByPowerIndexKey(feed.SignalID, feed.Power)) +} + +// GetSupportedFeedsByPower gets the current group of bonded validators sorted by power-rank. +func (k Keeper) GetSupportedFeedsByPower(ctx sdk.Context) []types.Feed { + maxFeeds := k.GetParams(ctx).MaxSupportedFeeds + feeds := make([]types.Feed, maxFeeds) + + iterator := k.FeedsPowerStoreIterator(ctx) + defer func(iterator sdk.Iterator) { + _ = iterator.Close() + }(iterator) + + i := 0 + for ; iterator.Valid() && i < int(maxFeeds); iterator.Next() { + bz := iterator.Value() + signalID := string(bz) + feed, err := k.GetFeed(ctx, signalID) + if err != nil || feed.Interval == 0 { + continue + } + + feeds[i] = feed + i++ + } + + return feeds[:i] // trim +} + +// FeedsPowerStoreIterator returns an iterator for feeds by power index store. +func (k Keeper) FeedsPowerStoreIterator(ctx sdk.Context) sdk.Iterator { + return sdk.KVStoreReversePrefixIterator(ctx.KVStore(k.storeKey), types.FeedsByPowerIndexKeyPrefix) +} diff --git a/x/feeds/keeper/keeper_price.go b/x/feeds/keeper/keeper_price.go new file mode 100644 index 000000000..911d99549 --- /dev/null +++ b/x/feeds/keeper/keeper_price.go @@ -0,0 +1,238 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// ================================== +// Price +// ================================== + +// GetPricesIterator returns an iterator for prices store. +func (k Keeper) GetPricesIterator(ctx sdk.Context) sdk.Iterator { + return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.PriceStoreKeyPrefix) +} + +// GetPrices returns a list of all prices. +func (k Keeper) GetPrices(ctx sdk.Context) (prices []types.Price) { + iterator := k.GetPricesIterator(ctx) + defer func(iterator sdk.Iterator) { + _ = iterator.Close() + }(iterator) + + for ; iterator.Valid(); iterator.Next() { + var price types.Price + k.cdc.MustUnmarshal(iterator.Value(), &price) + prices = append(prices, price) + } + + return prices +} + +// GetPrice returns a price by signal id. +func (k Keeper) GetPrice(ctx sdk.Context, signalID string) (types.Price, error) { + bz := ctx.KVStore(k.storeKey).Get(types.PriceStoreKey(signalID)) + if bz == nil { + return types.Price{}, types.ErrPriceNotFound.Wrapf("failed to get price for signal id: %s", signalID) + } + + var price types.Price + k.cdc.MustUnmarshal(bz, &price) + + return price, nil +} + +// SetPrice sets multiple prices. +func (k Keeper) SetPrices(ctx sdk.Context, prices []types.Price) { + for _, price := range prices { + k.SetPrice(ctx, price) + } +} + +// SetPRice sets a new price to the prices store or replace if price with the same signal id existed. +func (k Keeper) SetPrice(ctx sdk.Context, price types.Price) { + ctx.KVStore(k.storeKey).Set(types.PriceStoreKey(price.SignalID), k.cdc.MustMarshal(&price)) +} + +// DeletePrice deletes a price by signal id. +func (k Keeper) DeletePrice(ctx sdk.Context, signalID string) { + k.DeleteValidatorPrices(ctx, signalID) + ctx.KVStore(k.storeKey).Delete(types.PriceStoreKey(signalID)) +} + +// CalculatePrice calculates final price from price-validator and punish validators those did not report. +func (k Keeper) CalculatePrice(ctx sdk.Context, feed types.Feed) (types.Price, error) { + var priceFeedInfos []types.PriceFeedInfo + blockTime := ctx.BlockTime() + transitionTime := k.GetParams(ctx).TransitionTime + + k.stakingKeeper.IterateBondedValidatorsByPower( + ctx, + func(idx int64, val stakingtypes.ValidatorI) (stop bool) { + address := val.GetOperator() + power := val.GetTokens().Uint64() + status := k.oracleKeeper.GetValidatorStatus(ctx, address) + + if status.IsActive { + lastTime := status.Since.Unix() + priceVal, err := k.GetValidatorPrice(ctx, feed.SignalID, address) + + if err == nil { + // if timestamp of price is in acception period, append it + if priceVal.Timestamp >= blockTime.Unix()-feed.Interval { + priceFeedInfos = append( + priceFeedInfos, types.PriceFeedInfo{ + PriceStatus: priceVal.PriceStatus, + Price: priceVal.Price, + Power: power, + Deviation: 0, + Timestamp: priceVal.Timestamp, + Index: idx, + }, + ) + } + + // update last time of action + if priceVal.Timestamp > lastTime { + lastTime = priceVal.Timestamp + } + } + + if feed.LastIntervalUpdateTimestamp+transitionTime > lastTime { + lastTime = feed.LastIntervalUpdateTimestamp + transitionTime + } + + // deactivate if last time of action is too old + if lastTime < blockTime.Unix()-feed.Interval { + k.oracleKeeper.MissReport(ctx, address, blockTime) + } + } + + return false + }, + ) + + n := len(priceFeedInfos) + if n == 0 { + return types.Price{}, types.ErrNotEnoughValidatorPrice + } + + totalPower, availablePower, _, unsupportedPower := types.CalculatePricesPowers(priceFeedInfos) + // If more than half of the total have unsupported price status, it returns an unsupported price status. + if unsupportedPower > totalPower/2 { + return types.Price{ + PriceStatus: types.PriceStatusUnsupported, + SignalID: feed.SignalID, + Price: 0, + Timestamp: ctx.BlockTime().Unix(), + }, nil + } + // If less than half of total have available price status, it returns an unavailable price status. + if availablePower < totalPower/2 { + return types.Price{ + PriceStatus: types.PriceStatusUnavailable, + SignalID: feed.SignalID, + Price: 0, + Timestamp: ctx.BlockTime().Unix(), + }, nil + } + + price, err := types.CalculateMedianPriceFeedInfo( + types.FilterPriceFeedInfos(priceFeedInfos, types.PriceStatusAvailable), + ) + if err != nil { + return types.Price{}, err + } + + return types.Price{ + PriceStatus: types.PriceStatusAvailable, + SignalID: feed.SignalID, + Price: price, + Timestamp: ctx.BlockTime().Unix(), + }, nil +} + +// ================================== +// Validator Price +// ================================== + +// GetValidatorPricesIterator returns an iterator for price-validators store. +func (k Keeper) GetValidatorPricesIterator(ctx sdk.Context, signalID string) sdk.Iterator { + return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.ValidatorPricesStoreKey(signalID)) +} + +// GetValidatorPrices gets a list of all price-validators. +func (k Keeper) GetValidatorPrices(ctx sdk.Context, signalID string) (priceVals []types.ValidatorPrice) { + iterator := k.GetValidatorPricesIterator(ctx, signalID) + defer func(iterator sdk.Iterator) { + _ = iterator.Close() + }(iterator) + + for ; iterator.Valid(); iterator.Next() { + var priceVal types.ValidatorPrice + k.cdc.MustUnmarshal(iterator.Value(), &priceVal) + priceVals = append(priceVals, priceVal) + } + + return priceVals +} + +// GetValidatorPrice gets a price-validator by signal id. +func (k Keeper) GetValidatorPrice(ctx sdk.Context, signalID string, val sdk.ValAddress) (types.ValidatorPrice, error) { + bz := ctx.KVStore(k.storeKey).Get(types.ValidatorPriceStoreKey(signalID, val)) + if bz == nil { + return types.ValidatorPrice{}, types.ErrValidatorPriceNotFound.Wrapf( + "failed to get validator price for signal id: %s, validator: %s", + signalID, + val.String(), + ) + } + + var priceVal types.ValidatorPrice + k.cdc.MustUnmarshal(bz, &priceVal) + + return priceVal, nil +} + +// SetValidatorPrices sets multiple price-validator. +func (k Keeper) SetValidatorPrices(ctx sdk.Context, priceVals []types.ValidatorPrice) error { + for _, priceVal := range priceVals { + if err := k.SetValidatorPrice(ctx, priceVal); err != nil { + return err + } + } + return nil +} + +// SetValidatorPrice sets a new price-validator or replace if price-validator with the same signal id and validator address existed. +func (k Keeper) SetValidatorPrice(ctx sdk.Context, priceVal types.ValidatorPrice) error { + valAddress, err := sdk.ValAddressFromBech32(priceVal.Validator) + if err != nil { + return err + } + + ctx.KVStore(k.storeKey). + Set(types.ValidatorPriceStoreKey(priceVal.SignalID, valAddress), k.cdc.MustMarshal(&priceVal)) + + return nil +} + +// DeleteValidatorPrices deletes all price-validator of specified signal id. +func (k Keeper) DeleteValidatorPrices(ctx sdk.Context, signalID string) { + iterator := k.GetValidatorPricesIterator(ctx, signalID) + defer func(iterator sdk.Iterator) { + _ = iterator.Close() + }(iterator) + + for ; iterator.Valid(); iterator.Next() { + ctx.KVStore(k.storeKey).Delete(iterator.Key()) + } +} + +// DeleteValidatorPrice deletes a price-validators. +func (k Keeper) DeleteValidatorPrice(ctx sdk.Context, signalID string, val sdk.ValAddress) { + ctx.KVStore(k.storeKey).Delete(types.ValidatorPriceStoreKey(signalID, val)) +} diff --git a/x/feeds/keeper/keeper_price_service.go b/x/feeds/keeper/keeper_price_service.go new file mode 100644 index 000000000..78a5499f4 --- /dev/null +++ b/x/feeds/keeper/keeper_price_service.go @@ -0,0 +1,29 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// GetPriceService gets the current price service. +func (k Keeper) GetPriceService(ctx sdk.Context) (oc types.PriceService) { + bz := ctx.KVStore(k.storeKey).Get(types.PriceServiceStoreKey) + if bz == nil { + return oc + } + + k.cdc.MustUnmarshal(bz, &oc) + + return oc +} + +// SetPriceService sets new price service to the store. +func (k Keeper) SetPriceService(ctx sdk.Context, ps types.PriceService) error { + if err := ps.Validate(); err != nil { + return err + } + + ctx.KVStore(k.storeKey).Set(types.PriceServiceStoreKey, k.cdc.MustMarshal(&ps)) + return nil +} diff --git a/x/feeds/keeper/keeper_price_service_test.go b/x/feeds/keeper/keeper_price_service_test.go new file mode 100644 index 000000000..7172e553e --- /dev/null +++ b/x/feeds/keeper/keeper_price_service_test.go @@ -0,0 +1,22 @@ +package keeper_test + +import ( + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func (suite *KeeperTestSuite) TestGetSetPriceService() { + ctx := suite.ctx + + // set + expPriceService := types.PriceService{ + Hash: "hash", + Version: "1.0.0", + Url: "https://bandprotocol.com/", + } + err := suite.feedsKeeper.SetPriceService(ctx, expPriceService) + suite.Require().NoError(err) + + // get + priceService := suite.feedsKeeper.GetPriceService(ctx) + suite.Require().Equal(expPriceService, priceService) +} diff --git a/x/feeds/keeper/keeper_price_test.go b/x/feeds/keeper/keeper_price_test.go new file mode 100644 index 000000000..16d39d844 --- /dev/null +++ b/x/feeds/keeper/keeper_price_test.go @@ -0,0 +1,144 @@ +package keeper_test + +import ( + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func (suite *KeeperTestSuite) TestGetSetDeletePrice() { + ctx := suite.ctx + + // set + expPrice := types.Price{ + SignalID: "crypto_price.bandusd", + Price: 1e10, + Timestamp: ctx.BlockTime().Unix(), + } + suite.feedsKeeper.SetPrice(ctx, expPrice) + + // get + price, err := suite.feedsKeeper.GetPrice(ctx, "crypto_price.bandusd") + suite.Require().NoError(err) + suite.Require().Equal(expPrice, price) + + // delete + suite.feedsKeeper.DeletePrice(ctx, "crypto_price.bandusd") + + // get + _, err = suite.feedsKeeper.GetPrice(ctx, "crypto_price.bandusd") + suite.Require().ErrorContains(err, "price not found") +} + +func (suite *KeeperTestSuite) TestGetSetPrices() { + ctx := suite.ctx + + // set + expPrices := []types.Price{ + { + SignalID: "crypto_price.atomusd", + Price: 1e10, + Timestamp: ctx.BlockTime().Unix(), + }, + { + SignalID: "crypto_price.bandusd", + Price: 1e10, + Timestamp: ctx.BlockTime().Unix(), + }, + } + suite.feedsKeeper.SetPrices(ctx, expPrices) + + // get + prices := suite.feedsKeeper.GetPrices(ctx) + suite.Require().Equal(expPrices, prices) +} + +func (suite *KeeperTestSuite) TestGetSetDeleteValidatorPrice() { + ctx := suite.ctx + + // set + expPriceVal := types.ValidatorPrice{ + Validator: ValidValidator.String(), + SignalID: "crypto_price.bandusd", + Price: 1e10, + Timestamp: ctx.BlockTime().Unix(), + } + err := suite.feedsKeeper.SetValidatorPrice(ctx, expPriceVal) + suite.Require().NoError(err) + + // get + priceVal, err := suite.feedsKeeper.GetValidatorPrice(ctx, "crypto_price.bandusd", ValidValidator) + suite.Require().NoError(err) + suite.Require().Equal(expPriceVal, priceVal) + + // delete + suite.feedsKeeper.DeleteValidatorPrice(ctx, "crypto_price.bandusd", ValidValidator) + + // get + _, err = suite.feedsKeeper.GetValidatorPrice(ctx, "crypto_price.bandusd", ValidValidator) + suite.Require().ErrorContains(err, "validator price not found") +} + +func (suite *KeeperTestSuite) TestGetSetValidatorPrices() { + ctx := suite.ctx + + // set + expPriceVals := []types.ValidatorPrice{ + { + Validator: ValidValidator.String(), + SignalID: "crypto_price.bandusd", + Price: 1e10, + Timestamp: ctx.BlockTime().Unix(), + }, + { + Validator: ValidValidator2.String(), + SignalID: "crypto_price.bandusd", + Price: 1e10 + 5, + Timestamp: ctx.BlockTime().Unix(), + }, + } + err := suite.feedsKeeper.SetValidatorPrices(ctx, expPriceVals) + suite.Require().NoError(err) + + // get + priceVals := suite.feedsKeeper.GetValidatorPrices(ctx, "crypto_price.bandusd") + suite.Require().Equal(expPriceVals, priceVals) +} + +func (suite *KeeperTestSuite) TestCalculatePrice() { + ctx := suite.ctx + + // set + feed := types.Feed{ + SignalID: "crypto_price.bandusd", + Power: 1e10, + Interval: 60, + LastIntervalUpdateTimestamp: ctx.BlockTime().Unix(), + } + suite.feedsKeeper.SetFeed(ctx, feed) + err := suite.feedsKeeper.SetValidatorPrices(ctx, []types.ValidatorPrice{ + { + PriceStatus: types.PriceStatusAvailable, + Validator: ValidValidator.String(), + SignalID: "crypto_price.bandusd", + Price: 1000, + Timestamp: ctx.BlockTime().Unix(), + }, + { + PriceStatus: types.PriceStatusAvailable, + Validator: ValidValidator2.String(), + SignalID: "crypto_price.bandusd", + Price: 2000, + Timestamp: ctx.BlockTime().Unix(), + }, + }) + suite.Require().NoError(err) + + // cal + price, err := suite.feedsKeeper.CalculatePrice(ctx, feed) + suite.Require().NoError(err) + suite.Require().Equal(types.Price{ + PriceStatus: types.PriceStatusAvailable, + SignalID: "crypto_price.bandusd", + Price: 1000, + Timestamp: ctx.BlockTime().Unix(), + }, price) +} diff --git a/x/feeds/keeper/keeper_signal.go b/x/feeds/keeper/keeper_signal.go new file mode 100644 index 000000000..0deac7f6f --- /dev/null +++ b/x/feeds/keeper/keeper_signal.go @@ -0,0 +1,60 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// GetDelegatorSignals returns a list of all signals of a delegator. +func (k Keeper) GetDelegatorSignals(ctx sdk.Context, delegator sdk.AccAddress) []types.Signal { + bz := ctx.KVStore(k.storeKey).Get(types.DelegatorSignalStoreKey(delegator)) + if bz == nil { + return nil + } + + var s types.DelegatorSignals + k.cdc.MustUnmarshal(bz, &s) + + return s.Signals +} + +// DeleteDelegatorSignals deletes all signals of a delegator. +func (k Keeper) DeleteDelegatorSignals(ctx sdk.Context, delegator sdk.AccAddress) { + ctx.KVStore(k.storeKey). + Delete(types.DelegatorSignalStoreKey(delegator)) +} + +// SetDelegatorSignals sets multiple signals of a delegator. +func (k Keeper) SetDelegatorSignals(ctx sdk.Context, signals types.DelegatorSignals) { + ctx.KVStore(k.storeKey). + Set(types.DelegatorSignalStoreKey(sdk.MustAccAddressFromBech32(signals.Delegator)), k.cdc.MustMarshal(&signals)) +} + +// GetDelegatorSignalsIterator returns an iterator of the delegator-signals store. +func (k Keeper) GetDelegatorSignalsIterator(ctx sdk.Context) sdk.Iterator { + return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.DelegatorSignalStoreKeyPrefix) +} + +// GetAllDelegatorSignals returns a list of all delegator-signals. +func (k Keeper) GetAllDelegatorSignals(ctx sdk.Context) (delegatorSignalsList []types.DelegatorSignals) { + iterator := k.GetDelegatorSignalsIterator(ctx) + defer func(iterator sdk.Iterator) { + _ = iterator.Close() + }(iterator) + + for ; iterator.Valid(); iterator.Next() { + var ds types.DelegatorSignals + k.cdc.MustUnmarshal(iterator.Value(), &ds) + delegatorSignalsList = append(delegatorSignalsList, ds) + } + + return delegatorSignalsList +} + +// SetAllDelegatorSignals sets multiple delegator-signals. +func (k Keeper) SetAllDelegatorSignals(ctx sdk.Context, delegatorSignalsList []types.DelegatorSignals) { + for _, ds := range delegatorSignalsList { + k.SetDelegatorSignals(ctx, ds) + } +} diff --git a/x/feeds/keeper/keeper_signal_test.go b/x/feeds/keeper/keeper_signal_test.go new file mode 100644 index 000000000..143090347 --- /dev/null +++ b/x/feeds/keeper/keeper_signal_test.go @@ -0,0 +1,29 @@ +package keeper_test + +import ( + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func (suite *KeeperTestSuite) TestGetSetDelegatorSignals() { + ctx := suite.ctx + + // set + expSignals := types.DelegatorSignals{ + Delegator: ValidDelegator.String(), + Signals: []types.Signal{ + { + ID: "crypto_price.bandusd", + Power: 1e9, + }, + { + ID: "crypto_price.btcusd", + Power: 1e9, + }, + }, + } + suite.feedsKeeper.SetDelegatorSignals(ctx, expSignals) + + // get + signals := suite.feedsKeeper.GetDelegatorSignals(ctx, ValidDelegator) + suite.Require().Equal(expSignals.Signals, signals) +} diff --git a/x/feeds/keeper/keeper_symbol_test.go b/x/feeds/keeper/keeper_symbol_test.go new file mode 100644 index 000000000..a2af5f730 --- /dev/null +++ b/x/feeds/keeper/keeper_symbol_test.go @@ -0,0 +1,89 @@ +package keeper_test + +import ( + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func (suite *KeeperTestSuite) TestGetSetDeleteSymbol() { + ctx := suite.ctx + + // set + expFeed := types.Feed{ + SignalID: "crypto_price.bandusd", + Power: 1e10, + Interval: 60, + LastIntervalUpdateTimestamp: ctx.BlockTime().Unix(), + } + suite.feedsKeeper.SetFeed(ctx, expFeed) + + // get + feed, err := suite.feedsKeeper.GetFeed(ctx, "crypto_price.bandusd") + suite.Require().NoError(err) + suite.Require().Equal(expFeed, feed) + + // delete + suite.feedsKeeper.DeleteFeed(ctx, feed) + + // get + _, err = suite.feedsKeeper.GetFeed(ctx, "crypto_price.bandusd") + suite.Require().ErrorContains(err, "feed not found") +} + +func (suite *KeeperTestSuite) TestGetSetFeeds() { + ctx := suite.ctx + + // set + expFeeds := []types.Feed{ + { + SignalID: "crypto_price.atomusd", + Power: 1e10, + Interval: 60, + LastIntervalUpdateTimestamp: ctx.BlockTime().Unix(), + }, + { + SignalID: "crypto_price.bandusd", + Power: 1e10, + Interval: 60, + LastIntervalUpdateTimestamp: ctx.BlockTime().Unix(), + }, + } + suite.feedsKeeper.SetFeeds(ctx, expFeeds) + + // get + feeds := suite.feedsKeeper.GetFeeds(ctx) + suite.Require().Equal(expFeeds, feeds) +} + +func (suite *KeeperTestSuite) TestGetSetDeleteSymbolByPower() { + ctx := suite.ctx + + // set + expFeeds := []types.Feed{ + { + SignalID: "crypto_price.bandusd", + Power: 1e10, + Interval: 60, + LastIntervalUpdateTimestamp: ctx.BlockTime().Unix(), + }, + { + SignalID: "crypto_price.atomusd", + Power: 1e9, + Interval: 60, + LastIntervalUpdateTimestamp: ctx.BlockTime().Unix(), + }, + } + for _, expFeed := range expFeeds { + suite.feedsKeeper.SetFeed(ctx, expFeed) + } + + // get + feeds := suite.feedsKeeper.GetSupportedFeedsByPower(ctx) + suite.Require().Equal(expFeeds, feeds) + + // delete + suite.feedsKeeper.DeleteFeed(ctx, expFeeds[0]) + + // get + feeds = suite.feedsKeeper.GetSupportedFeedsByPower(ctx) + suite.Require().Equal(expFeeds[1:], feeds) +} diff --git a/x/feeds/keeper/keeper_test.go b/x/feeds/keeper/keeper_test.go new file mode 100644 index 000000000..21078aa79 --- /dev/null +++ b/x/feeds/keeper/keeper_test.go @@ -0,0 +1,133 @@ +package keeper_test + +import ( + "testing" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + tmtime "github.com/cometbft/cometbft/types/time" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/testutil" + sdk "github.com/cosmos/cosmos-sdk/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/stretchr/testify/suite" + "go.uber.org/mock/gomock" + + "github.com/bandprotocol/chain/v2/x/feeds/keeper" + feedstestutil "github.com/bandprotocol/chain/v2/x/feeds/testutil" + "github.com/bandprotocol/chain/v2/x/feeds/types" + oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" +) + +var ( + ValidValidator = sdk.ValAddress("1234567890") + ValidValidator2 = sdk.ValAddress("2345678901") + ValidDelegator = sdk.AccAddress("3456789012") + InvalidValidator = sdk.ValAddress("9876543210") + InvalidDelegator = sdk.AccAddress("8765432109") +) + +type KeeperTestSuite struct { + suite.Suite + + ctx sdk.Context + feedsKeeper keeper.Keeper + oracleKeeper *feedstestutil.MockOracleKeeper + stakingKeeper *feedstestutil.MockStakingKeeper + + queryClient types.QueryClient + msgServer types.MsgServer +} + +func TestKeeperTestSuite(t *testing.T) { + suite.Run(t, new(KeeperTestSuite)) +} + +func (suite *KeeperTestSuite) SetupTest() { + key := sdk.NewKVStoreKey(types.StoreKey) + testCtx := testutil.DefaultContextWithDB(suite.T(), key, sdk.NewTransientStoreKey("transient_test")) + suite.ctx = testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: tmtime.Now()}) + encCfg := moduletestutil.MakeTestEncodingConfig() + + // gomock initializations + ctrl := gomock.NewController(suite.T()) + oracleKeeper := feedstestutil.NewMockOracleKeeper(ctrl) + oracleKeeper.EXPECT(). + GetValidatorStatus(gomock.Any(), gomock.Eq(ValidValidator)). + Return(oracletypes.NewValidatorStatus(true, suite.ctx.BlockHeader().Time)). + AnyTimes() + oracleKeeper.EXPECT(). + GetValidatorStatus(gomock.Any(), gomock.Eq(ValidValidator2)). + Return(oracletypes.NewValidatorStatus(true, suite.ctx.BlockHeader().Time)). + AnyTimes() + oracleKeeper.EXPECT(). + GetValidatorStatus(gomock.Any(), gomock.Eq(InvalidValidator)). + Return(oracletypes.NewValidatorStatus(false, suite.ctx.BlockHeader().Time)). + AnyTimes() + suite.oracleKeeper = oracleKeeper + + stakingKeeper := feedstestutil.NewMockStakingKeeper(ctrl) + stakingKeeper.EXPECT(). + GetValidator(gomock.Any(), gomock.Eq(ValidValidator)). + Return(stakingtypes.Validator{Status: stakingtypes.Bonded}, true). + AnyTimes() + stakingKeeper.EXPECT(). + GetValidator(gomock.Any(), gomock.Eq(ValidValidator2)). + Return(stakingtypes.Validator{Status: stakingtypes.Bonded}, true). + AnyTimes() + stakingKeeper.EXPECT(). + GetValidator(gomock.Any(), gomock.Eq(InvalidValidator)). + Return(stakingtypes.Validator{Status: stakingtypes.Unbonded}, true). + AnyTimes() + stakingKeeper.EXPECT(). + IterateBondedValidatorsByPower(gomock.Any(), gomock.Any()). + DoAndReturn(func(ctx sdk.Context, fn func(index int64, validator stakingtypes.ValidatorI) bool) { + vals := []stakingtypes.Validator{ + { + OperatorAddress: ValidValidator.String(), + Tokens: sdk.NewInt(5000), + }, + { + OperatorAddress: ValidValidator2.String(), + Tokens: sdk.NewInt(3000), + }, + } + + for i, val := range vals { + stop := fn(int64(i), val) + if stop { + break + } + } + }). + AnyTimes() + stakingKeeper.EXPECT(). + GetDelegatorBonded(gomock.Any(), ValidDelegator). + Return(sdk.NewInt(1e10)). + AnyTimes() + stakingKeeper.EXPECT(). + GetDelegatorBonded(gomock.Any(), InvalidDelegator). + Return(sdk.NewInt(0)). + AnyTimes() + suite.stakingKeeper = stakingKeeper + + suite.feedsKeeper = keeper.NewKeeper( + encCfg.Codec, + key, + oracleKeeper, + stakingKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + suite.feedsKeeper.InitGenesis(suite.ctx, *types.DefaultGenesisState()) + + queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, encCfg.InterfaceRegistry) + queryServer := keeper.NewQueryServer(suite.feedsKeeper) + + types.RegisterInterfaces(encCfg.InterfaceRegistry) + types.RegisterQueryServer(queryHelper, queryServer) + queryClient := types.NewQueryClient(queryHelper) + suite.queryClient = queryClient + suite.msgServer = keeper.NewMsgServerImpl(suite.feedsKeeper) +} diff --git a/x/feeds/keeper/msg_server.go b/x/feeds/keeper/msg_server.go new file mode 100644 index 000000000..654e3a37e --- /dev/null +++ b/x/feeds/keeper/msg_server.go @@ -0,0 +1,163 @@ +package keeper + +import ( + "context" + "sort" + + sdk "github.com/cosmos/cosmos-sdk/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +var _ types.MsgServer = msgServer{} + +type msgServer struct { + Keeper +} + +// NewMsgServerImpl returns an implementation of the x/feeds MsgServer interface. +func NewMsgServerImpl(k Keeper) types.MsgServer { + return &msgServer{ + Keeper: k, + } +} + +// SubmitSignals register new signals and update feeds. +func (ms msgServer) SubmitSignals( + goCtx context.Context, + req *types.MsgSubmitSignals, +) (*types.MsgSubmitSignalsResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + delegator, err := sdk.AccAddressFromBech32(req.Delegator) + if err != nil { + return nil, err + } + + // check whether delegator has enough delegation for signals + err = ms.CheckDelegatorDelegation(ctx, delegator, req.Signals) + if err != nil { + return nil, err + } + + // calculate power different of each signal by decresing signal power with previous signal + signalIDToPowerDiff := ms.CalculateDelegatorSignalsPowerDiff(ctx, delegator, req.Signals) + + // sort keys to guarantee order of signalIDToPowerDiff iteration + keys := make([]string, 0, len(signalIDToPowerDiff)) + for k := range signalIDToPowerDiff { + keys = append(keys, k) + } + sort.Strings(keys) + + for _, signalID := range keys { + powerDiff := signalIDToPowerDiff[signalID] + feed, err := ms.GetFeed(ctx, signalID) + if err != nil { + feed = types.Feed{ + SignalID: signalID, + Power: 0, + Interval: 0, + LastIntervalUpdateTimestamp: ctx.BlockTime().Unix(), + } + } + feed.Power += powerDiff + + if feed.Power < 0 { + return nil, types.ErrPowerNegative + } + + feed.Interval, feed.DeviationInThousandth = calculateIntervalAndDeviation(feed.Power, ms.GetParams(ctx)) + ms.SetFeed(ctx, feed) + } + + return &types.MsgSubmitSignalsResponse{}, nil +} + +// SubmitPrices register new validator-prices. +func (ms msgServer) SubmitPrices( + goCtx context.Context, + req *types.MsgSubmitPrices, +) (*types.MsgSubmitPricesResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + blockTime := ctx.BlockTime().Unix() + + val, err := sdk.ValAddressFromBech32(req.Validator) + if err != nil { + return nil, err + } + + // check if it's in top bonded validators. + err = ms.ValidateSubmitPricesRequest(ctx, blockTime, req) + if err != nil { + return nil, err + } + + cooldownTime := ms.GetParams(ctx).CooldownTime + + for _, price := range req.Prices { + valPrice, err := ms.NewValidatorPrice(ctx, blockTime, price, val, cooldownTime) + if err != nil { + return nil, err + } + + err = ms.SetValidatorPrice(ctx, valPrice) + if err != nil { + return nil, err + } + + emitEventSubmitPrice(ctx, valPrice) + } + + return &types.MsgSubmitPricesResponse{}, nil +} + +// UpdatePriceService updates price service. +func (ms msgServer) UpdatePriceService( + goCtx context.Context, + req *types.MsgUpdatePriceService, +) (*types.MsgUpdatePriceServiceResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + admin := ms.GetParams(ctx).Admin + if admin != req.Admin { + return nil, types.ErrInvalidSigner.Wrapf( + "invalid admin; expected %s, got %s", + admin, + req.Admin, + ) + } + + if err := ms.SetPriceService(ctx, req.PriceService); err != nil { + return nil, err + } + + emitEventUpdatePriceService(ctx, req.PriceService) + + return &types.MsgUpdatePriceServiceResponse{}, nil +} + +// UpdateParams updates the feeds module params. +func (ms msgServer) UpdateParams( + goCtx context.Context, + req *types.MsgUpdateParams, +) (*types.MsgUpdateParamsResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + if ms.authority != req.Authority { + return nil, govtypes.ErrInvalidSigner.Wrapf( + "invalid authority; expected %s, got %s", + ms.authority, + req.Authority, + ) + } + + if err := ms.SetParams(ctx, req.Params); err != nil { + return nil, err + } + + emitEventUpdateParams(ctx, req.Params) + + return &types.MsgUpdateParamsResponse{}, nil +} diff --git a/x/feeds/keeper/msg_server_test.go b/x/feeds/keeper/msg_server_test.go new file mode 100644 index 000000000..0386357b9 --- /dev/null +++ b/x/feeds/keeper/msg_server_test.go @@ -0,0 +1,362 @@ +package keeper_test + +import "github.com/bandprotocol/chain/v2/x/feeds/types" + +func (suite *KeeperTestSuite) TestMsgSubmitSignals() { + testCases := []struct { + name string + input *types.MsgSubmitSignals + expErr bool + expErrMsg string + postCheck func() + }{ + { + name: "no delegation", + input: &types.MsgSubmitSignals{ + Delegator: InvalidDelegator.String(), + Signals: []types.Signal{ + { + ID: "crypto_price.bandusd", + Power: 10, + }, + }, + }, + expErr: true, + expErrMsg: "not enough delegation", + postCheck: func() {}, + }, + { + name: "1 signal more than delegations", + input: &types.MsgSubmitSignals{ + Delegator: ValidDelegator.String(), + Signals: []types.Signal{ + { + ID: "crypto_price.bandusd", + Power: 1e10 + 1, + }, + }, + }, + expErr: true, + expErrMsg: "not enough delegation", + postCheck: func() {}, + }, + { + name: "2 signals more than delegations", + input: &types.MsgSubmitSignals{ + Delegator: ValidDelegator.String(), + Signals: []types.Signal{ + { + ID: "crypto_price.bandusd", + Power: 1e10, + }, + { + ID: "crypto_price.atomusd", + Power: 1, + }, + }, + }, + expErr: true, + expErrMsg: "not enough delegation", + postCheck: func() {}, + }, + { + name: "valid request", + input: &types.MsgSubmitSignals{ + Delegator: ValidDelegator.String(), + Signals: []types.Signal{ + { + ID: "crypto_price.bandusd", + Power: 1e10, + }, + }, + }, + expErr: false, + expErrMsg: "", + postCheck: func() { + suite.Require().Equal( + []types.Signal{ + { + ID: "crypto_price.bandusd", + Power: 1e10, + }, + }, + suite.feedsKeeper.GetDelegatorSignals(suite.ctx, ValidDelegator), + ) + suite.Require().Equal( + []types.Feed{ + { + SignalID: "crypto_price.bandusd", + Power: 1e10, + Interval: 360, + DeviationInThousandth: 30, + LastIntervalUpdateTimestamp: suite.ctx.BlockTime().Unix(), + }, + }, + suite.feedsKeeper.GetSupportedFeedsByPower(suite.ctx), + ) + }, + }, + { + name: "valid request (replace)", + input: &types.MsgSubmitSignals{ + Delegator: ValidDelegator.String(), + Signals: []types.Signal{ + { + ID: "crypto_price.bandusd", + Power: 1e9, + }, + { + ID: "crypto_price.btcusd", + Power: 1e9, + }, + }, + }, + expErr: false, + expErrMsg: "", + postCheck: func() { + suite.Require().Equal( + []types.Signal{ + { + ID: "crypto_price.bandusd", + Power: 1e9, + }, + { + ID: "crypto_price.btcusd", + Power: 1e9, + }, + }, + suite.feedsKeeper.GetDelegatorSignals(suite.ctx, ValidDelegator), + ) + suite.Require().Equal( + []types.Feed{ + { + SignalID: "crypto_price.bandusd", + Power: 1e9, + Interval: 3600, + DeviationInThousandth: 300, + LastIntervalUpdateTimestamp: suite.ctx.BlockTime().Unix(), + }, + { + SignalID: "crypto_price.btcusd", + Power: 1e9, + Interval: 3600, + DeviationInThousandth: 300, + LastIntervalUpdateTimestamp: suite.ctx.BlockTime().Unix(), + }, + }, + suite.feedsKeeper.GetSupportedFeedsByPower(suite.ctx), + ) + }, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + _, err := suite.msgServer.SubmitSignals(suite.ctx, tc.input) + + if tc.expErr { + suite.Require().Error(err) + suite.Require().Contains(err.Error(), tc.expErrMsg) + } else { + suite.Require().NoError(err) + } + + tc.postCheck() + }) + } +} + +func (suite *KeeperTestSuite) TestMsgSubmitPrices() { + suite.feedsKeeper.SetFeed(suite.ctx, types.Feed{ + SignalID: "crypto_price.bandusd", + Power: 10e6, + Interval: 100, + LastIntervalUpdateTimestamp: suite.ctx.BlockTime().Unix(), + }) + + testCases := []struct { + name string + input *types.MsgSubmitPrices + expErr bool + expErrMsg string + }{ + { + name: "invalid validator", + input: &types.MsgSubmitPrices{ + Validator: InvalidValidator.String(), + Timestamp: suite.ctx.BlockTime().Unix(), + Prices: []types.SubmitPrice{ + { + PriceStatus: types.PriceStatusAvailable, + SignalID: "crypto_price.bandusd", + Price: 10e12, + }, + }, + }, + expErr: true, + expErrMsg: "not bonded validator", + }, + { + name: "invalid symbol", + input: &types.MsgSubmitPrices{ + Validator: ValidValidator.String(), + Timestamp: suite.ctx.BlockTime().Unix(), + Prices: []types.SubmitPrice{ + { + PriceStatus: types.PriceStatusAvailable, + SignalID: "crypto_price.btcusd", + Price: 10e12, + }, + }, + }, + expErr: true, + expErrMsg: "feed not found", + }, + { + name: "invalid timestamp", + input: &types.MsgSubmitPrices{ + Validator: ValidValidator.String(), + Timestamp: suite.ctx.BlockTime().Unix() - 200, + Prices: []types.SubmitPrice{ + { + PriceStatus: types.PriceStatusAvailable, + SignalID: "crypto_price.bandusd", + Price: 10e12, + }, + }, + }, + expErr: true, + expErrMsg: "invalid timestamp", + }, + { + name: "valid message", + input: &types.MsgSubmitPrices{ + Validator: ValidValidator.String(), + Timestamp: suite.ctx.BlockTime().Unix(), + Prices: []types.SubmitPrice{ + { + PriceStatus: types.PriceStatusAvailable, + SignalID: "crypto_price.bandusd", + Price: 10e12, + }, + }, + }, + expErr: false, + expErrMsg: "", + }, + { + name: "price too fast", + input: &types.MsgSubmitPrices{ + Validator: ValidValidator.String(), + Timestamp: suite.ctx.BlockTime().Unix(), + Prices: []types.SubmitPrice{ + { + PriceStatus: types.PriceStatusAvailable, + SignalID: "crypto_price.bandusd", + Price: 10e12, + }, + }, + }, + expErr: true, + expErrMsg: "price is too fast", + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + _, err := suite.msgServer.SubmitPrices(suite.ctx, tc.input) + + if tc.expErr { + suite.Require().Error(err) + suite.Require().Contains(err.Error(), tc.expErrMsg) + } else { + suite.Require().NoError(err) + } + }) + } +} + +func (suite *KeeperTestSuite) TestMsgUpdatePriceService() { + params := suite.feedsKeeper.GetParams(suite.ctx) + priceService := types.DefaultPriceService() + + testCases := []struct { + name string + input *types.MsgUpdatePriceService + expErr bool + expErrMsg string + }{ + { + name: "invalid admin", + input: &types.MsgUpdatePriceService{ + Admin: "invalid", + PriceService: priceService, + }, + expErr: true, + expErrMsg: "invalid admin", + }, + { + name: "all good", + input: &types.MsgUpdatePriceService{ + Admin: params.Admin, + PriceService: priceService, + }, + expErr: false, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + _, err := suite.msgServer.UpdatePriceService(suite.ctx, tc.input) + + if tc.expErr { + suite.Require().Error(err) + suite.Require().Contains(err.Error(), tc.expErrMsg) + } else { + suite.Require().NoError(err) + } + }) + } +} + +func (suite *KeeperTestSuite) TestMsgUpdateParams() { + params := types.DefaultParams() + + testCases := []struct { + name string + input *types.MsgUpdateParams + expErr bool + expErrMsg string + }{ + { + name: "invalid authority", + input: &types.MsgUpdateParams{ + Authority: "invalid", + Params: params, + }, + expErr: true, + expErrMsg: "invalid authority", + }, + { + name: "all good", + input: &types.MsgUpdateParams{ + Authority: suite.feedsKeeper.GetAuthority(), + Params: params, + }, + expErr: false, + }, + } + + for _, tc := range testCases { + suite.Run(tc.name, func() { + _, err := suite.msgServer.UpdateParams(suite.ctx, tc.input) + + if tc.expErr { + suite.Require().Error(err) + suite.Require().Contains(err.Error(), tc.expErrMsg) + } else { + suite.Require().NoError(err) + } + }) + } +} diff --git a/x/feeds/keeper/params.go b/x/feeds/keeper/params.go new file mode 100644 index 000000000..60b4083ac --- /dev/null +++ b/x/feeds/keeper/params.go @@ -0,0 +1,28 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// SetParams sets the x/feeds module parameters. +func (k Keeper) SetParams(ctx sdk.Context, p types.Params) error { + if err := p.Validate(); err != nil { + return err + } + + ctx.KVStore(k.storeKey).Set(types.ParamsKey, k.cdc.MustMarshal(&p)) + return nil +} + +// GetParams returns the current x/feeds module parameters. +func (k Keeper) GetParams(ctx sdk.Context) (p types.Params) { + bz := ctx.KVStore(k.storeKey).Get(types.ParamsKey) + if bz == nil { + return p + } + + k.cdc.MustUnmarshal(bz, &p) + return p +} diff --git a/x/feeds/keeper/params_test.go b/x/feeds/keeper/params_test.go new file mode 100644 index 000000000..0757de035 --- /dev/null +++ b/x/feeds/keeper/params_test.go @@ -0,0 +1,14 @@ +package keeper_test + +import ( + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func (suite *KeeperTestSuite) TestGetSetParams() { + ctx := suite.ctx + + expectedParams := types.DefaultParams() + err := suite.feedsKeeper.SetParams(ctx, expectedParams) + suite.Require().NoError(err) + suite.Require().Equal(expectedParams, suite.feedsKeeper.GetParams(ctx)) +} diff --git a/x/feeds/keeper/price.go b/x/feeds/keeper/price.go new file mode 100644 index 000000000..3b997cb7d --- /dev/null +++ b/x/feeds/keeper/price.go @@ -0,0 +1,68 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// ValidateSubmitPricesRequest validates price submission. +func (k Keeper) ValidateSubmitPricesRequest(ctx sdk.Context, blockTime int64, req *types.MsgSubmitPrices) error { + val, err := sdk.ValAddressFromBech32(req.Validator) + if err != nil { + return err + } + + isValid := k.IsBondedValidator(ctx, req.Validator) + if !isValid { + return types.ErrNotBondedValidator + } + + status := k.oracleKeeper.GetValidatorStatus(ctx, val) + if !status.IsActive { + return types.ErrOracleStatusNotActive.Wrapf("val: %s", val.String()) + } + + if types.AbsInt64(req.Timestamp-blockTime) > k.GetParams(ctx).AllowableBlockTimeDiscrepancy { + return types.ErrInvalidTimestamp.Wrapf( + "block_time: %d, timestamp: %d", + blockTime, + req.Timestamp, + ) + } + return nil +} + +// NewValidatorPrice creates new ValidatorPrice. +func (k Keeper) NewValidatorPrice( + ctx sdk.Context, + blockTime int64, + price types.SubmitPrice, + val sdk.ValAddress, + cooldownTime int64, +) (types.ValidatorPrice, error) { + f, err := k.GetFeed(ctx, price.SignalID) + if err != nil { + return types.ValidatorPrice{}, err + } + + // check if price is not too fast + priceVal, err := k.GetValidatorPrice(ctx, price.SignalID, val) + if err == nil && blockTime < priceVal.Timestamp+cooldownTime { + return types.ValidatorPrice{}, types.ErrPriceTooFast.Wrapf( + "signal_id: %s, old: %d, new: %d, interval: %d", + price.SignalID, + priceVal.Timestamp, + blockTime, + f.Interval, + ) + } + + return types.ValidatorPrice{ + PriceStatus: price.PriceStatus, + Validator: val.String(), + SignalID: price.SignalID, + Price: price.Price, + Timestamp: blockTime, + }, nil +} diff --git a/x/feeds/keeper/signal.go b/x/feeds/keeper/signal.go new file mode 100644 index 000000000..8b53137d2 --- /dev/null +++ b/x/feeds/keeper/signal.go @@ -0,0 +1,42 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// CheckDelegatorDelegation checks whether the delegator has enough delegation for signals. +func (k Keeper) CheckDelegatorDelegation( + ctx sdk.Context, + delegator sdk.AccAddress, + signals []types.Signal, +) error { + sumPower := sumPower(signals) + sumDelegation := k.stakingKeeper.GetDelegatorBonded(ctx, delegator).Int64() + if sumPower > sumDelegation { + return types.ErrNotEnoughDelegation + } + return nil +} + +// CalculateDelegatorSignalsPowerDiff calculates feed power differences from delegator's previous signals and new signals. +func (k Keeper) CalculateDelegatorSignalsPowerDiff( + ctx sdk.Context, + delegator sdk.AccAddress, + signals []types.Signal, +) map[string]int64 { + signalIDToPowerDiff := make(map[string]int64) + prevSignals := k.GetDelegatorSignals(ctx, delegator) + k.DeleteDelegatorSignals(ctx, delegator) + + for _, prevSignal := range prevSignals { + signalIDToPowerDiff[prevSignal.ID] -= prevSignal.Power + } + + k.SetDelegatorSignals(ctx, types.DelegatorSignals{Delegator: delegator.String(), Signals: signals}) + for _, signal := range signals { + signalIDToPowerDiff[signal.ID] += signal.Power + } + return signalIDToPowerDiff +} diff --git a/x/feeds/module.go b/x/feeds/module.go new file mode 100644 index 000000000..026b75702 --- /dev/null +++ b/x/feeds/module.go @@ -0,0 +1,143 @@ +package feeds + +import ( + "context" + "encoding/json" + "fmt" + + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + + "github.com/bandprotocol/chain/v2/x/feeds/client/cli" + "github.com/bandprotocol/chain/v2/x/feeds/keeper" + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +// ConsensusVersion defines the current x/feeds module consensus version. +const ConsensusVersion = 1 + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} +) + +// ---------------------------------------------------------------------------- +// AppModuleBasic +// ---------------------------------------------------------------------------- + +// AppModuleBasic implements the AppModuleBasic interface that defines the independent methods a Cosmos SDK module needs to implement. +type AppModuleBasic struct { + cdc codec.BinaryCodec +} + +// NewAppModuleBasic returns a new AppModuleBasic +func NewAppModuleBasic(cdc codec.BinaryCodec) AppModuleBasic { + return AppModuleBasic{cdc: cdc} +} + +// Name returns the name of the module as a string +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec does nothing. Feeds does not support amino. +func (AppModuleBasic) RegisterLegacyAminoCodec(_ *codec.LegacyAmino) { +} + +// RegisterInterfaces registers a module's interface types and their concrete implementations as proto.Message +func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(reg) +} + +// DefaultGenesis returns a default GenesisState for the module, marshaled to json.RawMessage. The default GenesisState needs to be defined by the module developer and is primarily used for testing +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesisState()) +} + +// ValidateGenesis used to validate the GenesisState, given in its json.RawMessage form +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { + var genState types.GenesisState + if err := cdc.UnmarshalJSON(bz, &genState); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + return genState.Validate() +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + _ = types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) +} + +// GetTxCmd returns the root Tx command for the module. The subcommands of this root command are used by end-users to generate new transactions containing messages defined in the module +func (a AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + +// GetQueryCmd returns the root query command for the module. The subcommands of this root command are used by end-users to generate new queries to the subset of the state defined by the module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// ---------------------------------------------------------------------------- +// AppModule +// ---------------------------------------------------------------------------- + +// AppModule implements the AppModule interface that defines the inter-dependent methods that modules need to implement +type AppModule struct { + AppModuleBasic + + keeper keeper.Keeper +} + +// NewAppModule returns a new AppModule +func NewAppModule( + cdc codec.Codec, + keeper keeper.Keeper, +) AppModule { + return AppModule{ + AppModuleBasic: NewAppModuleBasic(cdc), + keeper: keeper, + } +} + +// RegisterServices registers a gRPC query service to respond to the module-specific gRPC queries +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) + types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServer(am.keeper)) +} + +// RegisterInvariants registers the invariants of the module. If an invariant deviates from its predicted value, the InvariantRegistry triggers appropriate logic (most often the chain will be halted) +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// InitGenesis performs the module's genesis initialization. It returns no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { + var genState types.GenesisState + cdc.MustUnmarshalJSON(gs, &genState) + am.keeper.InitGenesis(ctx, genState) + return []abci.ValidatorUpdate{} +} + +// ExportGenesis returns the module's exported genesis state as raw JSON bytes. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + gs := am.keeper.ExportGenesis(ctx) + return cdc.MustMarshalJSON(gs) +} + +// ConsensusVersion is a sequence number for state-breaking change of the module. It should be incremented on each consensus-breaking change introduced by the module. To avoid wrong/empty versions, the initial version should be set to 1 +func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } + +// BeginBlock contains the logic automatically triggered at the beginning of each block +func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) { +} + +// EndBlock contains the logic automatically triggered at the end of each block +func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + HandleEndBlock(ctx, am.keeper) + return []abci.ValidatorUpdate{} +} diff --git a/x/feeds/testutil/mock_expected_keepers.go b/x/feeds/testutil/mock_expected_keepers.go new file mode 100644 index 000000000..cc701c4bd --- /dev/null +++ b/x/feeds/testutil/mock_expected_keepers.go @@ -0,0 +1,149 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: x/feeds/types/expected_keepers.go +// +// Generated by this command: +// +// mockgen -source=x/feeds/types/expected_keepers.go -package testutil -destination x/feeds/testutil/mock_expected_keepers.go +// + +// Package testutil is a generated GoMock package. +package testutil + +import ( + reflect "reflect" + time "time" + + math "cosmossdk.io/math" + types "github.com/bandprotocol/chain/v2/x/oracle/types" + types0 "github.com/cosmos/cosmos-sdk/types" + types1 "github.com/cosmos/cosmos-sdk/x/staking/types" + gomock "go.uber.org/mock/gomock" +) + +// MockOracleKeeper is a mock of OracleKeeper interface. +type MockOracleKeeper struct { + ctrl *gomock.Controller + recorder *MockOracleKeeperMockRecorder +} + +// MockOracleKeeperMockRecorder is the mock recorder for MockOracleKeeper. +type MockOracleKeeperMockRecorder struct { + mock *MockOracleKeeper +} + +// NewMockOracleKeeper creates a new mock instance. +func NewMockOracleKeeper(ctrl *gomock.Controller) *MockOracleKeeper { + mock := &MockOracleKeeper{ctrl: ctrl} + mock.recorder = &MockOracleKeeperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockOracleKeeper) EXPECT() *MockOracleKeeperMockRecorder { + return m.recorder +} + +// GetValidatorStatus mocks base method. +func (m *MockOracleKeeper) GetValidatorStatus(ctx types0.Context, val types0.ValAddress) types.ValidatorStatus { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetValidatorStatus", ctx, val) + ret0, _ := ret[0].(types.ValidatorStatus) + return ret0 +} + +// GetValidatorStatus indicates an expected call of GetValidatorStatus. +func (mr *MockOracleKeeperMockRecorder) GetValidatorStatus(ctx, val any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetValidatorStatus", reflect.TypeOf((*MockOracleKeeper)(nil).GetValidatorStatus), ctx, val) +} + +// MissReport mocks base method. +func (m *MockOracleKeeper) MissReport(ctx types0.Context, val types0.ValAddress, requestTime time.Time) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "MissReport", ctx, val, requestTime) +} + +// MissReport indicates an expected call of MissReport. +func (mr *MockOracleKeeperMockRecorder) MissReport(ctx, val, requestTime any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MissReport", reflect.TypeOf((*MockOracleKeeper)(nil).MissReport), ctx, val, requestTime) +} + +// MockStakingKeeper is a mock of StakingKeeper interface. +type MockStakingKeeper struct { + ctrl *gomock.Controller + recorder *MockStakingKeeperMockRecorder +} + +// MockStakingKeeperMockRecorder is the mock recorder for MockStakingKeeper. +type MockStakingKeeperMockRecorder struct { + mock *MockStakingKeeper +} + +// NewMockStakingKeeper creates a new mock instance. +func NewMockStakingKeeper(ctrl *gomock.Controller) *MockStakingKeeper { + mock := &MockStakingKeeper{ctrl: ctrl} + mock.recorder = &MockStakingKeeperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockStakingKeeper) EXPECT() *MockStakingKeeperMockRecorder { + return m.recorder +} + +// GetDelegation mocks base method. +func (m *MockStakingKeeper) GetDelegation(ctx types0.Context, delAddr types0.AccAddress, valAddr types0.ValAddress) (types1.Delegation, bool) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetDelegation", ctx, delAddr, valAddr) + ret0, _ := ret[0].(types1.Delegation) + ret1, _ := ret[1].(bool) + return ret0, ret1 +} + +// GetDelegation indicates an expected call of GetDelegation. +func (mr *MockStakingKeeperMockRecorder) GetDelegation(ctx, delAddr, valAddr any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegation", reflect.TypeOf((*MockStakingKeeper)(nil).GetDelegation), ctx, delAddr, valAddr) +} + +// GetDelegatorBonded mocks base method. +func (m *MockStakingKeeper) GetDelegatorBonded(ctx types0.Context, delegator types0.AccAddress) math.Int { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetDelegatorBonded", ctx, delegator) + ret0, _ := ret[0].(math.Int) + return ret0 +} + +// GetDelegatorBonded indicates an expected call of GetDelegatorBonded. +func (mr *MockStakingKeeperMockRecorder) GetDelegatorBonded(ctx, delegator any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegatorBonded", reflect.TypeOf((*MockStakingKeeper)(nil).GetDelegatorBonded), ctx, delegator) +} + +// GetValidator mocks base method. +func (m *MockStakingKeeper) GetValidator(ctx types0.Context, addr types0.ValAddress) (types1.Validator, bool) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetValidator", ctx, addr) + ret0, _ := ret[0].(types1.Validator) + ret1, _ := ret[1].(bool) + return ret0, ret1 +} + +// GetValidator indicates an expected call of GetValidator. +func (mr *MockStakingKeeperMockRecorder) GetValidator(ctx, addr any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetValidator", reflect.TypeOf((*MockStakingKeeper)(nil).GetValidator), ctx, addr) +} + +// IterateBondedValidatorsByPower mocks base method. +func (m *MockStakingKeeper) IterateBondedValidatorsByPower(ctx types0.Context, fn func(int64, types1.ValidatorI) bool) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "IterateBondedValidatorsByPower", ctx, fn) +} + +// IterateBondedValidatorsByPower indicates an expected call of IterateBondedValidatorsByPower. +func (mr *MockStakingKeeperMockRecorder) IterateBondedValidatorsByPower(ctx, fn any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IterateBondedValidatorsByPower", reflect.TypeOf((*MockStakingKeeper)(nil).IterateBondedValidatorsByPower), ctx, fn) +} diff --git a/x/feeds/types/codec.go b/x/feeds/types/codec.go new file mode 100644 index 000000000..edc5645e3 --- /dev/null +++ b/x/feeds/types/codec.go @@ -0,0 +1,46 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/legacy" + "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" +) + +// RegisterLegacyAminoCodec registers concrete types on the LegacyAmino codec +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + legacy.RegisterAminoMsg(cdc, &MsgSubmitSignals{}, "feeds/MsgSubmitSignals") + legacy.RegisterAminoMsg(cdc, &MsgSubmitPrices{}, "feeds/MsgSubmitPrices") + legacy.RegisterAminoMsg(cdc, &MsgUpdatePriceService{}, "feeds/MsgUpdatePriceService") + legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "feeds/MsgUpdateParams") +} + +// RegisterInterfaces register the feeds module interfaces to protobuf Any. +func RegisterInterfaces(registry types.InterfaceRegistry) { + registry.RegisterImplementations( + (*sdk.Msg)(nil), + &MsgSubmitSignals{}, + &MsgSubmitPrices{}, + &MsgUpdatePriceService{}, + &MsgUpdateParams{}, + ) + + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} + +var ( + amino = codec.NewLegacyAmino() + + // ModuleCdc references the global x/feeds module codec. Note, the codec + // should ONLY be used in certain instances of tests and for JSON encoding. + // + // The actual codec used for serialization should be provided to x/feeds and + // defined at the application level + ModuleCdc = codec.NewAminoCodec(amino) +) + +func init() { + RegisterLegacyAminoCodec(amino) + sdk.RegisterLegacyAminoCodec(amino) +} diff --git a/x/feeds/types/errors.go b/x/feeds/types/errors.go new file mode 100644 index 000000000..63c6e4a0a --- /dev/null +++ b/x/feeds/types/errors.go @@ -0,0 +1,22 @@ +package types + +import ( + errorsmod "cosmossdk.io/errors" +) + +// x/feeds module sentinel errors +var ( + ErrPriceNotFound = errorsmod.Register(ModuleName, 2, "price not found") + ErrValidatorPriceNotFound = errorsmod.Register(ModuleName, 3, "validator price not found") + ErrFeedNotFound = errorsmod.Register(ModuleName, 4, "feed not found") + ErrOracleStatusNotActive = errorsmod.Register(ModuleName, 5, "oracle status not active") + ErrPriceTooFast = errorsmod.Register(ModuleName, 6, "price is too fast") + ErrInvalidTimestamp = errorsmod.Register(ModuleName, 7, "invalid timestamp") + ErrNotEnoughValidatorPrice = errorsmod.Register(ModuleName, 8, "not enough validator price") + ErrInvalidSigner = errorsmod.Register(ModuleName, 9, "expected admin to be signer") + ErrNotBondedValidator = errorsmod.Register(ModuleName, 10, "not bonded validator") + ErrNotEnoughDelegation = errorsmod.Register(ModuleName, 11, "not enough delegation") + ErrUnableToUndelegate = errorsmod.Register(ModuleName, 12, "unable to undelegate") + ErrInvalidWeightedPriceArray = errorsmod.Register(ModuleName, 13, "invalid weighted price array") + ErrPowerNegative = errorsmod.Register(ModuleName, 14, "power is negative") +) diff --git a/x/feeds/types/events.go b/x/feeds/types/events.go new file mode 100644 index 000000000..35473da3c --- /dev/null +++ b/x/feeds/types/events.go @@ -0,0 +1,27 @@ +package types + +// events +const ( + EventTypeSubmitPrice = "submit_price" + EventTypeUpdatePrice = "update_price" + EventTypeUpdateFeed = "update_feed" + EventTypeDeleteFeed = "delete_feed" + EventTypeCalculatePriceFailed = "calculate_price_failed" + EventTypeUpdatePriceService = "update_price_service" + EventTypeUpdateParams = "update_params" + + AttributeKeyPriceStatus = "price_status" + AttributeKeyValidator = "validator" + AttributeKeyPrice = "price" + AttributeKeyTimestamp = "timestamp" + AttributeKeySignalID = "signal_id" + AttributeKeyPower = "power" + AttributeKeyInterval = "interval" + AttributeKeyLastIntervalUpdateTimestamp = "last_interval_update_timestamp" + AttributeKeyDeviationInThousandth = "deviation_in_thousandth" + AttributeKeyErrorMessage = "error_message" + AttributeKeyHash = "hash" + AttributeKeyVersion = "version" + AttributeKeyURL = "url" + AttributeKeyParams = "params" +) diff --git a/x/feeds/types/expected_keepers.go b/x/feeds/types/expected_keepers.go new file mode 100644 index 000000000..d46a326ee --- /dev/null +++ b/x/feeds/types/expected_keepers.go @@ -0,0 +1,32 @@ +package types + +import ( + "time" + + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" +) + +// OracleKeeper defines the expected oracle keeper +type OracleKeeper interface { + MissReport(ctx sdk.Context, val sdk.ValAddress, requestTime time.Time) + GetValidatorStatus(ctx sdk.Context, val sdk.ValAddress) oracletypes.ValidatorStatus +} + +// StakingKeeper defines the expected staking keeper. +type StakingKeeper interface { + GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) + IterateBondedValidatorsByPower( + ctx sdk.Context, + fn func(index int64, validator stakingtypes.ValidatorI) (stop bool), + ) + GetDelegatorBonded(ctx sdk.Context, delegator sdk.AccAddress) math.Int + GetDelegation( + ctx sdk.Context, + delAddr sdk.AccAddress, + valAddr sdk.ValAddress, + ) (delegation stakingtypes.Delegation, found bool) +} diff --git a/x/feeds/types/feed.go b/x/feeds/types/feed.go new file mode 100644 index 000000000..f0730f3b7 --- /dev/null +++ b/x/feeds/types/feed.go @@ -0,0 +1,10 @@ +package types + +// Validate validates a Feed. +func (f *Feed) Validate() error { + if err := validateInt64("interval", true, f.Interval); err != nil { + return err + } + + return nil +} diff --git a/x/feeds/types/feeds.pb.go b/x/feeds/types/feeds.pb.go new file mode 100644 index 000000000..941782131 --- /dev/null +++ b/x/feeds/types/feeds.pb.go @@ -0,0 +1,2300 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: feeds/v1beta1/feeds.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// PriceStatus is a structure that defines the price status of a price. +type PriceStatus int32 + +const ( + // PRICE_STATUS_UNSPECIFIED is an unspecified price status. + PriceStatusUnspecified PriceStatus = 0 + // PRICE_STATUS_UNSUPPORTED is an unsupported price status. + PriceStatusUnsupported PriceStatus = 1 + // PRICE_STATUS_UNAVAILABLE is an unavailable price status. + PriceStatusUnavailable PriceStatus = 2 + // PRICE_STATUS_AVAILABLE is an available price status. + PriceStatusAvailable PriceStatus = 3 +) + +var PriceStatus_name = map[int32]string{ + 0: "PRICE_STATUS_UNSPECIFIED", + 1: "PRICE_STATUS_UNSUPPORTED", + 2: "PRICE_STATUS_UNAVAILABLE", + 3: "PRICE_STATUS_AVAILABLE", +} + +var PriceStatus_value = map[string]int32{ + "PRICE_STATUS_UNSPECIFIED": 0, + "PRICE_STATUS_UNSUPPORTED": 1, + "PRICE_STATUS_UNAVAILABLE": 2, + "PRICE_STATUS_AVAILABLE": 3, +} + +func (x PriceStatus) String() string { + return proto.EnumName(PriceStatus_name, int32(x)) +} + +func (PriceStatus) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_4b338829e148e6ea, []int{0} +} + +// Signal is the data structure that contains signal id and power of that signal. +type Signal struct { + // ID is the id of the signal. + ID string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + // Power is the power of the corresponding signal id. + Power int64 `protobuf:"varint,2,opt,name=power,proto3" json:"power,omitempty"` +} + +func (m *Signal) Reset() { *m = Signal{} } +func (m *Signal) String() string { return proto.CompactTextString(m) } +func (*Signal) ProtoMessage() {} +func (*Signal) Descriptor() ([]byte, []int) { + return fileDescriptor_4b338829e148e6ea, []int{0} +} +func (m *Signal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Signal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Signal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Signal) XXX_Merge(src proto.Message) { + xxx_messageInfo_Signal.Merge(m, src) +} +func (m *Signal) XXX_Size() int { + return m.Size() +} +func (m *Signal) XXX_DiscardUnknown() { + xxx_messageInfo_Signal.DiscardUnknown(m) +} + +var xxx_messageInfo_Signal proto.InternalMessageInfo + +func (m *Signal) GetID() string { + if m != nil { + return m.ID + } + return "" +} + +func (m *Signal) GetPower() int64 { + if m != nil { + return m.Power + } + return 0 +} + +// DelegatorSignals is the data structure that contains array of signals of a delegator. +type DelegatorSignals struct { + // Delegator is the address of the delegator of this signals. + Delegator string `protobuf:"bytes,1,opt,name=delegator,proto3" json:"delegator,omitempty"` + // Signals is a list of signals submit by the delegator. + Signals []Signal `protobuf:"bytes,2,rep,name=signals,proto3" json:"signals"` +} + +func (m *DelegatorSignals) Reset() { *m = DelegatorSignals{} } +func (m *DelegatorSignals) String() string { return proto.CompactTextString(m) } +func (*DelegatorSignals) ProtoMessage() {} +func (*DelegatorSignals) Descriptor() ([]byte, []int) { + return fileDescriptor_4b338829e148e6ea, []int{1} +} +func (m *DelegatorSignals) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *DelegatorSignals) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_DelegatorSignals.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *DelegatorSignals) XXX_Merge(src proto.Message) { + xxx_messageInfo_DelegatorSignals.Merge(m, src) +} +func (m *DelegatorSignals) XXX_Size() int { + return m.Size() +} +func (m *DelegatorSignals) XXX_DiscardUnknown() { + xxx_messageInfo_DelegatorSignals.DiscardUnknown(m) +} + +var xxx_messageInfo_DelegatorSignals proto.InternalMessageInfo + +func (m *DelegatorSignals) GetDelegator() string { + if m != nil { + return m.Delegator + } + return "" +} + +func (m *DelegatorSignals) GetSignals() []Signal { + if m != nil { + return m.Signals + } + return nil +} + +// Feed is a structure that holds a signal id, its total power, and its calculated interval. +type Feed struct { + // SignalID is the unique string that identifies the unit of feed. + SignalID string `protobuf:"bytes,1,opt,name=signal_id,json=signalId,proto3" json:"signal_id,omitempty"` + // Power is the power of the corresponding feed. + Power int64 `protobuf:"varint,2,opt,name=power,proto3" json:"power,omitempty"` + // Interval is the interval of the price feed. + Interval int64 `protobuf:"varint,3,opt,name=interval,proto3" json:"interval,omitempty"` + // LastIntervalUpdateTimestamp is the timestamp of the last time interval is updated. + LastIntervalUpdateTimestamp int64 `protobuf:"varint,4,opt,name=last_interval_update_timestamp,json=lastIntervalUpdateTimestamp,proto3" json:"last_interval_update_timestamp,omitempty"` + // DeviationInThousandth is the maximum deviation value the feed can tolerate, expressed in thousandths. + DeviationInThousandth int64 `protobuf:"varint,5,opt,name=deviation_in_thousandth,json=deviationInThousandth,proto3" json:"deviation_in_thousandth,omitempty"` +} + +func (m *Feed) Reset() { *m = Feed{} } +func (m *Feed) String() string { return proto.CompactTextString(m) } +func (*Feed) ProtoMessage() {} +func (*Feed) Descriptor() ([]byte, []int) { + return fileDescriptor_4b338829e148e6ea, []int{2} +} +func (m *Feed) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Feed) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Feed.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Feed) XXX_Merge(src proto.Message) { + xxx_messageInfo_Feed.Merge(m, src) +} +func (m *Feed) XXX_Size() int { + return m.Size() +} +func (m *Feed) XXX_DiscardUnknown() { + xxx_messageInfo_Feed.DiscardUnknown(m) +} + +var xxx_messageInfo_Feed proto.InternalMessageInfo + +func (m *Feed) GetSignalID() string { + if m != nil { + return m.SignalID + } + return "" +} + +func (m *Feed) GetPower() int64 { + if m != nil { + return m.Power + } + return 0 +} + +func (m *Feed) GetInterval() int64 { + if m != nil { + return m.Interval + } + return 0 +} + +func (m *Feed) GetLastIntervalUpdateTimestamp() int64 { + if m != nil { + return m.LastIntervalUpdateTimestamp + } + return 0 +} + +func (m *Feed) GetDeviationInThousandth() int64 { + if m != nil { + return m.DeviationInThousandth + } + return 0 +} + +// Price is a structure that defines the price of a signal id. +type Price struct { + // PriceStatus is the price status of a signal id. + PriceStatus PriceStatus `protobuf:"varint,1,opt,name=price_status,json=priceStatus,proto3,enum=feeds.v1beta1.PriceStatus" json:"price_status,omitempty"` + // SignalID is the signal id of the price. + SignalID string `protobuf:"bytes,2,opt,name=signal_id,json=signalId,proto3" json:"signal_id,omitempty"` + // Price is the price of the signal id. + Price uint64 `protobuf:"varint,3,opt,name=price,proto3" json:"price,omitempty"` + // Timestamp is the timestamp at which the price was aggregated. + Timestamp int64 `protobuf:"varint,4,opt,name=timestamp,proto3" json:"timestamp,omitempty"` +} + +func (m *Price) Reset() { *m = Price{} } +func (m *Price) String() string { return proto.CompactTextString(m) } +func (*Price) ProtoMessage() {} +func (*Price) Descriptor() ([]byte, []int) { + return fileDescriptor_4b338829e148e6ea, []int{3} +} +func (m *Price) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Price) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Price.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Price) XXX_Merge(src proto.Message) { + xxx_messageInfo_Price.Merge(m, src) +} +func (m *Price) XXX_Size() int { + return m.Size() +} +func (m *Price) XXX_DiscardUnknown() { + xxx_messageInfo_Price.DiscardUnknown(m) +} + +var xxx_messageInfo_Price proto.InternalMessageInfo + +func (m *Price) GetPriceStatus() PriceStatus { + if m != nil { + return m.PriceStatus + } + return PriceStatusUnspecified +} + +func (m *Price) GetSignalID() string { + if m != nil { + return m.SignalID + } + return "" +} + +func (m *Price) GetPrice() uint64 { + if m != nil { + return m.Price + } + return 0 +} + +func (m *Price) GetTimestamp() int64 { + if m != nil { + return m.Timestamp + } + return 0 +} + +// SubmitPrice is a structure that defines the submit price of a signal id. +type SubmitPrice struct { + // PriceStatus is the price status of a signal id. + PriceStatus PriceStatus `protobuf:"varint,1,opt,name=price_status,json=priceStatus,proto3,enum=feeds.v1beta1.PriceStatus" json:"price_status,omitempty"` + // SignalID is the signal id of the price. + SignalID string `protobuf:"bytes,2,opt,name=signal_id,json=signalId,proto3" json:"signal_id,omitempty"` + // Price is the price submitted by the validator. + Price uint64 `protobuf:"varint,3,opt,name=price,proto3" json:"price,omitempty"` +} + +func (m *SubmitPrice) Reset() { *m = SubmitPrice{} } +func (m *SubmitPrice) String() string { return proto.CompactTextString(m) } +func (*SubmitPrice) ProtoMessage() {} +func (*SubmitPrice) Descriptor() ([]byte, []int) { + return fileDescriptor_4b338829e148e6ea, []int{4} +} +func (m *SubmitPrice) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SubmitPrice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SubmitPrice.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *SubmitPrice) XXX_Merge(src proto.Message) { + xxx_messageInfo_SubmitPrice.Merge(m, src) +} +func (m *SubmitPrice) XXX_Size() int { + return m.Size() +} +func (m *SubmitPrice) XXX_DiscardUnknown() { + xxx_messageInfo_SubmitPrice.DiscardUnknown(m) +} + +var xxx_messageInfo_SubmitPrice proto.InternalMessageInfo + +func (m *SubmitPrice) GetPriceStatus() PriceStatus { + if m != nil { + return m.PriceStatus + } + return PriceStatusUnspecified +} + +func (m *SubmitPrice) GetSignalID() string { + if m != nil { + return m.SignalID + } + return "" +} + +func (m *SubmitPrice) GetPrice() uint64 { + if m != nil { + return m.Price + } + return 0 +} + +// ValidatorPrice is a structure that defines the price submitted by a validator for a signal id. +type ValidatorPrice struct { + // PriceStatus is the price status of a price submitted. + PriceStatus PriceStatus `protobuf:"varint,1,opt,name=price_status,json=priceStatus,proto3,enum=feeds.v1beta1.PriceStatus" json:"price_status,omitempty"` + // Validator is the validator address. + Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` + // SignalID is the signal id of the price. + SignalID string `protobuf:"bytes,3,opt,name=signal_id,json=signalId,proto3" json:"signal_id,omitempty"` + // Price is the price submitted by the validator. + Price uint64 `protobuf:"varint,4,opt,name=price,proto3" json:"price,omitempty"` + // Timestamp is the timestamp at which the price was submitted. + Timestamp int64 `protobuf:"varint,5,opt,name=timestamp,proto3" json:"timestamp,omitempty"` +} + +func (m *ValidatorPrice) Reset() { *m = ValidatorPrice{} } +func (m *ValidatorPrice) String() string { return proto.CompactTextString(m) } +func (*ValidatorPrice) ProtoMessage() {} +func (*ValidatorPrice) Descriptor() ([]byte, []int) { + return fileDescriptor_4b338829e148e6ea, []int{5} +} +func (m *ValidatorPrice) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ValidatorPrice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ValidatorPrice.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ValidatorPrice) XXX_Merge(src proto.Message) { + xxx_messageInfo_ValidatorPrice.Merge(m, src) +} +func (m *ValidatorPrice) XXX_Size() int { + return m.Size() +} +func (m *ValidatorPrice) XXX_DiscardUnknown() { + xxx_messageInfo_ValidatorPrice.DiscardUnknown(m) +} + +var xxx_messageInfo_ValidatorPrice proto.InternalMessageInfo + +func (m *ValidatorPrice) GetPriceStatus() PriceStatus { + if m != nil { + return m.PriceStatus + } + return PriceStatusUnspecified +} + +func (m *ValidatorPrice) GetValidator() string { + if m != nil { + return m.Validator + } + return "" +} + +func (m *ValidatorPrice) GetSignalID() string { + if m != nil { + return m.SignalID + } + return "" +} + +func (m *ValidatorPrice) GetPrice() uint64 { + if m != nil { + return m.Price + } + return 0 +} + +func (m *ValidatorPrice) GetTimestamp() int64 { + if m != nil { + return m.Timestamp + } + return 0 +} + +// PriceService is a structure that defines the information of price service. +type PriceService struct { + // Hash is the hash of the price service. + Hash string `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"` + // Version is the version of the price service. + Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` + // Url is the URL of the price service. + Url string `protobuf:"bytes,3,opt,name=url,proto3" json:"url,omitempty"` +} + +func (m *PriceService) Reset() { *m = PriceService{} } +func (m *PriceService) String() string { return proto.CompactTextString(m) } +func (*PriceService) ProtoMessage() {} +func (*PriceService) Descriptor() ([]byte, []int) { + return fileDescriptor_4b338829e148e6ea, []int{6} +} +func (m *PriceService) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PriceService) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PriceService.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PriceService) XXX_Merge(src proto.Message) { + xxx_messageInfo_PriceService.Merge(m, src) +} +func (m *PriceService) XXX_Size() int { + return m.Size() +} +func (m *PriceService) XXX_DiscardUnknown() { + xxx_messageInfo_PriceService.DiscardUnknown(m) +} + +var xxx_messageInfo_PriceService proto.InternalMessageInfo + +func (m *PriceService) GetHash() string { + if m != nil { + return m.Hash + } + return "" +} + +func (m *PriceService) GetVersion() string { + if m != nil { + return m.Version + } + return "" +} + +func (m *PriceService) GetUrl() string { + if m != nil { + return m.Url + } + return "" +} + +func init() { + proto.RegisterEnum("feeds.v1beta1.PriceStatus", PriceStatus_name, PriceStatus_value) + proto.RegisterType((*Signal)(nil), "feeds.v1beta1.Signal") + proto.RegisterType((*DelegatorSignals)(nil), "feeds.v1beta1.DelegatorSignals") + proto.RegisterType((*Feed)(nil), "feeds.v1beta1.Feed") + proto.RegisterType((*Price)(nil), "feeds.v1beta1.Price") + proto.RegisterType((*SubmitPrice)(nil), "feeds.v1beta1.SubmitPrice") + proto.RegisterType((*ValidatorPrice)(nil), "feeds.v1beta1.ValidatorPrice") + proto.RegisterType((*PriceService)(nil), "feeds.v1beta1.PriceService") +} + +func init() { proto.RegisterFile("feeds/v1beta1/feeds.proto", fileDescriptor_4b338829e148e6ea) } + +var fileDescriptor_4b338829e148e6ea = []byte{ + // 689 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x54, 0x41, 0x6b, 0x13, 0x41, + 0x14, 0xce, 0x24, 0x9b, 0xb6, 0x99, 0xd4, 0x12, 0x86, 0xb4, 0x6e, 0xd7, 0xb2, 0x09, 0x3d, 0x55, + 0xc1, 0x2c, 0xad, 0x5a, 0x44, 0xf4, 0x90, 0x34, 0x29, 0x2e, 0x14, 0x0d, 0x9b, 0xa4, 0x07, 0x2f, + 0xcb, 0x24, 0x3b, 0x4d, 0x06, 0x36, 0x3b, 0xcb, 0xce, 0x64, 0xd5, 0xa3, 0x37, 0xe9, 0x49, 0xf0, + 0x5c, 0x10, 0x3c, 0x7a, 0xf5, 0x47, 0xf4, 0x58, 0x7a, 0xf2, 0x54, 0x24, 0x05, 0xf1, 0x1f, 0x78, + 0x95, 0xec, 0x6c, 0x92, 0xa6, 0xa4, 0xe8, 0xc1, 0x83, 0xb7, 0xf7, 0xbd, 0xf7, 0x7d, 0x2f, 0xdf, + 0xfb, 0xd8, 0x0c, 0x5c, 0x3f, 0x22, 0xc4, 0xe1, 0x46, 0xb8, 0xdd, 0x26, 0x02, 0x6f, 0x1b, 0x11, + 0x2a, 0xf9, 0x01, 0x13, 0x0c, 0xdd, 0x92, 0x20, 0x1e, 0x69, 0xeb, 0x1d, 0xc6, 0xfb, 0x8c, 0xdb, + 0xd1, 0xd0, 0x90, 0x40, 0x32, 0xb5, 0x7c, 0x97, 0x75, 0x99, 0xec, 0x8f, 0x2a, 0xd9, 0xdd, 0x7c, + 0x0a, 0x17, 0x1a, 0xb4, 0xeb, 0x61, 0x17, 0xad, 0xc1, 0x24, 0x75, 0x54, 0x50, 0x04, 0x5b, 0x99, + 0xca, 0xc2, 0xf0, 0xa2, 0x90, 0x34, 0xab, 0x56, 0x92, 0x3a, 0x28, 0x0f, 0xd3, 0x3e, 0x7b, 0x4d, + 0x02, 0x35, 0x59, 0x04, 0x5b, 0x29, 0x4b, 0x82, 0x27, 0xca, 0xcf, 0x4f, 0x05, 0xb0, 0xf9, 0x0e, + 0xc0, 0x5c, 0x95, 0xb8, 0xa4, 0x8b, 0x05, 0x0b, 0xe4, 0x1e, 0x8e, 0x76, 0x61, 0xc6, 0x19, 0xf7, + 0xe2, 0x7d, 0xea, 0xf9, 0xd7, 0xfb, 0xf9, 0xd8, 0x4d, 0xd9, 0x71, 0x02, 0xc2, 0x79, 0x43, 0x04, + 0xd4, 0xeb, 0x5a, 0x53, 0x2a, 0x7a, 0x04, 0x17, 0xb9, 0x5c, 0xa1, 0x26, 0x8b, 0xa9, 0xad, 0xec, + 0xce, 0x6a, 0x69, 0xe6, 0xb8, 0x92, 0xfc, 0x81, 0x8a, 0x72, 0x7a, 0x51, 0x48, 0x58, 0x63, 0xee, + 0xe6, 0x0f, 0x00, 0x95, 0x7d, 0x42, 0x1c, 0x74, 0x17, 0x66, 0x64, 0xcf, 0x9e, 0xdc, 0xb1, 0x3c, + 0xbc, 0x28, 0x2c, 0x49, 0x99, 0x59, 0xb5, 0x96, 0xe4, 0xd8, 0xbc, 0xe1, 0x26, 0xa4, 0xc1, 0x25, + 0xea, 0x09, 0x12, 0x84, 0xd8, 0x55, 0x53, 0xd1, 0x60, 0x82, 0xd1, 0x1e, 0xd4, 0x5d, 0xcc, 0x85, + 0x3d, 0x6e, 0xd8, 0x03, 0xdf, 0xc1, 0x82, 0xd8, 0x82, 0xf6, 0x09, 0x17, 0xb8, 0xef, 0xab, 0x4a, + 0xa4, 0xb8, 0x33, 0x62, 0x99, 0x31, 0xa9, 0x15, 0x71, 0x9a, 0x63, 0x0a, 0xda, 0x85, 0xb7, 0x1d, + 0x12, 0x52, 0x2c, 0x28, 0xf3, 0x6c, 0xea, 0xd9, 0xa2, 0xc7, 0x06, 0x1c, 0x7b, 0x8e, 0xe8, 0xa9, + 0xe9, 0x48, 0xbd, 0x3a, 0x19, 0x9b, 0x5e, 0x73, 0x32, 0x8c, 0xc3, 0xfe, 0x02, 0x60, 0xba, 0x1e, + 0xd0, 0x0e, 0x41, 0xcf, 0xe0, 0xb2, 0x3f, 0x2a, 0x6c, 0x2e, 0xb0, 0x18, 0xf0, 0xe8, 0xd8, 0x95, + 0x1d, 0xed, 0x5a, 0x5c, 0x11, 0xb7, 0x11, 0x31, 0xac, 0xac, 0x3f, 0x05, 0xb3, 0x41, 0x25, 0xff, + 0x18, 0xd4, 0x48, 0x19, 0xe5, 0xa1, 0x58, 0x12, 0xa0, 0x0d, 0x98, 0xb9, 0x7e, 0xf7, 0xb4, 0x11, + 0xbb, 0xfd, 0x08, 0x60, 0xb6, 0x31, 0x68, 0xf7, 0xa9, 0xf8, 0x2f, 0x3c, 0xc7, 0xae, 0xce, 0x01, + 0x5c, 0x39, 0xc4, 0x2e, 0x75, 0x46, 0x5f, 0xdc, 0x3f, 0x31, 0xb6, 0x01, 0x33, 0xe1, 0x78, 0xa1, + 0x34, 0x66, 0x4d, 0x1b, 0xb3, 0xb6, 0x53, 0x7f, 0x67, 0x5b, 0xb9, 0x31, 0xea, 0xf4, 0xfc, 0xa8, + 0x9b, 0x70, 0x59, 0xda, 0x23, 0x41, 0x38, 0xd2, 0x20, 0xa8, 0xf4, 0x30, 0xef, 0xc9, 0xff, 0x80, + 0x15, 0xd5, 0x48, 0x85, 0x8b, 0x21, 0x09, 0x38, 0x65, 0x5e, 0x6c, 0x72, 0x0c, 0x51, 0x0e, 0xa6, + 0x06, 0x81, 0xfc, 0xe0, 0x33, 0xd6, 0xa8, 0x94, 0x5b, 0xef, 0xfd, 0x02, 0x30, 0x7b, 0xe5, 0x6a, + 0xf4, 0x18, 0xaa, 0x75, 0xcb, 0xdc, 0xab, 0xd9, 0x8d, 0x66, 0xb9, 0xd9, 0x6a, 0xd8, 0xad, 0x17, + 0x8d, 0x7a, 0x6d, 0xcf, 0xdc, 0x37, 0x6b, 0xd5, 0x5c, 0x42, 0xd3, 0x8e, 0x4f, 0x8a, 0x6b, 0x57, + 0xe8, 0x2d, 0x8f, 0xfb, 0xa4, 0x43, 0x8f, 0x28, 0x71, 0xe6, 0x29, 0x5b, 0xf5, 0xfa, 0x4b, 0xab, + 0x59, 0xab, 0xe6, 0xc0, 0x3c, 0xe5, 0xc0, 0xf7, 0x59, 0x20, 0xe6, 0x2a, 0xcb, 0x87, 0x65, 0xf3, + 0xa0, 0x5c, 0x39, 0xa8, 0xe5, 0x92, 0x73, 0x94, 0x38, 0xc4, 0xd4, 0xc5, 0x6d, 0x97, 0xa0, 0x87, + 0x70, 0x6d, 0x46, 0x39, 0xd5, 0xa5, 0x34, 0xf5, 0xf8, 0xa4, 0x98, 0xbf, 0xa2, 0x2b, 0x8f, 0x55, + 0x9a, 0xf2, 0xfe, 0xb3, 0x9e, 0xa8, 0x3c, 0x3f, 0x1d, 0xea, 0xe0, 0x6c, 0xa8, 0x83, 0xef, 0x43, + 0x1d, 0x7c, 0xb8, 0xd4, 0x13, 0x67, 0x97, 0x7a, 0xe2, 0xdb, 0xa5, 0x9e, 0x78, 0x55, 0xea, 0x52, + 0xd1, 0x1b, 0xb4, 0x4b, 0x1d, 0xd6, 0x37, 0xda, 0xd8, 0x73, 0xa2, 0x37, 0xb4, 0xc3, 0x5c, 0xa3, + 0xd3, 0xc3, 0xd4, 0x33, 0xc2, 0x1d, 0xe3, 0x8d, 0x7c, 0x9d, 0x0d, 0xf1, 0xd6, 0x27, 0xbc, 0xbd, + 0x10, 0x11, 0x1e, 0xfc, 0x0e, 0x00, 0x00, 0xff, 0xff, 0x16, 0x3f, 0xa5, 0xc0, 0xc1, 0x05, 0x00, + 0x00, +} + +func (this *Signal) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Signal) + if !ok { + that2, ok := that.(Signal) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.ID != that1.ID { + return false + } + if this.Power != that1.Power { + return false + } + return true +} +func (this *Feed) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Feed) + if !ok { + that2, ok := that.(Feed) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.SignalID != that1.SignalID { + return false + } + if this.Power != that1.Power { + return false + } + if this.Interval != that1.Interval { + return false + } + if this.LastIntervalUpdateTimestamp != that1.LastIntervalUpdateTimestamp { + return false + } + if this.DeviationInThousandth != that1.DeviationInThousandth { + return false + } + return true +} +func (this *Price) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Price) + if !ok { + that2, ok := that.(Price) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.PriceStatus != that1.PriceStatus { + return false + } + if this.SignalID != that1.SignalID { + return false + } + if this.Price != that1.Price { + return false + } + if this.Timestamp != that1.Timestamp { + return false + } + return true +} +func (this *SubmitPrice) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*SubmitPrice) + if !ok { + that2, ok := that.(SubmitPrice) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.PriceStatus != that1.PriceStatus { + return false + } + if this.SignalID != that1.SignalID { + return false + } + if this.Price != that1.Price { + return false + } + return true +} +func (this *ValidatorPrice) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ValidatorPrice) + if !ok { + that2, ok := that.(ValidatorPrice) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.PriceStatus != that1.PriceStatus { + return false + } + if this.Validator != that1.Validator { + return false + } + if this.SignalID != that1.SignalID { + return false + } + if this.Price != that1.Price { + return false + } + if this.Timestamp != that1.Timestamp { + return false + } + return true +} +func (this *PriceService) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*PriceService) + if !ok { + that2, ok := that.(PriceService) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Hash != that1.Hash { + return false + } + if this.Version != that1.Version { + return false + } + if this.Url != that1.Url { + return false + } + return true +} +func (m *Signal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Signal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Signal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Power != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.Power)) + i-- + dAtA[i] = 0x10 + } + if len(m.ID) > 0 { + i -= len(m.ID) + copy(dAtA[i:], m.ID) + i = encodeVarintFeeds(dAtA, i, uint64(len(m.ID))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *DelegatorSignals) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *DelegatorSignals) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DelegatorSignals) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Signals) > 0 { + for iNdEx := len(m.Signals) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Signals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintFeeds(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.Delegator) > 0 { + i -= len(m.Delegator) + copy(dAtA[i:], m.Delegator) + i = encodeVarintFeeds(dAtA, i, uint64(len(m.Delegator))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *Feed) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Feed) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Feed) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.DeviationInThousandth != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.DeviationInThousandth)) + i-- + dAtA[i] = 0x28 + } + if m.LastIntervalUpdateTimestamp != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.LastIntervalUpdateTimestamp)) + i-- + dAtA[i] = 0x20 + } + if m.Interval != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.Interval)) + i-- + dAtA[i] = 0x18 + } + if m.Power != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.Power)) + i-- + dAtA[i] = 0x10 + } + if len(m.SignalID) > 0 { + i -= len(m.SignalID) + copy(dAtA[i:], m.SignalID) + i = encodeVarintFeeds(dAtA, i, uint64(len(m.SignalID))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *Price) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Price) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Price) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Timestamp != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.Timestamp)) + i-- + dAtA[i] = 0x20 + } + if m.Price != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.Price)) + i-- + dAtA[i] = 0x18 + } + if len(m.SignalID) > 0 { + i -= len(m.SignalID) + copy(dAtA[i:], m.SignalID) + i = encodeVarintFeeds(dAtA, i, uint64(len(m.SignalID))) + i-- + dAtA[i] = 0x12 + } + if m.PriceStatus != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.PriceStatus)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *SubmitPrice) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *SubmitPrice) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SubmitPrice) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Price != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.Price)) + i-- + dAtA[i] = 0x18 + } + if len(m.SignalID) > 0 { + i -= len(m.SignalID) + copy(dAtA[i:], m.SignalID) + i = encodeVarintFeeds(dAtA, i, uint64(len(m.SignalID))) + i-- + dAtA[i] = 0x12 + } + if m.PriceStatus != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.PriceStatus)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ValidatorPrice) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ValidatorPrice) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ValidatorPrice) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Timestamp != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.Timestamp)) + i-- + dAtA[i] = 0x28 + } + if m.Price != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.Price)) + i-- + dAtA[i] = 0x20 + } + if len(m.SignalID) > 0 { + i -= len(m.SignalID) + copy(dAtA[i:], m.SignalID) + i = encodeVarintFeeds(dAtA, i, uint64(len(m.SignalID))) + i-- + dAtA[i] = 0x1a + } + if len(m.Validator) > 0 { + i -= len(m.Validator) + copy(dAtA[i:], m.Validator) + i = encodeVarintFeeds(dAtA, i, uint64(len(m.Validator))) + i-- + dAtA[i] = 0x12 + } + if m.PriceStatus != 0 { + i = encodeVarintFeeds(dAtA, i, uint64(m.PriceStatus)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *PriceService) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PriceService) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PriceService) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Url) > 0 { + i -= len(m.Url) + copy(dAtA[i:], m.Url) + i = encodeVarintFeeds(dAtA, i, uint64(len(m.Url))) + i-- + dAtA[i] = 0x1a + } + if len(m.Version) > 0 { + i -= len(m.Version) + copy(dAtA[i:], m.Version) + i = encodeVarintFeeds(dAtA, i, uint64(len(m.Version))) + i-- + dAtA[i] = 0x12 + } + if len(m.Hash) > 0 { + i -= len(m.Hash) + copy(dAtA[i:], m.Hash) + i = encodeVarintFeeds(dAtA, i, uint64(len(m.Hash))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintFeeds(dAtA []byte, offset int, v uint64) int { + offset -= sovFeeds(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Signal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ID) + if l > 0 { + n += 1 + l + sovFeeds(uint64(l)) + } + if m.Power != 0 { + n += 1 + sovFeeds(uint64(m.Power)) + } + return n +} + +func (m *DelegatorSignals) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Delegator) + if l > 0 { + n += 1 + l + sovFeeds(uint64(l)) + } + if len(m.Signals) > 0 { + for _, e := range m.Signals { + l = e.Size() + n += 1 + l + sovFeeds(uint64(l)) + } + } + return n +} + +func (m *Feed) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.SignalID) + if l > 0 { + n += 1 + l + sovFeeds(uint64(l)) + } + if m.Power != 0 { + n += 1 + sovFeeds(uint64(m.Power)) + } + if m.Interval != 0 { + n += 1 + sovFeeds(uint64(m.Interval)) + } + if m.LastIntervalUpdateTimestamp != 0 { + n += 1 + sovFeeds(uint64(m.LastIntervalUpdateTimestamp)) + } + if m.DeviationInThousandth != 0 { + n += 1 + sovFeeds(uint64(m.DeviationInThousandth)) + } + return n +} + +func (m *Price) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PriceStatus != 0 { + n += 1 + sovFeeds(uint64(m.PriceStatus)) + } + l = len(m.SignalID) + if l > 0 { + n += 1 + l + sovFeeds(uint64(l)) + } + if m.Price != 0 { + n += 1 + sovFeeds(uint64(m.Price)) + } + if m.Timestamp != 0 { + n += 1 + sovFeeds(uint64(m.Timestamp)) + } + return n +} + +func (m *SubmitPrice) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PriceStatus != 0 { + n += 1 + sovFeeds(uint64(m.PriceStatus)) + } + l = len(m.SignalID) + if l > 0 { + n += 1 + l + sovFeeds(uint64(l)) + } + if m.Price != 0 { + n += 1 + sovFeeds(uint64(m.Price)) + } + return n +} + +func (m *ValidatorPrice) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PriceStatus != 0 { + n += 1 + sovFeeds(uint64(m.PriceStatus)) + } + l = len(m.Validator) + if l > 0 { + n += 1 + l + sovFeeds(uint64(l)) + } + l = len(m.SignalID) + if l > 0 { + n += 1 + l + sovFeeds(uint64(l)) + } + if m.Price != 0 { + n += 1 + sovFeeds(uint64(m.Price)) + } + if m.Timestamp != 0 { + n += 1 + sovFeeds(uint64(m.Timestamp)) + } + return n +} + +func (m *PriceService) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Hash) + if l > 0 { + n += 1 + l + sovFeeds(uint64(l)) + } + l = len(m.Version) + if l > 0 { + n += 1 + l + sovFeeds(uint64(l)) + } + l = len(m.Url) + if l > 0 { + n += 1 + l + sovFeeds(uint64(l)) + } + return n +} + +func sovFeeds(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozFeeds(x uint64) (n int) { + return sovFeeds(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Signal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Signal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Signal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthFeeds + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeds + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType) + } + m.Power = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Power |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipFeeds(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthFeeds + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *DelegatorSignals) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: DelegatorSignals: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DelegatorSignals: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Delegator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthFeeds + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeds + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Delegator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signals", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthFeeds + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthFeeds + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signals = append(m.Signals, Signal{}) + if err := m.Signals[len(m.Signals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipFeeds(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthFeeds + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Feed) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Feed: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Feed: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignalID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthFeeds + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeds + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SignalID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Power", wireType) + } + m.Power = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Power |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Interval", wireType) + } + m.Interval = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Interval |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastIntervalUpdateTimestamp", wireType) + } + m.LastIntervalUpdateTimestamp = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastIntervalUpdateTimestamp |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DeviationInThousandth", wireType) + } + m.DeviationInThousandth = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.DeviationInThousandth |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipFeeds(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthFeeds + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Price) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Price: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Price: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PriceStatus", wireType) + } + m.PriceStatus = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PriceStatus |= PriceStatus(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignalID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthFeeds + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeds + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SignalID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) + } + m.Price = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Price |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + m.Timestamp = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Timestamp |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipFeeds(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthFeeds + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SubmitPrice) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: SubmitPrice: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SubmitPrice: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PriceStatus", wireType) + } + m.PriceStatus = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PriceStatus |= PriceStatus(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignalID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthFeeds + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeds + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SignalID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) + } + m.Price = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Price |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipFeeds(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthFeeds + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ValidatorPrice) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ValidatorPrice: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ValidatorPrice: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PriceStatus", wireType) + } + m.PriceStatus = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PriceStatus |= PriceStatus(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthFeeds + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeds + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Validator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignalID", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthFeeds + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeds + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SignalID = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) + } + m.Price = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Price |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + m.Timestamp = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Timestamp |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipFeeds(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthFeeds + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PriceService) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PriceService: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PriceService: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Hash", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthFeeds + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeds + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Hash = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthFeeds + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeds + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Version = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Url", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeds + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthFeeds + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeds + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Url = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipFeeds(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthFeeds + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipFeeds(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowFeeds + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowFeeds + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowFeeds + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthFeeds + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupFeeds + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthFeeds + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthFeeds = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowFeeds = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupFeeds = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/feeds/types/genesis.go b/x/feeds/types/genesis.go new file mode 100644 index 000000000..a48f4da1e --- /dev/null +++ b/x/feeds/types/genesis.go @@ -0,0 +1,60 @@ +package types + +import ( + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// NewGenesisState creates new GenesisState +func NewGenesisState(params Params, feeds []Feed, ps PriceService, ds []DelegatorSignals) *GenesisState { + return &GenesisState{ + Params: params, + Feeds: feeds, + PriceService: ps, + DelegatorSignals: ds, + } +} + +// DefaultGenesisState returns the default genesis state +func DefaultGenesisState() *GenesisState { + return NewGenesisState(DefaultParams(), []Feed{}, DefaultPriceService(), []DelegatorSignals{}) +} + +// Validate performs basic genesis state validation +func (gs GenesisState) Validate() error { + if err := gs.Params.Validate(); err != nil { + return err + } + + for _, feed := range gs.Feeds { + if err := validateInt64("power", true, feed.Power); err != nil { + return err + } + if err := validateInt64("interval", true, feed.Interval); err != nil { + return err + } + if err := validateInt64("timestamp", true, feed.LastIntervalUpdateTimestamp); err != nil { + return err + } + } + + if err := gs.PriceService.Validate(); err != nil { + return err + } + + for _, ds := range gs.DelegatorSignals { + if _, err := sdk.AccAddressFromBech32(ds.Delegator); err != nil { + return errorsmod.Wrap(err, "invalid delegator address") + } + for _, signal := range ds.Signals { + if signal.ID == "" || signal.Power == 0 { + return sdkerrors.ErrInvalidRequest.Wrap( + "signal id cannot be empty and its power cannot be zero", + ) + } + } + } + + return nil +} diff --git a/x/feeds/types/genesis.pb.go b/x/feeds/types/genesis.pb.go new file mode 100644 index 000000000..d2c4427f8 --- /dev/null +++ b/x/feeds/types/genesis.pb.go @@ -0,0 +1,508 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: feeds/v1beta1/genesis.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// GenesisState is a structure that defines the feeds module's genesis state. +type GenesisState struct { + // Params is all parameters of the module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + // Feeds is a list of feeds that requires validators to submit the price. + Feeds []Feed `protobuf:"bytes,2,rep,name=feeds,proto3" json:"feeds"` + // PriceService is the information about price service. + PriceService PriceService `protobuf:"bytes,3,opt,name=price_service,json=priceService,proto3" json:"price_service"` + // DelegatorSignals is a list of delegator signals submitted by delegators. + DelegatorSignals []DelegatorSignals `protobuf:"bytes,4,rep,name=delegator_signals,json=delegatorSignals,proto3" json:"delegator_signals"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_f6c07c49716d7448, []int{0} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func (m *GenesisState) GetFeeds() []Feed { + if m != nil { + return m.Feeds + } + return nil +} + +func (m *GenesisState) GetPriceService() PriceService { + if m != nil { + return m.PriceService + } + return PriceService{} +} + +func (m *GenesisState) GetDelegatorSignals() []DelegatorSignals { + if m != nil { + return m.DelegatorSignals + } + return nil +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "feeds.v1beta1.GenesisState") +} + +func init() { proto.RegisterFile("feeds/v1beta1/genesis.proto", fileDescriptor_f6c07c49716d7448) } + +var fileDescriptor_f6c07c49716d7448 = []byte{ + // 300 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x5c, 0x90, 0xc1, 0x4e, 0xc2, 0x30, + 0x18, 0xc7, 0x37, 0x40, 0x0e, 0x05, 0x12, 0x9d, 0x9a, 0xcc, 0x91, 0x14, 0xe2, 0x89, 0x53, 0x1b, + 0xe0, 0x0d, 0x8c, 0x41, 0x8f, 0x06, 0x6e, 0x5e, 0x48, 0xb7, 0x7d, 0x96, 0x26, 0xb0, 0x2e, 0x6b, + 0x25, 0xfa, 0x16, 0x3c, 0x16, 0x47, 0x8e, 0x9e, 0x8c, 0xd9, 0x5e, 0xc4, 0xd0, 0xd6, 0xc4, 0xed, + 0xd6, 0x7c, 0xff, 0xdf, 0xf7, 0xfb, 0x37, 0x1f, 0x1a, 0xbe, 0x01, 0xa4, 0x8a, 0xee, 0xa7, 0x31, + 0x68, 0x36, 0xa5, 0x1c, 0x32, 0x50, 0x42, 0x91, 0xbc, 0x90, 0x5a, 0x06, 0x03, 0x13, 0x12, 0x17, + 0x46, 0x37, 0x5c, 0x72, 0x69, 0x12, 0x7a, 0x7e, 0x59, 0x28, 0x8a, 0xea, 0x86, 0x9c, 0x15, 0x6c, + 0xe7, 0x04, 0xd1, 0x5d, 0x3d, 0xb3, 0x3a, 0x13, 0xdd, 0x1f, 0x5a, 0xa8, 0xff, 0x64, 0xdb, 0x56, + 0x9a, 0x69, 0x08, 0xe6, 0xa8, 0x6b, 0x77, 0x43, 0x7f, 0xec, 0x4f, 0x7a, 0xb3, 0x5b, 0x52, 0x6b, + 0x27, 0x2f, 0x26, 0x7c, 0xe8, 0x1c, 0xbf, 0x47, 0xde, 0xd2, 0xa1, 0x01, 0x45, 0x17, 0x86, 0x0a, + 0x5b, 0xe3, 0xf6, 0xa4, 0x37, 0xbb, 0x6e, 0xec, 0x2c, 0x00, 0x52, 0xb7, 0x61, 0xb9, 0x60, 0x81, + 0x06, 0x79, 0x21, 0x12, 0x58, 0x2b, 0x28, 0xf6, 0x22, 0x81, 0xb0, 0x6d, 0xca, 0x86, 0xcd, 0xb2, + 0x33, 0xb3, 0xb2, 0x88, 0x13, 0xf4, 0xf3, 0x7f, 0xb3, 0x60, 0x89, 0xae, 0x52, 0xd8, 0x02, 0x67, + 0x5a, 0x16, 0x6b, 0x25, 0x78, 0xc6, 0xb6, 0x2a, 0xec, 0x98, 0x4f, 0x8c, 0x1a, 0xae, 0xc7, 0x3f, + 0x6e, 0x65, 0x31, 0xe7, 0xbb, 0x4c, 0x9b, 0xf3, 0xe7, 0x63, 0x89, 0xfd, 0x53, 0x89, 0xfd, 0x9f, + 0x12, 0xfb, 0x87, 0x0a, 0x7b, 0xa7, 0x0a, 0x7b, 0x5f, 0x15, 0xf6, 0x5e, 0x09, 0x17, 0x7a, 0xf3, + 0x1e, 0x93, 0x44, 0xee, 0x68, 0xcc, 0xb2, 0xd4, 0x9c, 0x30, 0x91, 0x5b, 0x9a, 0x6c, 0x98, 0xc8, + 0xe8, 0x7e, 0x46, 0x3f, 0xec, 0x71, 0xa9, 0xfe, 0xcc, 0x41, 0xc5, 0x5d, 0x03, 0xcc, 0x7f, 0x03, + 0x00, 0x00, 0xff, 0xff, 0x9f, 0xd4, 0xd5, 0xc7, 0xde, 0x01, 0x00, 0x00, +} + +func (m *GenesisState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.DelegatorSignals) > 0 { + for iNdEx := len(m.DelegatorSignals) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DelegatorSignals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + { + size, err := m.PriceService.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if len(m.Feeds) > 0 { + for iNdEx := len(m.Feeds) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Feeds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { + offset -= sovGenesis(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovGenesis(uint64(l)) + if len(m.Feeds) > 0 { + for _, e := range m.Feeds { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + l = m.PriceService.Size() + n += 1 + l + sovGenesis(uint64(l)) + if len(m.DelegatorSignals) > 0 { + for _, e := range m.DelegatorSignals { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Feeds", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Feeds = append(m.Feeds, Feed{}) + if err := m.Feeds[len(m.Feeds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PriceService", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PriceService.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DelegatorSignals", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DelegatorSignals = append(m.DelegatorSignals, DelegatorSignals{}) + if err := m.DelegatorSignals[len(m.DelegatorSignals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenesis(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthGenesis + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenesis + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenesis + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/feeds/types/genesis_test.go b/x/feeds/types/genesis_test.go new file mode 100644 index 000000000..7a36cc226 --- /dev/null +++ b/x/feeds/types/genesis_test.go @@ -0,0 +1,77 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestGenesisStateValidate(t *testing.T) { + testCases := []struct { + name string + genesisState GenesisState + expErr bool + }{ + { + "valid genesisState", + GenesisState{ + Params: DefaultParams(), + Feeds: []Feed{}, + PriceService: DefaultPriceService(), + }, + false, + }, + { + "empty genesisState", + GenesisState{}, + true, + }, + { + "invalid params", + GenesisState{ + Params: Params{}, + Feeds: []Feed{}, + PriceService: DefaultPriceService(), + }, + true, + }, + { + "invalid symbol", + GenesisState{ + Params: DefaultParams(), + Feeds: []Feed{ + { + SignalID: "crypto_price.bandusd", + Power: 10, + Interval: -5, + LastIntervalUpdateTimestamp: 1234567890, + }, + }, + PriceService: DefaultPriceService(), + }, + true, + }, + { + "invalid price service", + GenesisState{ + Params: DefaultParams(), + Feeds: []Feed{}, + PriceService: PriceService{}, + }, + true, + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(tt *testing.T) { + err := tc.genesisState.Validate() + + if tc.expErr { + require.Error(tt, err) + } else { + require.NoError(tt, err) + } + }) + } +} diff --git a/x/feeds/types/keys.go b/x/feeds/types/keys.go new file mode 100644 index 000000000..26ff94329 --- /dev/null +++ b/x/feeds/types/keys.go @@ -0,0 +1,84 @@ +package types + +import ( + "encoding/binary" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + // ModuleName defines the module name + ModuleName = "feeds" + + // StoreKey defines the primary module store key + StoreKey = ModuleName + + // RouterKey defines the module's message routing key + RouterKey = ModuleName + + // QuerierRoute is the querier route for the feeds module + QuerierRoute = ModuleName +) + +// Constants for keys +var ( + GlobalStoreKeyPrefix = []byte{0x00} + + PriceServiceStoreKey = append(GlobalStoreKeyPrefix, []byte("PriceService")...) + + FeedStoreKeyPrefix = []byte{0x01} + ValidatorPriceStoreKeyPrefix = []byte{0x02} + PriceStoreKeyPrefix = []byte{0x03} + DelegatorSignalStoreKeyPrefix = []byte{0x04} + + ParamsKey = []byte{0x10} + + FeedsByPowerIndexKeyPrefix = []byte{0x20} +) + +// DelegatorSignalStoreKey creates a key for storing delegator signals +func DelegatorSignalStoreKey(delegator sdk.AccAddress) []byte { + return append(DelegatorSignalStoreKeyPrefix, delegator...) +} + +// FeedStoreKey creates a key for storing feed data +func FeedStoreKey(signalID string) []byte { + return append(FeedStoreKeyPrefix, []byte(signalID)...) +} + +// ValidatorPricesStoreKey creates a key for storing validator prices +func ValidatorPricesStoreKey(signalID string) []byte { + return append(ValidatorPriceStoreKeyPrefix, []byte(signalID)...) +} + +// ValidatorPriceStoreKey creates a key for storing a validator price +func ValidatorPriceStoreKey(signalID string, validator sdk.ValAddress) []byte { + return append(ValidatorPricesStoreKey(signalID), validator...) +} + +// PriceStoreKey creates a key for storing price data +func PriceStoreKey(signalID string) []byte { + return append(PriceStoreKeyPrefix, []byte(signalID)...) +} + +// FeedsByPowerIndexKey creates a key for storing feeds by power index +func FeedsByPowerIndexKey(signalID string, power int64) []byte { + powerBytes := make([]byte, 8) + binary.BigEndian.PutUint64(powerBytes, uint64(power)) + powerBytesLen := len(powerBytes) // 8 + + signalIDBytes := []byte(signalID) + for i, b := range signalIDBytes { + signalIDBytes[i] = ^b + } + + signalIDBytesLen := len(signalIDBytes) + + key := make([]byte, 1+powerBytesLen+1+signalIDBytesLen) + key[0] = FeedsByPowerIndexKeyPrefix[0] + copy(key[1:powerBytesLen+1], powerBytes) + key[powerBytesLen+1] = byte(signalIDBytesLen) + copy(key[powerBytesLen+2:], signalIDBytes) + + return key +} diff --git a/x/feeds/types/keys_test.go b/x/feeds/types/keys_test.go new file mode 100644 index 000000000..c4d69e962 --- /dev/null +++ b/x/feeds/types/keys_test.go @@ -0,0 +1,41 @@ +package types + +import ( + "encoding/hex" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" +) + +func TestDelegatorSignalStoreKey(t *testing.T) { + acc, _ := sdk.AccAddressFromHexUnsafe("b80f2a5df7d5710b15622d1a9f1e3830ded5bda8") + expect, _ := hex.DecodeString("04b80f2a5df7d5710b15622d1a9f1e3830ded5bda8") + require.Equal(t, expect, DelegatorSignalStoreKey(acc)) +} + +func TestFeedStoreKey(t *testing.T) { + expect, _ := hex.DecodeString("0142414e44") + require.Equal(t, expect, FeedStoreKey("BAND")) +} + +func TestValidatorPricesStoreKey(t *testing.T) { + expect, _ := hex.DecodeString("0242414e44") + require.Equal(t, expect, ValidatorPricesStoreKey("BAND")) +} + +func TestValidatorPriceStoreKey(t *testing.T) { + acc, _ := sdk.ValAddressFromHex("b80f2a5df7d5710b15622d1a9f1e3830ded5bda8") + expect, _ := hex.DecodeString("0242414e44b80f2a5df7d5710b15622d1a9f1e3830ded5bda8") + require.Equal(t, expect, ValidatorPriceStoreKey("BAND", acc)) +} + +func TestPriceStoreKey(t *testing.T) { + expect, _ := hex.DecodeString("0342414e44") + require.Equal(t, expect, PriceStoreKey("BAND")) +} + +func TestFeedsByPowerIndexKey(t *testing.T) { + expect, _ := hex.DecodeString("20000000000098968004bdbeb1bb") + require.Equal(t, expect, FeedsByPowerIndexKey("BAND", 10e6)) +} diff --git a/x/feeds/types/median.go b/x/feeds/types/median.go new file mode 100644 index 000000000..b35604790 --- /dev/null +++ b/x/feeds/types/median.go @@ -0,0 +1,150 @@ +package types + +import ( + "sort" +) + +// Constants representing multipliers +func getMultipliers() [5]uint64 { + return [5]uint64{60, 40, 20, 11, 10} +} + +// Constants representing sections +func getSections() [5]uint64 { + return [5]uint64{1, 3, 7, 15, 32} +} + +// PriceFeedInfo contains information about a price feed +type PriceFeedInfo struct { + PriceStatus PriceStatus // PriceStatus represents the state of the price feed + Power uint64 // Power represents the power of the price feed + Price uint64 // Price represents the reported price + Deviation uint64 // Deviation represents the deviation from the reported price + Timestamp int64 // Timestamp represents the time at which the price feed was reported + Index int64 // Index represents the index of the price feed +} + +// FilterPriceFeedInfos filters price feed infos based on price status +func FilterPriceFeedInfos(pfInfos []PriceFeedInfo, opt PriceStatus) []PriceFeedInfo { + filtered := []PriceFeedInfo{} + for _, pfInfo := range pfInfos { + if pfInfo.PriceStatus == opt { + filtered = append(filtered, pfInfo) + } + } + return filtered +} + +// CalculatePricesPowers calculates total, available, unavailable, and unsupported powers +func CalculatePricesPowers( + priceFeedInfos []PriceFeedInfo, +) (totalPower uint64, availablePower uint64, unavailablePower uint64, unsupportedPower uint64) { + for _, pfInfo := range priceFeedInfos { + totalPower += pfInfo.Power + + switch pfInfo.PriceStatus { + case PriceStatusAvailable: + availablePower += pfInfo.Power + case PriceStatusUnavailable: + unavailablePower += pfInfo.Power + case PriceStatusUnsupported: + unsupportedPower += pfInfo.Power + } + } + return totalPower, availablePower, unavailablePower, unsupportedPower +} + +// CalculateMedianPriceFeedInfo calculates the median price feed info by timestamp and power +func CalculateMedianPriceFeedInfo(priceFeedInfos []PriceFeedInfo) (uint64, error) { + totalPower, _, _, _ := CalculatePricesPowers(priceFeedInfos) + + sort.Slice(priceFeedInfos, func(i, j int) bool { + if priceFeedInfos[i].Timestamp == priceFeedInfos[j].Timestamp { + if priceFeedInfos[i].Power == priceFeedInfos[j].Power { + return priceFeedInfos[i].Index < priceFeedInfos[j].Index + } + return priceFeedInfos[i].Power > priceFeedInfos[j].Power + } + return priceFeedInfos[i].Timestamp > priceFeedInfos[j].Timestamp + }) + + multipliers := getMultipliers() + sections := getSections() + + var wps []WeightedPrice + currentSection := 0 + currentPower := uint64(0) + for _, priceFeedInfo := range priceFeedInfos { + leftPower := priceFeedInfo.Power * 32 + totalWeight := uint64(0) + for ; currentSection < len(sections); currentSection++ { + takePower := uint64(0) + if currentPower+leftPower <= totalPower*sections[currentSection] { + takePower = leftPower + } else { + takePower = totalPower*sections[currentSection] - currentPower + } + totalWeight += takePower * multipliers[currentSection] + currentPower += takePower + leftPower -= takePower + if leftPower == 0 { + break + } + } + wps = append( + wps, + GetDeviationWeightedPrices( + priceFeedInfo.Price, + priceFeedInfo.Deviation, + totalWeight, + )..., + ) + } + + return CalculateMedianWeightedPrice(wps) +} + +// GetDeviationWeightedPrices returns weighted prices with deviations +func GetDeviationWeightedPrices(price uint64, deviation uint64, power uint64) []WeightedPrice { + return []WeightedPrice{{ + Price: price, + Power: power, + }, { + Price: price - deviation, + Power: power, + }, { + Price: price + deviation, + Power: power, + }} +} + +// WeightedPrice represents a weighted price +type WeightedPrice struct { + Power uint64 // Power represents the power for the price + Price uint64 // Price represents the price +} + +// CalculateMedianWeightedPrice calculates the median of weighted prices +func CalculateMedianWeightedPrice(wps []WeightedPrice) (uint64, error) { + sort.Slice(wps, func(i, j int) bool { + if wps[i].Price == wps[j].Price { + return wps[i].Power < wps[j].Power + } + return wps[i].Price < wps[j].Price + }) + + totalPower := uint64(0) + for _, wp := range wps { + totalPower += wp.Power + } + + currentPower := uint64(0) + for _, wp := range wps { + currentPower += wp.Power + if currentPower*2 >= totalPower { + return wp.Price, nil + } + } + + return 0, ErrInvalidWeightedPriceArray +} diff --git a/x/feeds/types/median_test.go b/x/feeds/types/median_test.go new file mode 100644 index 000000000..13da12f5b --- /dev/null +++ b/x/feeds/types/median_test.go @@ -0,0 +1,107 @@ +package types_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func TestCalculateMedianPriceFeedInfo(t *testing.T) { + testCases := []struct { + name string + priceFeedInfos []types.PriceFeedInfo + expRes uint64 + }{ + { + name: "case 1", + priceFeedInfos: []types.PriceFeedInfo{ + {Price: 100, Deviation: 10, Power: 100, Timestamp: 100, Index: 0}, + {Price: 103, Deviation: 10, Power: 100, Timestamp: 101, Index: 1}, + {Price: 105, Deviation: 10, Power: 100, Timestamp: 102, Index: 2}, + {Price: 107, Deviation: 10, Power: 100, Timestamp: 103, Index: 3}, + {Price: 109, Deviation: 10, Power: 100, Timestamp: 104, Index: 4}, + }, + expRes: 107, + }, + { + name: "case 2", + priceFeedInfos: []types.PriceFeedInfo{ + {Price: 100, Deviation: 10, Power: 100, Timestamp: 100, Index: 0}, + {Price: 103, Deviation: 10, Power: 200, Timestamp: 101, Index: 1}, + {Price: 105, Deviation: 10, Power: 300, Timestamp: 102, Index: 2}, + {Price: 107, Deviation: 10, Power: 400, Timestamp: 103, Index: 3}, + {Price: 109, Deviation: 10, Power: 500, Timestamp: 104, Index: 4}, + }, + expRes: 109, + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(tt *testing.T) { + price, err := types.CalculateMedianPriceFeedInfo(tc.priceFeedInfos) + require.NoError(tt, err) + require.Equal(tt, tc.expRes, price) + }) + } +} + +func TestGetDeviationWeightedPrices(t *testing.T) { + dwp := types.GetDeviationWeightedPrices(100, 5, 1000) + require.Equal(t, []types.WeightedPrice{ + { + Power: 1000, + Price: 100, + }, + { + Power: 1000, + Price: 95, + }, + { + Power: 1000, + Price: 105, + }, + }, dwp) +} + +func TestCalculateMedianWeightedPrice(t *testing.T) { + testCases := []struct { + name string + weightedPrices []types.WeightedPrice + expRes uint64 + }{ + { + name: "case 1", + weightedPrices: []types.WeightedPrice{ + {Price: 100, Power: 100}, + {Price: 103, Power: 100}, + {Price: 105, Power: 100}, + {Price: 107, Power: 100}, + {Price: 109, Power: 100}, + }, + expRes: 105, + }, + { + name: "case 2", + weightedPrices: []types.WeightedPrice{ + {Price: 100, Power: 100}, + {Price: 103, Power: 200}, + {Price: 105, Power: 300}, + {Price: 107, Power: 400}, + {Price: 109, Power: 500}, + }, + expRes: 107, + }, + } + + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(tt *testing.T) { + price, err := types.CalculateMedianWeightedPrice(tc.weightedPrices) + require.NoError(tt, err) + require.Equal(tt, tc.expRes, price) + }) + } +} diff --git a/x/feeds/types/msgs.go b/x/feeds/types/msgs.go new file mode 100644 index 000000000..0d967e2cf --- /dev/null +++ b/x/feeds/types/msgs.go @@ -0,0 +1,200 @@ +package types + +import ( + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +var _, _, _, _ sdk.Msg = &MsgSubmitPrices{}, &MsgUpdateParams{}, &MsgUpdatePriceService{}, &MsgSubmitSignals{} + +// ==================================== +// MsgSubmitPrices +// ==================================== + +// NewMsgSubmitPrices creates a new MsgSubmitPrices instance. +func NewMsgSubmitPrices( + validator string, + timestamp int64, + prices []SubmitPrice, +) *MsgSubmitPrices { + return &MsgSubmitPrices{ + Validator: validator, + Timestamp: timestamp, + Prices: prices, + } +} + +// Route Implements Msg. +func (m MsgSubmitPrices) Route() string { return sdk.MsgTypeURL(&m) } + +// Type Implements Msg. +func (m MsgSubmitPrices) Type() string { return sdk.MsgTypeURL(&m) } + +// GetSignBytes implements the LegacyMsg interface. +func (m MsgSubmitPrices) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +// GetSigners returns the expected signers for the message. +func (m *MsgSubmitPrices) GetSigners() []sdk.AccAddress { + validator, _ := sdk.ValAddressFromBech32(m.Validator) + return []sdk.AccAddress{sdk.AccAddress(validator)} +} + +// ValidateBasic does a check on the provided data. +func (m *MsgSubmitPrices) ValidateBasic() error { + valAddr, err := sdk.ValAddressFromBech32(m.Validator) + if err != nil { + return err + } + + if err := sdk.VerifyAddressFormat(valAddr); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("validator: %s", m.Validator) + } + + for _, price := range m.Prices { + if price.PriceStatus != PriceStatusAvailable && price.Price != 0 { + return sdkerrors.ErrInvalidRequest.Wrap( + "price must be initial value if price status is unsupported or unavailable", + ) + } + } + + return nil +} + +// ==================================== +// MsgUpdateParams +// ==================================== + +// NewMsgUpdateParams creates a new MsgUpdateParams instance. +func NewMsgUpdateParams( + authority string, + params Params, +) *MsgUpdateParams { + return &MsgUpdateParams{ + Authority: authority, + Params: params, + } +} + +// Route Implements Msg. +func (m MsgUpdateParams) Route() string { return sdk.MsgTypeURL(&m) } + +// Type Implements Msg. +func (m MsgUpdateParams) Type() string { return sdk.MsgTypeURL(&m) } + +// GetSignBytes implements the LegacyMsg interface. +func (m MsgUpdateParams) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +// GetSigners returns the expected signers for the message. +func (m *MsgUpdateParams) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{sdk.MustAccAddressFromBech32(m.Authority)} +} + +// ValidateBasic does a check on the provided data. +func (m *MsgUpdateParams) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { + return errorsmod.Wrap(err, "invalid authority address") + } + + if err := m.Params.Validate(); err != nil { + return err + } + + return nil +} + +// ==================================== +// MsgUpdatePriceService +// ==================================== + +// NewMsgUpdatePriceService creates a new MsgUpdatePriceService instance. +func NewMsgUpdatePriceService( + admin string, + priceService PriceService, +) *MsgUpdatePriceService { + return &MsgUpdatePriceService{ + Admin: admin, + PriceService: priceService, + } +} + +// Route Implements Msg. +func (m MsgUpdatePriceService) Route() string { return sdk.MsgTypeURL(&m) } + +// Type Implements Msg. +func (m MsgUpdatePriceService) Type() string { return sdk.MsgTypeURL(&m) } + +// GetSignBytes implements the LegacyMsg interface. +func (m MsgUpdatePriceService) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +// GetSigners returns the expected signers for the message. +func (m *MsgUpdatePriceService) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{sdk.MustAccAddressFromBech32(m.Admin)} +} + +// ValidateBasic does a check on the provided data. +func (m *MsgUpdatePriceService) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(m.Admin); err != nil { + return errorsmod.Wrap(err, "invalid admin address") + } + + if err := m.PriceService.Validate(); err != nil { + return err + } + + return nil +} + +// ==================================== +// MsgSubmitSignals +// ==================================== + +// NewMsgSubmitSignals creates a new MsgSubmitSignals instance. +func NewMsgSubmitSignals( + delegator string, + signals []Signal, +) *MsgSubmitSignals { + return &MsgSubmitSignals{ + Delegator: delegator, + Signals: signals, + } +} + +// Route Implements Msg. +func (m MsgSubmitSignals) Route() string { return sdk.MsgTypeURL(&m) } + +// Type Implements Msg. +func (m MsgSubmitSignals) Type() string { return sdk.MsgTypeURL(&m) } + +// GetSignBytes implements the LegacyMsg interface. +func (m MsgSubmitSignals) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +// GetSigners returns the expected signers for the message. +func (m *MsgSubmitSignals) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{sdk.MustAccAddressFromBech32(m.Delegator)} +} + +// ValidateBasic does a check on the provided data. +func (m *MsgSubmitSignals) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(m.Delegator); err != nil { + return errorsmod.Wrap(err, "invalid delegator address") + } + for _, signal := range m.Signals { + if signal.ID == "" || signal.Power <= 0 { + return sdkerrors.ErrInvalidRequest.Wrap( + "signal id cannot be empty and its power must be positive", + ) + } + } + + return nil +} diff --git a/x/feeds/types/msgs_test.go b/x/feeds/types/msgs_test.go new file mode 100644 index 000000000..25e3f9d61 --- /dev/null +++ b/x/feeds/types/msgs_test.go @@ -0,0 +1,219 @@ +package types + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" +) + +var ( + ValidValidator = "cosmosvaloper1vdhhxmt0wdmxzmr0wpjhyzzdttz" + ValidAuthority = "cosmos1xxjxtce966clgkju06qp475j663tg8pmklxcy8" + ValidAdmin = "cosmos1quh7acmun7tx6ywkvqr53m3fe39gxu9k00t4ds" + ValidDelegator = "cosmos13jt28pf6s8rgjddv8wwj8v3ngrfsccpgsdhjhw" + ValidSignals = []Signal{ + { + ID: "crypto_price.bandusd", + Power: 10000000000, + }, + } + ValidParams = DefaultParams() + ValidPriceService = DefaultPriceService() + ValidTimestamp = int64(1234567890) + ValidSubmitPrices = []SubmitPrice{ + { + PriceStatus: PriceStatusAvailable, + SignalID: "crypto_price.btcusd", + Price: 100000 * 10e9, + }, + } + + InvalidValidator = "invalidValidator" + InvalidAuthority = "invalidAuthority" + InvalidAdmin = "invalidAdmin" + InvalidDelegator = "invalidDelegator" +) + +// ==================================== +// MsgSubmitPrices +// ==================================== + +func TestNewMsgSubmitPrices(t *testing.T) { + msg := NewMsgSubmitPrices(ValidValidator, ValidTimestamp, ValidSubmitPrices) + require.Equal(t, ValidValidator, msg.Validator) + require.Equal(t, ValidTimestamp, msg.Timestamp) + require.Equal(t, ValidSubmitPrices, msg.Prices) +} + +func TestMsgSubmitPrices_Route(t *testing.T) { + msg := NewMsgSubmitPrices(ValidValidator, ValidTimestamp, ValidSubmitPrices) + require.Equal(t, "/feeds.v1beta1.MsgSubmitPrices", msg.Route()) +} + +func TestMsgSubmitPrices_Type(t *testing.T) { + msg := NewMsgSubmitPrices(ValidValidator, ValidTimestamp, ValidSubmitPrices) + require.Equal(t, "/feeds.v1beta1.MsgSubmitPrices", msg.Type()) +} + +func TestMsgSubmitPrices_GetSignBytes(t *testing.T) { + msg := NewMsgSubmitPrices(ValidValidator, ValidTimestamp, ValidSubmitPrices) + expected := `{"type":"feeds/MsgSubmitPrices","value":{"prices":[{"price":"1000000000000000","price_status":3,"signal_id":"crypto_price.btcusd"}],"timestamp":"1234567890","validator":"cosmosvaloper1vdhhxmt0wdmxzmr0wpjhyzzdttz"}}` + require.Equal(t, expected, string(msg.GetSignBytes())) +} + +func TestMsgSubmitPrices_GetSigners(t *testing.T) { + msg := NewMsgSubmitPrices(ValidValidator, ValidTimestamp, ValidSubmitPrices) + signers := msg.GetSigners() + require.Equal(t, 1, len(signers)) + + val, _ := sdk.ValAddressFromBech32(ValidValidator) + require.Equal(t, sdk.AccAddress(val), signers[0]) +} + +func TestMsgSubmitPrices_ValidateBasic(t *testing.T) { + // Valid validator + msg := NewMsgSubmitPrices(ValidValidator, ValidTimestamp, ValidSubmitPrices) + err := msg.ValidateBasic() + require.NoError(t, err) + + // Invalid validator + msg = NewMsgSubmitPrices(InvalidValidator, ValidTimestamp, ValidSubmitPrices) + err = msg.ValidateBasic() + require.Error(t, err) +} + +// ==================================== +// MsgUpdateParams +// ==================================== + +func TestNewMsgUpdateParams(t *testing.T) { + msg := NewMsgUpdateParams(ValidAuthority, ValidParams) + require.Equal(t, ValidAuthority, msg.Authority) + require.Equal(t, ValidParams, msg.Params) +} + +func TestMsgUpdateParams_Route(t *testing.T) { + msg := NewMsgUpdateParams(ValidAuthority, ValidParams) + require.Equal(t, "/feeds.v1beta1.MsgUpdateParams", msg.Route()) +} + +func TestMsgUpdateParams_Type(t *testing.T) { + msg := NewMsgUpdateParams(ValidAuthority, ValidParams) + require.Equal(t, "/feeds.v1beta1.MsgUpdateParams", msg.Type()) +} + +func TestMsgUpdateParams_GetSignBytes(t *testing.T) { + msg := NewMsgUpdateParams(ValidAuthority, ValidParams) + expected := `{"type":"feeds/MsgUpdateParams","value":{"authority":"cosmos1xxjxtce966clgkju06qp475j663tg8pmklxcy8","params":{"admin":"[NOT_SET]","allowable_block_time_discrepancy":"30","cooldown_time":"30","max_deviation_in_thousandth":"300","max_interval":"3600","max_supported_feeds":"100","min_deviation_in_thousandth":"5","min_interval":"60","power_threshold":"1000000000","transition_time":"30"}}}` + require.Equal(t, expected, string(msg.GetSignBytes())) +} + +func TestMsgUpdateParams_GetSigners(t *testing.T) { + msg := NewMsgUpdateParams(ValidAuthority, ValidParams) + signers := msg.GetSigners() + require.Equal(t, 1, len(signers)) + require.Equal(t, sdk.MustAccAddressFromBech32(ValidAuthority), signers[0]) +} + +func TestMsgUpdateParams_ValidateBasic(t *testing.T) { + // Valid authority + msg := NewMsgUpdateParams(ValidAuthority, ValidParams) + err := msg.ValidateBasic() + require.NoError(t, err) + + // Invalid authority + msg = NewMsgUpdateParams(InvalidAuthority, ValidParams) + err = msg.ValidateBasic() + require.Error(t, err) +} + +// ==================================== +// MsgUpdatePriceService +// ==================================== + +func TestNewMsgUpdatePriceService(t *testing.T) { + msg := NewMsgUpdatePriceService(ValidAdmin, ValidPriceService) + require.Equal(t, ValidAdmin, msg.Admin) + require.Equal(t, ValidPriceService, msg.PriceService) +} + +func TestMsgUpdatePriceService_Route(t *testing.T) { + msg := NewMsgUpdatePriceService(ValidAdmin, ValidPriceService) + require.Equal(t, "/feeds.v1beta1.MsgUpdatePriceService", msg.Route()) +} + +func TestMsgUpdatePriceService_Type(t *testing.T) { + msg := NewMsgUpdatePriceService(ValidAdmin, ValidPriceService) + require.Equal(t, "/feeds.v1beta1.MsgUpdatePriceService", msg.Type()) +} + +func TestMsgUpdatePriceService_GetSignBytes(t *testing.T) { + msg := NewMsgUpdatePriceService(ValidAdmin, ValidPriceService) + expected := `{"type":"feeds/MsgUpdatePriceService","value":{"admin":"cosmos1quh7acmun7tx6ywkvqr53m3fe39gxu9k00t4ds","price_service":{"hash":"hash","url":"https://","version":"0.0.1"}}}` + require.Equal(t, expected, string(msg.GetSignBytes())) +} + +func TestMsgUpdatePriceService_GetSigners(t *testing.T) { + msg := NewMsgUpdatePriceService(ValidAdmin, ValidPriceService) + signers := msg.GetSigners() + require.Equal(t, 1, len(signers)) + require.Equal(t, sdk.MustAccAddressFromBech32(ValidAdmin), signers[0]) +} + +func TestMsgUpdatePriceService_ValidateBasic(t *testing.T) { + // Valid admin + msg := NewMsgUpdatePriceService(ValidAdmin, ValidPriceService) + err := msg.ValidateBasic() + require.NoError(t, err) + + // Invalid admin + msg = NewMsgUpdatePriceService(InvalidAdmin, ValidPriceService) + err = msg.ValidateBasic() + require.Error(t, err) +} + +// ==================================== +// MsgSubmitSignals +// ==================================== + +func TestNewMsgSubmitSignals(t *testing.T) { + msg := NewMsgSubmitSignals(ValidDelegator, ValidSignals) + require.Equal(t, ValidDelegator, msg.Delegator) + require.Equal(t, ValidSignals, msg.Signals) +} + +func TestMsgSubmitSignals_Route(t *testing.T) { + msg := NewMsgSubmitSignals(ValidDelegator, ValidSignals) + require.Equal(t, "/feeds.v1beta1.MsgSubmitSignals", msg.Route()) +} + +func TestMsgSubmitSignals_Type(t *testing.T) { + msg := NewMsgSubmitSignals(ValidDelegator, ValidSignals) + require.Equal(t, "/feeds.v1beta1.MsgSubmitSignals", msg.Type()) +} + +func TestMsgSubmitSignals_GetSignBytes(t *testing.T) { + msg := NewMsgSubmitSignals(ValidDelegator, ValidSignals) + expected := `{"type":"feeds/MsgSubmitSignals","value":{"delegator":"cosmos13jt28pf6s8rgjddv8wwj8v3ngrfsccpgsdhjhw","signals":[{"id":"crypto_price.bandusd","power":"10000000000"}]}}` + require.Equal(t, expected, string(msg.GetSignBytes())) +} + +func TestMsgSubmitSignals_GetSigners(t *testing.T) { + msg := NewMsgSubmitSignals(ValidDelegator, ValidSignals) + signers := msg.GetSigners() + require.Equal(t, 1, len(signers)) + require.Equal(t, sdk.MustAccAddressFromBech32(ValidDelegator), signers[0]) +} + +func TestMsgSubmitSignals_ValidateBasic(t *testing.T) { + // Valid delegator + msg := NewMsgSubmitSignals(ValidDelegator, ValidSignals) + err := msg.ValidateBasic() + require.NoError(t, err) + + // Invalid delegator + msg = NewMsgSubmitSignals(InvalidDelegator, ValidSignals) + err = msg.ValidateBasic() + require.Error(t, err) +} diff --git a/x/feeds/types/params.go b/x/feeds/types/params.go new file mode 100644 index 000000000..f83c00418 --- /dev/null +++ b/x/feeds/types/params.go @@ -0,0 +1,103 @@ +package types + +import ( + "gopkg.in/yaml.v2" +) + +const ( + // Default values for Params + DefaultAllowableBlockTimeDiscrepancy = int64(30) + DefaultTransitionTime = int64(30) + DefaultMinInterval = int64(60) + DefaultMaxInterval = int64(3600) + DefaultPowerThreshold = int64(1_000_000_000) + DefaultMaxSupportedFeeds = int64(100) + DefaultCooldownTime = int64(30) + DefaultMinDeviationInThousandth = int64(5) + DefaultMaxDeviationInThousandth = int64(300) +) + +// NewParams creates a new Params instance +func NewParams( + admin string, + allowableBlockTimeDiscrepancy int64, + transitionTime int64, + minInterval int64, + maxInterval int64, + powerThreshold int64, + maxSupportedFeeds int64, + cooldownTime int64, + minDeviationInThousandth int64, + maxDeviationInThousandth int64, +) Params { + return Params{ + Admin: admin, + AllowableBlockTimeDiscrepancy: allowableBlockTimeDiscrepancy, + TransitionTime: transitionTime, + MinInterval: minInterval, + MaxInterval: maxInterval, + PowerThreshold: powerThreshold, + MaxSupportedFeeds: maxSupportedFeeds, + CooldownTime: cooldownTime, + MinDeviationInThousandth: minDeviationInThousandth, + MaxDeviationInThousandth: maxDeviationInThousandth, + } +} + +// DefaultParams returns a default set of parameters +func DefaultParams() Params { + return NewParams( + "[NOT_SET]", + DefaultAllowableBlockTimeDiscrepancy, + DefaultTransitionTime, + DefaultMinInterval, + DefaultMaxInterval, + DefaultPowerThreshold, + DefaultMaxSupportedFeeds, + DefaultCooldownTime, + DefaultMinDeviationInThousandth, + DefaultMaxDeviationInThousandth, + ) +} + +// Validate validates the set of params +func (p Params) Validate() error { + if err := validateString("admin", true, p.Admin); err != nil { + return err + } + if err := validateInt64("allowable block time discrepancy", true, p.AllowableBlockTimeDiscrepancy); err != nil { + return err + } + if err := validateInt64("transition time", true, p.TransitionTime); err != nil { + return err + } + if err := validateInt64("min interval", true, p.MinInterval); err != nil { + return err + } + if err := validateInt64("max interval", true, p.MaxInterval); err != nil { + return err + } + if err := validateInt64("power threshold", true, p.PowerThreshold); err != nil { + return err + } + if err := validateInt64("max supported feeds", true, p.MaxSupportedFeeds); err != nil { + return err + } + if err := validateInt64("cooldown time", true, p.CooldownTime); err != nil { + return err + } + if err := validateInt64("min deviation in thousandth", true, p.MinDeviationInThousandth); err != nil { + return err + } + if err := validateInt64("max deviation in thousandth", true, p.MaxDeviationInThousandth); err != nil { + return err + } + + return nil +} + +// String implements the Stringer interface. +func (p Params) String() string { + out, _ := yaml.Marshal(p) + return string(out) +} diff --git a/x/feeds/types/params.pb.go b/x/feeds/types/params.pb.go new file mode 100644 index 000000000..c2efab464 --- /dev/null +++ b/x/feeds/types/params.pb.go @@ -0,0 +1,713 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: feeds/v1beta1/params.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/gogoproto/gogoproto" + proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// Params is the data structure that keeps the parameters of the feeds module. +type Params struct { + // Admin is the address of the admin that is allowed to perform operations on modules. + Admin string `protobuf:"bytes,1,opt,name=admin,proto3" json:"admin,omitempty"` + // AllowableBlockTimeDiscrepancy is the allowed discrepancy (in seconds) between validator price timestamp and + // block_time. + AllowableBlockTimeDiscrepancy int64 `protobuf:"varint,2,opt,name=allowable_block_time_discrepancy,json=allowableBlockTimeDiscrepancy,proto3" json:"allowable_block_time_discrepancy,omitempty"` + // TransitionTime is the time (in seconds) given for validators to adapt to changing in feed's interval. + TransitionTime int64 `protobuf:"varint,3,opt,name=transition_time,json=transitionTime,proto3" json:"transition_time,omitempty"` + // MinInterval is the minimum limit of every feeds' interval (in seconds). + // If the calculated interval is lower than this, it will be capped at this value. + MinInterval int64 `protobuf:"varint,4,opt,name=min_interval,json=minInterval,proto3" json:"min_interval,omitempty"` + // MaxInterval is the maximum limit of every feeds' interval (in seconds). + // If the calculated interval of a feed is higher than this, it will not be recognized as a supported feed. + MaxInterval int64 `protobuf:"varint,5,opt,name=max_interval,json=maxInterval,proto3" json:"max_interval,omitempty"` + // PowerThreshold is the amount of minimum power required to put feed in the supported list. + PowerThreshold int64 `protobuf:"varint,6,opt,name=power_threshold,json=powerThreshold,proto3" json:"power_threshold,omitempty"` + // MaxSupportedFeeds is the maximum number of feeds supported at a time. + MaxSupportedFeeds int64 `protobuf:"varint,7,opt,name=max_supported_feeds,json=maxSupportedFeeds,proto3" json:"max_supported_feeds,omitempty"` + // CooldownTime represents the duration (in seconds) during which validators are prohibited from sending new prices. + CooldownTime int64 `protobuf:"varint,8,opt,name=cooldown_time,json=cooldownTime,proto3" json:"cooldown_time,omitempty"` + // MinDeviationInThousandth is the minimum limit of every feeds' deviation (in thousandth). + MinDeviationInThousandth int64 `protobuf:"varint,9,opt,name=min_deviation_in_thousandth,json=minDeviationInThousandth,proto3" json:"min_deviation_in_thousandth,omitempty"` + // MaxDeviationInThousandth is the maximum limit of every feeds' deviation (in thousandth). + MaxDeviationInThousandth int64 `protobuf:"varint,10,opt,name=max_deviation_in_thousandth,json=maxDeviationInThousandth,proto3" json:"max_deviation_in_thousandth,omitempty"` +} + +func (m *Params) Reset() { *m = Params{} } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_bbfae8ad171874f3, []int{0} +} +func (m *Params) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Params.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Params) XXX_Merge(src proto.Message) { + xxx_messageInfo_Params.Merge(m, src) +} +func (m *Params) XXX_Size() int { + return m.Size() +} +func (m *Params) XXX_DiscardUnknown() { + xxx_messageInfo_Params.DiscardUnknown(m) +} + +var xxx_messageInfo_Params proto.InternalMessageInfo + +func (m *Params) GetAdmin() string { + if m != nil { + return m.Admin + } + return "" +} + +func (m *Params) GetAllowableBlockTimeDiscrepancy() int64 { + if m != nil { + return m.AllowableBlockTimeDiscrepancy + } + return 0 +} + +func (m *Params) GetTransitionTime() int64 { + if m != nil { + return m.TransitionTime + } + return 0 +} + +func (m *Params) GetMinInterval() int64 { + if m != nil { + return m.MinInterval + } + return 0 +} + +func (m *Params) GetMaxInterval() int64 { + if m != nil { + return m.MaxInterval + } + return 0 +} + +func (m *Params) GetPowerThreshold() int64 { + if m != nil { + return m.PowerThreshold + } + return 0 +} + +func (m *Params) GetMaxSupportedFeeds() int64 { + if m != nil { + return m.MaxSupportedFeeds + } + return 0 +} + +func (m *Params) GetCooldownTime() int64 { + if m != nil { + return m.CooldownTime + } + return 0 +} + +func (m *Params) GetMinDeviationInThousandth() int64 { + if m != nil { + return m.MinDeviationInThousandth + } + return 0 +} + +func (m *Params) GetMaxDeviationInThousandth() int64 { + if m != nil { + return m.MaxDeviationInThousandth + } + return 0 +} + +func init() { + proto.RegisterType((*Params)(nil), "feeds.v1beta1.Params") +} + +func init() { proto.RegisterFile("feeds/v1beta1/params.proto", fileDescriptor_bbfae8ad171874f3) } + +var fileDescriptor_bbfae8ad171874f3 = []byte{ + // 443 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x31, 0x6f, 0xd3, 0x40, + 0x14, 0xc7, 0x63, 0x4a, 0x43, 0x7b, 0xb4, 0x54, 0x98, 0x0e, 0x47, 0x10, 0x6e, 0x80, 0xa1, 0x5d, + 0xb0, 0x55, 0xd8, 0x90, 0x18, 0x88, 0x2a, 0xa0, 0x1b, 0x6a, 0x33, 0xb1, 0x58, 0xcf, 0xbe, 0x23, + 0x3e, 0xe1, 0xbb, 0x67, 0xdd, 0x5d, 0x12, 0xf7, 0x5b, 0x30, 0x32, 0xf6, 0x43, 0xf0, 0x21, 0x18, + 0x2b, 0x26, 0x46, 0x94, 0x2c, 0x7c, 0x02, 0x66, 0xe4, 0x67, 0x27, 0x59, 0x60, 0xb3, 0xff, 0xbf, + 0xdf, 0xff, 0x59, 0xcf, 0x7a, 0x6c, 0xf0, 0x49, 0x4a, 0xe1, 0x92, 0xd9, 0x69, 0x26, 0x3d, 0x9c, + 0x26, 0x15, 0x58, 0xd0, 0x2e, 0xae, 0x2c, 0x7a, 0x0c, 0xf7, 0x89, 0xc5, 0x1d, 0x1b, 0x1c, 0x4e, + 0x70, 0x82, 0x44, 0x92, 0xe6, 0xa9, 0x95, 0x06, 0x0f, 0x73, 0x74, 0x1a, 0x5d, 0xda, 0x82, 0xf6, + 0xa5, 0x45, 0x4f, 0xff, 0x6c, 0xb1, 0xfe, 0x07, 0x1a, 0x18, 0xc6, 0x6c, 0x1b, 0x84, 0x56, 0x86, + 0x07, 0xc3, 0xe0, 0x64, 0x77, 0xc4, 0x7f, 0x7c, 0x7b, 0x7e, 0xd8, 0xb9, 0x6f, 0x84, 0xb0, 0xd2, + 0xb9, 0x4b, 0x6f, 0x95, 0x99, 0x5c, 0xb4, 0x5a, 0xf8, 0x8e, 0x0d, 0xa1, 0x2c, 0x71, 0x0e, 0x59, + 0x29, 0xd3, 0xac, 0xc4, 0xfc, 0x73, 0xea, 0x95, 0x96, 0xa9, 0x50, 0x2e, 0xb7, 0xb2, 0x02, 0x93, + 0x5f, 0xf1, 0x5b, 0xc3, 0xe0, 0x64, 0xeb, 0xe2, 0xf1, 0xda, 0x1b, 0x35, 0xda, 0x58, 0x69, 0x79, + 0xb6, 0x91, 0xc2, 0x63, 0x76, 0xe0, 0x2d, 0x18, 0xa7, 0xbc, 0x42, 0x43, 0x33, 0xf8, 0x16, 0xf5, + 0xee, 0x6d, 0xe2, 0xa6, 0x13, 0x3e, 0x61, 0x7b, 0x5a, 0x99, 0x54, 0x19, 0x2f, 0xed, 0x0c, 0x4a, + 0x7e, 0x9b, 0xac, 0xbb, 0x5a, 0x99, 0xf3, 0x2e, 0x22, 0x05, 0xea, 0x8d, 0xb2, 0xdd, 0x29, 0x50, + 0xaf, 0x95, 0x63, 0x76, 0x50, 0xe1, 0x5c, 0xda, 0xd4, 0x17, 0x56, 0xba, 0x02, 0x4b, 0xc1, 0xfb, + 0xed, 0xe7, 0x28, 0x1e, 0xaf, 0xd2, 0x30, 0x66, 0x0f, 0x9a, 0x59, 0x6e, 0x5a, 0x55, 0x68, 0xbd, + 0x14, 0x29, 0xfd, 0x6b, 0x7e, 0x87, 0xe4, 0xfb, 0x1a, 0xea, 0xcb, 0x15, 0x79, 0xdb, 0x80, 0xf0, + 0x19, 0xdb, 0xcf, 0x11, 0x4b, 0x81, 0xf3, 0x6e, 0x8b, 0x1d, 0x32, 0xf7, 0x56, 0x21, 0xed, 0xf0, + 0x9a, 0x3d, 0x6a, 0x76, 0x10, 0x72, 0xa6, 0x80, 0xf6, 0x55, 0x26, 0xf5, 0x05, 0x4e, 0x1d, 0x18, + 0xe1, 0x0b, 0xbe, 0x4b, 0x15, 0xae, 0x95, 0x39, 0x5b, 0x19, 0xe7, 0x66, 0xbc, 0xe6, 0x54, 0x87, + 0xfa, 0xbf, 0x75, 0xd6, 0xd5, 0xa1, 0xfe, 0x67, 0xfd, 0xd5, 0xce, 0xd7, 0xeb, 0xa3, 0xde, 0xef, + 0xeb, 0xa3, 0x60, 0xf4, 0xfe, 0xfb, 0x22, 0x0a, 0x6e, 0x16, 0x51, 0xf0, 0x6b, 0x11, 0x05, 0x5f, + 0x96, 0x51, 0xef, 0x66, 0x19, 0xf5, 0x7e, 0x2e, 0xa3, 0xde, 0xc7, 0x78, 0xa2, 0x7c, 0x31, 0xcd, + 0xe2, 0x1c, 0x75, 0x92, 0x81, 0x11, 0x74, 0x28, 0x39, 0x96, 0x49, 0x5e, 0x80, 0x32, 0xc9, 0xec, + 0x45, 0x52, 0x27, 0xed, 0x45, 0xfa, 0xab, 0x4a, 0xba, 0xac, 0x4f, 0xc2, 0xcb, 0xbf, 0x01, 0x00, + 0x00, 0xff, 0xff, 0xf8, 0xf9, 0x3a, 0x07, 0xa7, 0x02, 0x00, 0x00, +} + +func (this *Params) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Params) + if !ok { + that2, ok := that.(Params) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Admin != that1.Admin { + return false + } + if this.AllowableBlockTimeDiscrepancy != that1.AllowableBlockTimeDiscrepancy { + return false + } + if this.TransitionTime != that1.TransitionTime { + return false + } + if this.MinInterval != that1.MinInterval { + return false + } + if this.MaxInterval != that1.MaxInterval { + return false + } + if this.PowerThreshold != that1.PowerThreshold { + return false + } + if this.MaxSupportedFeeds != that1.MaxSupportedFeeds { + return false + } + if this.CooldownTime != that1.CooldownTime { + return false + } + if this.MinDeviationInThousandth != that1.MinDeviationInThousandth { + return false + } + if this.MaxDeviationInThousandth != that1.MaxDeviationInThousandth { + return false + } + return true +} +func (m *Params) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Params) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.MaxDeviationInThousandth != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.MaxDeviationInThousandth)) + i-- + dAtA[i] = 0x50 + } + if m.MinDeviationInThousandth != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.MinDeviationInThousandth)) + i-- + dAtA[i] = 0x48 + } + if m.CooldownTime != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.CooldownTime)) + i-- + dAtA[i] = 0x40 + } + if m.MaxSupportedFeeds != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.MaxSupportedFeeds)) + i-- + dAtA[i] = 0x38 + } + if m.PowerThreshold != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.PowerThreshold)) + i-- + dAtA[i] = 0x30 + } + if m.MaxInterval != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.MaxInterval)) + i-- + dAtA[i] = 0x28 + } + if m.MinInterval != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.MinInterval)) + i-- + dAtA[i] = 0x20 + } + if m.TransitionTime != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.TransitionTime)) + i-- + dAtA[i] = 0x18 + } + if m.AllowableBlockTimeDiscrepancy != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.AllowableBlockTimeDiscrepancy)) + i-- + dAtA[i] = 0x10 + } + if len(m.Admin) > 0 { + i -= len(m.Admin) + copy(dAtA[i:], m.Admin) + i = encodeVarintParams(dAtA, i, uint64(len(m.Admin))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintParams(dAtA []byte, offset int, v uint64) int { + offset -= sovParams(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Admin) + if l > 0 { + n += 1 + l + sovParams(uint64(l)) + } + if m.AllowableBlockTimeDiscrepancy != 0 { + n += 1 + sovParams(uint64(m.AllowableBlockTimeDiscrepancy)) + } + if m.TransitionTime != 0 { + n += 1 + sovParams(uint64(m.TransitionTime)) + } + if m.MinInterval != 0 { + n += 1 + sovParams(uint64(m.MinInterval)) + } + if m.MaxInterval != 0 { + n += 1 + sovParams(uint64(m.MaxInterval)) + } + if m.PowerThreshold != 0 { + n += 1 + sovParams(uint64(m.PowerThreshold)) + } + if m.MaxSupportedFeeds != 0 { + n += 1 + sovParams(uint64(m.MaxSupportedFeeds)) + } + if m.CooldownTime != 0 { + n += 1 + sovParams(uint64(m.CooldownTime)) + } + if m.MinDeviationInThousandth != 0 { + n += 1 + sovParams(uint64(m.MinDeviationInThousandth)) + } + if m.MaxDeviationInThousandth != 0 { + n += 1 + sovParams(uint64(m.MaxDeviationInThousandth)) + } + return n +} + +func sovParams(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozParams(x uint64) (n int) { + return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Params) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Params: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Admin = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field AllowableBlockTimeDiscrepancy", wireType) + } + m.AllowableBlockTimeDiscrepancy = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.AllowableBlockTimeDiscrepancy |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TransitionTime", wireType) + } + m.TransitionTime = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.TransitionTime |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinInterval", wireType) + } + m.MinInterval = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MinInterval |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxInterval", wireType) + } + m.MaxInterval = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MaxInterval |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PowerThreshold", wireType) + } + m.PowerThreshold = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PowerThreshold |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxSupportedFeeds", wireType) + } + m.MaxSupportedFeeds = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MaxSupportedFeeds |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 8: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CooldownTime", wireType) + } + m.CooldownTime = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CooldownTime |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 9: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MinDeviationInThousandth", wireType) + } + m.MinDeviationInThousandth = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MinDeviationInThousandth |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 10: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxDeviationInThousandth", wireType) + } + m.MaxDeviationInThousandth = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MaxDeviationInThousandth |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipParams(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowParams + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthParams + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupParams + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthParams + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/feeds/types/params_test.go b/x/feeds/types/params_test.go new file mode 100644 index 000000000..76f84ef8a --- /dev/null +++ b/x/feeds/types/params_test.go @@ -0,0 +1,40 @@ +package types_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func TestParamsEqual(t *testing.T) { + p1 := types.DefaultParams() + p2 := types.DefaultParams() + require.Equal(t, p1, p2) + + p1.MaxInterval += 10 + require.NotEqual(t, p1, p2) +} + +func TestParams_Validate(t *testing.T) { + tests := []struct { + name string + params types.Params + wantErr error + }{ + {"default params", types.DefaultParams(), nil}, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + got := tt.params.Validate() + if tt.wantErr == nil { + require.NoError(t, got) + return + } + require.Equal(t, tt.wantErr, got) + }) + } +} diff --git a/x/feeds/types/price.go b/x/feeds/types/price.go new file mode 100644 index 000000000..ec5ba3bd3 --- /dev/null +++ b/x/feeds/types/price.go @@ -0,0 +1,12 @@ +package types + +import "fmt" + +// Validate validates a Price. +func (p *Price) Validate() error { + if p.Timestamp <= 0 { + return fmt.Errorf("timestamp must be positive") + } + + return nil +} diff --git a/x/feeds/types/price_service.go b/x/feeds/types/price_service.go new file mode 100644 index 000000000..7a9738a27 --- /dev/null +++ b/x/feeds/types/price_service.go @@ -0,0 +1,36 @@ +package types + +// NewPriceService creates a new price service instance +func NewPriceService(hash string, version string, url string) PriceService { + return PriceService{ + Hash: hash, + Version: version, + Url: url, + } +} + +// DefaultPriceService returns a default set of price service's information +func DefaultPriceService() PriceService { + return NewPriceService("hash", "0.0.1", "https://") +} + +// Validate validates the price service +func (ps *PriceService) Validate() error { + if err := validateString("hash", false, ps.Hash); err != nil { + return err + } + + if err := validateString("version", false, ps.Version); err != nil { + return err + } + + if err := validateString("url", false, ps.Url); err != nil { + return err + } + + if err := validateURL("url", ps.Url); err != nil { + return err + } + + return nil +} diff --git a/x/feeds/types/price_service_test.go b/x/feeds/types/price_service_test.go new file mode 100644 index 000000000..41fde547f --- /dev/null +++ b/x/feeds/types/price_service_test.go @@ -0,0 +1,31 @@ +package types_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func TestPriceService_Validate(t *testing.T) { + tests := []struct { + name string + priceService types.PriceService + wantErr error + }{ + {"default price service", types.DefaultPriceService(), nil}, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + got := tt.priceService.Validate() + if tt.wantErr == nil { + require.NoError(t, got) + return + } + require.Equal(t, tt.wantErr, got) + }) + } +} diff --git a/x/feeds/types/query.pb.go b/x/feeds/types/query.pb.go new file mode 100644 index 000000000..c45c85cd5 --- /dev/null +++ b/x/feeds/types/query.pb.go @@ -0,0 +1,4334 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: feeds/v1beta1/query.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + query "github.com/cosmos/cosmos-sdk/types/query" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// QueryPricesRequest is the request type for the Query/Prices RPC method. +type QueryPricesRequest struct { + // SignalIDs is a List of signal ids to query prices for. + SignalIds []string `protobuf:"bytes,1,rep,name=signal_ids,json=signalIds,proto3" json:"signal_ids,omitempty"` + // Pagination is the pagination for the request. + Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryPricesRequest) Reset() { *m = QueryPricesRequest{} } +func (m *QueryPricesRequest) String() string { return proto.CompactTextString(m) } +func (*QueryPricesRequest) ProtoMessage() {} +func (*QueryPricesRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{0} +} +func (m *QueryPricesRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryPricesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPricesRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryPricesRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPricesRequest.Merge(m, src) +} +func (m *QueryPricesRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryPricesRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPricesRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPricesRequest proto.InternalMessageInfo + +func (m *QueryPricesRequest) GetSignalIds() []string { + if m != nil { + return m.SignalIds + } + return nil +} + +func (m *QueryPricesRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryPricesResponse is the response type for the Query/Prices RPC method. +type QueryPricesResponse struct { + // Prices is a list of prices. + Prices []*Price `protobuf:"bytes,1,rep,name=prices,proto3" json:"prices,omitempty"` + // Pagination is the pagination information in the response. + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryPricesResponse) Reset() { *m = QueryPricesResponse{} } +func (m *QueryPricesResponse) String() string { return proto.CompactTextString(m) } +func (*QueryPricesResponse) ProtoMessage() {} +func (*QueryPricesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{1} +} +func (m *QueryPricesResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryPricesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPricesResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryPricesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPricesResponse.Merge(m, src) +} +func (m *QueryPricesResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryPricesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPricesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPricesResponse proto.InternalMessageInfo + +func (m *QueryPricesResponse) GetPrices() []*Price { + if m != nil { + return m.Prices + } + return nil +} + +func (m *QueryPricesResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryPriceRequest is the request type for the Query/Price RPC method. +type QueryPriceRequest struct { + // SignalID is the signal id to query the price for. + SignalId string `protobuf:"bytes,1,opt,name=signal_id,json=signalId,proto3" json:"signal_id,omitempty"` +} + +func (m *QueryPriceRequest) Reset() { *m = QueryPriceRequest{} } +func (m *QueryPriceRequest) String() string { return proto.CompactTextString(m) } +func (*QueryPriceRequest) ProtoMessage() {} +func (*QueryPriceRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{2} +} +func (m *QueryPriceRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryPriceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPriceRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryPriceRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPriceRequest.Merge(m, src) +} +func (m *QueryPriceRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryPriceRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPriceRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPriceRequest proto.InternalMessageInfo + +func (m *QueryPriceRequest) GetSignalId() string { + if m != nil { + return m.SignalId + } + return "" +} + +// QueryPriceResponse is the response type for the Query/Price RPC method. +type QueryPriceResponse struct { + // Price is the aggregated price of the signal id. + Price Price `protobuf:"bytes,1,opt,name=price,proto3" json:"price"` + // ValidatorPrices is a list of prices from each validator. + ValidatorPrices []ValidatorPrice `protobuf:"bytes,2,rep,name=validator_prices,json=validatorPrices,proto3" json:"validator_prices"` +} + +func (m *QueryPriceResponse) Reset() { *m = QueryPriceResponse{} } +func (m *QueryPriceResponse) String() string { return proto.CompactTextString(m) } +func (*QueryPriceResponse) ProtoMessage() {} +func (*QueryPriceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{3} +} +func (m *QueryPriceResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryPriceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPriceResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryPriceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPriceResponse.Merge(m, src) +} +func (m *QueryPriceResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryPriceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPriceResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPriceResponse proto.InternalMessageInfo + +func (m *QueryPriceResponse) GetPrice() Price { + if m != nil { + return m.Price + } + return Price{} +} + +func (m *QueryPriceResponse) GetValidatorPrices() []ValidatorPrice { + if m != nil { + return m.ValidatorPrices + } + return nil +} + +// QueryValidatorPricesRequest is the request type for the Query/ValidatorPrices RPC method. +type QueryValidatorPricesRequest struct { + // Validator is the validator address to query prices for. + Validator string `protobuf:"bytes,1,opt,name=validator,proto3" json:"validator,omitempty"` +} + +func (m *QueryValidatorPricesRequest) Reset() { *m = QueryValidatorPricesRequest{} } +func (m *QueryValidatorPricesRequest) String() string { return proto.CompactTextString(m) } +func (*QueryValidatorPricesRequest) ProtoMessage() {} +func (*QueryValidatorPricesRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{4} +} +func (m *QueryValidatorPricesRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryValidatorPricesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryValidatorPricesRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryValidatorPricesRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryValidatorPricesRequest.Merge(m, src) +} +func (m *QueryValidatorPricesRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryValidatorPricesRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryValidatorPricesRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryValidatorPricesRequest proto.InternalMessageInfo + +func (m *QueryValidatorPricesRequest) GetValidator() string { + if m != nil { + return m.Validator + } + return "" +} + +// QueryValidatorPricesResponse is the response type for the Query/ValidatorPrices RPC method. +type QueryValidatorPricesResponse struct { + // ValidatorPrices is a list of prices submitted by the validator. + ValidatorPrices []ValidatorPrice `protobuf:"bytes,1,rep,name=validator_prices,json=validatorPrices,proto3" json:"validator_prices"` +} + +func (m *QueryValidatorPricesResponse) Reset() { *m = QueryValidatorPricesResponse{} } +func (m *QueryValidatorPricesResponse) String() string { return proto.CompactTextString(m) } +func (*QueryValidatorPricesResponse) ProtoMessage() {} +func (*QueryValidatorPricesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{5} +} +func (m *QueryValidatorPricesResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryValidatorPricesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryValidatorPricesResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryValidatorPricesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryValidatorPricesResponse.Merge(m, src) +} +func (m *QueryValidatorPricesResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryValidatorPricesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryValidatorPricesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryValidatorPricesResponse proto.InternalMessageInfo + +func (m *QueryValidatorPricesResponse) GetValidatorPrices() []ValidatorPrice { + if m != nil { + return m.ValidatorPrices + } + return nil +} + +// QueryValidatorPriceRequest is the request type for the Query/ValidatorPrice RPC method. +type QueryValidatorPriceRequest struct { + // SignalID is the signal id to query the price for. + SignalId string `protobuf:"bytes,1,opt,name=signal_id,json=signalId,proto3" json:"signal_id,omitempty"` + // Validator is the validator address to query the price for. + Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` +} + +func (m *QueryValidatorPriceRequest) Reset() { *m = QueryValidatorPriceRequest{} } +func (m *QueryValidatorPriceRequest) String() string { return proto.CompactTextString(m) } +func (*QueryValidatorPriceRequest) ProtoMessage() {} +func (*QueryValidatorPriceRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{6} +} +func (m *QueryValidatorPriceRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryValidatorPriceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryValidatorPriceRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryValidatorPriceRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryValidatorPriceRequest.Merge(m, src) +} +func (m *QueryValidatorPriceRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryValidatorPriceRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryValidatorPriceRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryValidatorPriceRequest proto.InternalMessageInfo + +func (m *QueryValidatorPriceRequest) GetSignalId() string { + if m != nil { + return m.SignalId + } + return "" +} + +func (m *QueryValidatorPriceRequest) GetValidator() string { + if m != nil { + return m.Validator + } + return "" +} + +// QueryValidatorPriceResponse is the response type for the Query/ValidatorPrice RPC method. +type QueryValidatorPriceResponse struct { + // ValidatorPrice is the requested price submitted by the validator. + ValidatorPrice ValidatorPrice `protobuf:"bytes,1,opt,name=validator_price,json=validatorPrice,proto3" json:"validator_price"` +} + +func (m *QueryValidatorPriceResponse) Reset() { *m = QueryValidatorPriceResponse{} } +func (m *QueryValidatorPriceResponse) String() string { return proto.CompactTextString(m) } +func (*QueryValidatorPriceResponse) ProtoMessage() {} +func (*QueryValidatorPriceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{7} +} +func (m *QueryValidatorPriceResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryValidatorPriceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryValidatorPriceResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryValidatorPriceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryValidatorPriceResponse.Merge(m, src) +} +func (m *QueryValidatorPriceResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryValidatorPriceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryValidatorPriceResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryValidatorPriceResponse proto.InternalMessageInfo + +func (m *QueryValidatorPriceResponse) GetValidatorPrice() ValidatorPrice { + if m != nil { + return m.ValidatorPrice + } + return ValidatorPrice{} +} + +// QueryValidValidatorRequest is the request type for the Query/ValidValidator RPC method. +type QueryValidValidatorRequest struct { + // Validator is the validator address to query the flag. + Validator string `protobuf:"bytes,1,opt,name=validator,proto3" json:"validator,omitempty"` +} + +func (m *QueryValidValidatorRequest) Reset() { *m = QueryValidValidatorRequest{} } +func (m *QueryValidValidatorRequest) String() string { return proto.CompactTextString(m) } +func (*QueryValidValidatorRequest) ProtoMessage() {} +func (*QueryValidValidatorRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{8} +} +func (m *QueryValidValidatorRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryValidValidatorRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryValidValidatorRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryValidValidatorRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryValidValidatorRequest.Merge(m, src) +} +func (m *QueryValidValidatorRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryValidValidatorRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryValidValidatorRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryValidValidatorRequest proto.InternalMessageInfo + +func (m *QueryValidValidatorRequest) GetValidator() string { + if m != nil { + return m.Validator + } + return "" +} + +// QueryValidValidatorResponse is the response type for the Query/ValidValidator RPC method. +type QueryValidValidatorResponse struct { + // Valid is a valid flag. + Valid bool `protobuf:"varint,1,opt,name=valid,proto3" json:"valid,omitempty"` +} + +func (m *QueryValidValidatorResponse) Reset() { *m = QueryValidValidatorResponse{} } +func (m *QueryValidValidatorResponse) String() string { return proto.CompactTextString(m) } +func (*QueryValidValidatorResponse) ProtoMessage() {} +func (*QueryValidValidatorResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{9} +} +func (m *QueryValidValidatorResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryValidValidatorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryValidValidatorResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryValidValidatorResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryValidValidatorResponse.Merge(m, src) +} +func (m *QueryValidValidatorResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryValidValidatorResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryValidValidatorResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryValidValidatorResponse proto.InternalMessageInfo + +func (m *QueryValidValidatorResponse) GetValid() bool { + if m != nil { + return m.Valid + } + return false +} + +// QueryFeedsRequest is the request type for the Query/Feeds RPC method. +type QueryFeedsRequest struct { + // SignalIDs is a list of signal ids to query. + SignalIds []string `protobuf:"bytes,1,rep,name=signal_ids,json=signalIds,proto3" json:"signal_ids,omitempty"` + // Pagination is the pagination for the request. + Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryFeedsRequest) Reset() { *m = QueryFeedsRequest{} } +func (m *QueryFeedsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryFeedsRequest) ProtoMessage() {} +func (*QueryFeedsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{10} +} +func (m *QueryFeedsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryFeedsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryFeedsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryFeedsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryFeedsRequest.Merge(m, src) +} +func (m *QueryFeedsRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryFeedsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryFeedsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryFeedsRequest proto.InternalMessageInfo + +func (m *QueryFeedsRequest) GetSignalIds() []string { + if m != nil { + return m.SignalIds + } + return nil +} + +func (m *QueryFeedsRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryFeedsResponse is the response type for the Query/Feeds RPC method. +type QueryFeedsResponse struct { + // Feeds is a list of feeds. + Feeds []*Feed `protobuf:"bytes,1,rep,name=feeds,proto3" json:"feeds,omitempty"` + // Pagination is the pagination information in the response. + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryFeedsResponse) Reset() { *m = QueryFeedsResponse{} } +func (m *QueryFeedsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryFeedsResponse) ProtoMessage() {} +func (*QueryFeedsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{11} +} +func (m *QueryFeedsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryFeedsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryFeedsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryFeedsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryFeedsResponse.Merge(m, src) +} +func (m *QueryFeedsResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryFeedsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryFeedsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryFeedsResponse proto.InternalMessageInfo + +func (m *QueryFeedsResponse) GetFeeds() []*Feed { + if m != nil { + return m.Feeds + } + return nil +} + +func (m *QueryFeedsResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryParamsRequest is the request type for the Query/Params RPC method. +type QueryParamsRequest struct { +} + +func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } +func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryParamsRequest) ProtoMessage() {} +func (*QueryParamsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{12} +} +func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsRequest.Merge(m, src) +} +func (m *QueryParamsRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo + +// QueryParamsResponse is the response type for the Query/Params RPC method. +type QueryParamsResponse struct { + // Params is the parameters of the module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } +func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryParamsResponse) ProtoMessage() {} +func (*QueryParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{13} +} +func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsResponse.Merge(m, src) +} +func (m *QueryParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo + +func (m *QueryParamsResponse) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +// QueryPriceServiceRequest is the request type for the Query/PriceService RPC method. +type QueryPriceServiceRequest struct { +} + +func (m *QueryPriceServiceRequest) Reset() { *m = QueryPriceServiceRequest{} } +func (m *QueryPriceServiceRequest) String() string { return proto.CompactTextString(m) } +func (*QueryPriceServiceRequest) ProtoMessage() {} +func (*QueryPriceServiceRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{14} +} +func (m *QueryPriceServiceRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryPriceServiceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPriceServiceRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryPriceServiceRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPriceServiceRequest.Merge(m, src) +} +func (m *QueryPriceServiceRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryPriceServiceRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPriceServiceRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPriceServiceRequest proto.InternalMessageInfo + +// QueryPriceServiceResponse is the response type for the Query/PriceService RPC method. +type QueryPriceServiceResponse struct { + // PriceService is the information about price service. + PriceService PriceService `protobuf:"bytes,1,opt,name=price_service,json=priceService,proto3" json:"price_service"` +} + +func (m *QueryPriceServiceResponse) Reset() { *m = QueryPriceServiceResponse{} } +func (m *QueryPriceServiceResponse) String() string { return proto.CompactTextString(m) } +func (*QueryPriceServiceResponse) ProtoMessage() {} +func (*QueryPriceServiceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{15} +} +func (m *QueryPriceServiceResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryPriceServiceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryPriceServiceResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryPriceServiceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryPriceServiceResponse.Merge(m, src) +} +func (m *QueryPriceServiceResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryPriceServiceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryPriceServiceResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryPriceServiceResponse proto.InternalMessageInfo + +func (m *QueryPriceServiceResponse) GetPriceService() PriceService { + if m != nil { + return m.PriceService + } + return PriceService{} +} + +// QueryDelegatorSignalsRequest is the request type for the Query/DelegatorSignals RPC method +type QueryDelegatorSignalsRequest struct { + // Delegator is the delegator address to query signal for. + Delegator string `protobuf:"bytes,1,opt,name=delegator,proto3" json:"delegator,omitempty"` +} + +func (m *QueryDelegatorSignalsRequest) Reset() { *m = QueryDelegatorSignalsRequest{} } +func (m *QueryDelegatorSignalsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryDelegatorSignalsRequest) ProtoMessage() {} +func (*QueryDelegatorSignalsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{16} +} +func (m *QueryDelegatorSignalsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryDelegatorSignalsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryDelegatorSignalsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryDelegatorSignalsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryDelegatorSignalsRequest.Merge(m, src) +} +func (m *QueryDelegatorSignalsRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryDelegatorSignalsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryDelegatorSignalsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryDelegatorSignalsRequest proto.InternalMessageInfo + +func (m *QueryDelegatorSignalsRequest) GetDelegator() string { + if m != nil { + return m.Delegator + } + return "" +} + +// QueryDelegatorSignalsResponse is the response type for the Query/DelegatorSignals RPC method +type QueryDelegatorSignalsResponse struct { + Signals []Signal `protobuf:"bytes,1,rep,name=signals,proto3" json:"signals"` +} + +func (m *QueryDelegatorSignalsResponse) Reset() { *m = QueryDelegatorSignalsResponse{} } +func (m *QueryDelegatorSignalsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryDelegatorSignalsResponse) ProtoMessage() {} +func (*QueryDelegatorSignalsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{17} +} +func (m *QueryDelegatorSignalsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryDelegatorSignalsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryDelegatorSignalsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryDelegatorSignalsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryDelegatorSignalsResponse.Merge(m, src) +} +func (m *QueryDelegatorSignalsResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryDelegatorSignalsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryDelegatorSignalsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryDelegatorSignalsResponse proto.InternalMessageInfo + +func (m *QueryDelegatorSignalsResponse) GetSignals() []Signal { + if m != nil { + return m.Signals + } + return nil +} + +// QuerySupportedFeedsRequest is the request type for the Query/SupportedFeeds RPC method +type QuerySupportedFeedsRequest struct { +} + +func (m *QuerySupportedFeedsRequest) Reset() { *m = QuerySupportedFeedsRequest{} } +func (m *QuerySupportedFeedsRequest) String() string { return proto.CompactTextString(m) } +func (*QuerySupportedFeedsRequest) ProtoMessage() {} +func (*QuerySupportedFeedsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{18} +} +func (m *QuerySupportedFeedsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QuerySupportedFeedsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QuerySupportedFeedsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QuerySupportedFeedsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QuerySupportedFeedsRequest.Merge(m, src) +} +func (m *QuerySupportedFeedsRequest) XXX_Size() int { + return m.Size() +} +func (m *QuerySupportedFeedsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QuerySupportedFeedsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QuerySupportedFeedsRequest proto.InternalMessageInfo + +// QuerySupportedFeedsResponse is the response type for the Query/SupportedFeeds RPC method +type QuerySupportedFeedsResponse struct { + // Feeds is a list of feeds. + Feeds []Feed `protobuf:"bytes,1,rep,name=feeds,proto3" json:"feeds"` +} + +func (m *QuerySupportedFeedsResponse) Reset() { *m = QuerySupportedFeedsResponse{} } +func (m *QuerySupportedFeedsResponse) String() string { return proto.CompactTextString(m) } +func (*QuerySupportedFeedsResponse) ProtoMessage() {} +func (*QuerySupportedFeedsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_8d77250ebbf26fe1, []int{19} +} +func (m *QuerySupportedFeedsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QuerySupportedFeedsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QuerySupportedFeedsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QuerySupportedFeedsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QuerySupportedFeedsResponse.Merge(m, src) +} +func (m *QuerySupportedFeedsResponse) XXX_Size() int { + return m.Size() +} +func (m *QuerySupportedFeedsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QuerySupportedFeedsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QuerySupportedFeedsResponse proto.InternalMessageInfo + +func (m *QuerySupportedFeedsResponse) GetFeeds() []Feed { + if m != nil { + return m.Feeds + } + return nil +} + +func init() { + proto.RegisterType((*QueryPricesRequest)(nil), "feeds.v1beta1.QueryPricesRequest") + proto.RegisterType((*QueryPricesResponse)(nil), "feeds.v1beta1.QueryPricesResponse") + proto.RegisterType((*QueryPriceRequest)(nil), "feeds.v1beta1.QueryPriceRequest") + proto.RegisterType((*QueryPriceResponse)(nil), "feeds.v1beta1.QueryPriceResponse") + proto.RegisterType((*QueryValidatorPricesRequest)(nil), "feeds.v1beta1.QueryValidatorPricesRequest") + proto.RegisterType((*QueryValidatorPricesResponse)(nil), "feeds.v1beta1.QueryValidatorPricesResponse") + proto.RegisterType((*QueryValidatorPriceRequest)(nil), "feeds.v1beta1.QueryValidatorPriceRequest") + proto.RegisterType((*QueryValidatorPriceResponse)(nil), "feeds.v1beta1.QueryValidatorPriceResponse") + proto.RegisterType((*QueryValidValidatorRequest)(nil), "feeds.v1beta1.QueryValidValidatorRequest") + proto.RegisterType((*QueryValidValidatorResponse)(nil), "feeds.v1beta1.QueryValidValidatorResponse") + proto.RegisterType((*QueryFeedsRequest)(nil), "feeds.v1beta1.QueryFeedsRequest") + proto.RegisterType((*QueryFeedsResponse)(nil), "feeds.v1beta1.QueryFeedsResponse") + proto.RegisterType((*QueryParamsRequest)(nil), "feeds.v1beta1.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "feeds.v1beta1.QueryParamsResponse") + proto.RegisterType((*QueryPriceServiceRequest)(nil), "feeds.v1beta1.QueryPriceServiceRequest") + proto.RegisterType((*QueryPriceServiceResponse)(nil), "feeds.v1beta1.QueryPriceServiceResponse") + proto.RegisterType((*QueryDelegatorSignalsRequest)(nil), "feeds.v1beta1.QueryDelegatorSignalsRequest") + proto.RegisterType((*QueryDelegatorSignalsResponse)(nil), "feeds.v1beta1.QueryDelegatorSignalsResponse") + proto.RegisterType((*QuerySupportedFeedsRequest)(nil), "feeds.v1beta1.QuerySupportedFeedsRequest") + proto.RegisterType((*QuerySupportedFeedsResponse)(nil), "feeds.v1beta1.QuerySupportedFeedsResponse") +} + +func init() { proto.RegisterFile("feeds/v1beta1/query.proto", fileDescriptor_8d77250ebbf26fe1) } + +var fileDescriptor_8d77250ebbf26fe1 = []byte{ + // 1020 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x57, 0xcf, 0x6f, 0xe3, 0x44, + 0x14, 0xae, 0x0b, 0x29, 0x9b, 0xb7, 0x3f, 0xba, 0xcc, 0x66, 0x21, 0x75, 0xd3, 0x90, 0x0e, 0xb0, + 0xfd, 0x41, 0xe3, 0xd9, 0x6d, 0x59, 0x84, 0x38, 0x41, 0x85, 0xca, 0x0f, 0xa1, 0xd5, 0xe2, 0x42, + 0x0f, 0x5c, 0x2a, 0x27, 0x1e, 0xbc, 0x86, 0xd4, 0x76, 0x3d, 0x6e, 0x60, 0xa9, 0x7a, 0xe1, 0x02, + 0x07, 0x24, 0x90, 0x90, 0xf6, 0xcc, 0x81, 0x0b, 0x77, 0xfe, 0x88, 0x3d, 0xae, 0xe0, 0xc2, 0x09, + 0xa1, 0x96, 0xff, 0x81, 0x2b, 0xca, 0xcc, 0xb3, 0x63, 0x7b, 0xc7, 0x4d, 0xa4, 0x45, 0xdc, 0x92, + 0x79, 0xdf, 0xbc, 0xef, 0x7b, 0x6f, 0xde, 0xfb, 0xd2, 0xc2, 0xc2, 0xa7, 0x9c, 0xbb, 0x82, 0x0d, + 0x6f, 0xf5, 0x78, 0xe2, 0xdc, 0x62, 0x87, 0x47, 0x3c, 0xbe, 0x6f, 0x45, 0x71, 0x98, 0x84, 0xe4, + 0xb2, 0x0c, 0x59, 0x18, 0x32, 0x1b, 0x5e, 0xe8, 0x85, 0x32, 0xc2, 0x46, 0x9f, 0x14, 0xc8, 0x6c, + 0x79, 0x61, 0xe8, 0x0d, 0x38, 0x73, 0x22, 0x9f, 0x39, 0x41, 0x10, 0x26, 0x4e, 0xe2, 0x87, 0x81, + 0xc0, 0xe8, 0x42, 0x3f, 0x14, 0x07, 0xa1, 0xd8, 0x57, 0xd7, 0xd4, 0x17, 0x0c, 0xad, 0xab, 0x6f, + 0xac, 0xe7, 0x08, 0xae, 0x68, 0x33, 0x11, 0x91, 0xe3, 0xf9, 0x81, 0xcc, 0x93, 0xa6, 0x29, 0x8a, + 0x54, 0xba, 0x54, 0xc8, 0x2c, 0x86, 0x22, 0x27, 0x76, 0x0e, 0x30, 0x46, 0x8f, 0x81, 0x7c, 0x38, + 0x4a, 0x7c, 0x37, 0xf6, 0xfb, 0x5c, 0xd8, 0xfc, 0xf0, 0x88, 0x8b, 0x84, 0x2c, 0x01, 0x08, 0xdf, + 0x0b, 0x9c, 0xc1, 0xbe, 0xef, 0x8a, 0xa6, 0xd1, 0x79, 0x6a, 0xb5, 0x6e, 0xd7, 0xd5, 0xc9, 0x7b, + 0xae, 0x20, 0x3b, 0x00, 0x63, 0xfe, 0xe6, 0x6c, 0xc7, 0x58, 0xbd, 0xb8, 0x79, 0xc3, 0x42, 0xe9, + 0x23, 0xb1, 0x96, 0xea, 0x11, 0x32, 0x5a, 0x77, 0x1d, 0x8f, 0x63, 0x6a, 0x3b, 0x77, 0x93, 0x7e, + 0x67, 0xc0, 0xb5, 0x02, 0xbb, 0x88, 0xc2, 0x40, 0x70, 0xb2, 0x01, 0x73, 0x91, 0x3c, 0x91, 0xd4, + 0x17, 0x37, 0x1b, 0x56, 0xa1, 0xcd, 0x96, 0x84, 0xdb, 0x88, 0x21, 0xef, 0x68, 0xd4, 0xac, 0x4c, + 0x54, 0xa3, 0xa8, 0x0a, 0x72, 0x6e, 0xc2, 0xb3, 0x63, 0x35, 0x69, 0x2b, 0x16, 0xa1, 0x9e, 0xb5, + 0xa2, 0x69, 0x74, 0x8c, 0xd5, 0xba, 0x7d, 0x21, 0xed, 0x04, 0x7d, 0x60, 0xe4, 0xdb, 0x97, 0xe9, + 0xbf, 0x09, 0x35, 0xa9, 0x4d, 0xe2, 0x2b, 0xe4, 0x6f, 0x3f, 0xfd, 0xf0, 0xcf, 0x17, 0x66, 0x6c, + 0x05, 0x24, 0x77, 0xe0, 0xea, 0xd0, 0x19, 0xf8, 0xae, 0x93, 0x84, 0xf1, 0x3e, 0xd6, 0x3e, 0x2b, + 0x6b, 0x5f, 0x2a, 0x5d, 0xde, 0x4b, 0x61, 0xf9, 0x2c, 0xf3, 0xc3, 0xc2, 0xa9, 0xa0, 0x1f, 0xc3, + 0xa2, 0xd4, 0x55, 0x44, 0x67, 0xef, 0xfb, 0x1a, 0xd4, 0xb3, 0x1b, 0xaa, 0xa8, 0xed, 0xe6, 0x6f, + 0xbf, 0x76, 0x1b, 0xd8, 0xb4, 0xb7, 0x5c, 0x37, 0xe6, 0x42, 0xec, 0x26, 0xb1, 0x1f, 0x78, 0xf6, + 0x18, 0x4a, 0x03, 0x68, 0xe9, 0xd3, 0x62, 0xe1, 0xba, 0x32, 0x8c, 0x27, 0x28, 0xe3, 0x10, 0x4c, + 0x0d, 0xdf, 0x34, 0x4f, 0x53, 0x2c, 0x71, 0x76, 0xfa, 0x12, 0x3f, 0xd7, 0x76, 0x2e, 0xab, 0xf0, + 0x03, 0x98, 0x2f, 0x55, 0x88, 0x8f, 0x3c, 0x55, 0x81, 0x57, 0x8a, 0x05, 0xd2, 0x8f, 0xf2, 0xf5, + 0x65, 0x37, 0x9e, 0xf4, 0x95, 0xb6, 0xf2, 0x25, 0xe4, 0xb2, 0x62, 0x09, 0x0d, 0xa8, 0x49, 0xac, + 0x4c, 0x79, 0xc1, 0x56, 0x5f, 0xe8, 0x57, 0x38, 0xfc, 0x3b, 0xa3, 0x2a, 0xfe, 0x67, 0x1f, 0xf8, + 0x36, 0x5d, 0x23, 0x24, 0x47, 0xa1, 0x6b, 0x50, 0x93, 0x3d, 0xc5, 0x11, 0xba, 0x56, 0xea, 0xf0, + 0x08, 0x6c, 0x2b, 0xc4, 0x7f, 0xe7, 0x01, 0x8d, 0x74, 0xa1, 0xa5, 0x49, 0xa2, 0x58, 0xfa, 0x7e, + 0xea, 0x53, 0x78, 0x8a, 0x02, 0xb7, 0x60, 0x4e, 0x99, 0x29, 0xce, 0xc0, 0xf5, 0xf2, 0xa2, 0xcb, + 0x20, 0xbe, 0x3d, 0x42, 0xa9, 0x09, 0xcd, 0xb1, 0x65, 0xec, 0xf2, 0x78, 0x38, 0x9e, 0x68, 0xda, + 0x87, 0x05, 0x4d, 0x0c, 0xd9, 0x76, 0xe0, 0xb2, 0x1c, 0xb8, 0x7d, 0xa1, 0x02, 0x48, 0xba, 0xa8, + 0x73, 0x17, 0xbc, 0x8b, 0xd4, 0x97, 0xa2, 0xdc, 0x19, 0xdd, 0xc3, 0x25, 0x7e, 0x9b, 0x0f, 0xb8, + 0x37, 0x9a, 0x8c, 0x5d, 0xf9, 0xa0, 0x79, 0x73, 0x70, 0xd3, 0xd0, 0xe4, 0xb1, 0xcb, 0xa0, 0x74, + 0x0f, 0x96, 0x2a, 0xf2, 0x62, 0x01, 0xb7, 0xe1, 0x19, 0x35, 0x3b, 0xe9, 0x8b, 0x96, 0xfb, 0xa5, + 0x2e, 0xa0, 0xe8, 0x14, 0x4b, 0x5b, 0xb8, 0x24, 0xbb, 0x47, 0x51, 0x14, 0xc6, 0x09, 0x77, 0xf3, + 0x23, 0x4a, 0xef, 0xe0, 0xb0, 0x97, 0xa3, 0xc8, 0xc9, 0x26, 0xcf, 0x50, 0xea, 0xc4, 0x32, 0xb2, + 0xf9, 0x0f, 0x40, 0x4d, 0x26, 0x24, 0x01, 0xcc, 0x29, 0x1b, 0x22, 0xcb, 0xa5, 0x5b, 0x8f, 0xff, + 0x62, 0x9a, 0xf4, 0x3c, 0x88, 0xd2, 0x42, 0x97, 0xbe, 0xfe, 0xfd, 0xef, 0x1f, 0x67, 0x9f, 0x27, + 0xd7, 0x59, 0xe9, 0x07, 0x59, 0xb1, 0x7c, 0x01, 0x35, 0x79, 0x81, 0x74, 0x2a, 0x73, 0xa5, 0x6c, + 0xcb, 0xe7, 0x20, 0x90, 0x6c, 0x4d, 0x92, 0xbd, 0x48, 0x96, 0xb5, 0x64, 0xec, 0x38, 0xdb, 0xeb, + 0x13, 0xf2, 0x93, 0x01, 0xf3, 0x25, 0x47, 0x27, 0xeb, 0x3a, 0x06, 0xfd, 0xaf, 0x89, 0xf9, 0xca, + 0x54, 0x58, 0xd4, 0xf5, 0xaa, 0xd4, 0x65, 0x91, 0x8d, 0x92, 0xae, 0xcc, 0xbe, 0x04, 0x3b, 0xce, + 0x3e, 0x9f, 0xa4, 0xbd, 0xf9, 0xc5, 0x80, 0x2b, 0xc5, 0x8c, 0x64, 0x6d, 0x32, 0x6b, 0x2a, 0x70, + 0x7d, 0x1a, 0x28, 0xea, 0x7b, 0x53, 0xea, 0x7b, 0x83, 0xbc, 0x3e, 0xb1, 0x6f, 0x15, 0x92, 0xc9, + 0x83, 0x54, 0x6b, 0xc6, 0x70, 0x8e, 0xd6, 0xb2, 0xe9, 0x9f, 0xa3, 0xf5, 0x31, 0x27, 0xa7, 0x5d, + 0xa9, 0x75, 0x85, 0xbc, 0x3c, 0x55, 0x2f, 0xc9, 0x67, 0x50, 0x93, 0xcb, 0xa1, 0x1f, 0xb0, 0xfc, + 0x56, 0xe9, 0x07, 0xac, 0xb0, 0x59, 0xb4, 0x25, 0xc9, 0x9f, 0x23, 0x0d, 0xa6, 0xf9, 0xcb, 0x53, + 0x2e, 0x8f, 0xf4, 0xbb, 0x8a, 0xe5, 0xc9, 0xdb, 0x6b, 0xc5, 0xf2, 0x14, 0xbc, 0xb6, 0x7a, 0x79, + 0x14, 0xcb, 0x37, 0x06, 0x5c, 0xca, 0x3b, 0x1f, 0x59, 0xa9, 0x5c, 0x91, 0xa2, 0xe7, 0x9a, 0xab, + 0x93, 0x81, 0x28, 0xe1, 0x25, 0x29, 0xa1, 0x4d, 0x5a, 0xba, 0xd1, 0xe8, 0xa2, 0x2b, 0x93, 0x9f, + 0x0d, 0xb8, 0x5a, 0xb6, 0x40, 0xa2, 0x5d, 0x91, 0x0a, 0x03, 0x36, 0x37, 0xa6, 0x03, 0xa3, 0xaa, + 0xdb, 0x52, 0x15, 0x23, 0xdd, 0x92, 0xaa, 0xcc, 0x98, 0x05, 0x3b, 0xce, 0x3e, 0x9f, 0x30, 0x74, + 0x55, 0xf2, 0xbd, 0x01, 0x57, 0x8a, 0x9e, 0xa9, 0x9f, 0x52, 0xad, 0xeb, 0xea, 0xa7, 0x54, 0x6f, + 0xc1, 0xf4, 0x86, 0x14, 0xd8, 0x21, 0xed, 0x92, 0x40, 0x91, 0xc2, 0xbb, 0xf2, 0x7c, 0xfb, 0xdd, + 0x87, 0xa7, 0x6d, 0xe3, 0xd1, 0x69, 0xdb, 0xf8, 0xeb, 0xb4, 0x6d, 0xfc, 0x70, 0xd6, 0x9e, 0x79, + 0x74, 0xd6, 0x9e, 0xf9, 0xe3, 0xac, 0x3d, 0xf3, 0x89, 0xe5, 0xf9, 0xc9, 0xbd, 0xa3, 0x9e, 0xd5, + 0x0f, 0x0f, 0x58, 0xcf, 0x09, 0x5c, 0xf9, 0xaf, 0x4b, 0x3f, 0x1c, 0xb0, 0xfe, 0x3d, 0xc7, 0x0f, + 0xd8, 0x70, 0x93, 0x7d, 0x89, 0xb9, 0x93, 0xfb, 0x11, 0x17, 0xbd, 0x39, 0x09, 0xd8, 0xfa, 0x37, + 0x00, 0x00, 0xff, 0xff, 0x91, 0x38, 0x9e, 0xf5, 0xb9, 0x0d, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { + // Prices is a RPC method that returns all prices. + Prices(ctx context.Context, in *QueryPricesRequest, opts ...grpc.CallOption) (*QueryPricesResponse, error) + // Price is a RPC method that returns price by signal id. + Price(ctx context.Context, in *QueryPriceRequest, opts ...grpc.CallOption) (*QueryPriceResponse, error) + // ValidatorPrices is a RPC method that returns prices of a validator. + ValidatorPrices(ctx context.Context, in *QueryValidatorPricesRequest, opts ...grpc.CallOption) (*QueryValidatorPricesResponse, error) + // ValidatorPrice is a RPC method that returns price of validator by signal id. + ValidatorPrice(ctx context.Context, in *QueryValidatorPriceRequest, opts ...grpc.CallOption) (*QueryValidatorPriceResponse, error) + // ValidValidator is a RPC method that returns flag to show if the validator is required to send prices. + ValidValidator(ctx context.Context, in *QueryValidValidatorRequest, opts ...grpc.CallOption) (*QueryValidValidatorResponse, error) + // Feeds is a RPC method that returns all feeds. + Feeds(ctx context.Context, in *QueryFeedsRequest, opts ...grpc.CallOption) (*QueryFeedsResponse, error) + // Params is a RPC method that returns all parameters of the module. + Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) + // PriceService is a RPC method that returns information of price service. + PriceService(ctx context.Context, in *QueryPriceServiceRequest, opts ...grpc.CallOption) (*QueryPriceServiceResponse, error) + // DelegatorSignals is a RPC method that returns signals of a delegator + DelegatorSignals(ctx context.Context, in *QueryDelegatorSignalsRequest, opts ...grpc.CallOption) (*QueryDelegatorSignalsResponse, error) + // SupportedFeeds is a RPC method that return list of currect supported feeds + SupportedFeeds(ctx context.Context, in *QuerySupportedFeedsRequest, opts ...grpc.CallOption) (*QuerySupportedFeedsResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) Prices(ctx context.Context, in *QueryPricesRequest, opts ...grpc.CallOption) (*QueryPricesResponse, error) { + out := new(QueryPricesResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Query/Prices", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) Price(ctx context.Context, in *QueryPriceRequest, opts ...grpc.CallOption) (*QueryPriceResponse, error) { + out := new(QueryPriceResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Query/Price", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) ValidatorPrices(ctx context.Context, in *QueryValidatorPricesRequest, opts ...grpc.CallOption) (*QueryValidatorPricesResponse, error) { + out := new(QueryValidatorPricesResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Query/ValidatorPrices", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) ValidatorPrice(ctx context.Context, in *QueryValidatorPriceRequest, opts ...grpc.CallOption) (*QueryValidatorPriceResponse, error) { + out := new(QueryValidatorPriceResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Query/ValidatorPrice", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) ValidValidator(ctx context.Context, in *QueryValidValidatorRequest, opts ...grpc.CallOption) (*QueryValidValidatorResponse, error) { + out := new(QueryValidValidatorResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Query/ValidValidator", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) Feeds(ctx context.Context, in *QueryFeedsRequest, opts ...grpc.CallOption) (*QueryFeedsResponse, error) { + out := new(QueryFeedsResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Query/Feeds", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { + out := new(QueryParamsResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Query/Params", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) PriceService(ctx context.Context, in *QueryPriceServiceRequest, opts ...grpc.CallOption) (*QueryPriceServiceResponse, error) { + out := new(QueryPriceServiceResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Query/PriceService", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) DelegatorSignals(ctx context.Context, in *QueryDelegatorSignalsRequest, opts ...grpc.CallOption) (*QueryDelegatorSignalsResponse, error) { + out := new(QueryDelegatorSignalsResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Query/DelegatorSignals", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) SupportedFeeds(ctx context.Context, in *QuerySupportedFeedsRequest, opts ...grpc.CallOption) (*QuerySupportedFeedsResponse, error) { + out := new(QuerySupportedFeedsResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Query/SupportedFeeds", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // Prices is a RPC method that returns all prices. + Prices(context.Context, *QueryPricesRequest) (*QueryPricesResponse, error) + // Price is a RPC method that returns price by signal id. + Price(context.Context, *QueryPriceRequest) (*QueryPriceResponse, error) + // ValidatorPrices is a RPC method that returns prices of a validator. + ValidatorPrices(context.Context, *QueryValidatorPricesRequest) (*QueryValidatorPricesResponse, error) + // ValidatorPrice is a RPC method that returns price of validator by signal id. + ValidatorPrice(context.Context, *QueryValidatorPriceRequest) (*QueryValidatorPriceResponse, error) + // ValidValidator is a RPC method that returns flag to show if the validator is required to send prices. + ValidValidator(context.Context, *QueryValidValidatorRequest) (*QueryValidValidatorResponse, error) + // Feeds is a RPC method that returns all feeds. + Feeds(context.Context, *QueryFeedsRequest) (*QueryFeedsResponse, error) + // Params is a RPC method that returns all parameters of the module. + Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) + // PriceService is a RPC method that returns information of price service. + PriceService(context.Context, *QueryPriceServiceRequest) (*QueryPriceServiceResponse, error) + // DelegatorSignals is a RPC method that returns signals of a delegator + DelegatorSignals(context.Context, *QueryDelegatorSignalsRequest) (*QueryDelegatorSignalsResponse, error) + // SupportedFeeds is a RPC method that return list of currect supported feeds + SupportedFeeds(context.Context, *QuerySupportedFeedsRequest) (*QuerySupportedFeedsResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) Prices(ctx context.Context, req *QueryPricesRequest) (*QueryPricesResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Prices not implemented") +} +func (*UnimplementedQueryServer) Price(ctx context.Context, req *QueryPriceRequest) (*QueryPriceResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Price not implemented") +} +func (*UnimplementedQueryServer) ValidatorPrices(ctx context.Context, req *QueryValidatorPricesRequest) (*QueryValidatorPricesResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ValidatorPrices not implemented") +} +func (*UnimplementedQueryServer) ValidatorPrice(ctx context.Context, req *QueryValidatorPriceRequest) (*QueryValidatorPriceResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ValidatorPrice not implemented") +} +func (*UnimplementedQueryServer) ValidValidator(ctx context.Context, req *QueryValidValidatorRequest) (*QueryValidValidatorResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ValidValidator not implemented") +} +func (*UnimplementedQueryServer) Feeds(ctx context.Context, req *QueryFeedsRequest) (*QueryFeedsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Feeds not implemented") +} +func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") +} +func (*UnimplementedQueryServer) PriceService(ctx context.Context, req *QueryPriceServiceRequest) (*QueryPriceServiceResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PriceService not implemented") +} +func (*UnimplementedQueryServer) DelegatorSignals(ctx context.Context, req *QueryDelegatorSignalsRequest) (*QueryDelegatorSignalsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method DelegatorSignals not implemented") +} +func (*UnimplementedQueryServer) SupportedFeeds(ctx context.Context, req *QuerySupportedFeedsRequest) (*QuerySupportedFeedsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SupportedFeeds not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_Prices_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryPricesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Prices(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Query/Prices", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Prices(ctx, req.(*QueryPricesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_Price_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryPriceRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Price(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Query/Price", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Price(ctx, req.(*QueryPriceRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_ValidatorPrices_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryValidatorPricesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).ValidatorPrices(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Query/ValidatorPrices", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).ValidatorPrices(ctx, req.(*QueryValidatorPricesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_ValidatorPrice_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryValidatorPriceRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).ValidatorPrice(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Query/ValidatorPrice", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).ValidatorPrice(ctx, req.(*QueryValidatorPriceRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_ValidValidator_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryValidValidatorRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).ValidValidator(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Query/ValidValidator", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).ValidValidator(ctx, req.(*QueryValidValidatorRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_Feeds_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryFeedsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Feeds(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Query/Feeds", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Feeds(ctx, req.(*QueryFeedsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryParamsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Params(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Query/Params", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_PriceService_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryPriceServiceRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).PriceService(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Query/PriceService", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).PriceService(ctx, req.(*QueryPriceServiceRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_DelegatorSignals_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryDelegatorSignalsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).DelegatorSignals(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Query/DelegatorSignals", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).DelegatorSignals(ctx, req.(*QueryDelegatorSignalsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_SupportedFeeds_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QuerySupportedFeedsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).SupportedFeeds(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Query/SupportedFeeds", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).SupportedFeeds(ctx, req.(*QuerySupportedFeedsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "feeds.v1beta1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Prices", + Handler: _Query_Prices_Handler, + }, + { + MethodName: "Price", + Handler: _Query_Price_Handler, + }, + { + MethodName: "ValidatorPrices", + Handler: _Query_ValidatorPrices_Handler, + }, + { + MethodName: "ValidatorPrice", + Handler: _Query_ValidatorPrice_Handler, + }, + { + MethodName: "ValidValidator", + Handler: _Query_ValidValidator_Handler, + }, + { + MethodName: "Feeds", + Handler: _Query_Feeds_Handler, + }, + { + MethodName: "Params", + Handler: _Query_Params_Handler, + }, + { + MethodName: "PriceService", + Handler: _Query_PriceService_Handler, + }, + { + MethodName: "DelegatorSignals", + Handler: _Query_DelegatorSignals_Handler, + }, + { + MethodName: "SupportedFeeds", + Handler: _Query_SupportedFeeds_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "feeds/v1beta1/query.proto", +} + +func (m *QueryPricesRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryPricesRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPricesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.SignalIds) > 0 { + for iNdEx := len(m.SignalIds) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.SignalIds[iNdEx]) + copy(dAtA[i:], m.SignalIds[iNdEx]) + i = encodeVarintQuery(dAtA, i, uint64(len(m.SignalIds[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryPricesResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryPricesResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPricesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Prices) > 0 { + for iNdEx := len(m.Prices) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Prices[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryPriceRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryPriceRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPriceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.SignalId) > 0 { + i -= len(m.SignalId) + copy(dAtA[i:], m.SignalId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.SignalId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryPriceResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryPriceResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPriceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ValidatorPrices) > 0 { + for iNdEx := len(m.ValidatorPrices) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ValidatorPrices[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.Price.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *QueryValidatorPricesRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryValidatorPricesRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryValidatorPricesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Validator) > 0 { + i -= len(m.Validator) + copy(dAtA[i:], m.Validator) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Validator))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryValidatorPricesResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryValidatorPricesResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryValidatorPricesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ValidatorPrices) > 0 { + for iNdEx := len(m.ValidatorPrices) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ValidatorPrices[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryValidatorPriceRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryValidatorPriceRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryValidatorPriceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Validator) > 0 { + i -= len(m.Validator) + copy(dAtA[i:], m.Validator) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Validator))) + i-- + dAtA[i] = 0x12 + } + if len(m.SignalId) > 0 { + i -= len(m.SignalId) + copy(dAtA[i:], m.SignalId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.SignalId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryValidatorPriceResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryValidatorPriceResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryValidatorPriceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.ValidatorPrice.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *QueryValidValidatorRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryValidValidatorRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryValidValidatorRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Validator) > 0 { + i -= len(m.Validator) + copy(dAtA[i:], m.Validator) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Validator))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryValidValidatorResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryValidValidatorResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryValidValidatorResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Valid { + i-- + if m.Valid { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryFeedsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryFeedsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryFeedsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.SignalIds) > 0 { + for iNdEx := len(m.SignalIds) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.SignalIds[iNdEx]) + copy(dAtA[i:], m.SignalIds[iNdEx]) + i = encodeVarintQuery(dAtA, i, uint64(len(m.SignalIds[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryFeedsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryFeedsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryFeedsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Feeds) > 0 { + for iNdEx := len(m.Feeds) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Feeds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *QueryPriceServiceRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryPriceServiceRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPriceServiceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryPriceServiceResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryPriceServiceResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryPriceServiceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.PriceService.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *QueryDelegatorSignalsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryDelegatorSignalsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryDelegatorSignalsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Delegator) > 0 { + i -= len(m.Delegator) + copy(dAtA[i:], m.Delegator) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Delegator))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryDelegatorSignalsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryDelegatorSignalsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryDelegatorSignalsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Signals) > 0 { + for iNdEx := len(m.Signals) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Signals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QuerySupportedFeedsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QuerySupportedFeedsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QuerySupportedFeedsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QuerySupportedFeedsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QuerySupportedFeedsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QuerySupportedFeedsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Feeds) > 0 { + for iNdEx := len(m.Feeds) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Feeds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryPricesRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.SignalIds) > 0 { + for _, s := range m.SignalIds { + l = len(s) + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryPricesResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Prices) > 0 { + for _, e := range m.Prices { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryPriceRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.SignalId) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryPriceResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Price.Size() + n += 1 + l + sovQuery(uint64(l)) + if len(m.ValidatorPrices) > 0 { + for _, e := range m.ValidatorPrices { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func (m *QueryValidatorPricesRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Validator) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryValidatorPricesResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.ValidatorPrices) > 0 { + for _, e := range m.ValidatorPrices { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func (m *QueryValidatorPriceRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.SignalId) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.Validator) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryValidatorPriceResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.ValidatorPrice.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryValidValidatorRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Validator) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryValidValidatorResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Valid { + n += 2 + } + return n +} + +func (m *QueryFeedsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.SignalIds) > 0 { + for _, s := range m.SignalIds { + l = len(s) + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryFeedsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Feeds) > 0 { + for _, e := range m.Feeds { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryParamsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryPriceServiceRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryPriceServiceResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.PriceService.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryDelegatorSignalsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Delegator) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryDelegatorSignalsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Signals) > 0 { + for _, e := range m.Signals { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func (m *QuerySupportedFeedsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QuerySupportedFeedsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Feeds) > 0 { + for _, e := range m.Feeds { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *QueryPricesRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryPricesRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPricesRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignalIds", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SignalIds = append(m.SignalIds, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageRequest{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryPricesResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryPricesResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPricesResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Prices", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Prices = append(m.Prices, &Price{}) + if err := m.Prices[len(m.Prices)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageResponse{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryPriceRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryPriceRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPriceRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignalId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SignalId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryPriceResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryPriceResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPriceResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Price", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Price.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorPrices", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorPrices = append(m.ValidatorPrices, ValidatorPrice{}) + if err := m.ValidatorPrices[len(m.ValidatorPrices)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryValidatorPricesRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryValidatorPricesRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryValidatorPricesRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Validator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryValidatorPricesResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryValidatorPricesResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryValidatorPricesResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorPrices", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorPrices = append(m.ValidatorPrices, ValidatorPrice{}) + if err := m.ValidatorPrices[len(m.ValidatorPrices)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryValidatorPriceRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryValidatorPriceRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryValidatorPriceRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignalId", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SignalId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Validator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryValidatorPriceResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryValidatorPriceResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryValidatorPriceResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorPrice", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ValidatorPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryValidValidatorRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryValidValidatorRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryValidValidatorRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Validator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryValidValidatorResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryValidValidatorResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryValidValidatorResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Valid", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Valid = bool(v != 0) + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryFeedsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryFeedsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryFeedsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SignalIds", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SignalIds = append(m.SignalIds, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageRequest{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryFeedsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryFeedsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryFeedsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Feeds", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Feeds = append(m.Feeds, &Feed{}) + if err := m.Feeds[len(m.Feeds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageResponse{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryPriceServiceRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryPriceServiceRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPriceServiceRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryPriceServiceResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryPriceServiceResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryPriceServiceResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PriceService", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PriceService.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryDelegatorSignalsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryDelegatorSignalsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryDelegatorSignalsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Delegator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Delegator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryDelegatorSignalsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryDelegatorSignalsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryDelegatorSignalsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signals", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signals = append(m.Signals, Signal{}) + if err := m.Signals[len(m.Signals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QuerySupportedFeedsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QuerySupportedFeedsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QuerySupportedFeedsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QuerySupportedFeedsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QuerySupportedFeedsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QuerySupportedFeedsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Feeds", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Feeds = append(m.Feeds, Feed{}) + if err := m.Feeds[len(m.Feeds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/feeds/types/query.pb.gw.go b/x/feeds/types/query.pb.gw.go new file mode 100644 index 000000000..5d97cd8e4 --- /dev/null +++ b/x/feeds/types/query.pb.gw.go @@ -0,0 +1,976 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: feeds/v1beta1/query.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage +var _ = metadata.Join + +var ( + filter_Query_Prices_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Query_Prices_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPricesRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Prices_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.Prices(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Prices_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPricesRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Prices_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.Prices(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_Price_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPriceRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["signal_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "signal_id") + } + + protoReq.SignalId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "signal_id", err) + } + + msg, err := client.Price(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Price_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPriceRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["signal_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "signal_id") + } + + protoReq.SignalId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "signal_id", err) + } + + msg, err := server.Price(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_ValidatorPrices_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryValidatorPricesRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["validator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator") + } + + protoReq.Validator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator", err) + } + + msg, err := client.ValidatorPrices(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_ValidatorPrices_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryValidatorPricesRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["validator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator") + } + + protoReq.Validator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator", err) + } + + msg, err := server.ValidatorPrices(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_ValidatorPrice_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryValidatorPriceRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["signal_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "signal_id") + } + + protoReq.SignalId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "signal_id", err) + } + + val, ok = pathParams["validator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator") + } + + protoReq.Validator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator", err) + } + + msg, err := client.ValidatorPrice(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_ValidatorPrice_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryValidatorPriceRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["signal_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "signal_id") + } + + protoReq.SignalId, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "signal_id", err) + } + + val, ok = pathParams["validator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator") + } + + protoReq.Validator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator", err) + } + + msg, err := server.ValidatorPrice(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_ValidValidator_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryValidValidatorRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["validator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator") + } + + protoReq.Validator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator", err) + } + + msg, err := client.ValidValidator(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_ValidValidator_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryValidValidatorRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["validator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "validator") + } + + protoReq.Validator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "validator", err) + } + + msg, err := server.ValidValidator(ctx, &protoReq) + return msg, metadata, err + +} + +var ( + filter_Query_Feeds_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Query_Feeds_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryFeedsRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Feeds_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.Feeds(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Feeds_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryFeedsRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Feeds_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.Feeds(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := server.Params(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_PriceService_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPriceServiceRequest + var metadata runtime.ServerMetadata + + msg, err := client.PriceService(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_PriceService_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryPriceServiceRequest + var metadata runtime.ServerMetadata + + msg, err := server.PriceService(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_DelegatorSignals_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryDelegatorSignalsRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["delegator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator") + } + + protoReq.Delegator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator", err) + } + + msg, err := client.DelegatorSignals(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_DelegatorSignals_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryDelegatorSignalsRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["delegator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator") + } + + protoReq.Delegator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator", err) + } + + msg, err := server.DelegatorSignals(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_SupportedFeeds_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QuerySupportedFeedsRequest + var metadata runtime.ServerMetadata + + msg, err := client.SupportedFeeds(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_SupportedFeeds_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QuerySupportedFeedsRequest + var metadata runtime.ServerMetadata + + msg, err := server.SupportedFeeds(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". +// UnaryRPC :call QueryServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { + + mux.Handle("GET", pattern_Query_Prices_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Prices_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Prices_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Price_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Price_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Price_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ValidatorPrices_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_ValidatorPrices_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ValidatorPrices_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ValidatorPrice_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_ValidatorPrice_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ValidatorPrice_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ValidValidator_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_ValidValidator_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ValidValidator_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Feeds_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Feeds_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Feeds_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_PriceService_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_PriceService_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_PriceService_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_DelegatorSignals_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_DelegatorSignals_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_DelegatorSignals_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_SupportedFeeds_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_SupportedFeeds_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_SupportedFeeds_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterQueryHandler(ctx, mux, conn) +} + +// RegisterQueryHandler registers the http handlers for service Query to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) +} + +// RegisterQueryHandlerClient registers the http handlers for service Query +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "QueryClient" to call the correct interceptors. +func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { + + mux.Handle("GET", pattern_Query_Prices_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Prices_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Prices_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Price_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Price_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Price_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ValidatorPrices_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_ValidatorPrices_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ValidatorPrices_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ValidatorPrice_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_ValidatorPrice_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ValidatorPrice_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ValidValidator_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_ValidValidator_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ValidValidator_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Feeds_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Feeds_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Feeds_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_PriceService_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_PriceService_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_PriceService_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_DelegatorSignals_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_DelegatorSignals_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_DelegatorSignals_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_SupportedFeeds_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_SupportedFeeds_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_SupportedFeeds_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_Prices_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"feeds", "v1beta1", "prices"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_Price_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"feeds", "v1beta1", "prices", "signal_id"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_ValidatorPrices_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4}, []string{"feeds", "v1beta1", "validators", "validator", "prices"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_ValidatorPrice_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"feeds", "v1beta1", "prices", "signal_id", "validators", "validator"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_ValidValidator_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"feeds", "v1beta1", "validators", "validator"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_Feeds_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"feeds", "v1beta1"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"feeds", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_PriceService_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"feeds", "v1beta1", "price-service"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_DelegatorSignals_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4}, []string{"feeds", "v1beta1", "delegators", "delegator", "signals"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_SupportedFeeds_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"feeds", "v1beta1", "supported-feeds"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_Prices_0 = runtime.ForwardResponseMessage + + forward_Query_Price_0 = runtime.ForwardResponseMessage + + forward_Query_ValidatorPrices_0 = runtime.ForwardResponseMessage + + forward_Query_ValidatorPrice_0 = runtime.ForwardResponseMessage + + forward_Query_ValidValidator_0 = runtime.ForwardResponseMessage + + forward_Query_Feeds_0 = runtime.ForwardResponseMessage + + forward_Query_Params_0 = runtime.ForwardResponseMessage + + forward_Query_PriceService_0 = runtime.ForwardResponseMessage + + forward_Query_DelegatorSignals_0 = runtime.ForwardResponseMessage + + forward_Query_SupportedFeeds_0 = runtime.ForwardResponseMessage +) diff --git a/x/feeds/types/tx.pb.go b/x/feeds/types/tx.pb.go new file mode 100644 index 000000000..a574d98a2 --- /dev/null +++ b/x/feeds/types/tx.pb.go @@ -0,0 +1,1815 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: feeds/v1beta1/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/types/msgservice" + _ "github.com/cosmos/cosmos-sdk/types/tx/amino" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// MsgSubmitSignals is the transaction message to submit signals +type MsgSubmitSignals struct { + // Delegator is the address of the delegator that want to submit signals + Delegator string `protobuf:"bytes,1,opt,name=delegator,proto3" json:"delegator,omitempty"` + // Signals is a list of submitted signal + Signals []Signal `protobuf:"bytes,2,rep,name=signals,proto3" json:"signals"` +} + +func (m *MsgSubmitSignals) Reset() { *m = MsgSubmitSignals{} } +func (m *MsgSubmitSignals) String() string { return proto.CompactTextString(m) } +func (*MsgSubmitSignals) ProtoMessage() {} +func (*MsgSubmitSignals) Descriptor() ([]byte, []int) { + return fileDescriptor_72c83eeeb8b31e80, []int{0} +} +func (m *MsgSubmitSignals) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSubmitSignals) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSubmitSignals.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgSubmitSignals) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSubmitSignals.Merge(m, src) +} +func (m *MsgSubmitSignals) XXX_Size() int { + return m.Size() +} +func (m *MsgSubmitSignals) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSubmitSignals.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSubmitSignals proto.InternalMessageInfo + +func (m *MsgSubmitSignals) GetDelegator() string { + if m != nil { + return m.Delegator + } + return "" +} + +func (m *MsgSubmitSignals) GetSignals() []Signal { + if m != nil { + return m.Signals + } + return nil +} + +// MsgSubmitPricesResponse is the response type for the Msg/SubmitSignals RPC method. +type MsgSubmitSignalsResponse struct { +} + +func (m *MsgSubmitSignalsResponse) Reset() { *m = MsgSubmitSignalsResponse{} } +func (m *MsgSubmitSignalsResponse) String() string { return proto.CompactTextString(m) } +func (*MsgSubmitSignalsResponse) ProtoMessage() {} +func (*MsgSubmitSignalsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_72c83eeeb8b31e80, []int{1} +} +func (m *MsgSubmitSignalsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSubmitSignalsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSubmitSignalsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgSubmitSignalsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSubmitSignalsResponse.Merge(m, src) +} +func (m *MsgSubmitSignalsResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgSubmitSignalsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSubmitSignalsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSubmitSignalsResponse proto.InternalMessageInfo + +// MsgSubmitPrices is the transaction message to submit multiple prices. +type MsgSubmitPrices struct { + // Validator is the address of the validator that is performing the operation. + Validator string `protobuf:"bytes,1,opt,name=validator,proto3" json:"validator,omitempty"` + // Timestamp is the timestamp use as reference of the data. + Timestamp int64 `protobuf:"varint,2,opt,name=timestamp,proto3" json:"timestamp,omitempty"` + // Prices is a list of prices to submit. + Prices []SubmitPrice `protobuf:"bytes,3,rep,name=prices,proto3" json:"prices"` +} + +func (m *MsgSubmitPrices) Reset() { *m = MsgSubmitPrices{} } +func (m *MsgSubmitPrices) String() string { return proto.CompactTextString(m) } +func (*MsgSubmitPrices) ProtoMessage() {} +func (*MsgSubmitPrices) Descriptor() ([]byte, []int) { + return fileDescriptor_72c83eeeb8b31e80, []int{2} +} +func (m *MsgSubmitPrices) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSubmitPrices) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSubmitPrices.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgSubmitPrices) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSubmitPrices.Merge(m, src) +} +func (m *MsgSubmitPrices) XXX_Size() int { + return m.Size() +} +func (m *MsgSubmitPrices) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSubmitPrices.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSubmitPrices proto.InternalMessageInfo + +func (m *MsgSubmitPrices) GetValidator() string { + if m != nil { + return m.Validator + } + return "" +} + +func (m *MsgSubmitPrices) GetTimestamp() int64 { + if m != nil { + return m.Timestamp + } + return 0 +} + +func (m *MsgSubmitPrices) GetPrices() []SubmitPrice { + if m != nil { + return m.Prices + } + return nil +} + +// MsgSubmitPricesResponse is the response type for the Msg/SubmitPrices RPC method. +type MsgSubmitPricesResponse struct { +} + +func (m *MsgSubmitPricesResponse) Reset() { *m = MsgSubmitPricesResponse{} } +func (m *MsgSubmitPricesResponse) String() string { return proto.CompactTextString(m) } +func (*MsgSubmitPricesResponse) ProtoMessage() {} +func (*MsgSubmitPricesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_72c83eeeb8b31e80, []int{3} +} +func (m *MsgSubmitPricesResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSubmitPricesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSubmitPricesResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgSubmitPricesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSubmitPricesResponse.Merge(m, src) +} +func (m *MsgSubmitPricesResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgSubmitPricesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSubmitPricesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSubmitPricesResponse proto.InternalMessageInfo + +// MsgUpdatePriceService is the transaction message to update price service's information. +type MsgUpdatePriceService struct { + // Admin is the address of the admin that is performing the operation. + Admin string `protobuf:"bytes,1,opt,name=admin,proto3" json:"admin,omitempty"` + // PriceService is the information of price service. + PriceService PriceService `protobuf:"bytes,2,opt,name=price_service,json=priceService,proto3" json:"price_service"` +} + +func (m *MsgUpdatePriceService) Reset() { *m = MsgUpdatePriceService{} } +func (m *MsgUpdatePriceService) String() string { return proto.CompactTextString(m) } +func (*MsgUpdatePriceService) ProtoMessage() {} +func (*MsgUpdatePriceService) Descriptor() ([]byte, []int) { + return fileDescriptor_72c83eeeb8b31e80, []int{4} +} +func (m *MsgUpdatePriceService) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdatePriceService) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdatePriceService.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgUpdatePriceService) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdatePriceService.Merge(m, src) +} +func (m *MsgUpdatePriceService) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdatePriceService) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdatePriceService.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdatePriceService proto.InternalMessageInfo + +func (m *MsgUpdatePriceService) GetAdmin() string { + if m != nil { + return m.Admin + } + return "" +} + +func (m *MsgUpdatePriceService) GetPriceService() PriceService { + if m != nil { + return m.PriceService + } + return PriceService{} +} + +// MsgUpdatePriceServiceResponse is the response type for the Msg/UpdatePriceService RPC method. +type MsgUpdatePriceServiceResponse struct { +} + +func (m *MsgUpdatePriceServiceResponse) Reset() { *m = MsgUpdatePriceServiceResponse{} } +func (m *MsgUpdatePriceServiceResponse) String() string { return proto.CompactTextString(m) } +func (*MsgUpdatePriceServiceResponse) ProtoMessage() {} +func (*MsgUpdatePriceServiceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_72c83eeeb8b31e80, []int{5} +} +func (m *MsgUpdatePriceServiceResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdatePriceServiceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdatePriceServiceResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgUpdatePriceServiceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdatePriceServiceResponse.Merge(m, src) +} +func (m *MsgUpdatePriceServiceResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdatePriceServiceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdatePriceServiceResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdatePriceServiceResponse proto.InternalMessageInfo + +// MsgUpdateParams is the transaction message to update parameters. +type MsgUpdateParams struct { + // Authority is the address of the governance account. + Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` + // Params is the x/feeds parameters to update. + Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` +} + +func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } +func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParams) ProtoMessage() {} +func (*MsgUpdateParams) Descriptor() ([]byte, []int) { + return fileDescriptor_72c83eeeb8b31e80, []int{6} +} +func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParams.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgUpdateParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParams.Merge(m, src) +} +func (m *MsgUpdateParams) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParams) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo + +func (m *MsgUpdateParams) GetAuthority() string { + if m != nil { + return m.Authority + } + return "" +} + +func (m *MsgUpdateParams) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +// MsgUpdateParamsResponse is the response type for the Msg/UpdateParams RPC method. +type MsgUpdateParamsResponse struct { +} + +func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } +func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParamsResponse) ProtoMessage() {} +func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_72c83eeeb8b31e80, []int{7} +} +func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParamsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) +} +func (m *MsgUpdateParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgSubmitSignals)(nil), "feeds.v1beta1.MsgSubmitSignals") + proto.RegisterType((*MsgSubmitSignalsResponse)(nil), "feeds.v1beta1.MsgSubmitSignalsResponse") + proto.RegisterType((*MsgSubmitPrices)(nil), "feeds.v1beta1.MsgSubmitPrices") + proto.RegisterType((*MsgSubmitPricesResponse)(nil), "feeds.v1beta1.MsgSubmitPricesResponse") + proto.RegisterType((*MsgUpdatePriceService)(nil), "feeds.v1beta1.MsgUpdatePriceService") + proto.RegisterType((*MsgUpdatePriceServiceResponse)(nil), "feeds.v1beta1.MsgUpdatePriceServiceResponse") + proto.RegisterType((*MsgUpdateParams)(nil), "feeds.v1beta1.MsgUpdateParams") + proto.RegisterType((*MsgUpdateParamsResponse)(nil), "feeds.v1beta1.MsgUpdateParamsResponse") +} + +func init() { proto.RegisterFile("feeds/v1beta1/tx.proto", fileDescriptor_72c83eeeb8b31e80) } + +var fileDescriptor_72c83eeeb8b31e80 = []byte{ + // 605 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xc1, 0x6f, 0x12, 0x4f, + 0x14, 0xc7, 0xd9, 0xf2, 0xfb, 0xd5, 0x30, 0x85, 0xa8, 0x93, 0x62, 0x97, 0x55, 0x17, 0x42, 0x8c, + 0x62, 0xa3, 0x3b, 0x81, 0x46, 0x63, 0x7a, 0x93, 0x83, 0xf1, 0x42, 0x62, 0x20, 0x36, 0xd1, 0x4b, + 0x33, 0xec, 0x8e, 0xcb, 0x24, 0xec, 0xce, 0x66, 0x67, 0x20, 0xed, 0xd5, 0xa3, 0x27, 0xff, 0x0c, + 0x0f, 0x1e, 0x7a, 0xf0, 0xe2, 0x7f, 0xd0, 0xc4, 0x4b, 0xe3, 0xc9, 0x93, 0x31, 0x70, 0xe8, 0xff, + 0xe0, 0xc9, 0x30, 0x33, 0x2c, 0xec, 0x96, 0x4a, 0xbd, 0x00, 0xf3, 0xbe, 0xdf, 0x79, 0xef, 0x7d, + 0xe6, 0x0d, 0x03, 0x6e, 0xbd, 0x23, 0xc4, 0xe3, 0x68, 0xdc, 0xec, 0x13, 0x81, 0x9b, 0x48, 0x1c, + 0x39, 0x51, 0xcc, 0x04, 0x83, 0x25, 0x19, 0x77, 0x74, 0xdc, 0xda, 0xf6, 0x99, 0xcf, 0xa4, 0x82, + 0x66, 0xbf, 0x94, 0xc9, 0xaa, 0xa4, 0x37, 0xab, 0x2d, 0x4a, 0xb2, 0xd2, 0x52, 0x84, 0x63, 0x1c, + 0xcc, 0xb5, 0x8a, 0xcb, 0x78, 0xc0, 0xf8, 0xa1, 0xca, 0xa7, 0x16, 0x5a, 0xda, 0x51, 0x2b, 0x14, + 0x70, 0x1f, 0x8d, 0x9b, 0xb3, 0x2f, 0x2d, 0xdc, 0xc4, 0x01, 0x0d, 0x19, 0x92, 0x9f, 0x2a, 0x54, + 0xff, 0x6c, 0x80, 0x1b, 0x1d, 0xee, 0xf7, 0x46, 0xfd, 0x80, 0x8a, 0x1e, 0xf5, 0x43, 0x3c, 0xe4, + 0xf0, 0x29, 0x28, 0x78, 0x64, 0x48, 0x7c, 0x2c, 0x58, 0x6c, 0x1a, 0x35, 0xa3, 0x51, 0x68, 0x9b, + 0xdf, 0xbf, 0x3c, 0xde, 0xd6, 0x55, 0x9e, 0x7b, 0x5e, 0x4c, 0x38, 0xef, 0x89, 0x98, 0x86, 0x7e, + 0x77, 0x61, 0x85, 0x4f, 0xc0, 0x35, 0xae, 0x52, 0x98, 0x1b, 0xb5, 0x7c, 0x63, 0xab, 0x55, 0x76, + 0x52, 0x27, 0xe0, 0xa8, 0x02, 0xed, 0xff, 0x4e, 0x7f, 0x56, 0x73, 0xdd, 0xb9, 0x77, 0xff, 0xe1, + 0xfb, 0xf3, 0x93, 0xdd, 0x45, 0x9a, 0x0f, 0xe7, 0x27, 0xbb, 0xfa, 0x44, 0xb3, 0x9d, 0xd5, 0x2d, + 0x60, 0x66, 0x63, 0x5d, 0xc2, 0x23, 0x16, 0x72, 0x52, 0xff, 0x66, 0x80, 0xeb, 0x89, 0xf8, 0x2a, + 0xa6, 0x2e, 0x91, 0x24, 0x63, 0x3c, 0xa4, 0xde, 0xd5, 0x48, 0x12, 0x2b, 0xbc, 0x03, 0x0a, 0x82, + 0x06, 0x84, 0x0b, 0x1c, 0x44, 0xe6, 0x46, 0xcd, 0x68, 0xe4, 0xbb, 0x8b, 0x00, 0x7c, 0x06, 0x36, + 0x23, 0x99, 0xdf, 0xcc, 0x4b, 0x4c, 0x2b, 0x8b, 0xb9, 0x68, 0x41, 0xb3, 0x6a, 0xff, 0x7e, 0x43, + 0xa2, 0x26, 0x75, 0x66, 0xa8, 0xe5, 0x0c, 0xaa, 0xea, 0xbc, 0x5e, 0x01, 0x3b, 0x99, 0x50, 0x02, + 0xfa, 0xd5, 0x00, 0xe5, 0x0e, 0xf7, 0x5f, 0x47, 0x1e, 0x16, 0x44, 0x6a, 0x3d, 0x12, 0x8f, 0xa9, + 0x4b, 0xa0, 0x03, 0xfe, 0xc7, 0x5e, 0x40, 0xc3, 0xb5, 0xa8, 0xca, 0x06, 0x5f, 0x80, 0x92, 0x6c, + 0xec, 0x90, 0xab, 0x04, 0x12, 0x75, 0xab, 0x75, 0x3b, 0xc3, 0xb3, 0x5c, 0x43, 0x03, 0x15, 0xa3, + 0xa5, 0x98, 0xc6, 0xc2, 0x23, 0x31, 0x60, 0x31, 0x15, 0xc7, 0x69, 0x2c, 0xdd, 0xa7, 0xbc, 0xbc, + 0xf5, 0x2a, 0xb8, 0xbb, 0xb2, 0xf5, 0x04, 0xee, 0x93, 0x9a, 0xe2, 0xf2, 0xa6, 0xd9, 0x14, 0x93, + 0xdc, 0xeb, 0xa7, 0x98, 0x58, 0xe1, 0x1e, 0xd8, 0x54, 0xff, 0x19, 0xcd, 0x95, 0xbd, 0x8e, 0x2a, + 0x7d, 0x32, 0x22, 0xb9, 0xfa, 0x07, 0x16, 0x35, 0xa2, 0xe5, 0xd0, 0x9c, 0xa2, 0xf5, 0x7b, 0x03, + 0xe4, 0x3b, 0xdc, 0x87, 0x07, 0xa0, 0x98, 0xba, 0x8f, 0x76, 0xa6, 0x83, 0xcc, 0x88, 0xad, 0xfb, + 0x7f, 0xd7, 0xe7, 0xf9, 0xe1, 0x00, 0xc0, 0x15, 0xe3, 0xbf, 0x77, 0x71, 0xf7, 0x45, 0x97, 0xf5, + 0xe8, 0x2a, 0xae, 0xa4, 0xd2, 0x01, 0x28, 0xa6, 0x66, 0x61, 0x5f, 0xba, 0x5b, 0xea, 0xab, 0x08, + 0x56, 0x9d, 0x10, 0x7c, 0x03, 0x4a, 0xe9, 0x47, 0xa7, 0x7a, 0x19, 0xba, 0x36, 0x58, 0x0f, 0xd6, + 0x18, 0xe6, 0xa9, 0xdb, 0x2f, 0x4f, 0x27, 0xb6, 0x71, 0x36, 0xb1, 0x8d, 0x5f, 0x13, 0xdb, 0xf8, + 0x38, 0xb5, 0x73, 0x67, 0x53, 0x3b, 0xf7, 0x63, 0x6a, 0xe7, 0xde, 0x3a, 0x3e, 0x15, 0x83, 0x51, + 0xdf, 0x71, 0x59, 0x80, 0xfa, 0x38, 0xf4, 0xe4, 0x1b, 0xe8, 0xb2, 0x21, 0x72, 0x07, 0x98, 0x86, + 0x68, 0xdc, 0x42, 0x47, 0xea, 0x01, 0x46, 0xe2, 0x38, 0x22, 0xbc, 0xbf, 0x29, 0x0d, 0x7b, 0x7f, + 0x02, 0x00, 0x00, 0xff, 0xff, 0x18, 0xfd, 0xef, 0x20, 0xe1, 0x05, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// MsgClient is the client API for Msg service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type MsgClient interface { + // SubmitPrices is a RPC method to submit prices + SubmitPrices(ctx context.Context, in *MsgSubmitPrices, opts ...grpc.CallOption) (*MsgSubmitPricesResponse, error) + // UpdatePriceService is a RPC method to update price service information + UpdatePriceService(ctx context.Context, in *MsgUpdatePriceService, opts ...grpc.CallOption) (*MsgUpdatePriceServiceResponse, error) + // UpdateParams is a RPC method to update parameters + UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) + // SubmitSignals is a RPC method to signal ids and their powers + SubmitSignals(ctx context.Context, in *MsgSubmitSignals, opts ...grpc.CallOption) (*MsgSubmitSignalsResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) SubmitPrices(ctx context.Context, in *MsgSubmitPrices, opts ...grpc.CallOption) (*MsgSubmitPricesResponse, error) { + out := new(MsgSubmitPricesResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Msg/SubmitPrices", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) UpdatePriceService(ctx context.Context, in *MsgUpdatePriceService, opts ...grpc.CallOption) (*MsgUpdatePriceServiceResponse, error) { + out := new(MsgUpdatePriceServiceResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Msg/UpdatePriceService", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { + out := new(MsgUpdateParamsResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Msg/UpdateParams", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) SubmitSignals(ctx context.Context, in *MsgSubmitSignals, opts ...grpc.CallOption) (*MsgSubmitSignalsResponse, error) { + out := new(MsgSubmitSignalsResponse) + err := c.cc.Invoke(ctx, "/feeds.v1beta1.Msg/SubmitSignals", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + // SubmitPrices is a RPC method to submit prices + SubmitPrices(context.Context, *MsgSubmitPrices) (*MsgSubmitPricesResponse, error) + // UpdatePriceService is a RPC method to update price service information + UpdatePriceService(context.Context, *MsgUpdatePriceService) (*MsgUpdatePriceServiceResponse, error) + // UpdateParams is a RPC method to update parameters + UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) + // SubmitSignals is a RPC method to signal ids and their powers + SubmitSignals(context.Context, *MsgSubmitSignals) (*MsgSubmitSignalsResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func (*UnimplementedMsgServer) SubmitPrices(ctx context.Context, req *MsgSubmitPrices) (*MsgSubmitPricesResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SubmitPrices not implemented") +} +func (*UnimplementedMsgServer) UpdatePriceService(ctx context.Context, req *MsgUpdatePriceService) (*MsgUpdatePriceServiceResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdatePriceService not implemented") +} +func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") +} +func (*UnimplementedMsgServer) SubmitSignals(ctx context.Context, req *MsgSubmitSignals) (*MsgSubmitSignalsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SubmitSignals not implemented") +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_SubmitPrices_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgSubmitPrices) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).SubmitPrices(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Msg/SubmitPrices", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).SubmitPrices(ctx, req.(*MsgSubmitPrices)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_UpdatePriceService_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUpdatePriceService) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).UpdatePriceService(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Msg/UpdatePriceService", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdatePriceService(ctx, req.(*MsgUpdatePriceService)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUpdateParams) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).UpdateParams(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Msg/UpdateParams", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_SubmitSignals_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgSubmitSignals) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).SubmitSignals(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/feeds.v1beta1.Msg/SubmitSignals", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).SubmitSignals(ctx, req.(*MsgSubmitSignals)) + } + return interceptor(ctx, in, info, handler) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "feeds.v1beta1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "SubmitPrices", + Handler: _Msg_SubmitPrices_Handler, + }, + { + MethodName: "UpdatePriceService", + Handler: _Msg_UpdatePriceService_Handler, + }, + { + MethodName: "UpdateParams", + Handler: _Msg_UpdateParams_Handler, + }, + { + MethodName: "SubmitSignals", + Handler: _Msg_SubmitSignals_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "feeds/v1beta1/tx.proto", +} + +func (m *MsgSubmitSignals) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgSubmitSignals) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSubmitSignals) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Signals) > 0 { + for iNdEx := len(m.Signals) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Signals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.Delegator) > 0 { + i -= len(m.Delegator) + copy(dAtA[i:], m.Delegator) + i = encodeVarintTx(dAtA, i, uint64(len(m.Delegator))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgSubmitSignalsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgSubmitSignalsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSubmitSignalsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgSubmitPrices) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgSubmitPrices) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSubmitPrices) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Prices) > 0 { + for iNdEx := len(m.Prices) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Prices[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if m.Timestamp != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.Timestamp)) + i-- + dAtA[i] = 0x10 + } + if len(m.Validator) > 0 { + i -= len(m.Validator) + copy(dAtA[i:], m.Validator) + i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgSubmitPricesResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgSubmitPricesResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSubmitPricesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgUpdatePriceService) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgUpdatePriceService) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdatePriceService) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.PriceService.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Admin) > 0 { + i -= len(m.Admin) + copy(dAtA[i:], m.Admin) + i = encodeVarintTx(dAtA, i, uint64(len(m.Admin))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUpdatePriceServiceResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgUpdatePriceServiceResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdatePriceServiceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgUpdateParams) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Authority) > 0 { + i -= len(m.Authority) + copy(dAtA[i:], m.Authority) + i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUpdateParamsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintTx(dAtA []byte, offset int, v uint64) int { + offset -= sovTx(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgSubmitSignals) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Delegator) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if len(m.Signals) > 0 { + for _, e := range m.Signals { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } + } + return n +} + +func (m *MsgSubmitSignalsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgSubmitPrices) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Validator) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.Timestamp != 0 { + n += 1 + sovTx(uint64(m.Timestamp)) + } + if len(m.Prices) > 0 { + for _, e := range m.Prices { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } + } + return n +} + +func (m *MsgSubmitPricesResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgUpdatePriceService) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Admin) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.PriceService.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgUpdatePriceServiceResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgUpdateParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Authority) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.Params.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgUpdateParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovTx(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTx(x uint64) (n int) { + return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *MsgSubmitSignals) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgSubmitSignals: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSubmitSignals: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Delegator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Delegator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Signals", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Signals = append(m.Signals, Signal{}) + if err := m.Signals[len(m.Signals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgSubmitSignalsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgSubmitSignalsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSubmitSignalsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgSubmitPrices) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgSubmitPrices: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSubmitPrices: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Validator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + m.Timestamp = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Timestamp |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Prices", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Prices = append(m.Prices, SubmitPrice{}) + if err := m.Prices[len(m.Prices)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgSubmitPricesResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgSubmitPricesResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSubmitPricesResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgUpdatePriceService) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgUpdatePriceService: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdatePriceService: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Admin = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PriceService", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PriceService.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgUpdatePriceServiceResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgUpdatePriceServiceResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdatePriceServiceResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgUpdateParams) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgUpdateParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Authority = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgUpdateParamsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgUpdateParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTx(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTx + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTx + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTx + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/feeds/types/utils.go b/x/feeds/types/utils.go new file mode 100644 index 000000000..f220bbf06 --- /dev/null +++ b/x/feeds/types/utils.go @@ -0,0 +1,10 @@ +package types + +// AbsInt64 returns an absolute of int64. +// Panics on min int64 (-9223372036854775808). +func AbsInt64(x int64) int64 { + if x < 0 { + return -1 * x + } + return x +} diff --git a/x/feeds/types/utils_test.go b/x/feeds/types/utils_test.go new file mode 100644 index 000000000..d4475fd54 --- /dev/null +++ b/x/feeds/types/utils_test.go @@ -0,0 +1,15 @@ +package types_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/bandprotocol/chain/v2/x/feeds/types" +) + +func TestAbsInt64(t *testing.T) { + require.Equal(t, int64(5), types.AbsInt64(-5)) + require.Equal(t, int64(5), types.AbsInt64(5)) + require.Equal(t, int64(0), types.AbsInt64(0)) +} diff --git a/x/feeds/types/validate.go b/x/feeds/types/validate.go new file mode 100644 index 000000000..0de7a69f9 --- /dev/null +++ b/x/feeds/types/validate.go @@ -0,0 +1,39 @@ +package types + +import ( + "fmt" + "net/url" +) + +// validateInt64 validates int64 and check its positivity. +func validateInt64(name string, positiveOnly bool, i interface{}) error { + v, ok := i.(int64) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + if v <= 0 && positiveOnly { + return fmt.Errorf("%s must be positive: %d", name, v) + } + return nil +} + +// validateURL validates URL format. +func validateURL(name string, u string) error { + _, err := url.ParseRequestURI(u) + if err != nil { + return fmt.Errorf("%s has invalid URL format", name) + } + return nil +} + +// validateString validates string. +func validateString(name string, allowEmpty bool, i interface{}) error { + s, ok := i.(string) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + if s == "" && !allowEmpty { + return fmt.Errorf("%s cannot be empty", name) + } + return nil +} diff --git a/x/globalfee/feechecker/feechecker.go b/x/globalfee/feechecker/feechecker.go index 76a554791..743151e7a 100644 --- a/x/globalfee/feechecker/feechecker.go +++ b/x/globalfee/feechecker/feechecker.go @@ -11,6 +11,8 @@ import ( bandtsskeeper "github.com/bandprotocol/chain/v2/x/bandtss/keeper" bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" + feedskeeper "github.com/bandprotocol/chain/v2/x/feeds/keeper" + feedstypes "github.com/bandprotocol/chain/v2/x/feeds/types" "github.com/bandprotocol/chain/v2/x/globalfee/keeper" oraclekeeper "github.com/bandprotocol/chain/v2/x/oracle/keeper" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" @@ -25,9 +27,11 @@ type FeeChecker struct { StakingKeeper *stakingkeeper.Keeper TSSKeeper *tsskeeper.Keeper BandtssKeeper *bandtsskeeper.Keeper + FeedsKeeper *feedskeeper.Keeper TSSMsgServer tsstypes.MsgServer BandtssMsgServer bandtsstypes.MsgServer + FeedsMsgServer feedstypes.MsgServer } func NewFeeChecker( @@ -37,9 +41,11 @@ func NewFeeChecker( stakingKeeper *stakingkeeper.Keeper, tssKeeper *tsskeeper.Keeper, bandtssKeeper *bandtsskeeper.Keeper, + feedsKeeper *feedskeeper.Keeper, ) FeeChecker { tssMsgServer := tsskeeper.NewMsgServerImpl(tssKeeper) bandtssMsgServer := bandtsskeeper.NewMsgServerImpl(bandtssKeeper) + feedsMsgServer := feedskeeper.NewMsgServerImpl(*feedsKeeper) return FeeChecker{ AuthzKeeper: authzKeeper, @@ -48,12 +54,15 @@ func NewFeeChecker( StakingKeeper: stakingKeeper, TSSKeeper: tssKeeper, BandtssKeeper: bandtssKeeper, + FeedsKeeper: feedsKeeper, TSSMsgServer: tssMsgServer, BandtssMsgServer: bandtssMsgServer, + FeedsMsgServer: feedsMsgServer, } } -func (fc FeeChecker) CheckTxFeeWithMinGasPrices( +// CheckTxFee is responsible for verifying whether a transaction contains the necessary fee. +func (fc FeeChecker) CheckTxFee( ctx sdk.Context, tx sdk.Tx, ) (sdk.Coins, int64, error) { @@ -64,51 +73,52 @@ func (fc FeeChecker) CheckTxFeeWithMinGasPrices( feeCoins := feeTx.GetFee() gas := feeTx.GetGas() + priority := getTxPriority(feeCoins, int64(gas), fc.GetBondDenom(ctx)) // Ensure that the provided fees meet minimum-gas-prices and globalFees, // if this is a CheckTx. This is only for local mempool purposes, and thus // is only ran on check tx. - if ctx.IsCheckTx() { - // Check if this tx should be free or not - isBypassMinFeeTx := fc.IsBypassMinFeeTx(ctx, tx) - if isBypassMinFeeTx { - return sdk.Coins{}, int64(math.MaxInt64), nil - } + if !ctx.IsCheckTx() { + return feeCoins, priority, nil + } - minGasPrices := getMinGasPrices(ctx) - globalMinGasPrices, err := fc.GetGlobalMinGasPrices(ctx) - if err != nil { - return nil, 0, err - } + // Check if this tx should be free or not + if fc.IsBypassMinFeeTx(ctx, tx) { + return sdk.Coins{}, int64(math.MaxInt64), nil + } + + minGasPrices := getMinGasPrices(ctx) + globalMinGasPrices, err := fc.GetGlobalMinGasPrices(ctx) + if err != nil { + return nil, 0, err + } + + allGasPrices := CombinedGasPricesRequirement(minGasPrices, globalMinGasPrices) - allGasPrices := CombinedGasPricesRequirement(minGasPrices, globalMinGasPrices) - - // Calculate all fees from all gas prices - gas := feeTx.GetGas() - var allFees sdk.Coins - if !allGasPrices.IsZero() { - glDec := sdk.NewDec(int64(gas)) - for _, gp := range allGasPrices { - if !gp.IsZero() { - fee := gp.Amount.Mul(glDec) - allFees = append(allFees, sdk.NewCoin(gp.Denom, fee.Ceil().RoundInt())) - } + // Calculate all fees from all gas prices + var allFees sdk.Coins + if !allGasPrices.IsZero() { + glDec := sdk.NewDec(int64(gas)) + for _, gp := range allGasPrices { + if !gp.IsZero() { + fee := gp.Amount.Mul(glDec) + allFees = append(allFees, sdk.NewCoin(gp.Denom, fee.Ceil().RoundInt())) } } + } - if !allFees.IsZero() && !feeCoins.IsAnyGTE(allFees) { - return nil, 0, sdkerrors.ErrInsufficientFee.Wrapf( - "insufficient fees; got: %s required: %s", - feeCoins, - allFees, - ) - } + if !allFees.IsZero() && !feeCoins.IsAnyGTE(allFees) { + return nil, 0, sdkerrors.ErrInsufficientFee.Wrapf( + "insufficient fees; got: %s required: %s", + feeCoins, + allFees, + ) } - priority := getTxPriority(feeCoins, int64(gas), fc.GetBondDenom(ctx)) return feeCoins, priority, nil } +// IsBypassMinFeeTx checks whether tx is min fee bypassable. func (fc FeeChecker) IsBypassMinFeeTx(ctx sdk.Context, tx sdk.Tx) bool { newCtx, _ := ctx.CacheContext() @@ -122,12 +132,17 @@ func (fc FeeChecker) IsBypassMinFeeTx(ctx sdk.Context, tx sdk.Tx) bool { return true } +// IsBypassMinFeeMsg checks whether msg is min fee bypassable. func (fc FeeChecker) IsBypassMinFeeMsg(ctx sdk.Context, msg sdk.Msg) bool { switch msg := msg.(type) { case *oracletypes.MsgReportData: if err := checkValidMsgReport(ctx, fc.OracleKeeper, msg); err != nil { return false } + case *feedstypes.MsgSubmitPrices: + if _, err := fc.FeedsMsgServer.SubmitPrices(ctx, msg); err != nil { + return false + } case *tsstypes.MsgSubmitDKGRound1: if _, err := fc.TSSMsgServer.SubmitDKGRound1(ctx, msg); err != nil { return false @@ -191,21 +206,22 @@ func (fc FeeChecker) IsBypassMinFeeMsg(ctx sdk.Context, msg sdk.Msg) bool { return true } +// GetGlobalMinGasPrices returns global min gas prices func (fc FeeChecker) GetGlobalMinGasPrices(ctx sdk.Context) (sdk.DecCoins, error) { - var ( - globalMinGasPrices sdk.DecCoins - err error - ) - - globalMinGasPrices = fc.GlobalfeeKeeper.GetParams(ctx).MinimumGasPrices + globalMinGasPrices := fc.GlobalfeeKeeper.GetParams(ctx).MinimumGasPrices + if len(globalMinGasPrices) != 0 { + return globalMinGasPrices.Sort(), nil + } // global fee is empty set, set global fee to 0uband (bondDenom) - if len(globalMinGasPrices) == 0 { - globalMinGasPrices, err = fc.DefaultZeroGlobalFee(ctx) + globalMinGasPrices, err := fc.DefaultZeroGlobalFee(ctx) + if err != nil { + return globalMinGasPrices, err } - return globalMinGasPrices.Sort(), err + return globalMinGasPrices.Sort(), nil } +// DefaultZeroGlobalFee returns a zero coin with the staking module bond denom func (fc FeeChecker) DefaultZeroGlobalFee(ctx sdk.Context) ([]sdk.DecCoin, error) { bondDenom := fc.GetBondDenom(ctx) if bondDenom == "" { @@ -215,6 +231,7 @@ func (fc FeeChecker) DefaultZeroGlobalFee(ctx sdk.Context) ([]sdk.DecCoin, error return []sdk.DecCoin{sdk.NewDecCoinFromDec(bondDenom, sdk.NewDec(0))}, nil } +// GetBondDenom returns Bondable coin denomination func (fc FeeChecker) GetBondDenom(ctx sdk.Context) string { return fc.StakingKeeper.BondDenom(ctx) } diff --git a/x/globalfee/feechecker/feechecker_test.go b/x/globalfee/feechecker/feechecker_test.go index 4e12d8e2f..2a21f16bc 100644 --- a/x/globalfee/feechecker/feechecker_test.go +++ b/x/globalfee/feechecker/feechecker_test.go @@ -12,6 +12,7 @@ import ( "github.com/bandprotocol/chain/v2/pkg/tss" bandtesting "github.com/bandprotocol/chain/v2/testing" + feedstypes "github.com/bandprotocol/chain/v2/x/feeds/types" "github.com/bandprotocol/chain/v2/x/globalfee/feechecker" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" @@ -72,16 +73,18 @@ func (suite *FeeCheckerTestSuite) SetupTest() { suite.Require().NoError(err) expiration := ctx.BlockTime().Add(1000 * time.Hour) - err = app.AuthzKeeper.SaveGrant( - ctx, - bandtesting.Alice.Address, - bandtesting.Validators[0].Address, - authz.NewGenericAuthorization( - sdk.MsgTypeURL(&tsstypes.MsgSubmitDEs{}), - ), - &expiration, - ) - suite.Require().NoError(err) + + msgTypeURLs := []sdk.Msg{&tsstypes.MsgSubmitDEs{}, &feedstypes.MsgSubmitPrices{}} + for _, msg := range msgTypeURLs { + err = app.AuthzKeeper.SaveGrant( + ctx, + bandtesting.Alice.Address, + bandtesting.Validators[0].Address, + authz.NewGenericAuthorization(sdk.MsgTypeURL(msg)), + &expiration, + ) + suite.Require().NoError(err) + } req := oracletypes.NewRequest( 1, @@ -95,7 +98,6 @@ func (suite *FeeCheckerTestSuite) SetupTest() { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ) @@ -108,6 +110,7 @@ func (suite *FeeCheckerTestSuite) SetupTest() { app.StakingKeeper, app.TSSKeeper, app.BandtssKeeper, + &app.FeedsKeeper, ) } @@ -121,8 +124,8 @@ func (suite *FeeCheckerTestSuite) TestValidRawReport() { isReportTx := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, msgs[0]) suite.Require().True(isReportTx) - // test - check tx fee with min gas prices - fee, priority, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + // test - check tx fee + fee, priority, err := suite.FeeChecker.CheckTxFee(suite.ctx, stubTx) suite.Require().NoError(err) suite.Require().Equal(sdk.Coins{}, fee) suite.Require().Equal(int64(math.MaxInt64), priority) @@ -136,8 +139,8 @@ func (suite *FeeCheckerTestSuite) TestNotValidRawReport() { isReportTx := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, msgs[0]) suite.Require().False(isReportTx) - // test - check tx fee with min gas prices - _, _, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + // test - check tx fee + _, _, err := suite.FeeChecker.CheckTxFee(suite.ctx, stubTx) suite.Require().Error(err) } @@ -152,8 +155,8 @@ func (suite *FeeCheckerTestSuite) TestValidReport() { isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, reportMsgs[0]) suite.Require().True(isBypassMinFeeMsg) - // test - check tx fee with min gas prices - fee, priority, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + // test - check tx fee + fee, priority, err := suite.FeeChecker.CheckTxFee(suite.ctx, stubTx) suite.Require().NoError(err) suite.Require().Equal(sdk.Coins{}, fee) suite.Require().Equal(int64(math.MaxInt64), priority) @@ -170,8 +173,8 @@ func (suite *FeeCheckerTestSuite) TestNoAuthzReport() { isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, &authzMsg) suite.Require().False(isBypassMinFeeMsg) - // test - check tx fee with min gas prices - _, _, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + // test - check tx fee + _, _, err := suite.FeeChecker.CheckTxFee(suite.ctx, stubTx) suite.Require().NoError(err) } @@ -190,8 +193,8 @@ func (suite *FeeCheckerTestSuite) TestNotValidReport() { isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, &authzMsg) suite.Require().False(isBypassMinFeeMsg) - // test - check tx fee with min gas prices - _, _, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + // test - check tx fee + _, _, err := suite.FeeChecker.CheckTxFee(suite.ctx, stubTx) suite.Require().Error(err) } @@ -207,7 +210,6 @@ func (suite *FeeCheckerTestSuite) TestNotReportMsg() { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) stubTx := &StubTx{ Msgs: []sdk.Msg{requestMsg}, @@ -226,19 +228,15 @@ func (suite *FeeCheckerTestSuite) TestNotReportMsg() { isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, requestMsg) suite.Require().False(isBypassMinFeeMsg) - // test - check tx fee with min gas prices - fee, priority, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + // test - check tx fee + fee, priority, err := suite.FeeChecker.CheckTxFee(suite.ctx, stubTx) suite.Require().NoError(err) suite.Require().Equal(stubTx.GetFee(), fee) suite.Require().Equal(int64(30), priority) } func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameAuthzMsgs() { - reportMsg := oracletypes.NewMsgReportData( - suite.requestID, - []oracletypes.RawReport{}, - bandtesting.Validators[0].ValAddress, - ) + reportMsg := oracletypes.NewMsgReportData(suite.requestID, []oracletypes.RawReport{}, bandtesting.Validators[0].ValAddress) requestMsg := oracletypes.NewMsgRequestData( 1, BasicCalldata, @@ -250,7 +248,6 @@ func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameAuthzMsg bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) msgs := []sdk.Msg{reportMsg, requestMsg} authzMsg := authz.NewMsgExec(bandtesting.Alice.Address, msgs) @@ -260,8 +257,8 @@ func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameAuthzMsg isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, &authzMsg) suite.Require().False(isBypassMinFeeMsg) - // test - check tx fee with min gas prices - fee, priority, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + // test - check tx fee + fee, priority, err := suite.FeeChecker.CheckTxFee(suite.ctx, stubTx) suite.Require().NoError(err) suite.Require().Equal(stubTx.GetFee(), fee) suite.Require().Equal(int64(10000), priority) @@ -284,7 +281,6 @@ func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameTx() { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) stubTx := &StubTx{ Msgs: []sdk.Msg{reportMsg, requestMsg}, @@ -295,14 +291,14 @@ func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameTx() { isBypassMinFeeMsg := suite.FeeChecker.IsBypassMinFeeMsg(suite.ctx, requestMsg) suite.Require().False(isBypassMinFeeMsg) - // test - check tx fee with min gas prices - fee, priority, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + // test - check tx fee + fee, priority, err := suite.FeeChecker.CheckTxFee(suite.ctx, stubTx) suite.Require().NoError(err) suite.Require().Equal(stubTx.GetFee(), fee) suite.Require().Equal(int64(10000), priority) } -func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPrices() { +func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFee() { testCases := []struct { name string stubTx func() *StubTx @@ -529,7 +525,6 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) return &StubTx{ @@ -575,7 +570,6 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) msgs := []sdk.Msg{msgReportData, msgRequestData} authzMsg := authz.NewMsgExec(bandtesting.Alice.Address, msgs) @@ -611,7 +605,6 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) return &StubTx{ @@ -626,6 +619,109 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri ), expPriority: 10000, }, + { + name: "valid MsgSubmitPrices", + stubTx: func() *StubTx { + return &StubTx{ + Msgs: []sdk.Msg{ + feedstypes.NewMsgSubmitPrices( + bandtesting.Validators[0].ValAddress.String(), + suite.ctx.BlockTime().Unix(), + []feedstypes.SubmitPrice{}, + ), + }, + } + }, + expIsBypassMinFeeTx: true, + expErr: nil, + expFee: sdk.Coins{}, + expPriority: math.MaxInt64, + }, + { + name: "valid MsgSubmitPrices in valid MsgExec", + stubTx: func() *StubTx { + msgExec := authz.NewMsgExec(bandtesting.Alice.Address, []sdk.Msg{ + feedstypes.NewMsgSubmitPrices( + bandtesting.Validators[0].ValAddress.String(), + suite.ctx.BlockTime().Unix(), + []feedstypes.SubmitPrice{}, + ), + }) + + return &StubTx{ + Msgs: []sdk.Msg{ + &msgExec, + }, + } + }, + expIsBypassMinFeeTx: true, + expErr: nil, + expFee: sdk.Coins{}, + expPriority: math.MaxInt64, + }, + { + name: "invalid MsgSubmitPrices with not enough fee", + stubTx: func() *StubTx { + return &StubTx{ + Msgs: []sdk.Msg{ + feedstypes.NewMsgSubmitPrices( + bandtesting.Alice.ValAddress.String(), + suite.ctx.BlockTime().Unix(), + []feedstypes.SubmitPrice{}, + ), + }, + } + }, + expIsBypassMinFeeTx: false, + expErr: sdkerrors.ErrInsufficientFee, + expFee: nil, + expPriority: 0, + }, + { + name: "invalid MsgSubmitPrices in valid MsgExec with not enough fee", + stubTx: func() *StubTx { + msgExec := authz.NewMsgExec(bandtesting.Alice.Address, []sdk.Msg{ + feedstypes.NewMsgSubmitPrices( + bandtesting.Alice.ValAddress.String(), + suite.ctx.BlockTime().Unix(), + []feedstypes.SubmitPrice{}, + ), + }) + + return &StubTx{ + Msgs: []sdk.Msg{ + &msgExec, + }, + } + }, + expIsBypassMinFeeTx: false, + expErr: sdkerrors.ErrInsufficientFee, + expFee: nil, + expPriority: 0, + }, + { + name: "valid MsgSubmitPrices in invalid MsgExec with enough fee", + stubTx: func() *StubTx { + msgExec := authz.NewMsgExec(bandtesting.Bob.Address, []sdk.Msg{ + feedstypes.NewMsgSubmitPrices( + bandtesting.Validators[0].ValAddress.String(), + suite.ctx.BlockTime().Unix(), + []feedstypes.SubmitPrice{}, + ), + }) + + return &StubTx{ + Msgs: []sdk.Msg{ + &msgExec, + }, + GasPrices: sdk.NewDecCoins(sdk.NewDecCoin("uband", sdk.NewInt(1))), + } + }, + expIsBypassMinFeeTx: false, + expErr: nil, + expFee: sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(1000000))), + expPriority: 10000, + }, } for _, tc := range testCases { @@ -636,8 +732,8 @@ func (suite *FeeCheckerTestSuite) TestIsBypassMinFeeTxAndCheckTxFeeWithMinGasPri isByPassMinFeeTx := suite.FeeChecker.IsBypassMinFeeTx(suite.ctx, stubTx) suite.Require().Equal(tc.expIsBypassMinFeeTx, isByPassMinFeeTx) - // test - CheckTxFeeWithMinGasPrices - fee, priority, err := suite.FeeChecker.CheckTxFeeWithMinGasPrices(suite.ctx, stubTx) + // test - CheckTxFee + fee, priority, err := suite.FeeChecker.CheckTxFee(suite.ctx, stubTx) suite.Require().ErrorIs(err, tc.expErr) suite.Require().Equal(fee, tc.expFee) suite.Require().Equal(tc.expPriority, priority) diff --git a/x/globalfee/keeper/grpc_query_test.go b/x/globalfee/keeper/grpc_query_test.go index e482070eb..27ed7711c 100644 --- a/x/globalfee/keeper/grpc_query_test.go +++ b/x/globalfee/keeper/grpc_query_test.go @@ -30,22 +30,20 @@ func TestQueryParams(t *testing.T) { }, "multiple coins": { setupStore: func(ctx sdk.Context, k keeper.Keeper) { - if err := k.SetParams(ctx, types.Params{ + err := k.SetParams(ctx, types.Params{ MinimumGasPrices: sdk.NewDecCoins( sdk.NewDecCoin("ALX", sdk.OneInt()), sdk.NewDecCoin("BLX", sdk.NewInt(2)), ), - }); err != nil { - t.Error(err) - } + }) + require.NoError(t, err) }, expMin: sdk.NewDecCoins(sdk.NewDecCoin("ALX", sdk.OneInt()), sdk.NewDecCoin("BLX", sdk.NewInt(2))), }, "no min gas price set": { setupStore: func(ctx sdk.Context, k keeper.Keeper) { - if err := k.SetParams(ctx, types.Params{}); err != nil { - t.Error(err) - } + err := k.SetParams(ctx, types.Params{}) + require.NoError(t, err) }, }, "no param set": { diff --git a/x/oracle/app_test.go b/x/oracle/app_test.go index 70461272f..26db00843 100644 --- a/x/oracle/app_test.go +++ b/x/oracle/app_test.go @@ -31,7 +31,6 @@ func TestSuccessRequestOracleData(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Validators[0].Address, 0, - 0, ) res, err := handler(ctx, requestMsg) require.NotNil(t, res) @@ -57,7 +56,6 @@ func TestSuccessRequestOracleData(t *testing.T) { nil, bandtesting.TestDefaultExecuteGas, 0, - 0, bandtesting.Validators[0].Address.String(), nil, ) @@ -153,7 +151,6 @@ func TestExpiredRequestOracleData(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Validators[0].Address, 0, - 0, ) res, err := handler(ctx, requestMsg) require.NotNil(t, res) @@ -179,7 +176,6 @@ func TestExpiredRequestOracleData(t *testing.T) { nil, bandtesting.TestDefaultExecuteGas, 0, - 0, bandtesting.Validators[0].Address.String(), nil, ) diff --git a/x/oracle/client/cli/tx.go b/x/oracle/client/cli/tx.go index 09d5fe40e..0baed908d 100644 --- a/x/oracle/client/cli/tx.go +++ b/x/oracle/client/cli/tx.go @@ -15,7 +15,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/authz" "github.com/spf13/cobra" - "github.com/bandprotocol/chain/v2/pkg/tss" bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -31,7 +30,6 @@ const ( flagSourceCodeURL = "url" flagPrepareGas = "prepare-gas" flagExecuteGas = "execute-gas" - flagTSSGroupID = "tss-group-id" flagTSSEncodeType = "tss-encode-type" flagFeeLimit = "fee-limit" flagFee = "fee" @@ -129,11 +127,6 @@ $ %s tx oracle request 1 4 3 --calldata 1234abcdef --client-id cliend-id --fee-l return err } - tssGroupID, err := cmd.Flags().GetUint64(flagTSSGroupID) - if err != nil { - return err - } - tssEncodeType, err := cmd.Flags().GetInt32(flagTSSEncodeType) if err != nil { return err @@ -149,7 +142,6 @@ $ %s tx oracle request 1 4 3 --calldata 1234abcdef --client-id cliend-id --fee-l prepareGas, executeGas, clientCtx.GetFromAddress(), - tss.GroupID(tssGroupID), types.EncodeType(tssEncodeType), ) @@ -167,7 +159,6 @@ $ %s tx oracle request 1 4 3 --calldata 1234abcdef --client-id cliend-id --fee-l cmd.Flags().Uint64(flagExecuteGas, 300000, "Execute gas used in fee counting for execute request") cmd.Flags(). String(flagFeeLimit, "", "The maximum tokens paid to all data source and TSS signature providers, if any") - cmd.Flags().Uint64(flagTSSGroupID, 0, "The TSS group that is requested to sign the oracle result data") cmd.Flags(). Int32(flagTSSEncodeType, 0, "The encode type of oracle result that will be sent to TSS (1=proto, 2=ABI, 3=Partial ABI)") @@ -699,12 +690,12 @@ $ %s tx oracle remove-reporters band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun band func GetCmdRequestSignature() *cobra.Command { return &cobra.Command{ Use: "oracle-result [request-id] [encode-type]", - Short: "Request TSS signature from request id", + Short: "Request bandtss signature from oracle request id", Args: cobra.ExactArgs(2), Long: strings.TrimSpace( fmt.Sprintf(`Request signature from request id. Example: -$ %s tx tss request-signature oracle-result 1 --fee-limit 10uband +$ %s tx bandtss request-signature oracle-result 1 --fee-limit 10uband `, version.AppName, ), @@ -724,6 +715,9 @@ $ %s tx tss request-signature oracle-result 1 --fee-limit 10uband if err != nil { return err } + if encodeType == int64(types.ENCODE_TYPE_UNSPECIFIED) { + return types.ErrInvalidOracleEncodeType + } coinStr, err := cmd.Flags().GetString(flagFeeLimit) if err != nil { diff --git a/x/oracle/client/signature_order_handler.go b/x/oracle/client/signature_order_handler.go index 571921fdf..11a839219 100644 --- a/x/oracle/client/signature_order_handler.go +++ b/x/oracle/client/signature_order_handler.go @@ -1,9 +1,9 @@ package client import ( + bandtssclient "github.com/bandprotocol/chain/v2/x/bandtss/client" "github.com/bandprotocol/chain/v2/x/oracle/client/cli" - tssclient "github.com/bandprotocol/chain/v2/x/tss/client" ) -// OracleSignatureOrderHandler is the request signature handler. -var OracleSignatureOrderHandler = tssclient.NewSignatureOrderHandler(cli.GetCmdRequestSignature) +// OracleRequestSignatureHandler is the request signature handler. +var OracleRequestSignatureHandler = bandtssclient.NewRequestSignatureHandler(cli.GetCmdRequestSignature) diff --git a/x/oracle/handler_test.go b/x/oracle/handler_test.go index 0f80972c1..94776dbde 100644 --- a/x/oracle/handler_test.go +++ b/x/oracle/handler_test.go @@ -454,7 +454,6 @@ func TestRequestDataSuccess(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) @@ -474,7 +473,6 @@ func TestRequestDataSuccess(t *testing.T) { nil, bandtesting.TestDefaultExecuteGas, 0, - 0, bandtesting.FeePayer.Address.String(), sdk.NewCoins(sdk.NewInt64Coin("uband", 94000000)), ), k.MustGetRequest(ctx, 1)) @@ -528,7 +526,6 @@ func TestRequestDataSuccess(t *testing.T) { {Key: types.AttributeKeyCalldata, Value: "62656562"}, // "beeb" in hex {Key: types.AttributeKeyAskCount, Value: "2"}, {Key: types.AttributeKeyMinCount, Value: "2"}, - {Key: types.AttributeKeyTSSGroupID, Value: "0"}, {Key: types.AttributeKeyGasUsed, Value: "5294700000"}, {Key: types.AttributeKeyTotalFees, Value: "6000000uband"}, {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[2].ValAddress.String()}, @@ -591,7 +588,6 @@ func TestRequestDataFail(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ), ) bandtesting.CheckErrorf(t, err, types.ErrInsufficientValidators, "0 < 2") @@ -616,7 +612,6 @@ func TestRequestDataFail(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ), ) bandtesting.CheckErrorf(t, err, types.ErrTooLargeCalldata, "got: 8000, max: 512") @@ -637,7 +632,6 @@ func TestRequestDataFail(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ), ) bandtesting.CheckErrorf(t, err, types.ErrInsufficientValidators, "2 < 3") @@ -658,7 +652,6 @@ func TestRequestDataFail(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ), ) bandtesting.CheckErrorf(t, err, types.ErrOracleScriptNotFound, "id: 999") @@ -679,7 +672,6 @@ func TestRequestDataFail(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ), ) bandtesting.CheckErrorf(t, err, types.ErrNotEnoughFee, "require: 2000000uband, max: 0uband") @@ -710,7 +702,6 @@ func TestReportSuccess(t *testing.T) { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) @@ -750,7 +741,6 @@ func TestReportSuccess(t *testing.T) { []byte("RESOLVE_RESULT!"), 1234, 0, - 0, ) res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, bandtesting.Validators[2].ValAddress)) require.NoError(t, err) @@ -793,7 +783,6 @@ func TestReportFail(t *testing.T) { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) diff --git a/x/oracle/ibc_test.go b/x/oracle/ibc_test.go index 0a89b3d4c..2fa28daba 100644 --- a/x/oracle/ibc_test.go +++ b/x/oracle/ibc_test.go @@ -781,7 +781,6 @@ func (suite *OracleTestSuite) TestIBCResolveRequestNoReturnData() { &types.IBCChannel{PortId: path.EndpointB.ChannelConfig.PortID, ChannelId: path.EndpointB.ChannelID}, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) @@ -840,7 +839,6 @@ func (suite *OracleTestSuite) TestIBCResolveRequestWasmFailure() { &types.IBCChannel{PortId: path.EndpointB.ChannelConfig.PortID, ChannelId: path.EndpointB.ChannelID}, bandtesting.TestDefaultExecuteGas, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) @@ -899,7 +897,6 @@ func (suite *OracleTestSuite) TestIBCResolveRequestCallReturnDataSeveralTimes() &types.IBCChannel{PortId: path.EndpointB.ChannelConfig.PortID, ChannelId: path.EndpointB.ChannelID}, bandtesting.TestDefaultExecuteGas, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) diff --git a/x/oracle/keeper/grpc_query.go b/x/oracle/keeper/grpc_query.go index d5cf80728..940fb9d47 100644 --- a/x/oracle/keeper/grpc_query.go +++ b/x/oracle/keeper/grpc_query.go @@ -218,9 +218,6 @@ func (k Querier) Validator( return nil, err } status := k.GetValidatorStatus(ctx, val) - if err != nil { - return nil, err - } return &types.QueryValidatorResponse{Status: &status}, nil } diff --git a/x/oracle/keeper/grpc_query_test.go b/x/oracle/keeper/grpc_query_test.go index adc3c7dc2..80afba6f3 100644 --- a/x/oracle/keeper/grpc_query_test.go +++ b/x/oracle/keeper/grpc_query_test.go @@ -57,7 +57,6 @@ func (suite *RequestVerificationTestSuite) SetupTest() { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ) @@ -605,7 +604,6 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ) @@ -625,7 +623,6 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ) @@ -648,7 +645,6 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ) @@ -671,7 +667,6 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ) diff --git a/x/oracle/keeper/owasm.go b/x/oracle/keeper/owasm.go index 6ca521dc0..3fd6bc555 100644 --- a/x/oracle/keeper/owasm.go +++ b/x/oracle/keeper/owasm.go @@ -105,7 +105,6 @@ func (k Keeper) PrepareRequest( nil, ibcChannel, r.GetExecuteGas(), - r.GetTSSGroupID(), r.GetTSSEncodeType(), feePayer.String(), r.GetFeeLimit(), @@ -156,7 +155,6 @@ func (k Keeper) PrepareRequest( sdk.NewAttribute(types.AttributeKeyCalldata, hex.EncodeToString(req.Calldata)), sdk.NewAttribute(types.AttributeKeyAskCount, fmt.Sprintf("%d", askCount)), sdk.NewAttribute(types.AttributeKeyMinCount, fmt.Sprintf("%d", req.MinCount)), - sdk.NewAttribute(types.AttributeKeyTSSGroupID, fmt.Sprintf("%d", req.TSSGroupID)), sdk.NewAttribute(types.AttributeKeyGasUsed, fmt.Sprintf("%d", output.GasUsed)), sdk.NewAttribute(types.AttributeKeyTotalFees, totalFees.String()), ) @@ -201,7 +199,7 @@ func (k Keeper) ResolveRequest(ctx sdk.Context, reqID types.RequestID) { } else if env.Retdata == nil { k.ResolveFailure(ctx, reqID, "no return data") } else { - k.ResolveSuccess(ctx, reqID, req.Requester, req.FeeLimit, env.Retdata, output.GasUsed, req.TSSGroupID, req.TSSEncodeType) + k.ResolveSuccess(ctx, reqID, req.Requester, req.FeeLimit, env.Retdata, output.GasUsed, req.TSSEncodeType) } } diff --git a/x/oracle/keeper/owasm_test.go b/x/oracle/keeper/owasm_test.go index d1a914920..68d37a1b2 100644 --- a/x/oracle/keeper/owasm_test.go +++ b/x/oracle/keeper/owasm_test.go @@ -155,7 +155,6 @@ func TestPrepareRequestSuccessBasic(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) @@ -166,7 +165,7 @@ func TestPrepareRequestSuccessBasic(t *testing.T) { types.NewRawRequest(1, 1, []byte("beeb")), types.NewRawRequest(2, 2, []byte("beeb")), types.NewRawRequest(3, 3, []byte("beeb")), - }, nil, bandtesting.TestDefaultExecuteGas, 0, 0, + }, nil, bandtesting.TestDefaultExecuteGas, 0, bandtesting.FeePayer.Address.String(), sdk.NewCoins(sdk.NewInt64Coin("uband", 97000000)), ), k.MustGetRequest(ctx, 1)) @@ -227,7 +226,6 @@ func TestPrepareRequestSuccessBasic(t *testing.T) { sdk.NewAttribute(types.AttributeKeyCalldata, hex.EncodeToString(BasicCalldata)), sdk.NewAttribute(types.AttributeKeyAskCount, "1"), sdk.NewAttribute(types.AttributeKeyMinCount, "1"), - sdk.NewAttribute(types.AttributeKeyTSSGroupID, "0"), sdk.NewAttribute(types.AttributeKeyGasUsed, "5294700000"), sdk.NewAttribute(types.AttributeKeyTotalFees, "3000000uband"), sdk.NewAttribute(types.AttributeKeyValidator, bandtesting.Validators[0].ValAddress.String()), @@ -284,7 +282,6 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 1000000uband, max: 0uband: not enough fee") @@ -299,7 +296,6 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 2000000uband, max: 1000000uband: not enough fee") @@ -314,7 +310,6 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 3000000uband, max: 2000000uband: not enough fee") @@ -329,7 +324,6 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 3000000uband, max: 2999999uband: not enough fee") @@ -344,7 +338,6 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.FeePayer.Address, 0, - 0, ) id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.NoError(t, err) @@ -368,7 +361,6 @@ func TestPrepareRequestNotEnoughFund(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) _, err := k.PrepareRequest(ctx, m, bandtesting.Alice.Address, nil) require.EqualError(t, err, "spendable balance is smaller than 1000000uband: insufficient funds") @@ -389,7 +381,6 @@ func TestPrepareRequestInvalidCalldataSize(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "got: 2000, max: 512: too large calldata") @@ -415,7 +406,6 @@ func TestPrepareRequestNotEnoughPrepareGas(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrBadWasmExecution) @@ -450,7 +440,6 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrInvalidAskCount) @@ -470,7 +459,6 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrInsufficientValidators) @@ -490,7 +478,6 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) @@ -520,7 +507,6 @@ func TestPrepareRequestBaseOwasmFeePanic(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) ctx = ctx.WithGasMeter(sdk.NewGasMeter(90000)) require.PanicsWithValue( @@ -554,7 +540,6 @@ func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) ctx = ctx.WithGasMeter(sdk.NewGasMeter(90000)) require.PanicsWithValue( @@ -573,7 +558,6 @@ func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) ctx = ctx.WithGasMeter(sdk.NewGasMeter(1000000)) id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) @@ -596,7 +580,6 @@ func TestPrepareRequestEmptyCalldata(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "runtime error while executing the Wasm script: bad wasm execution") @@ -617,7 +600,6 @@ func TestPrepareRequestOracleScriptNotFound(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "id: 999: oracle script not found") @@ -638,7 +620,6 @@ func TestPrepareRequestBadWasmExecutionFail(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "OEI action to invoke is not available: bad wasm execution") @@ -659,7 +640,6 @@ func TestPrepareRequestWithEmptyRawRequest(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "empty raw requests") @@ -672,7 +652,7 @@ func TestPrepareRequestUnknownDataSource(t *testing.T) { m := types.NewMsgRequestData(4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2, 99}, Calldata: "beeb", - }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, 0) + }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0) _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "id: 99: data source not found") } @@ -688,13 +668,13 @@ func TestPrepareRequestInvalidDataSourceCount(t *testing.T) { m := types.NewMsgRequestData(4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2, 3, 4}, Calldata: "beeb", - }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, 0) + }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0) _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrBadWasmExecution) m = types.NewMsgRequestData(4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2, 3}, Calldata: "beeb", - }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, 0) + }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0) id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) @@ -715,7 +695,6 @@ func TestPrepareRequestTooMuchWasmGas(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) @@ -731,7 +710,6 @@ func TestPrepareRequestTooMuchWasmGas(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "out-of-gas while executing the wasm script: bad wasm execution") @@ -752,7 +730,6 @@ func TestPrepareRequestTooLargeCalldata(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) @@ -768,7 +745,6 @@ func TestPrepareRequestTooLargeCalldata(t *testing.T) { bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address, 0, - 0, ) _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "span to write is too small: bad wasm execution") @@ -790,7 +766,7 @@ func TestResolveRequestSuccess(t *testing.T) { BasicClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, bandtesting.TestDefaultExecuteGas, 0, 0, + }, nil, bandtesting.TestDefaultExecuteGas, 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) @@ -807,16 +783,14 @@ func TestResolveRequestSuccess(t *testing.T) { ) require.Equal(t, expectResult, k.MustGetResult(ctx, 42)) - require.Equal( - t, - sdk.Events{ - sdk.NewEvent(types.EventTypeResolve, - sdk.NewAttribute(types.AttributeKeyID, "42"), - sdk.NewAttribute(types.AttributeKeyResolveStatus, "1"), - sdk.NewAttribute(types.AttributeKeyResult, "62656562"), // hex of "beeb" - sdk.NewAttribute(types.AttributeKeyGasUsed, "2485000000"), - ), - }, + require.Equal(t, sdk.Events{ + sdk.NewEvent(types.EventTypeResolve, + sdk.NewAttribute(types.AttributeKeyID, "42"), + sdk.NewAttribute(types.AttributeKeyResolveStatus, "1"), + sdk.NewAttribute(types.AttributeKeyResult, "62656562"), // hex of "beeb" + sdk.NewAttribute(types.AttributeKeyGasUsed, "2485000000"), + ), + }, ctx.EventManager().Events(), ) } @@ -835,7 +809,7 @@ func TestResolveRequestSuccessComplex(t *testing.T) { 42, bandtesting.ParseTime(1581589790), BasicClientID, []types.RawRequest{ types.NewRawRequest(0, 1, BasicCalldata), types.NewRawRequest(1, 2, BasicCalldata), - }, nil, bandtesting.TestDefaultExecuteGas, 0, 0, + }, nil, bandtesting.TestDefaultExecuteGas, 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) @@ -862,18 +836,16 @@ func TestResolveRequestSuccessComplex(t *testing.T) { obi.MustEncode(testdata.Wasm4Output{Ret: "beebd1v1beebd1v2beebd2v1beebd2v2"}), ) require.Equal(t, result, k.MustGetResult(ctx, 42)) - require.Equal(t, sdk.Events{ - sdk.NewEvent( - types.EventTypeResolve, - sdk.NewAttribute(types.AttributeKeyID, "42"), - sdk.NewAttribute(types.AttributeKeyResolveStatus, "1"), - sdk.NewAttribute( - types.AttributeKeyResult, - "000000206265656264317631626565626431763262656562643276316265656264327632", - ), - sdk.NewAttribute(types.AttributeKeyGasUsed, "32492250000"), + require.Equal(t, sdk.Events{sdk.NewEvent( + types.EventTypeResolve, + sdk.NewAttribute(types.AttributeKeyID, "42"), + sdk.NewAttribute(types.AttributeKeyResolveStatus, "1"), + sdk.NewAttribute( + types.AttributeKeyResult, + "000000206265656264317631626565626431763262656562643276316265656264327632", ), - }, ctx.EventManager().Events()) + sdk.NewAttribute(types.AttributeKeyGasUsed, "32492250000"), + )}, ctx.EventManager().Events()) } func TestResolveRequestOutOfGas(t *testing.T) { @@ -892,7 +864,7 @@ func TestResolveRequestOutOfGas(t *testing.T) { BasicClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, 0, 0, 0, + }, nil, 0, 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) @@ -924,7 +896,7 @@ func TestResolveReadNilExternalData(t *testing.T) { 42, bandtesting.ParseTime(1581589790), BasicClientID, []types.RawRequest{ types.NewRawRequest(0, 1, BasicCalldata), types.NewRawRequest(1, 2, BasicCalldata), - }, nil, bandtesting.TestDefaultExecuteGas, 0, 0, + }, nil, bandtesting.TestDefaultExecuteGas, 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) @@ -951,14 +923,12 @@ func TestResolveReadNilExternalData(t *testing.T) { obi.MustEncode(testdata.Wasm4Output{Ret: "beebd1v2beebd2v1"}), ) require.Equal(t, result, k.MustGetResult(ctx, 42)) - require.Equal(t, sdk.Events{ - sdk.NewEvent(types.EventTypeResolve, - sdk.NewAttribute(types.AttributeKeyID, "42"), - sdk.NewAttribute(types.AttributeKeyResolveStatus, "1"), - sdk.NewAttribute(types.AttributeKeyResult, "0000001062656562643176326265656264327631"), - sdk.NewAttribute(types.AttributeKeyGasUsed, "31168050000"), - ), - }, ctx.EventManager().Events()) + require.Equal(t, sdk.Events{sdk.NewEvent(types.EventTypeResolve, + sdk.NewAttribute(types.AttributeKeyID, "42"), + sdk.NewAttribute(types.AttributeKeyResolveStatus, "1"), + sdk.NewAttribute(types.AttributeKeyResult, "0000001062656562643176326265656264327631"), + sdk.NewAttribute(types.AttributeKeyGasUsed, "31168050000"), + )}, ctx.EventManager().Events()) } func TestResolveRequestNoReturnData(t *testing.T) { @@ -977,7 +947,7 @@ func TestResolveRequestNoReturnData(t *testing.T) { BasicClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, 1, 0, 0, + }, nil, 1, 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) @@ -1016,7 +986,7 @@ func TestResolveRequestWasmFailure(t *testing.T) { BasicClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, 0, 0, 0, + }, nil, 0, 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) @@ -1055,7 +1025,7 @@ func TestResolveRequestCallReturnDataSeveralTimes(t *testing.T) { BasicClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, bandtesting.TestDefaultExecuteGas, 0, 0, + }, nil, bandtesting.TestDefaultExecuteGas, 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, )) diff --git a/x/oracle/keeper/report_test.go b/x/oracle/keeper/report_test.go index 60c71b0a4..4c7aff677 100644 --- a/x/oracle/keeper/report_test.go +++ b/x/oracle/keeper/report_test.go @@ -18,7 +18,7 @@ func defaultRequest() types.Request { BasicClientID, []types.RawRequest{ types.NewRawRequest(42, 1, BasicCalldata), types.NewRawRequest(43, 2, BasicCalldata), - }, nil, 0, 0, 0, + }, nil, 0, 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ) diff --git a/x/oracle/keeper/request_test.go b/x/oracle/keeper/request_test.go index 902ea6a7f..0c79c8784 100644 --- a/x/oracle/keeper/request_test.go +++ b/x/oracle/keeper/request_test.go @@ -55,7 +55,6 @@ func TestHasRequest(t *testing.T) { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ), @@ -83,7 +82,6 @@ func TestDeleteRequest(t *testing.T) { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ), @@ -118,7 +116,6 @@ func TestSetterGetterRequest(t *testing.T) { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ) @@ -134,7 +131,6 @@ func TestSetterGetterRequest(t *testing.T) { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ) @@ -196,7 +192,6 @@ func TestAddDataSourceBasic(t *testing.T) { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ), @@ -217,7 +212,6 @@ func TestAddDataSourceBasic(t *testing.T) { nil, 0, 0, - 0, bandtesting.FeePayer.Address.String(), bandtesting.Coins100000000uband, ), @@ -283,9 +277,9 @@ func TestProcessExpiredRequests(t *testing.T) { require.NoError(t, err) // Request 1, 2 and 4 gets resolved. Request 3 does not. - k.ResolveSuccess(ctx, 1, defaultRequest().Requester, defaultRequest().FeeLimit, BasicResult, 1234, 0, 0) + k.ResolveSuccess(ctx, 1, defaultRequest().Requester, defaultRequest().FeeLimit, BasicResult, 1234, 0) k.ResolveFailure(ctx, 2, "ARBITRARY_REASON") - k.ResolveSuccess(ctx, 4, defaultRequest().Requester, defaultRequest().FeeLimit, BasicResult, 1234, 0, 0) + k.ResolveSuccess(ctx, 4, defaultRequest().Requester, defaultRequest().FeeLimit, BasicResult, 1234, 0) // Initially, last expired request ID should be 0. require.Equal(t, types.RequestID(0), k.GetRequestLastExpired(ctx)) diff --git a/x/oracle/keeper/result.go b/x/oracle/keeper/result.go index 7b94a31c2..af9e05123 100644 --- a/x/oracle/keeper/result.go +++ b/x/oracle/keeper/result.go @@ -5,13 +5,12 @@ import ( "fmt" "time" - "cosmossdk.io/errors" + errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" host "github.com/cosmos/ibc-go/v7/modules/core/24-host" ctxcache "github.com/bandprotocol/chain/v2/pkg/ctxcache" - "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -62,7 +61,6 @@ func (k Keeper) ResolveSuccess( feeLimit sdk.Coins, result []byte, gasUsed uint64, - gid tss.GroupID, encodeType types.EncodeType, ) { k.SaveResult(ctx, id, types.RESOLVE_STATUS_SUCCESS, result) @@ -76,7 +74,7 @@ func (k Keeper) ResolveSuccess( ) // Doesn't require signature from tss module; emit an event and end process here - if gid == tss.GroupID(0) { + if encodeType == types.ENCODE_TYPE_UNSPECIFIED { ctx.EventManager().EmitEvent(event) return } @@ -107,7 +105,7 @@ func (k Keeper) ResolveSuccess( } if err := ctxcache.ApplyFuncIfNoError(ctx, createSigningFunc); err != nil { - k.handleCreateSigningFailed(ctx, id, gid, event, err) + k.handleCreateSigningFailed(ctx, id, event, err) return } @@ -117,11 +115,10 @@ func (k Keeper) ResolveSuccess( func (k Keeper) handleCreateSigningFailed( ctx sdk.Context, id types.RequestID, - gid tss.GroupID, existingEvents sdk.Event, err error, ) { - codespace, code, _ := errors.ABCIInfo(err, false) + codespace, code, _ := errorsmod.ABCIInfo(err, false) signingResult := &types.SigningResult{ ErrorCodespace: codespace, ErrorCode: uint64(code), @@ -132,7 +129,6 @@ func (k Keeper) handleCreateSigningFailed( ctx.EventManager().EmitEvent(sdk.NewEvent( types.EventTypeHandleRequestSignFail, sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", id)), - sdk.NewAttribute(types.AttributeKeyTSSGroupID, fmt.Sprintf("%d", gid)), sdk.NewAttribute(types.AttributeKeyReason, err.Error()), )) diff --git a/x/oracle/keeper/result_test.go b/x/oracle/keeper/result_test.go index 61c83e8b4..7a2824ac1 100644 --- a/x/oracle/keeper/result_test.go +++ b/x/oracle/keeper/result_test.go @@ -57,7 +57,7 @@ func TestResolveSuccess(t *testing.T) { k.SetRequest(ctx, 42, defaultRequest()) // See report_test.go k.SetReport(ctx, 42, types.NewReport(bandtesting.Validators[0].ValAddress, true, nil)) - k.ResolveSuccess(ctx, 42, defaultRequest().Requester, defaultRequest().FeeLimit, BasicResult, 1234, 0, 0) + k.ResolveSuccess(ctx, 42, defaultRequest().Requester, defaultRequest().FeeLimit, BasicResult, 1234, 0) require.Equal(t, types.RESOLVE_STATUS_SUCCESS, k.MustGetResult(ctx, 42).ResolveStatus) require.Equal(t, BasicResult, k.MustGetResult(ctx, 42).Result) require.Equal(t, sdk.Events{sdk.NewEvent( diff --git a/x/oracle/keeper/signing.go b/x/oracle/keeper/signing.go index f08331f2b..d85251b39 100644 --- a/x/oracle/keeper/signing.go +++ b/x/oracle/keeper/signing.go @@ -11,7 +11,7 @@ func (k Keeper) SetSigningResult(ctx sdk.Context, rid types.RequestID, signingRe ctx.KVStore(k.storeKey).Set(types.SigningResultStoreKey(rid), k.cdc.MustMarshal(&signingResult)) } -// GetSigningID retrieves the signing ID associated with the given request ID from the store. +// GetSigningResult retrieves the signing result associated with the given request ID from the store. func (k Keeper) GetSigningResult(ctx sdk.Context, rid types.RequestID) (types.SigningResult, error) { bz := ctx.KVStore(k.storeKey).Get(types.SigningResultStoreKey(rid)) diff --git a/x/oracle/simulation/decoder_test.go b/x/oracle/simulation/decoder_test.go index 0bede559b..c04fd8e6d 100644 --- a/x/oracle/simulation/decoder_test.go +++ b/x/oracle/simulation/decoder_test.go @@ -41,7 +41,6 @@ func TestDecodeStore(t *testing.T) { nil, 100000, 0, - 0, accAddr.String(), sdk.NewCoins(sdk.NewInt64Coin("band", 1000)), ) diff --git a/x/oracle/simulation/operations_test.go b/x/oracle/simulation/operations_test.go index 1956bb825..a86bd8227 100644 --- a/x/oracle/simulation/operations_test.go +++ b/x/oracle/simulation/operations_test.go @@ -149,7 +149,6 @@ func (suite *SimTestSuite) TestSimulateMsgReportData() { nil, 300000, 0, - 0, suite.accs[0].PubKey.String(), sdk.NewCoins(sdk.NewInt64Coin("band", 1000)), ), diff --git a/x/oracle/tss_handler.go b/x/oracle/tss_handler.go index c43eda4da..6a8c4e6da 100644 --- a/x/oracle/tss_handler.go +++ b/x/oracle/tss_handler.go @@ -1,7 +1,6 @@ package oracle import ( - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -17,7 +16,7 @@ var ( EncodeTypePartialABIPrefix = tsslib.Hash([]byte("PartialABI"))[:4] ) -// NewSignatureOrderHandler creates a TSS Handler to handle oracle result signature order +// NewSignatureOrderHandler creates a tss handler to handle oracle result signature order func NewSignatureOrderHandler(k keeper.Keeper) tsstypes.Handler { return func(ctx sdk.Context, content tsstypes.Content) ([]byte, error) { switch c := content.(type) { @@ -28,20 +27,20 @@ func NewSignatureOrderHandler(k keeper.Keeper) tsstypes.Handler { } switch c.EncodeType { - case types.ENCODE_TYPE_UNSPECIFIED, types.ENCODE_TYPE_PROTO: + case types.ENCODE_TYPE_PROTO: bz, err := k.MarshalResult(ctx, result) if err != nil { return nil, err } - return append(EncodeTypeFullABIPrefix, bz...), nil + return append(EncodeTypeProtoPrefix, bz...), nil case types.ENCODE_TYPE_FULL_ABI: bz, err := result.PackFullABI() if err != nil { return nil, err } - return append(EncodeTypeProtoPrefix, bz...), nil + return append(EncodeTypeFullABIPrefix, bz...), nil case types.ENCODE_TYPE_PARTIAL_ABI: bz, err := result.PackPartialABI() if err != nil { @@ -50,16 +49,14 @@ func NewSignatureOrderHandler(k keeper.Keeper) tsstypes.Handler { return append(EncodeTypePartialABIPrefix, bz...), nil default: - return nil, errors.Wrapf( - sdkerrors.ErrUnknownRequest, + return nil, sdkerrors.ErrUnknownRequest.Wrapf( "unrecognized encode type: %d", c.EncodeType, ) } default: - return nil, errors.Wrapf( - sdkerrors.ErrUnknownRequest, + return nil, sdkerrors.ErrUnknownRequest.Wrapf( "unrecognized tss request signature type: %s", c.OrderType(), ) diff --git a/x/oracle/types/error.go b/x/oracle/types/error.go index a242e9554..fcd468fc9 100644 --- a/x/oracle/types/error.go +++ b/x/oracle/types/error.go @@ -51,6 +51,8 @@ var ( ErrIBCRequestDisabled = errorsmod.Register(ModuleName, 45, "sending oracle request via IBC is disabled") ErrSigningResultNotFound = errorsmod.Register(ModuleName, 46, "signing result not found") ErrReportNotFound = errorsmod.Register(ModuleName, 47, "report not found") + ErrInvalidRequestID = errorsmod.Register(ModuleName, 48, "invalid request id") + ErrInvalidOracleEncodeType = errorsmod.Register(ModuleName, 49, "invalid oracle encode type") ) // WrapMaxError wraps an error message with additional info of the current and max values. diff --git a/x/oracle/types/events.go b/x/oracle/types/events.go index e2de62b56..e39ba6006 100644 --- a/x/oracle/types/events.go +++ b/x/oracle/types/events.go @@ -18,7 +18,6 @@ const ( EventTypeHandleRequestSignFail = "handle_request_sign_fail" AttributeKeyID = "id" - AttributeKeyTSSGroupID = "tss_group_id" AttributeKeySigningID = "signing_id" AttributeKeyDataSourceID = "data_source_id" AttributeKeyOracleScriptID = "oracle_script_id" diff --git a/x/oracle/types/exec_env_test.go b/x/oracle/types/exec_env_test.go index bc1fdff68..6b0a58ba3 100644 --- a/x/oracle/types/exec_env_test.go +++ b/x/oracle/types/exec_env_test.go @@ -22,7 +22,7 @@ var ( validatorAddress1 = sdk.ValAddress(addr1) validatorAddress2 = sdk.ValAddress(addr2) validatorAddress3 = sdk.ValAddress(addr3) - address4 = sdk.AccAddress(addr4) + accountAddress4 = sdk.AccAddress(addr4) coins1 = sdk.NewCoins(sdk.NewInt64Coin("uband", 1000000)) ) @@ -46,8 +46,7 @@ func mockExecEnv() *ExecuteEnv { nil, 0, 0, - 0, - address4.String(), + accountAddress4.String(), coins1, ) rawReport1 := NewRawReport(1, 0, []byte("DATA1")) @@ -79,8 +78,7 @@ func mockFreshPrepareEnv() *PrepareEnv { nil, 0, 0, - 0, - address4.String(), + accountAddress4.String(), coins1, ) env := NewPrepareEnv(request, int64(DefaultMaxCalldataSize), 3, 1024) diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go index 0ad180c2d..7fc34458b 100644 --- a/x/oracle/types/msgs.go +++ b/x/oracle/types/msgs.go @@ -6,8 +6,6 @@ import ( errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/bandprotocol/chain/v2/pkg/tss" ) // oracle message types @@ -44,7 +42,6 @@ func NewMsgRequestData( feeLimit sdk.Coins, prepareGas, executeGas uint64, sender sdk.AccAddress, - tssGroupID tss.GroupID, tssEncodeType EncodeType, ) *MsgRequestData { return &MsgRequestData{ @@ -54,10 +51,9 @@ func NewMsgRequestData( MinCount: minCount, ClientID: clientID, FeeLimit: feeLimit, + Sender: sender.String(), PrepareGas: prepareGas, ExecuteGas: executeGas, - Sender: sender.String(), - TSSGroupID: tssGroupID, TSSEncodeType: tssEncodeType, } } diff --git a/x/oracle/types/msgs_test.go b/x/oracle/types/msgs_test.go index 9a30fbd2d..a8774306c 100644 --- a/x/oracle/types/msgs_test.go +++ b/x/oracle/types/msgs_test.go @@ -108,7 +108,7 @@ func TestMsgGetSigners(t *testing.T) { require.Equal( t, signers, - NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", emptyCoins, 1, 1, signerAcc, 0, 0).GetSigners(), + NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", emptyCoins, 1, 1, signerAcc, 0).GetSigners(), ) require.Equal( t, @@ -201,7 +201,6 @@ func TestMsgGetSignBytes(t *testing.T) { 250000, GoodTestAddr, 0, - 0, ).GetSignBytes(), ), ) @@ -539,29 +538,14 @@ func TestMsgEditOracleScriptValidation(t *testing.T) { func TestMsgRequestDataValidation(t *testing.T) { performValidateTests(t, []validateTestCase{ - {true, NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", GoodCoins, 1, 1, GoodTestAddr, 0, 0)}, - {false, NewMsgRequestData(1, []byte("calldata"), 2, 5, "client-id", GoodCoins, 1, 1, GoodTestAddr, 0, 0)}, - {false, NewMsgRequestData(1, []byte("calldata"), 0, 0, "client-id", GoodCoins, 1, 1, GoodTestAddr, 0, 0)}, - { - false, - NewMsgRequestData( - 1, - []byte("calldata"), - 10, - 5, - strings.Repeat("x", 300), - GoodCoins, - 1, - 1, - GoodTestAddr, - 0, - 0, - ), - }, - {false, NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", GoodCoins, 1, 1, EmptyAddr, 0, 0)}, - {false, NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", BadCoins, 1, 1, GoodTestAddr, 0, 0)}, - {false, NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", GoodCoins, 0, 1, GoodTestAddr, 0, 0)}, - {false, NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", GoodCoins, 1, 0, GoodTestAddr, 0, 0)}, + {true, NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", GoodCoins, 1, 1, GoodTestAddr, 0)}, + {false, NewMsgRequestData(1, []byte("calldata"), 2, 5, "client-id", GoodCoins, 1, 1, GoodTestAddr, 0)}, + {false, NewMsgRequestData(1, []byte("calldata"), 0, 0, "client-id", GoodCoins, 1, 1, GoodTestAddr, 0)}, + {false, NewMsgRequestData(1, []byte("calldata"), 10, 5, strings.Repeat("x", 300), GoodCoins, 1, 1, GoodTestAddr, 0)}, + {false, NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", GoodCoins, 1, 1, EmptyAddr, 0)}, + {false, NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", BadCoins, 1, 1, GoodTestAddr, 0)}, + {false, NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", GoodCoins, 0, 1, GoodTestAddr, 0)}, + {false, NewMsgRequestData(1, []byte("calldata"), 10, 5, "client-id", GoodCoins, 1, 0, GoodTestAddr, 0)}, }) } diff --git a/x/oracle/types/oracle.pb.go b/x/oracle/types/oracle.pb.go index 847f9e896..9d165d555 100644 --- a/x/oracle/types/oracle.pb.go +++ b/x/oracle/types/oracle.pb.go @@ -6,7 +6,6 @@ package types import ( bytes "bytes" fmt "fmt" - github_com_bandprotocol_chain_v2_pkg_tss "github.com/bandprotocol/chain/v2/pkg/tss" github_com_bandprotocol_chain_v2_x_bandtss_types "github.com/bandprotocol/chain/v2/x/bandtss/types" github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" types "github.com/cosmos/cosmos-sdk/types" @@ -69,7 +68,7 @@ func (ResolveStatus) EnumDescriptor() ([]byte, []int) { return fileDescriptor_652b57db11528d07, []int{0} } -// EncodeType represent encode type of oracle result when using in TSS +// EncodeType represent encode type of oracle result when using in bandtss type EncodeType int32 const ( @@ -455,14 +454,12 @@ type Request struct { IBCChannel *IBCChannel `protobuf:"bytes,9,opt,name=ibc_channel,json=ibcChannel,proto3" json:"ibc_channel,omitempty"` // ExecuteGas is amount of gas to reserve for executing ExecuteGas uint64 `protobuf:"varint,10,opt,name=execute_gas,json=executeGas,proto3" json:"execute_gas,omitempty"` - // TSSGroupID is ID of the group that assign for sign the result data on tss module. - TSSGroupID github_com_bandprotocol_chain_v2_pkg_tss.GroupID `protobuf:"varint,11,opt,name=tss_group_id,json=tssGroupId,proto3,casttype=github.com/bandprotocol/chain/v2/pkg/tss.GroupID" json:"tss_group_id,omitempty"` // TSSEncodeType is the encode type of oracle result that will be sent to TSS. - TSSEncodeType EncodeType `protobuf:"varint,12,opt,name=tss_encode_type,json=tssEncodeType,proto3,enum=oracle.v1.EncodeType" json:"tss_encode_type,omitempty"` - // request is the address of requester - Requester string `protobuf:"bytes,13,opt,name=requester,proto3" json:"requester,omitempty"` - // fee_limit is the fee left for paying fee in this request. - FeeLimit github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,14,rep,name=fee_limit,json=feeLimit,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"fee_limit"` + TSSEncodeType EncodeType `protobuf:"varint,11,opt,name=tss_encode_type,json=tssEncodeType,proto3,enum=oracle.v1.EncodeType" json:"tss_encode_type,omitempty"` + // Requester is the address of person who requests the data. + Requester string `protobuf:"bytes,12,opt,name=requester,proto3" json:"requester,omitempty"` + // FeeLimit is the maximum tokens that will be paid for this request. + FeeLimit github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,13,rep,name=fee_limit,json=feeLimit,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"fee_limit"` } func (m *Request) Reset() { *m = Request{} } @@ -568,13 +565,6 @@ func (m *Request) GetExecuteGas() uint64 { return 0 } -func (m *Request) GetTSSGroupID() github_com_bandprotocol_chain_v2_pkg_tss.GroupID { - if m != nil { - return m.TSSGroupID - } - return 0 -} - func (m *Request) GetTSSEncodeType() EncodeType { if m != nil { return m.TSSEncodeType @@ -689,10 +679,8 @@ type OracleRequestPacketData struct { PrepareGas uint64 `protobuf:"varint,7,opt,name=prepare_gas,json=prepareGas,proto3" json:"prepare_gas,omitempty"` // ExecuteGas is amount of gas to reserve for executing ExecuteGas uint64 `protobuf:"varint,8,opt,name=execute_gas,json=executeGas,proto3" json:"execute_gas,omitempty"` - // TSSGroupID is ID of the group that assign for sign the result data on tss module. - TSSGroupID github_com_bandprotocol_chain_v2_pkg_tss.GroupID `protobuf:"varint,9,opt,name=tss_group_id,json=tssGroupId,proto3,casttype=github.com/bandprotocol/chain/v2/pkg/tss.GroupID" json:"tss_group_id,omitempty"` // TSSEncodeType is the encode type of oracle result that will be sent to TSS. - TSSEncodeType EncodeType `protobuf:"varint,10,opt,name=tss_encode_type,json=tssEncodeType,proto3,enum=oracle.v1.EncodeType" json:"tss_encode_type,omitempty"` + TSSEncodeType EncodeType `protobuf:"varint,9,opt,name=tss_encode_type,json=tssEncodeType,proto3,enum=oracle.v1.EncodeType" json:"tss_encode_type,omitempty"` } func (m *OracleRequestPacketData) Reset() { *m = OracleRequestPacketData{} } @@ -784,13 +772,6 @@ func (m *OracleRequestPacketData) GetExecuteGas() uint64 { return 0 } -func (m *OracleRequestPacketData) GetTSSGroupID() github_com_bandprotocol_chain_v2_pkg_tss.GroupID { - if m != nil { - return m.TSSGroupID - } - return 0 -} - func (m *OracleRequestPacketData) GetTSSEncodeType() EncodeType { if m != nil { return m.TSSEncodeType @@ -1102,7 +1083,7 @@ func (m *Result) GetResult() []byte { // SigningResult encodes a result of signing of request type SigningResult struct { - // signing_id is the id of the signing + // signing_id is the id of the bandtss signing SigningID github_com_bandprotocol_chain_v2_x_bandtss_types.SigningID `protobuf:"varint,1,opt,name=signing_id,json=signingId,proto3,casttype=github.com/bandprotocol/chain/v2/x/bandtss/types.SigningID" json:"signing_id,omitempty"` // error_codespace is the codespace of the error ErrorCodespace string `protobuf:"bytes,2,opt,name=error_codespace,json=errorCodespace,proto3" json:"error_codespace,omitempty"` @@ -1692,11 +1673,11 @@ func (m *PriceResult) GetResolveTime() int64 { return 0 } -// OracleResultSignatureOrder defines a request id to request TSS signature from the oracle result. +// OracleResultSignatureOrder defines a request id to request bandtss signature from the oracle result. type OracleResultSignatureOrder struct { - // RequestID is BandChain's unique identifier for this oracle request. + // RequestID is oracle's unique identifier for this oracle request. RequestID RequestID `protobuf:"varint,1,opt,name=request_id,json=requestId,proto3,casttype=RequestID" json:"request_id,omitempty"` - // EncodeType is encoding type of the oracle result when it's sent to TSS + // EncodeType is encoding type of the oracle result when it's sent to bandtss EncodeType EncodeType `protobuf:"varint,2,opt,name=encode_type,json=encodeType,proto3,enum=oracle.v1.EncodeType" json:"encode_type,omitempty"` } @@ -1760,136 +1741,133 @@ func init() { func init() { proto.RegisterFile("oracle/v1/oracle.proto", fileDescriptor_652b57db11528d07) } var fileDescriptor_652b57db11528d07 = []byte{ - // 2054 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x58, 0xcd, 0x6f, 0x1b, 0xc7, - 0x15, 0xd7, 0x92, 0x14, 0x45, 0x3e, 0x52, 0x94, 0x34, 0x96, 0x65, 0x9a, 0x76, 0x45, 0xd6, 0x48, - 0x5b, 0xd7, 0x48, 0xc9, 0x58, 0x2d, 0x82, 0xd8, 0xe9, 0x07, 0x44, 0x8a, 0x4e, 0xd9, 0x0a, 0x16, - 0x31, 0xa4, 0x8c, 0xb6, 0x40, 0xb1, 0x18, 0xee, 0x8e, 0xa8, 0xad, 0x96, 0xbb, 0xdb, 0x99, 0xa5, - 0x3e, 0x72, 0xeb, 0x2d, 0xf0, 0x29, 0x97, 0x02, 0xbd, 0x18, 0x30, 0x90, 0x53, 0x7b, 0x2d, 0xfa, - 0x0f, 0xf4, 0xe4, 0x9e, 0x9a, 0x43, 0x51, 0xf4, 0xa4, 0x14, 0xf4, 0x25, 0xff, 0x40, 0x2f, 0xed, - 0xa5, 0x98, 0x8f, 0xdd, 0x25, 0x69, 0x25, 0x8a, 0xed, 0x34, 0x87, 0x9e, 0xc4, 0xf7, 0x7b, 0xf3, - 0x66, 0xdf, 0x7b, 0xf3, 0x7e, 0x6f, 0xde, 0x08, 0x36, 0x7c, 0x46, 0x2c, 0x97, 0x36, 0x8e, 0xef, - 0x36, 0xd4, 0xaf, 0x7a, 0xc0, 0xfc, 0xd0, 0x47, 0x79, 0x2d, 0x1d, 0xdf, 0xad, 0xac, 0x0f, 0xfd, - 0xa1, 0x2f, 0xd1, 0x86, 0xf8, 0xa5, 0x16, 0x54, 0xaa, 0x43, 0xdf, 0x1f, 0xba, 0xb4, 0x21, 0xa5, - 0xc1, 0xf8, 0xa0, 0x11, 0x3a, 0x23, 0xca, 0x43, 0x32, 0x0a, 0xf4, 0x82, 0x4d, 0xcb, 0xe7, 0x23, - 0x9f, 0x37, 0x06, 0x84, 0x8b, 0xed, 0x07, 0x34, 0x24, 0x77, 0x1b, 0x96, 0xef, 0x78, 0x4a, 0x7f, - 0xeb, 0x5f, 0x06, 0xc0, 0x0e, 0x09, 0x49, 0xcf, 0x1f, 0x33, 0x8b, 0xa2, 0x75, 0x58, 0xf4, 0x4f, - 0x3c, 0xca, 0xca, 0x46, 0xcd, 0xb8, 0x9d, 0xc7, 0x4a, 0x40, 0x08, 0x32, 0x1e, 0x19, 0xd1, 0x72, - 0x4a, 0x82, 0xf2, 0x37, 0xaa, 0x41, 0xc1, 0xa6, 0xdc, 0x62, 0x4e, 0x10, 0x3a, 0xbe, 0x57, 0x4e, - 0x4b, 0xd5, 0x34, 0x84, 0x2a, 0x90, 0x3b, 0x70, 0x5c, 0x2a, 0x2d, 0x33, 0x52, 0x1d, 0xcb, 0x42, - 0x17, 0x32, 0x4a, 0xf8, 0x98, 0x9d, 0x95, 0x17, 0x95, 0x2e, 0x92, 0xd1, 0x2f, 0x21, 0x7d, 0x40, - 0x69, 0x39, 0x5b, 0x4b, 0xdf, 0x2e, 0x6c, 0x5d, 0xaf, 0xab, 0x00, 0xea, 0x22, 0x80, 0xba, 0x0e, - 0xa0, 0xde, 0xf2, 0x1d, 0xaf, 0xf9, 0xd6, 0xb3, 0xf3, 0xea, 0xc2, 0x1f, 0x3e, 0xa9, 0xde, 0x1e, - 0x3a, 0xe1, 0xe1, 0x78, 0x50, 0xb7, 0xfc, 0x51, 0x43, 0x47, 0xab, 0xfe, 0x7c, 0x87, 0xdb, 0x47, - 0x8d, 0xf0, 0x2c, 0xa0, 0x5c, 0x1a, 0x70, 0x2c, 0xf6, 0xbd, 0x9f, 0xf9, 0xf4, 0x69, 0xd5, 0xb8, - 0xf5, 0x57, 0x03, 0x8a, 0x7b, 0x32, 0xb9, 0x3d, 0xe9, 0xf0, 0x57, 0x16, 0xf9, 0x06, 0x64, 0xb9, - 0x75, 0x48, 0x47, 0x44, 0xc7, 0xad, 0x25, 0x74, 0x0f, 0x56, 0xb8, 0x3c, 0x03, 0xd3, 0xf2, 0x6d, - 0x6a, 0x8e, 0x99, 0x5b, 0xce, 0x8a, 0x05, 0xcd, 0xb5, 0xc9, 0x79, 0x75, 0x59, 0x1d, 0x4f, 0xcb, - 0xb7, 0xe9, 0x3e, 0xde, 0xc5, 0xcb, 0x3c, 0x11, 0x99, 0xab, 0x23, 0xfa, 0x93, 0x01, 0x80, 0xc9, - 0x09, 0xa6, 0xbf, 0x1e, 0x53, 0x1e, 0xa2, 0x1f, 0x40, 0x81, 0x9e, 0x86, 0x94, 0x79, 0xc4, 0x35, - 0x1d, 0x5b, 0x46, 0x95, 0x69, 0xde, 0x9c, 0x9c, 0x57, 0xa1, 0xad, 0xe1, 0xce, 0xce, 0xbf, 0x67, - 0x24, 0x0c, 0x91, 0x41, 0xc7, 0x46, 0x0f, 0xa0, 0x64, 0x93, 0x90, 0x98, 0xda, 0x27, 0xc7, 0x96, - 0x29, 0xc8, 0x34, 0x6b, 0x93, 0xf3, 0x6a, 0x31, 0x29, 0x18, 0xb9, 0xc7, 0x8c, 0x8c, 0x8b, 0x76, - 0x22, 0xd9, 0x22, 0x15, 0x16, 0x71, 0x5d, 0x81, 0xc9, 0x4c, 0x15, 0x71, 0x2c, 0x6b, 0xbf, 0x7f, - 0x63, 0x40, 0x5e, 0xfa, 0x1d, 0xf8, 0xec, 0xb5, 0xdd, 0xbe, 0x01, 0x79, 0x7a, 0xea, 0x84, 0x32, - 0x87, 0xd2, 0xe3, 0x65, 0x9c, 0x13, 0x80, 0x48, 0x95, 0x38, 0xcc, 0x29, 0x3f, 0x32, 0x53, 0x3e, - 0xfc, 0x3e, 0x0b, 0x4b, 0x51, 0xe2, 0x1e, 0xc2, 0xaa, 0x62, 0x9d, 0xa9, 0x0e, 0x34, 0x71, 0xe3, - 0x8d, 0xc9, 0x79, 0xb5, 0x34, 0x5d, 0x34, 0xd2, 0x95, 0x39, 0x04, 0x97, 0xfc, 0x69, 0x79, 0x36, - 0x03, 0xa9, 0xd9, 0x0c, 0xa0, 0xbb, 0xb0, 0xce, 0xd4, 0x67, 0xa9, 0x6d, 0x1e, 0x13, 0xd7, 0xb1, - 0x49, 0xe8, 0x33, 0x5e, 0x4e, 0xd7, 0xd2, 0xb7, 0xf3, 0xf8, 0x4a, 0xac, 0x7b, 0x14, 0xab, 0x44, - 0x84, 0x23, 0xc7, 0x33, 0x2d, 0x7f, 0xec, 0x85, 0xb2, 0xb8, 0x32, 0x38, 0x37, 0x72, 0xbc, 0x96, - 0x90, 0xd1, 0x37, 0xa0, 0xa4, 0x6d, 0xcc, 0x43, 0xea, 0x0c, 0x0f, 0x43, 0x59, 0x64, 0x69, 0xbc, - 0xac, 0xd1, 0x1f, 0x4b, 0x10, 0x7d, 0x1d, 0x8a, 0xd1, 0x32, 0xd1, 0x2f, 0x64, 0xa1, 0xa5, 0x71, - 0x41, 0x63, 0x7d, 0x67, 0x44, 0xd1, 0xb7, 0x21, 0x6f, 0xb9, 0x0e, 0xf5, 0x64, 0xf8, 0x4b, 0xb2, - 0x10, 0x8b, 0x93, 0xf3, 0x6a, 0xae, 0x25, 0xc1, 0xce, 0x0e, 0xce, 0x29, 0x75, 0xc7, 0x46, 0x3f, - 0x84, 0x22, 0x23, 0x27, 0xa6, 0xb6, 0xe6, 0xe5, 0x9c, 0x24, 0xee, 0xd5, 0x7a, 0xdc, 0xbb, 0xea, - 0x49, 0x59, 0x36, 0x33, 0x82, 0xb4, 0xb8, 0xc0, 0x62, 0x84, 0xa3, 0x07, 0x50, 0x70, 0x06, 0x96, - 0x69, 0x1d, 0x12, 0xcf, 0xa3, 0x6e, 0x39, 0x5f, 0x33, 0xe6, 0xcc, 0x3b, 0xcd, 0x56, 0x4b, 0x29, - 0x9b, 0x25, 0x51, 0x09, 0x89, 0x8c, 0xc1, 0x19, 0x58, 0xfa, 0x37, 0xaa, 0x8a, 0xd2, 0xa1, 0xd6, - 0x38, 0xa4, 0xe6, 0x90, 0xf0, 0x32, 0xc8, 0xdc, 0x80, 0x86, 0xde, 0x23, 0x1c, 0xd9, 0x50, 0x0c, - 0x39, 0x37, 0x87, 0xcc, 0x1f, 0x07, 0x22, 0xac, 0x82, 0x3c, 0xd5, 0xa6, 0xd8, 0xb2, 0xdf, 0xeb, - 0xbd, 0x27, 0x60, 0x79, 0xa2, 0x6f, 0x4d, 0x35, 0x94, 0x01, 0xf1, 0x6c, 0xd9, 0x29, 0x2d, 0xdf, - 0x6d, 0x58, 0x87, 0xc4, 0xf1, 0x1a, 0xc7, 0x5b, 0x8d, 0xe0, 0x68, 0xd8, 0x08, 0x39, 0xaf, 0x6b, - 0x1b, 0x0c, 0x21, 0xe7, 0xea, 0xb7, 0x8d, 0xba, 0xb0, 0x22, 0xbe, 0x42, 0x3d, 0xc9, 0x63, 0xd1, - 0x7e, 0xca, 0xc5, 0x9a, 0x71, 0xbb, 0x34, 0x13, 0x52, 0x5b, 0x6a, 0xfb, 0x67, 0x01, 0x55, 0xfc, - 0xee, 0xf7, 0x7a, 0x09, 0x84, 0x97, 0x43, 0xce, 0x13, 0x11, 0xdd, 0x84, 0x7c, 0x54, 0x09, 0xac, - 0xbc, 0x2c, 0xbb, 0x46, 0x02, 0xa0, 0x43, 0xc8, 0x1f, 0x50, 0x6a, 0xba, 0xce, 0xc8, 0x09, 0xcb, - 0xa5, 0x2f, 0xbf, 0x69, 0xe6, 0x0e, 0x28, 0xdd, 0x15, 0x9b, 0x6b, 0xae, 0xfc, 0xd6, 0x80, 0xac, - 0x26, 0xeb, 0x4d, 0xc8, 0xc7, 0x45, 0xab, 0xfb, 0x66, 0x02, 0xa0, 0x3b, 0xb0, 0xe6, 0x78, 0xe6, - 0x80, 0x1e, 0xf8, 0x8c, 0x9a, 0x8c, 0x72, 0xdf, 0x3d, 0x56, 0x9c, 0xcc, 0xe1, 0x15, 0xc7, 0x6b, - 0x4a, 0x1c, 0x2b, 0x18, 0xbd, 0x0b, 0x05, 0x55, 0x43, 0x62, 0x5f, 0x55, 0xff, 0x85, 0xad, 0xf5, - 0xf9, 0x12, 0x12, 0x4a, 0x5d, 0x41, 0xc0, 0x22, 0x80, 0x6b, 0xbf, 0xfe, 0x96, 0x81, 0x6b, 0x8a, - 0x8a, 0xba, 0xb2, 0xba, 0xc4, 0x3a, 0xa2, 0xa1, 0xe8, 0x4d, 0xb3, 0xd5, 0x6c, 0x7c, 0x6e, 0x35, - 0x5f, 0x44, 0xff, 0xd4, 0x97, 0x44, 0xff, 0xb9, 0x06, 0x28, 0xb8, 0x4c, 0xf8, 0xd1, 0x2c, 0x97, - 0x09, 0x3f, 0x52, 0x5c, 0x9e, 0x21, 0xfa, 0xe2, 0x1c, 0xd1, 0x67, 0x0e, 0x3d, 0xfb, 0x3f, 0x3c, - 0x74, 0xc1, 0xaa, 0x80, 0xd1, 0x80, 0x30, 0xc5, 0xaa, 0x25, 0xc5, 0x2a, 0x0d, 0x09, 0x56, 0xcd, - 0xd1, 0x2e, 0x77, 0x29, 0xed, 0xf2, 0x5f, 0x15, 0xed, 0xe0, 0xb5, 0x68, 0xa7, 0xcb, 0x8a, 0xc2, - 0xad, 0x0b, 0xaa, 0x6a, 0xdb, 0x3a, 0xf2, 0xfc, 0x13, 0x97, 0xda, 0x43, 0x3a, 0xa2, 0x5e, 0x88, - 0xee, 0x01, 0x44, 0x1d, 0x35, 0xbe, 0x2e, 0x2a, 0x93, 0xf3, 0x6a, 0x5e, 0x5b, 0xc9, 0x00, 0x13, - 0x21, 0xe6, 0x6f, 0xc7, 0xd6, 0x9f, 0xf9, 0x73, 0x0a, 0xca, 0xd1, 0x77, 0x78, 0xe0, 0x7b, 0x9c, - 0xbe, 0x5a, 0xf9, 0xce, 0x3a, 0x92, 0x7a, 0x09, 0x47, 0x64, 0x35, 0x7a, 0x5c, 0x17, 0x5c, 0x5a, - 0x57, 0xa3, 0xc7, 0x55, 0xc1, 0xcd, 0x5f, 0x19, 0x99, 0x17, 0xaf, 0x0c, 0xb9, 0x44, 0xd2, 0x59, - 0x2d, 0x59, 0x8c, 0x96, 0x48, 0x4c, 0x2e, 0xf9, 0x91, 0xb8, 0x9f, 0xd4, 0x12, 0x1e, 0x92, 0x70, - 0xcc, 0xe5, 0xd5, 0x53, 0xda, 0x2a, 0x4f, 0x33, 0x5d, 0x2d, 0xe8, 0x49, 0xbd, 0xb8, 0xb9, 0xa6, - 0x44, 0x31, 0x3d, 0x31, 0xca, 0xc7, 0x6e, 0x28, 0x0b, 0xb1, 0x88, 0xb5, 0xa4, 0x93, 0xf8, 0xf7, - 0xb4, 0x68, 0x4d, 0x02, 0xf8, 0xff, 0x63, 0xfc, 0xec, 0xc1, 0x66, 0x5f, 0xf9, 0x60, 0x97, 0x2e, - 0x39, 0xd8, 0xdc, 0xe5, 0x07, 0x9b, 0xff, 0x22, 0x07, 0x0b, 0xaf, 0x7a, 0xb0, 0x85, 0x0b, 0x0e, - 0xf6, 0x2f, 0x06, 0x2c, 0xf7, 0x9c, 0xa1, 0xe7, 0x78, 0x43, 0x7d, 0xbe, 0xbf, 0x02, 0xe0, 0x0a, - 0x48, 0x08, 0xf7, 0x53, 0x91, 0x0e, 0xbd, 0x4c, 0xa6, 0xe3, 0xfe, 0xa5, 0x1d, 0xe5, 0x54, 0xe2, - 0x21, 0xe7, 0xba, 0xfb, 0xc5, 0xd6, 0x38, 0xaf, 0xb7, 0xef, 0xd8, 0xe8, 0x5b, 0xb0, 0x42, 0x19, - 0xf3, 0x99, 0x9c, 0x2a, 0x79, 0x40, 0xac, 0xe8, 0x3d, 0x50, 0x92, 0x70, 0x2b, 0x42, 0xd1, 0xd7, - 0x00, 0x92, 0x85, 0x9a, 0x42, 0xf9, 0x78, 0x8d, 0x8e, 0x25, 0x80, 0x95, 0x78, 0x9c, 0xd3, 0xc1, - 0xdf, 0x80, 0xbc, 0xc3, 0x4d, 0x62, 0x85, 0xce, 0x31, 0x95, 0xb1, 0xe4, 0x70, 0xce, 0xe1, 0xdb, - 0x52, 0x46, 0xf7, 0x61, 0x91, 0x3b, 0x9e, 0xfe, 0x66, 0x61, 0xab, 0x52, 0x57, 0x4f, 0xbe, 0x7a, - 0xf4, 0xe4, 0xab, 0xf7, 0xa3, 0x27, 0x5f, 0x33, 0x27, 0xfa, 0xfc, 0x87, 0x9f, 0x54, 0x0d, 0xac, - 0x4c, 0xf4, 0x17, 0xb7, 0x61, 0x45, 0xed, 0x15, 0x7f, 0x17, 0x95, 0x61, 0x89, 0xd8, 0x36, 0xa3, - 0x9c, 0xeb, 0x7b, 0x3b, 0x12, 0xc5, 0x3b, 0x28, 0xf0, 0x4f, 0x28, 0x53, 0x14, 0xc0, 0x4a, 0xb8, - 0xf5, 0x2c, 0x03, 0xd9, 0x2e, 0x61, 0x64, 0xc4, 0xd1, 0x5d, 0xb8, 0x3a, 0x22, 0xa7, 0xe6, 0xd4, - 0xc8, 0xa7, 0x2b, 0x4b, 0x1e, 0x02, 0x46, 0x23, 0x72, 0x9a, 0xcc, 0x7b, 0xaa, 0xc6, 0x6e, 0xc1, - 0xb2, 0x30, 0x49, 0x2a, 0x5f, 0xed, 0x5d, 0x18, 0x91, 0xd3, 0xed, 0xa8, 0xf8, 0xef, 0xc0, 0x9a, - 0x58, 0x13, 0x31, 0xc5, 0xe4, 0xce, 0xfb, 0x51, 0x0a, 0x57, 0x46, 0xe4, 0xb4, 0xa5, 0xf1, 0x9e, - 0xf3, 0x3e, 0x45, 0x0d, 0x58, 0x97, 0x2e, 0xc8, 0xfb, 0xdf, 0x4c, 0x96, 0x2b, 0x42, 0x89, 0x7d, - 0xd4, 0x68, 0xb0, 0x13, 0x19, 0x7c, 0x0f, 0x36, 0xe8, 0x69, 0xe0, 0x30, 0x22, 0x9e, 0x67, 0xe6, - 0xc0, 0xf5, 0xad, 0xa3, 0x19, 0x9a, 0xad, 0x27, 0xda, 0xa6, 0x50, 0x2a, 0x97, 0xde, 0x80, 0x92, - 0xb8, 0x4b, 0x4d, 0xff, 0x84, 0xf0, 0x91, 0xbc, 0xdc, 0x24, 0xed, 0x70, 0x51, 0xa0, 0x7b, 0x02, - 0x14, 0xd7, 0xdb, 0x3d, 0xb8, 0x1e, 0x50, 0x96, 0x4c, 0xef, 0x71, 0x56, 0x92, 0xeb, 0x72, 0x23, - 0xa0, 0x2c, 0xce, 0xbd, 0xce, 0x8c, 0x30, 0x7d, 0x13, 0x10, 0x27, 0xa3, 0xc0, 0x15, 0x55, 0x1c, - 0xb2, 0x33, 0xed, 0x92, 0xba, 0x41, 0x57, 0x23, 0x4d, 0x9f, 0x9d, 0x29, 0x77, 0xde, 0x81, 0xb2, - 0xee, 0x53, 0x8c, 0x9e, 0x10, 0x66, 0x9b, 0x01, 0x65, 0x16, 0xf5, 0x42, 0x32, 0x54, 0x94, 0xcc, - 0x60, 0xfd, 0x6f, 0x04, 0x2c, 0xd5, 0xdd, 0x58, 0x8b, 0xee, 0xc3, 0x75, 0xc7, 0x53, 0xe5, 0x65, - 0x06, 0xd4, 0x23, 0x6e, 0x78, 0x66, 0xda, 0x63, 0x15, 0xaf, 0x9e, 0x93, 0xaf, 0x45, 0x0b, 0xba, - 0x4a, 0xbf, 0xa3, 0xd5, 0xa8, 0x0d, 0x57, 0xc4, 0x74, 0x1e, 0x05, 0x45, 0x3d, 0x32, 0x70, 0xa9, - 0x9a, 0x9d, 0x73, 0xcd, 0xab, 0x93, 0xf3, 0xea, 0x5a, 0xa7, 0xd9, 0xd2, 0x31, 0xb5, 0x95, 0x12, - 0xaf, 0x39, 0x03, 0x6b, 0x16, 0xba, 0x9f, 0xfb, 0xdd, 0xd3, 0xea, 0x82, 0xac, 0xc6, 0x77, 0x01, - 0x75, 0xa9, 0x67, 0x2b, 0x2a, 0x8b, 0x0e, 0xb0, 0xeb, 0x70, 0x39, 0x66, 0x24, 0xed, 0x4d, 0x14, - 0x65, 0x5a, 0x4c, 0x11, 0x71, 0x0f, 0x8b, 0x86, 0xbc, 0x9f, 0xc0, 0xd4, 0xf4, 0x8f, 0xae, 0xc1, - 0x92, 0xac, 0x80, 0xa8, 0xc5, 0xe3, 0xac, 0x10, 0x3b, 0xb6, 0x20, 0xa2, 0x7e, 0x4e, 0x44, 0xcd, - 0x3c, 0x8f, 0xf3, 0x1a, 0x89, 0xaf, 0xdc, 0x8f, 0x52, 0x70, 0x45, 0x7b, 0xf9, 0x88, 0x32, 0xe7, - 0xc0, 0xb1, 0x54, 0xc4, 0xdf, 0x84, 0x9c, 0xec, 0x0f, 0xc9, 0xcd, 0x51, 0x98, 0x9c, 0x57, 0x97, - 0x5a, 0x02, 0xeb, 0xec, 0xe0, 0x25, 0xa9, 0xec, 0xd8, 0xb3, 0xd3, 0x6f, 0x6a, 0x7e, 0xfa, 0x9d, - 0xed, 0xd7, 0xe9, 0x97, 0xe9, 0xd7, 0x73, 0x6f, 0xe0, 0xcc, 0x6b, 0x3f, 0xdd, 0x17, 0x5f, 0xe5, - 0xe9, 0xae, 0xb3, 0xf4, 0x47, 0x03, 0x0a, 0x5d, 0xe6, 0x58, 0x54, 0x37, 0xde, 0x0d, 0xc8, 0xf2, - 0xb3, 0xd1, 0xc0, 0x77, 0xa3, 0x94, 0x2b, 0x09, 0x6d, 0x02, 0x8c, 0xc6, 0x6e, 0xe8, 0x04, 0xae, - 0x13, 0x37, 0x8f, 0x29, 0x04, 0x95, 0x20, 0x15, 0x9c, 0x6a, 0x42, 0xa7, 0x82, 0xd3, 0xb9, 0xfc, - 0x64, 0x5e, 0x26, 0x3f, 0x97, 0x0f, 0x1a, 0xe2, 0x91, 0x52, 0x89, 0xc7, 0xa9, 0xb1, 0x1b, 0x8a, - 0xbe, 0x4e, 0xc2, 0x31, 0xa3, 0x7b, 0xcc, 0xa6, 0xec, 0x35, 0xc6, 0x35, 0xf4, 0x36, 0x14, 0xa6, - 0x67, 0xcc, 0xd4, 0xe7, 0xcc, 0x98, 0x18, 0xe8, 0xd4, 0x34, 0xf9, 0xc1, 0xd3, 0xea, 0xc2, 0x9d, - 0xff, 0x18, 0xb0, 0x3c, 0x73, 0x0f, 0xa2, 0xef, 0x43, 0x15, 0xb7, 0x7b, 0x7b, 0xbb, 0x8f, 0xda, - 0x66, 0xaf, 0xbf, 0xdd, 0xdf, 0xef, 0x99, 0x7b, 0xdd, 0xf6, 0x43, 0x73, 0xff, 0x61, 0xaf, 0xdb, - 0x6e, 0x75, 0x1e, 0x74, 0xda, 0x3b, 0xab, 0x0b, 0x95, 0x6b, 0x8f, 0x9f, 0xd4, 0xae, 0x5c, 0xb0, - 0x0c, 0xbd, 0x0d, 0x1b, 0x73, 0x70, 0x6f, 0xbf, 0xd5, 0x6a, 0xf7, 0x7a, 0xab, 0x46, 0xa5, 0xf2, - 0xf8, 0x49, 0xed, 0x33, 0xb4, 0x17, 0xd8, 0x3d, 0xd8, 0xee, 0xec, 0xee, 0xe3, 0xf6, 0x6a, 0xea, - 0x42, 0x3b, 0xad, 0xbd, 0xc0, 0xae, 0xfd, 0xb3, 0x6e, 0x07, 0xb7, 0x77, 0x56, 0xd3, 0x17, 0xda, - 0x69, 0x6d, 0x25, 0xf3, 0xc1, 0x47, 0x9b, 0x0b, 0x77, 0x3e, 0x35, 0x00, 0xa6, 0xde, 0xb5, 0xef, - 0xc0, 0xb5, 0xf6, 0xc3, 0xd6, 0xde, 0x4e, 0xdb, 0xec, 0xff, 0xbc, 0xdb, 0x9e, 0x0b, 0xf9, 0xc6, - 0xe3, 0x27, 0xb5, 0xcf, 0x52, 0xa3, 0x37, 0x61, 0x6d, 0x5a, 0xd5, 0xc5, 0x7b, 0xfd, 0xbd, 0x55, - 0xa3, 0x72, 0xf5, 0xf1, 0x93, 0xda, 0x8b, 0x0a, 0xb4, 0x05, 0xeb, 0xd3, 0xe0, 0x83, 0xfd, 0xdd, - 0x5d, 0x73, 0xbb, 0xd9, 0x59, 0x4d, 0x55, 0xca, 0x8f, 0x9f, 0xd4, 0x2e, 0xd4, 0xcd, 0xfb, 0xd6, - 0xdd, 0xc6, 0xfd, 0xce, 0xb6, 0x32, 0x4b, 0xbf, 0xe8, 0xdb, 0x94, 0x5a, 0x85, 0xda, 0xec, 0x3c, - 0x9b, 0x6c, 0x1a, 0x1f, 0x4f, 0x36, 0x8d, 0x7f, 0x4e, 0x36, 0x8d, 0x0f, 0x9f, 0x6f, 0x2e, 0x7c, - 0xfc, 0x7c, 0x73, 0xe1, 0x1f, 0xcf, 0x37, 0x17, 0x7e, 0xd1, 0xf8, 0x02, 0x43, 0x89, 0xfe, 0x77, - 0xb0, 0x9c, 0x49, 0x06, 0x59, 0xb9, 0xe2, 0xbb, 0xff, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x83, 0x26, - 0x7f, 0x25, 0x25, 0x16, 0x00, 0x00, + // 2004 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x58, 0xcd, 0x73, 0x1b, 0x49, + 0x15, 0xf7, 0x48, 0xb2, 0x2d, 0x3d, 0xf9, 0xb3, 0xe3, 0x24, 0x8a, 0x12, 0x2c, 0x91, 0x5a, 0x20, + 0xa4, 0x16, 0x89, 0x18, 0x6a, 0x6b, 0x93, 0xe5, 0xa3, 0x2c, 0x59, 0x01, 0x81, 0x2b, 0x56, 0xb5, + 0xec, 0x14, 0x50, 0x45, 0x4d, 0xb5, 0x66, 0xda, 0x72, 0xe3, 0xd1, 0xcc, 0xd0, 0x3d, 0xb2, 0xe5, + 0xbd, 0x71, 0xdb, 0xca, 0x69, 0x2f, 0x54, 0x71, 0x49, 0x55, 0xaa, 0xf6, 0xc6, 0x95, 0xe2, 0x1f, + 0x80, 0x4b, 0x38, 0xb1, 0x27, 0x8a, 0x93, 0x97, 0x52, 0x2e, 0x7b, 0xe2, 0xc6, 0x05, 0x2e, 0x54, + 0x7f, 0xcc, 0x8c, 0xa4, 0x78, 0x37, 0x5f, 0x0b, 0x87, 0x3d, 0x59, 0xef, 0xf7, 0xba, 0x7b, 0xde, + 0xd7, 0xef, 0xf5, 0x6b, 0xc3, 0x95, 0x80, 0x13, 0xc7, 0xa3, 0xf5, 0x93, 0x3b, 0x75, 0xfd, 0xab, + 0x16, 0xf2, 0x20, 0x0a, 0x50, 0xc1, 0x48, 0x27, 0x77, 0xca, 0x1b, 0xfd, 0xa0, 0x1f, 0x28, 0xb4, + 0x2e, 0x7f, 0xe9, 0x05, 0xe5, 0x4a, 0x3f, 0x08, 0xfa, 0x1e, 0xad, 0x2b, 0xa9, 0x37, 0x3c, 0xac, + 0x47, 0x6c, 0x40, 0x45, 0x44, 0x06, 0xa1, 0x59, 0xb0, 0xe9, 0x04, 0x62, 0x10, 0x88, 0x7a, 0x8f, + 0x08, 0x79, 0x7c, 0x8f, 0x46, 0xe4, 0x4e, 0xdd, 0x09, 0x98, 0xaf, 0xf5, 0x37, 0xff, 0x65, 0x01, + 0xec, 0x90, 0x88, 0x74, 0x83, 0x21, 0x77, 0x28, 0xda, 0x80, 0xf9, 0xe0, 0xd4, 0xa7, 0xbc, 0x64, + 0x55, 0xad, 0x5b, 0x05, 0xac, 0x05, 0x84, 0x20, 0xe7, 0x93, 0x01, 0x2d, 0x65, 0x14, 0xa8, 0x7e, + 0xa3, 0x2a, 0x14, 0x5d, 0x2a, 0x1c, 0xce, 0xc2, 0x88, 0x05, 0x7e, 0x29, 0xab, 0x54, 0x93, 0x10, + 0x2a, 0x43, 0xfe, 0x90, 0x79, 0x54, 0xed, 0xcc, 0x29, 0x75, 0x22, 0x4b, 0x5d, 0xc4, 0x29, 0x11, + 0x43, 0x7e, 0x56, 0x9a, 0xd7, 0xba, 0x58, 0x46, 0xbf, 0x84, 0xec, 0x21, 0xa5, 0xa5, 0x85, 0x6a, + 0xf6, 0x56, 0x71, 0xeb, 0x5a, 0x4d, 0x3b, 0x50, 0x93, 0x0e, 0xd4, 0x8c, 0x03, 0xb5, 0x66, 0xc0, + 0xfc, 0xc6, 0xb7, 0x9f, 0x9e, 0x57, 0xe6, 0x7e, 0xff, 0x49, 0xe5, 0x56, 0x9f, 0x45, 0x47, 0xc3, + 0x5e, 0xcd, 0x09, 0x06, 0x75, 0xe3, 0xad, 0xfe, 0xf3, 0x2d, 0xe1, 0x1e, 0xd7, 0xa3, 0xb3, 0x90, + 0x0a, 0xb5, 0x41, 0x60, 0x79, 0xee, 0xbd, 0xdc, 0xa7, 0x4f, 0x2a, 0xd6, 0xcd, 0xbf, 0x5a, 0xb0, + 0xb4, 0xa7, 0x82, 0xdb, 0x55, 0x06, 0xff, 0xdf, 0x3c, 0xbf, 0x02, 0x0b, 0xc2, 0x39, 0xa2, 0x03, + 0x62, 0xfc, 0x36, 0x12, 0xba, 0x0b, 0xab, 0x42, 0xe5, 0xc0, 0x76, 0x02, 0x97, 0xda, 0x43, 0xee, + 0x95, 0x16, 0xe4, 0x82, 0xc6, 0xfa, 0xf8, 0xbc, 0xb2, 0xac, 0xd3, 0xd3, 0x0c, 0x5c, 0x7a, 0x80, + 0x77, 0xf1, 0xb2, 0x48, 0x45, 0xee, 0x19, 0x8f, 0xfe, 0x68, 0x01, 0x60, 0x72, 0x8a, 0xe9, 0xaf, + 0x87, 0x54, 0x44, 0xe8, 0xfb, 0x50, 0xa4, 0xa3, 0x88, 0x72, 0x9f, 0x78, 0x36, 0x73, 0x95, 0x57, + 0xb9, 0xc6, 0x8d, 0xf1, 0x79, 0x05, 0x5a, 0x06, 0x6e, 0xef, 0xfc, 0x7b, 0x4a, 0xc2, 0x10, 0x6f, + 0x68, 0xbb, 0xe8, 0x3e, 0xac, 0xb8, 0x24, 0x22, 0xb6, 0xb1, 0x89, 0xb9, 0x2a, 0x04, 0xb9, 0x46, + 0x75, 0x7c, 0x5e, 0x59, 0x4a, 0x0b, 0x46, 0x9d, 0x31, 0x25, 0xe3, 0x25, 0x37, 0x95, 0x5c, 0x19, + 0x0a, 0x87, 0x78, 0x9e, 0xc4, 0x54, 0xa4, 0x96, 0x70, 0x22, 0x1b, 0xbb, 0x7f, 0x63, 0x41, 0x41, + 0xd9, 0x1d, 0x06, 0xfc, 0x8d, 0xcd, 0xbe, 0x0e, 0x05, 0x3a, 0x62, 0x91, 0x8a, 0xa1, 0xb2, 0x78, + 0x19, 0xe7, 0x25, 0x20, 0x43, 0x25, 0x93, 0x39, 0x61, 0x47, 0x6e, 0xc2, 0x86, 0x3f, 0xcf, 0xc3, + 0x62, 0x1c, 0xb8, 0x07, 0xb0, 0xa6, 0x59, 0x67, 0xeb, 0x84, 0xa6, 0x66, 0xbc, 0x35, 0x3e, 0xaf, + 0xac, 0x4c, 0x16, 0x8d, 0x32, 0x65, 0x06, 0xc1, 0x2b, 0xc1, 0xa4, 0x3c, 0x1d, 0x81, 0xcc, 0x74, + 0x04, 0xd0, 0x1d, 0xd8, 0xe0, 0xfa, 0xb3, 0xd4, 0xb5, 0x4f, 0x88, 0xc7, 0x5c, 0x12, 0x05, 0x5c, + 0x94, 0xb2, 0xd5, 0xec, 0xad, 0x02, 0xbe, 0x94, 0xe8, 0x1e, 0x26, 0x2a, 0xe9, 0xe1, 0x80, 0xf9, + 0xb6, 0x13, 0x0c, 0xfd, 0x48, 0x15, 0x57, 0x0e, 0xe7, 0x07, 0xcc, 0x6f, 0x4a, 0x19, 0x7d, 0x0d, + 0x56, 0xcc, 0x1e, 0xfb, 0x88, 0xb2, 0xfe, 0x51, 0xa4, 0x8a, 0x2c, 0x8b, 0x97, 0x0d, 0xfa, 0x63, + 0x05, 0xa2, 0xaf, 0xc2, 0x52, 0xbc, 0x4c, 0xf6, 0x0b, 0x55, 0x68, 0x59, 0x5c, 0x34, 0xd8, 0x3e, + 0x1b, 0x50, 0xf4, 0x4d, 0x28, 0x38, 0x1e, 0xa3, 0xbe, 0x72, 0x7f, 0x51, 0x15, 0xe2, 0xd2, 0xf8, + 0xbc, 0x92, 0x6f, 0x2a, 0xb0, 0xbd, 0x83, 0xf3, 0x5a, 0xdd, 0x76, 0xd1, 0x0f, 0x60, 0x89, 0x93, + 0x53, 0xdb, 0xec, 0x16, 0xa5, 0xbc, 0x22, 0xee, 0xe5, 0x5a, 0xd2, 0xbb, 0x6a, 0x69, 0x59, 0x36, + 0x72, 0x92, 0xb4, 0xb8, 0xc8, 0x13, 0x44, 0xa0, 0xfb, 0x50, 0x64, 0x3d, 0xc7, 0x76, 0x8e, 0x88, + 0xef, 0x53, 0xaf, 0x54, 0xa8, 0x5a, 0x33, 0xdb, 0xdb, 0x8d, 0x66, 0x53, 0x2b, 0x1b, 0x2b, 0xb2, + 0x12, 0x52, 0x19, 0x03, 0xeb, 0x39, 0xe6, 0x37, 0xaa, 0xc8, 0xd2, 0xa1, 0xce, 0x30, 0xa2, 0x76, + 0x9f, 0x88, 0x12, 0xa8, 0xd8, 0x80, 0x81, 0x7e, 0x44, 0x04, 0xea, 0xc0, 0x6a, 0x24, 0x84, 0x4d, + 0x7d, 0xc5, 0x30, 0xd9, 0x18, 0x4a, 0xc5, 0xaa, 0x75, 0x6b, 0x65, 0xea, 0x63, 0x2d, 0xa5, 0xdd, + 0x3f, 0x0b, 0xa9, 0x66, 0xde, 0x7e, 0xb7, 0x9b, 0x42, 0x78, 0x39, 0x12, 0x22, 0x15, 0xd1, 0x0d, + 0x28, 0xc4, 0x39, 0xe2, 0xa5, 0x25, 0xc5, 0xe7, 0x14, 0x40, 0x47, 0x50, 0x38, 0xa4, 0xd4, 0xf6, + 0xd8, 0x80, 0x45, 0xa5, 0xe5, 0x2f, 0xbe, 0x9d, 0xe5, 0x0f, 0x29, 0xdd, 0x95, 0x87, 0x9b, 0x2a, + 0xfe, 0xad, 0x05, 0x0b, 0x86, 0x46, 0x37, 0xa0, 0x90, 0x94, 0x93, 0xe9, 0x68, 0x29, 0x80, 0x6e, + 0xc3, 0x3a, 0xf3, 0xed, 0x1e, 0x3d, 0x0c, 0x38, 0xb5, 0x39, 0x15, 0x81, 0x77, 0xa2, 0xd9, 0x92, + 0xc7, 0xab, 0xcc, 0x6f, 0x28, 0x1c, 0x6b, 0x18, 0xbd, 0x07, 0x45, 0x9d, 0x5d, 0x79, 0xae, 0xae, + 0xcc, 0xe2, 0xd6, 0xc6, 0x6c, 0x72, 0xa5, 0xd2, 0xe4, 0x16, 0x78, 0x0c, 0x08, 0x63, 0xd7, 0x3f, + 0xb3, 0x70, 0x55, 0x93, 0xc4, 0xe4, 0xbc, 0x43, 0x9c, 0x63, 0x1a, 0xc9, 0xae, 0x31, 0x5d, 0x67, + 0xd6, 0xe7, 0xd6, 0xd9, 0x45, 0xc4, 0xcc, 0x7c, 0x41, 0xc4, 0x9c, 0x69, 0x4d, 0x92, 0x65, 0x44, + 0x1c, 0x4f, 0xb3, 0x8c, 0x88, 0x63, 0xcd, 0xb2, 0x29, 0x0a, 0xce, 0xcf, 0x50, 0x70, 0x2a, 0xe9, + 0x0b, 0xff, 0xc3, 0xa4, 0xcb, 0x7a, 0x0f, 0x39, 0x0d, 0x09, 0xd7, 0xf5, 0xbe, 0xa8, 0xeb, 0xdd, + 0x40, 0xb2, 0xde, 0x67, 0x08, 0x91, 0x7f, 0x19, 0x42, 0x14, 0xde, 0x88, 0x10, 0x26, 0xe1, 0x14, + 0x6e, 0x5e, 0x90, 0xef, 0x6d, 0xe7, 0xd8, 0x0f, 0x4e, 0x3d, 0xea, 0xf6, 0xe9, 0x80, 0xfa, 0x11, + 0xba, 0x0b, 0x10, 0x77, 0xa1, 0xa4, 0xc5, 0x96, 0xc7, 0xe7, 0x95, 0x82, 0xd9, 0xa5, 0x92, 0x98, + 0x0a, 0x09, 0xb3, 0xda, 0xae, 0xf9, 0xcc, 0x9f, 0x32, 0x50, 0x8a, 0xbf, 0x23, 0xc2, 0xc0, 0x17, + 0xf4, 0xf5, 0x0a, 0x6b, 0xda, 0x90, 0xcc, 0x2b, 0x18, 0xa2, 0xea, 0xc4, 0x17, 0xa6, 0x14, 0xb2, + 0xa6, 0x4e, 0x7c, 0xa1, 0x4b, 0x61, 0xb6, 0xcd, 0xe6, 0x9e, 0x6f, 0xb3, 0x6a, 0x89, 0x22, 0x9a, + 0x5e, 0x32, 0x1f, 0x2f, 0x51, 0x98, 0x5a, 0xf2, 0x43, 0xd9, 0xd3, 0xf5, 0x12, 0x11, 0x91, 0x68, + 0x28, 0x54, 0xbb, 0x5e, 0xd9, 0x2a, 0x4d, 0x72, 0x50, 0x2f, 0xe8, 0x2a, 0xbd, 0xec, 0xf6, 0x13, + 0xa2, 0x9c, 0x38, 0x38, 0x15, 0x43, 0x2f, 0x52, 0x25, 0xb2, 0x84, 0x8d, 0x64, 0x82, 0xf8, 0xb7, + 0xac, 0x6c, 0x1a, 0x12, 0xf8, 0xf2, 0x71, 0x71, 0x3a, 0xb1, 0x0b, 0xaf, 0x9d, 0xd8, 0xc5, 0x17, + 0x24, 0x36, 0xff, 0xe2, 0xc4, 0x16, 0x5e, 0x26, 0xb1, 0xf0, 0xba, 0x89, 0x2d, 0x5e, 0x90, 0xd8, + 0xbf, 0x58, 0xb0, 0xdc, 0x65, 0x7d, 0x9f, 0xf9, 0x7d, 0x93, 0xdf, 0x5f, 0x01, 0x08, 0x0d, 0xa4, + 0x84, 0xfb, 0xa9, 0x0c, 0x87, 0x59, 0xa6, 0xc2, 0x71, 0x6f, 0xa2, 0x13, 0xf5, 0x88, 0xef, 0xaa, + 0x67, 0x82, 0x13, 0x78, 0x75, 0xe7, 0x88, 0x30, 0xbf, 0x7e, 0xb2, 0x55, 0x1f, 0x29, 0x3c, 0x12, + 0xc2, 0xf4, 0xa5, 0x64, 0x37, 0x2e, 0x98, 0xe3, 0xdb, 0x2e, 0xfa, 0x06, 0xac, 0x52, 0xce, 0x03, + 0xae, 0x26, 0x31, 0x11, 0x12, 0x27, 0x9e, 0xa1, 0x57, 0x14, 0xdc, 0x8c, 0x51, 0xf4, 0x15, 0x80, + 0x74, 0xa1, 0xa1, 0x50, 0x21, 0x59, 0x63, 0x7c, 0x09, 0x61, 0x35, 0x19, 0x81, 0x8c, 0xf3, 0xd7, + 0xa1, 0xc0, 0x84, 0x4d, 0x9c, 0x88, 0x9d, 0x50, 0xe5, 0x4b, 0x1e, 0xe7, 0x99, 0xd8, 0x56, 0x32, + 0xba, 0x07, 0xf3, 0x82, 0xf9, 0xe6, 0x9b, 0xc5, 0xad, 0x72, 0x4d, 0x3f, 0x93, 0x6a, 0xf1, 0x33, + 0xa9, 0xb6, 0x1f, 0x3f, 0x93, 0x1a, 0x79, 0xd9, 0x81, 0x3f, 0xfc, 0xa4, 0x62, 0x61, 0xbd, 0xc5, + 0x7c, 0x71, 0x1b, 0x56, 0xf5, 0x59, 0xc9, 0x77, 0x51, 0x09, 0x16, 0x89, 0xeb, 0x72, 0x2a, 0x84, + 0xb9, 0x51, 0x63, 0x51, 0xbe, 0x1d, 0xc2, 0xe0, 0x94, 0x72, 0x4d, 0x01, 0xac, 0x85, 0x9b, 0x4f, + 0x73, 0xb0, 0xd0, 0x21, 0x9c, 0x0c, 0x04, 0xba, 0x03, 0x97, 0x07, 0x64, 0x64, 0x4f, 0x8c, 0x49, + 0xa6, 0xb2, 0x54, 0x12, 0x30, 0x1a, 0x90, 0x51, 0x3a, 0x23, 0xe9, 0x1a, 0xbb, 0x09, 0xcb, 0x72, + 0x4b, 0x5a, 0xf9, 0xfa, 0xec, 0xe2, 0x80, 0x8c, 0xb6, 0xe3, 0xe2, 0xbf, 0x0d, 0xeb, 0x72, 0x4d, + 0xcc, 0x14, 0x5b, 0xb0, 0xf7, 0xe3, 0x10, 0xae, 0x0e, 0xc8, 0xa8, 0x69, 0xf0, 0x2e, 0x7b, 0x9f, + 0xa2, 0x3a, 0x6c, 0x28, 0x13, 0xd4, 0xcd, 0x6c, 0xa7, 0xcb, 0x35, 0xa1, 0xe4, 0x39, 0xfa, 0xd2, + 0xde, 0x89, 0x37, 0x7c, 0x17, 0xae, 0xd0, 0x51, 0xc8, 0x38, 0x91, 0x4f, 0x1a, 0xbb, 0xe7, 0x05, + 0xce, 0xf1, 0x14, 0xcd, 0x36, 0x52, 0x6d, 0x43, 0x2a, 0xb5, 0x49, 0x6f, 0xc1, 0x8a, 0xbc, 0xe5, + 0xec, 0xe0, 0x94, 0x88, 0x81, 0xba, 0x76, 0x14, 0xed, 0xf0, 0x92, 0x44, 0xf7, 0x24, 0x28, 0x2f, + 0x9e, 0xbb, 0x70, 0x2d, 0xa4, 0x3c, 0x9d, 0x78, 0x93, 0xa8, 0xa4, 0x17, 0xd9, 0x95, 0x90, 0xf2, + 0x24, 0xf6, 0x26, 0x32, 0x72, 0xeb, 0xdb, 0x80, 0x04, 0x19, 0x84, 0x9e, 0xac, 0xe2, 0x88, 0x9f, + 0x19, 0x93, 0xf4, 0xdd, 0xb6, 0x16, 0x6b, 0xf6, 0xf9, 0x99, 0x36, 0xe7, 0x5d, 0x28, 0x99, 0x3e, + 0xc5, 0xe9, 0x29, 0xe1, 0xae, 0x1d, 0x52, 0xee, 0x50, 0x3f, 0x22, 0x7d, 0x4d, 0xc9, 0x1c, 0x36, + 0x4f, 0x6f, 0xac, 0xd4, 0x9d, 0x44, 0x8b, 0xee, 0xc1, 0x35, 0xe6, 0xeb, 0xf2, 0xb2, 0x43, 0xea, + 0x13, 0x2f, 0x3a, 0xb3, 0xdd, 0xa1, 0xf6, 0xd7, 0xcc, 0x96, 0x57, 0xe3, 0x05, 0x1d, 0xad, 0xdf, + 0x31, 0x6a, 0xd4, 0x82, 0x4b, 0x72, 0xa2, 0x8d, 0x9d, 0xa2, 0x3e, 0xe9, 0x79, 0xd4, 0x55, 0x2c, + 0xcd, 0x37, 0x2e, 0x8f, 0xcf, 0x2b, 0xeb, 0xed, 0x46, 0xd3, 0xf8, 0xd4, 0xd2, 0x4a, 0xbc, 0xce, + 0x7a, 0xce, 0x34, 0x74, 0x2f, 0xff, 0xbb, 0x27, 0x95, 0x39, 0x55, 0x8d, 0xef, 0x01, 0xea, 0x50, + 0xdf, 0xd5, 0x54, 0x96, 0x1d, 0x60, 0x97, 0x09, 0x35, 0x00, 0xa4, 0xed, 0x4d, 0x16, 0x65, 0x56, + 0xde, 0xef, 0x49, 0x0f, 0x8b, 0xc7, 0xaf, 0x9f, 0xc0, 0xc4, 0xc4, 0x8c, 0xae, 0xc2, 0xa2, 0xaa, + 0x80, 0xb8, 0xc5, 0xe3, 0x05, 0x29, 0xb6, 0x5d, 0x49, 0x44, 0x33, 0x82, 0xc7, 0xcd, 0xbc, 0x80, + 0x0b, 0x06, 0x49, 0xae, 0xdc, 0x8f, 0x32, 0x70, 0xc9, 0x58, 0xf9, 0x90, 0x72, 0x76, 0xc8, 0x1c, + 0xed, 0xf1, 0xd7, 0x21, 0xaf, 0xfa, 0x43, 0x7a, 0x73, 0x14, 0xc7, 0xe7, 0x95, 0xc5, 0xa6, 0xc4, + 0xda, 0x3b, 0x78, 0x51, 0x29, 0xdb, 0xee, 0xf4, 0x5c, 0x9a, 0x99, 0x9d, 0x4b, 0xa7, 0xfb, 0x75, + 0xf6, 0x55, 0xfa, 0xf5, 0xcc, 0xbb, 0x31, 0xf7, 0xc6, 0xcf, 0xdd, 0xf9, 0xd7, 0x79, 0xee, 0x9a, + 0x28, 0xfd, 0xc1, 0x82, 0x62, 0x87, 0x33, 0x87, 0x9a, 0xc6, 0x2b, 0xdf, 0xfc, 0x67, 0x83, 0x5e, + 0xe0, 0xc5, 0x21, 0xd7, 0x12, 0xda, 0x04, 0x18, 0x0c, 0xbd, 0x88, 0x85, 0x1e, 0x4b, 0x9a, 0xc7, + 0x04, 0x82, 0x56, 0x20, 0x13, 0x8e, 0x0c, 0xa1, 0x33, 0xe1, 0x68, 0x26, 0x3e, 0xb9, 0x57, 0x89, + 0xcf, 0x8b, 0x07, 0x0d, 0xf9, 0x7c, 0x28, 0x27, 0xe3, 0xd4, 0xd0, 0x8b, 0x64, 0x5f, 0x27, 0xd1, + 0x90, 0xd3, 0x3d, 0xee, 0x52, 0xfe, 0x06, 0xe3, 0x1a, 0x7a, 0x07, 0x8a, 0x93, 0x33, 0x66, 0xe6, + 0x73, 0x66, 0x4c, 0x0c, 0x74, 0x62, 0x9a, 0xfc, 0xe0, 0x49, 0x65, 0xee, 0xf6, 0x7f, 0x2c, 0x58, + 0x9e, 0xba, 0x07, 0xd1, 0xf7, 0xa0, 0x82, 0x5b, 0xdd, 0xbd, 0xdd, 0x87, 0x2d, 0xbb, 0xbb, 0xbf, + 0xbd, 0x7f, 0xd0, 0xb5, 0xf7, 0x3a, 0xad, 0x07, 0xf6, 0xc1, 0x83, 0x6e, 0xa7, 0xd5, 0x6c, 0xdf, + 0x6f, 0xb7, 0x76, 0xd6, 0xe6, 0xca, 0x57, 0x1f, 0x3d, 0xae, 0x5e, 0xba, 0x60, 0x19, 0x7a, 0x07, + 0xae, 0xcc, 0xc0, 0xdd, 0x83, 0x66, 0xb3, 0xd5, 0xed, 0xae, 0x59, 0xe5, 0xf2, 0xa3, 0xc7, 0xd5, + 0xcf, 0xd0, 0x5e, 0xb0, 0xef, 0xfe, 0x76, 0x7b, 0xf7, 0x00, 0xb7, 0xd6, 0x32, 0x17, 0xee, 0x33, + 0xda, 0x0b, 0xf6, 0xb5, 0x7e, 0xd6, 0x69, 0xe3, 0xd6, 0xce, 0x5a, 0xf6, 0xc2, 0x7d, 0x46, 0x5b, + 0xce, 0x7d, 0xf0, 0xd1, 0xe6, 0xdc, 0xed, 0x4f, 0x2d, 0x80, 0x89, 0x17, 0xe7, 0xbb, 0x70, 0xb5, + 0xf5, 0xa0, 0xb9, 0xb7, 0xd3, 0xb2, 0xf7, 0x7f, 0xde, 0x69, 0xcd, 0xb8, 0x7c, 0xfd, 0xd1, 0xe3, + 0xea, 0x67, 0xa9, 0xd1, 0xdb, 0xb0, 0x3e, 0xa9, 0xea, 0xe0, 0xbd, 0xfd, 0xbd, 0x35, 0xab, 0x7c, + 0xf9, 0xd1, 0xe3, 0xea, 0xf3, 0x0a, 0xb4, 0x05, 0x1b, 0x93, 0xe0, 0xfd, 0x83, 0xdd, 0x5d, 0x7b, + 0xbb, 0xd1, 0x5e, 0xcb, 0x94, 0x4b, 0x8f, 0x1e, 0x57, 0x2f, 0xd4, 0xcd, 0xda, 0xd6, 0xd9, 0xc6, + 0xfb, 0xed, 0x6d, 0xbd, 0x2d, 0xfb, 0xbc, 0x6d, 0x13, 0x6a, 0xed, 0x6a, 0xa3, 0xfd, 0x74, 0xbc, + 0x69, 0x7d, 0x3c, 0xde, 0xb4, 0xfe, 0x31, 0xde, 0xb4, 0x3e, 0x7c, 0xb6, 0x39, 0xf7, 0xf1, 0xb3, + 0xcd, 0xb9, 0xbf, 0x3f, 0xdb, 0x9c, 0xfb, 0x45, 0xfd, 0x25, 0x86, 0x12, 0xf3, 0x2f, 0x54, 0x35, + 0x93, 0xf4, 0x16, 0xd4, 0x8a, 0xef, 0xfc, 0x37, 0x00, 0x00, 0xff, 0xff, 0x04, 0xe8, 0x27, 0x92, + 0x59, 0x15, 0x00, 0x00, } func (this *DataSource) Equal(that interface{}) bool { @@ -2094,9 +2072,6 @@ func (this *Request) Equal(that interface{}) bool { if this.ExecuteGas != that1.ExecuteGas { return false } - if this.TSSGroupID != that1.TSSGroupID { - return false - } if this.TSSEncodeType != that1.TSSEncodeType { return false } @@ -2196,9 +2171,6 @@ func (this *OracleRequestPacketData) Equal(that interface{}) bool { if this.ExecuteGas != that1.ExecuteGas { return false } - if this.TSSGroupID != that1.TSSGroupID { - return false - } if this.TSSEncodeType != that1.TSSEncodeType { return false } @@ -2775,7 +2747,7 @@ func (m *Request) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintOracle(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x72 + dAtA[i] = 0x6a } } if len(m.Requester) > 0 { @@ -2783,16 +2755,11 @@ func (m *Request) MarshalToSizedBuffer(dAtA []byte) (int, error) { copy(dAtA[i:], m.Requester) i = encodeVarintOracle(dAtA, i, uint64(len(m.Requester))) i-- - dAtA[i] = 0x6a + dAtA[i] = 0x62 } if m.TSSEncodeType != 0 { i = encodeVarintOracle(dAtA, i, uint64(m.TSSEncodeType)) i-- - dAtA[i] = 0x60 - } - if m.TSSGroupID != 0 { - i = encodeVarintOracle(dAtA, i, uint64(m.TSSGroupID)) - i-- dAtA[i] = 0x58 } if m.ExecuteGas != 0 { @@ -2949,11 +2916,6 @@ func (m *OracleRequestPacketData) MarshalToSizedBuffer(dAtA []byte) (int, error) if m.TSSEncodeType != 0 { i = encodeVarintOracle(dAtA, i, uint64(m.TSSEncodeType)) i-- - dAtA[i] = 0x50 - } - if m.TSSGroupID != 0 { - i = encodeVarintOracle(dAtA, i, uint64(m.TSSGroupID)) - i-- dAtA[i] = 0x48 } if m.ExecuteGas != 0 { @@ -3760,9 +3722,6 @@ func (m *Request) Size() (n int) { if m.ExecuteGas != 0 { n += 1 + sovOracle(uint64(m.ExecuteGas)) } - if m.TSSGroupID != 0 { - n += 1 + sovOracle(uint64(m.TSSGroupID)) - } if m.TSSEncodeType != 0 { n += 1 + sovOracle(uint64(m.TSSEncodeType)) } @@ -3836,9 +3795,6 @@ func (m *OracleRequestPacketData) Size() (n int) { if m.ExecuteGas != 0 { n += 1 + sovOracle(uint64(m.ExecuteGas)) } - if m.TSSGroupID != 0 { - n += 1 + sovOracle(uint64(m.TSSGroupID)) - } if m.TSSEncodeType != 0 { n += 1 + sovOracle(uint64(m.TSSEncodeType)) } @@ -5153,25 +5109,6 @@ func (m *Request) Unmarshal(dAtA []byte) error { } } case 11: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TSSGroupID", wireType) - } - m.TSSGroupID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOracle - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TSSGroupID |= github_com_bandprotocol_chain_v2_pkg_tss.GroupID(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 12: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field TSSEncodeType", wireType) } @@ -5190,7 +5127,7 @@ func (m *Request) Unmarshal(dAtA []byte) error { break } } - case 13: + case 12: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Requester", wireType) } @@ -5222,7 +5159,7 @@ func (m *Request) Unmarshal(dAtA []byte) error { } m.Requester = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 14: + case 13: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field FeeLimit", wireType) } @@ -5638,25 +5575,6 @@ func (m *OracleRequestPacketData) Unmarshal(dAtA []byte) error { } } case 9: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TSSGroupID", wireType) - } - m.TSSGroupID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOracle - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TSSGroupID |= github_com_bandprotocol_chain_v2_pkg_tss.GroupID(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 10: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field TSSEncodeType", wireType) } diff --git a/x/oracle/types/packets.go b/x/oracle/types/packets.go index 8fce2e08d..6491c23c2 100644 --- a/x/oracle/types/packets.go +++ b/x/oracle/types/packets.go @@ -3,8 +3,6 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/bandprotocol/chain/v2/pkg/tss" ) // NewOracleRequestPacketData contructs a new OracleRequestPacketData instance @@ -14,7 +12,7 @@ func NewOracleRequestPacketData( calldata []byte, askCount uint64, minCount uint64, - tssGroupID tss.GroupID, + tssEncodeType EncodeType, feeLimit sdk.Coins, prepareGas uint64, executeGas uint64, @@ -25,10 +23,10 @@ func NewOracleRequestPacketData( Calldata: calldata, AskCount: askCount, MinCount: minCount, - TSSGroupID: tssGroupID, FeeLimit: feeLimit, PrepareGas: prepareGas, ExecuteGas: executeGas, + TSSEncodeType: tssEncodeType, } } diff --git a/x/oracle/types/packets_test.go b/x/oracle/types/packets_test.go index 5f8481600..9b1e08f36 100644 --- a/x/oracle/types/packets_test.go +++ b/x/oracle/types/packets_test.go @@ -24,7 +24,6 @@ func TestGetBytesRequestPacket(t *testing.T) { AskCount: 1, MinCount: 1, FeeLimit: sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(10000))), - TSSGroupID: 0, // no require sign by tss module TSSEncodeType: 0, PrepareGas: 100, ExecuteGas: 100, @@ -32,7 +31,7 @@ func TestGetBytesRequestPacket(t *testing.T) { require.Equal( t, []byte( - `{"ask_count":"1","calldata":"AwAAAEJUQ2QAAAAAAAAA","client_id":"test","execute_gas":"100","fee_limit":[{"amount":"10000","denom":"uband"}],"min_count":"1","oracle_script_id":"1","prepare_gas":"100","tss_encode_type":"ENCODE_TYPE_UNSPECIFIED","tss_group_id":"0"}`, + `{"ask_count":"1","calldata":"AwAAAEJUQ2QAAAAAAAAA","client_id":"test","execute_gas":"100","fee_limit":[{"amount":"10000","denom":"uband"}],"min_count":"1","oracle_script_id":"1","prepare_gas":"100","tss_encode_type":"ENCODE_TYPE_UNSPECIFIED"}`, ), req.GetBytes(), ) diff --git a/x/oracle/types/query.pb.go b/x/oracle/types/query.pb.go index ec5068166..ec278e752 100644 --- a/x/oracle/types/query.pb.go +++ b/x/oracle/types/query.pb.go @@ -464,7 +464,7 @@ type QueryRequestResponse struct { Reports []Report `protobuf:"bytes,2,rep,name=reports,proto3" json:"reports"` // Result is a final form of result data Result *Result `protobuf:"bytes,3,opt,name=result,proto3" json:"result,omitempty"` - // Signing is the signing detail in the TSS module. + // Signing is the signing detail in the bandtss module. Signing *SigningResult `protobuf:"bytes,4,opt,name=signing,proto3" json:"signing,omitempty"` } diff --git a/x/oracle/types/request.go b/x/oracle/types/request.go index 4837acf51..61bad8711 100644 --- a/x/oracle/types/request.go +++ b/x/oracle/types/request.go @@ -4,8 +4,6 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/bandprotocol/chain/v2/pkg/tss" ) var ( @@ -23,7 +21,6 @@ type RequestSpec interface { GetPrepareGas() uint64 GetExecuteGas() uint64 GetFeeLimit() sdk.Coins - GetTSSGroupID() tss.GroupID GetTSSEncodeType() EncodeType } @@ -50,7 +47,6 @@ func NewRequest( rawRequests []RawRequest, ibcChannel *IBCChannel, executeGas uint64, - tssGroupID tss.GroupID, tssEncodeType EncodeType, requester string, feeLimit sdk.Coins, @@ -74,7 +70,6 @@ func NewRequest( RawRequests: rawRequests, IBCChannel: ibcChannel, ExecuteGas: executeGas, - TSSGroupID: tssGroupID, TSSEncodeType: tssEncodeType, Requester: requester, FeeLimit: feeLimit, diff --git a/x/oracle/types/signature_order.go b/x/oracle/types/signature_order.go index dbd248e2a..521138ee5 100644 --- a/x/oracle/types/signature_order.go +++ b/x/oracle/types/signature_order.go @@ -1,8 +1,6 @@ package types -import ( - tss "github.com/bandprotocol/chain/v2/x/tss/types" -) +import tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" // signature order types const ( @@ -10,15 +8,16 @@ const ( ) func init() { - tss.RegisterSignatureOrderTypeCodec( + tsstypes.RegisterSignatureOrderTypeCodec( &OracleResultSignatureOrder{}, "oracle/OracleResultSignatureOrder", ) } // Implements Content Interface -var _ tss.Content = &OracleResultSignatureOrder{} +var _ tsstypes.Content = &OracleResultSignatureOrder{} +// NewOracleResultSignatureOrder returns a new OracleResultSignatureOrder object func NewOracleResultSignatureOrder(rid RequestID, encodeType EncodeType) *OracleResultSignatureOrder { return &OracleResultSignatureOrder{RequestID: rid, EncodeType: encodeType} } @@ -33,6 +32,12 @@ func (o *OracleResultSignatureOrder) OrderType() string { // ValidateBasic validates the request's title and description of the request signature func (o *OracleResultSignatureOrder) ValidateBasic() error { - // TODO: Add validatebasic request id and encode type + if o.RequestID == 0 { + return ErrInvalidRequestID + } + + if o.EncodeType == ENCODE_TYPE_UNSPECIFIED { + return ErrInvalidOracleEncodeType + } return nil } diff --git a/x/oracle/types/tx.pb.go b/x/oracle/types/tx.pb.go index 24cc33407..9e2255bae 100644 --- a/x/oracle/types/tx.pb.go +++ b/x/oracle/types/tx.pb.go @@ -7,7 +7,6 @@ import ( bytes "bytes" context "context" fmt "fmt" - github_com_bandprotocol_chain_v2_pkg_tss "github.com/bandprotocol/chain/v2/pkg/tss" _ "github.com/cosmos/cosmos-proto" github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" types "github.com/cosmos/cosmos-sdk/types" @@ -57,10 +56,8 @@ type MsgRequestData struct { ExecuteGas uint64 `protobuf:"varint,8,opt,name=execute_gas,json=executeGas,proto3" json:"execute_gas,omitempty"` // Sender is an account address of message sender. Sender string `protobuf:"bytes,9,opt,name=sender,proto3" json:"sender,omitempty"` - // TSSGroupID is ID of the group that assign for sign the result data on tss module. - TSSGroupID github_com_bandprotocol_chain_v2_pkg_tss.GroupID `protobuf:"varint,10,opt,name=tss_group_id,json=tssGroupId,proto3,casttype=github.com/bandprotocol/chain/v2/pkg/tss.GroupID" json:"tss_group_id,omitempty"` - // TSSEncodeType is the encode type of oracle result that will be sent to TSS. - TSSEncodeType EncodeType `protobuf:"varint,11,opt,name=tss_encode_type,json=tssEncodeType,proto3,enum=oracle.v1.EncodeType" json:"tss_encode_type,omitempty"` + // TSSEncodeType is the encode type of oracle result that will be sent to bandtss. + TSSEncodeType EncodeType `protobuf:"varint,10,opt,name=tss_encode_type,json=tssEncodeType,proto3,enum=oracle.v1.EncodeType" json:"tss_encode_type,omitempty"` } func (m *MsgRequestData) Reset() { *m = MsgRequestData{} } @@ -159,13 +156,6 @@ func (m *MsgRequestData) GetSender() string { return "" } -func (m *MsgRequestData) GetTSSGroupID() github_com_bandprotocol_chain_v2_pkg_tss.GroupID { - if m != nil { - return m.TSSGroupID - } - return 0 -} - func (m *MsgRequestData) GetTSSEncodeType() EncodeType { if m != nil { return m.TSSEncodeType @@ -1100,88 +1090,86 @@ func init() { func init() { proto.RegisterFile("oracle/v1/tx.proto", fileDescriptor_31571edce0094a5d) } var fileDescriptor_31571edce0094a5d = []byte{ - // 1290 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x57, 0x4f, 0x6f, 0x13, 0x47, - 0x14, 0x8f, 0x63, 0xc7, 0xd8, 0xcf, 0x4e, 0x42, 0x16, 0x92, 0x6c, 0x4c, 0xb1, 0x5d, 0x0b, 0x45, - 0x86, 0x0a, 0x2f, 0xa4, 0x55, 0x25, 0xd2, 0x13, 0x0e, 0x94, 0x46, 0x25, 0x14, 0xad, 0xc3, 0x05, - 0xa9, 0x72, 0x27, 0xbb, 0xc3, 0x66, 0x15, 0x7b, 0xc7, 0x9d, 0x19, 0x07, 0x72, 0xed, 0xb1, 0x97, - 0xb6, 0xe7, 0x5e, 0x50, 0x8f, 0x3d, 0x71, 0xe8, 0x57, 0xa8, 0xc4, 0x11, 0xb5, 0x97, 0x9e, 0xdc, - 0xca, 0xa8, 0xa2, 0x9f, 0xa1, 0xa7, 0x6a, 0xfe, 0x78, 0xff, 0x38, 0x4e, 0x42, 0x10, 0xe5, 0x92, - 0xec, 0x7b, 0xbf, 0xf7, 0xde, 0xbc, 0x79, 0xbf, 0xf7, 0x66, 0xc6, 0x60, 0x10, 0x8a, 0x9c, 0x0e, - 0xb6, 0xf6, 0xaf, 0x5b, 0xfc, 0x49, 0xa3, 0x47, 0x09, 0x27, 0x46, 0x5e, 0xe9, 0x1a, 0xfb, 0xd7, - 0x4b, 0xe7, 0x3d, 0xe2, 0x11, 0xa9, 0xb5, 0xc4, 0x97, 0x32, 0x28, 0x2d, 0x45, 0x4e, 0xda, 0x54, - 0xe9, 0xcb, 0x0e, 0x61, 0x5d, 0xc2, 0xac, 0x1d, 0xc4, 0x04, 0xb8, 0x83, 0x39, 0xba, 0x6e, 0x39, - 0xc4, 0x0f, 0x34, 0xbe, 0xa2, 0xf0, 0xb6, 0x0a, 0xa8, 0x04, 0x0d, 0x2d, 0x6b, 0xd7, 0x2e, 0xf3, - 0x44, 0xd8, 0x2e, 0xf3, 0x34, 0xb0, 0x80, 0xba, 0x7e, 0x40, 0x2c, 0xf9, 0x57, 0xa9, 0x6a, 0x3f, - 0xce, 0xc0, 0xdc, 0x16, 0xf3, 0x6c, 0xfc, 0x75, 0x1f, 0x33, 0x7e, 0x0b, 0x71, 0x64, 0xdc, 0x83, - 0xb3, 0x2a, 0x93, 0x36, 0x73, 0xa8, 0xdf, 0xe3, 0x6d, 0xdf, 0x35, 0x53, 0xd5, 0x54, 0x3d, 0xd3, - 0xbc, 0x34, 0x1c, 0x54, 0xe6, 0xbe, 0x90, 0x58, 0x4b, 0x42, 0x9b, 0xb7, 0xfe, 0x3d, 0xa4, 0xb1, - 0xe7, 0x48, 0x5c, 0x76, 0x8d, 0x12, 0xe4, 0x1c, 0xd4, 0xe9, 0xb8, 0x88, 0x23, 0x73, 0xba, 0x9a, - 0xaa, 0x17, 0xed, 0x50, 0x36, 0x2e, 0x40, 0x1e, 0xb1, 0xbd, 0xb6, 0x43, 0xfa, 0x01, 0x37, 0xd3, - 0x62, 0x11, 0x3b, 0x87, 0xd8, 0xde, 0x86, 0x90, 0x05, 0xd8, 0xf5, 0x03, 0x0d, 0x66, 0x14, 0xd8, - 0xf5, 0x03, 0x05, 0x5e, 0x86, 0xbc, 0xd3, 0xf1, 0x71, 0x20, 0xd3, 0x9b, 0xa9, 0xa6, 0xea, 0xf9, - 0x66, 0x71, 0x38, 0xa8, 0xe4, 0x36, 0xa4, 0x72, 0xf3, 0x96, 0x9d, 0x53, 0xf0, 0xa6, 0x6b, 0xec, - 0x42, 0xfe, 0x11, 0xc6, 0xed, 0x8e, 0xdf, 0xf5, 0xb9, 0x99, 0xad, 0xa6, 0xeb, 0x85, 0xb5, 0x95, - 0x86, 0xae, 0x98, 0x28, 0x6f, 0x43, 0x97, 0xb7, 0xb1, 0x41, 0xfc, 0xa0, 0x79, 0xed, 0xf9, 0xa0, - 0x32, 0xf5, 0xf3, 0x9f, 0x95, 0xba, 0xe7, 0xf3, 0xdd, 0xfe, 0x4e, 0xc3, 0x21, 0x5d, 0x5d, 0x5e, - 0xfd, 0xef, 0x2a, 0x73, 0xf7, 0x2c, 0x7e, 0xd0, 0xc3, 0x4c, 0x3a, 0x30, 0x3b, 0xf7, 0x08, 0xe3, - 0xbb, 0x22, 0xb8, 0x51, 0x81, 0x42, 0x8f, 0xe2, 0x1e, 0xa2, 0xb8, 0xed, 0x21, 0x66, 0x9e, 0x91, - 0x39, 0x83, 0x56, 0xdd, 0x41, 0x4c, 0x18, 0xe0, 0x27, 0xd8, 0xe9, 0x73, 0x65, 0x90, 0x53, 0x06, - 0x5a, 0x25, 0x0c, 0xae, 0x41, 0x96, 0xe1, 0xc0, 0xc5, 0xd4, 0xcc, 0xcb, 0x3d, 0x99, 0xbf, 0xfd, - 0x72, 0xf5, 0xbc, 0xce, 0xf5, 0xa6, 0xeb, 0x52, 0xcc, 0x58, 0x8b, 0x53, 0x3f, 0xf0, 0x6c, 0x6d, - 0x67, 0xb8, 0x50, 0xe4, 0x8c, 0xb5, 0x3d, 0x4a, 0xfa, 0x3d, 0x51, 0x0b, 0x90, 0x54, 0x35, 0x87, - 0x83, 0x0a, 0x6c, 0xb7, 0x5a, 0x77, 0x84, 0x5a, 0xd2, 0x74, 0x2d, 0xb6, 0x9f, 0x1d, 0x14, 0xb8, - 0x92, 0x7f, 0x87, 0x74, 0x2c, 0x67, 0x17, 0xf9, 0x81, 0xb5, 0xbf, 0x66, 0xf5, 0xf6, 0x3c, 0x8b, - 0x33, 0xd6, 0xd0, 0x3e, 0x36, 0x70, 0xc6, 0xd4, 0xb7, 0x6b, 0xdc, 0x87, 0x79, 0xb1, 0x0a, 0x0e, - 0x1c, 0xe2, 0xe2, 0xb6, 0xd8, 0xbd, 0x59, 0xa8, 0xa6, 0xea, 0x73, 0x6b, 0x8b, 0x8d, 0xb0, 0xc3, - 0x1b, 0xb7, 0x25, 0xba, 0x7d, 0xd0, 0xc3, 0xcd, 0x85, 0xe1, 0xa0, 0x32, 0xbb, 0xdd, 0x6a, 0x45, - 0x2a, 0x7b, 0x96, 0x33, 0x16, 0x89, 0xeb, 0xb5, 0x7f, 0x9e, 0x56, 0x52, 0xdf, 0xbc, 0x7a, 0x76, - 0x45, 0x6f, 0xe4, 0xdb, 0x57, 0xcf, 0xae, 0xe8, 0xd6, 0xb1, 0x74, 0x3b, 0xd6, 0x4c, 0x58, 0x4a, - 0x36, 0xa7, 0x8d, 0x59, 0x8f, 0x04, 0x0c, 0xd7, 0xfe, 0x4e, 0xc1, 0xac, 0x84, 0x7a, 0x84, 0xaa, - 0xb6, 0xbd, 0x01, 0x40, 0x95, 0x61, 0xd4, 0xb0, 0xa5, 0xe1, 0xa0, 0x92, 0xd7, 0xee, 0xb2, 0x08, - 0x91, 0x60, 0xe7, 0xb5, 0xf5, 0xa6, 0x6b, 0x7c, 0x02, 0x05, 0x8a, 0x1e, 0xb7, 0xa9, 0x0c, 0xc6, - 0xcc, 0x69, 0xd9, 0x22, 0xe7, 0x63, 0x1b, 0xb3, 0xd1, 0x63, 0xb5, 0x52, 0x33, 0x23, 0xba, 0xc3, - 0x06, 0x3a, 0x52, 0x30, 0xe3, 0x63, 0xc8, 0xef, 0xa3, 0x8e, 0xef, 0x22, 0x4e, 0xa8, 0x6c, 0xe1, - 0xe3, 0x48, 0x8b, 0x4c, 0xd7, 0x2f, 0x8d, 0xf6, 0x1f, 0xe9, 0x44, 0x09, 0x66, 0xc3, 0x12, 0x88, - 0xf0, 0xb5, 0x65, 0x58, 0x4c, 0x6c, 0x33, 0x2c, 0xc0, 0x77, 0x69, 0x38, 0xb7, 0xc5, 0xbc, 0x0d, - 0x8a, 0x11, 0xc7, 0x02, 0x69, 0x91, 0x3e, 0x75, 0xb0, 0x61, 0x40, 0x26, 0x40, 0x5d, 0x2c, 0x0b, - 0x90, 0xb7, 0xe5, 0xb7, 0x51, 0x85, 0x82, 0x8b, 0xd5, 0x30, 0xfb, 0x24, 0x90, 0x43, 0x98, 0xb7, - 0xe3, 0x2a, 0xa3, 0x0c, 0xba, 0x09, 0xd1, 0x4e, 0x07, 0xcb, 0x5d, 0x14, 0xed, 0x98, 0xc6, 0xf8, - 0x12, 0xd2, 0x8f, 0x30, 0x36, 0x33, 0x6f, 0x7f, 0x78, 0x44, 0x5c, 0xe3, 0x23, 0xc8, 0x71, 0x8a, - 0x11, 0xeb, 0xd3, 0x03, 0x3d, 0xcb, 0x47, 0x97, 0x30, 0xb4, 0x34, 0x1a, 0x30, 0x43, 0x1e, 0x07, - 0x98, 0x9a, 0xd9, 0x13, 0x5c, 0x94, 0x59, 0x6c, 0xb6, 0xce, 0xbc, 0xde, 0x6c, 0xad, 0x7f, 0x30, - 0xa1, 0x47, 0x97, 0x35, 0x41, 0xe3, 0x95, 0xaf, 0x5d, 0x84, 0x0b, 0x13, 0x08, 0x09, 0x09, 0xfb, - 0x3d, 0x0d, 0x0b, 0x5b, 0xcc, 0xbb, 0xed, 0xfa, 0x3c, 0x46, 0xd7, 0xa7, 0x30, 0x27, 0x0e, 0xc2, - 0x36, 0x93, 0x62, 0xd4, 0xb9, 0xd5, 0xe1, 0xa0, 0x52, 0x8c, 0xec, 0x64, 0xf3, 0x26, 0x64, 0xbb, - 0xe8, 0x46, 0x92, 0x1b, 0xd2, 0x3e, 0x7d, 0x34, 0xed, 0xe9, 0x93, 0x68, 0xcf, 0x1c, 0x45, 0xfb, - 0xcc, 0x3b, 0xa0, 0x3d, 0x7b, 0x7a, 0xda, 0xcf, 0x9c, 0x96, 0xf6, 0xdc, 0x6b, 0xd2, 0x7e, 0x79, - 0x02, 0xed, 0x8b, 0x9a, 0xf6, 0x24, 0x7f, 0xb5, 0x0b, 0xb0, 0x72, 0x88, 0xd4, 0x90, 0xf2, 0x5f, - 0xa7, 0xe5, 0xf4, 0xaa, 0x96, 0x88, 0xdf, 0x92, 0x6f, 0x38, 0xa5, 0x4b, 0x90, 0x65, 0xce, 0x2e, - 0xee, 0x22, 0xcd, 0xa5, 0x96, 0x8c, 0x1b, 0x30, 0xaf, 0xfb, 0x47, 0x9e, 0xce, 0x7d, 0xda, 0x91, - 0x5c, 0xe6, 0xd5, 0x29, 0xac, 0x92, 0xda, 0x20, 0x2e, 0x7e, 0x60, 0xdf, 0xb5, 0x67, 0x59, 0x24, - 0xd2, 0x8e, 0x48, 0x44, 0xf8, 0xc8, 0xa9, 0x2b, 0xda, 0xf2, 0xfb, 0x1d, 0xcc, 0xd5, 0xd5, 0x09, - 0x05, 0x5e, 0x49, 0xcc, 0x55, 0xbc, 0x5a, 0xb5, 0x0a, 0x5c, 0x9c, 0x58, 0xc6, 0xb0, 0xd0, 0x3f, - 0xa8, 0xc3, 0x50, 0xd0, 0x90, 0x28, 0xf3, 0xdb, 0x7e, 0xca, 0xbc, 0xd9, 0x94, 0x45, 0xb4, 0x65, - 0x4e, 0xa2, 0x6d, 0xe6, 0x94, 0xb4, 0x65, 0x27, 0xd1, 0xf6, 0xbf, 0xcd, 0xc5, 0x71, 0xc7, 0xe1, - 0x78, 0xed, 0xf5, 0x71, 0x38, 0xae, 0x0e, 0x29, 0xeb, 0x42, 0x61, 0x8b, 0x79, 0x37, 0x1d, 0xee, - 0xef, 0x23, 0x8e, 0x93, 0xb7, 0x68, 0xea, 0xf5, 0x6f, 0xd1, 0xd5, 0xc9, 0xb7, 0xe8, 0xbc, 0xce, - 0x6a, 0x14, 0xbf, 0xb6, 0x28, 0x1b, 0x64, 0x24, 0x86, 0x59, 0xfc, 0x94, 0x82, 0xf9, 0x2d, 0xe6, - 0x3d, 0xe8, 0xb9, 0x88, 0xe3, 0xfb, 0x88, 0xa2, 0xae, 0xbc, 0xd0, 0x51, 0x9f, 0xef, 0x12, 0xea, - 0xf3, 0x83, 0x93, 0x53, 0x09, 0x4d, 0x0d, 0x0b, 0xb2, 0x3d, 0x19, 0x41, 0xb6, 0x47, 0x61, 0x6d, - 0x21, 0xf6, 0x80, 0x50, 0xa1, 0xf5, 0xeb, 0x41, 0x9b, 0xad, 0xaf, 0xca, 0xbc, 0xc3, 0x00, 0x22, - 0xef, 0x73, 0x3a, 0xef, 0x78, 0x42, 0xb5, 0x15, 0x58, 0x1e, 0xcb, 0x71, 0x94, 0xff, 0xda, 0xd3, - 0x19, 0x48, 0x6f, 0x31, 0xcf, 0xf8, 0x1c, 0x0a, 0xf1, 0x27, 0xfc, 0x4a, 0x6c, 0xe9, 0xe4, 0x03, - 0xaa, 0xf4, 0xfe, 0x91, 0xd0, 0x28, 0xa8, 0xf1, 0x19, 0x40, 0xec, 0x5d, 0x65, 0x8e, 0x3b, 0x8c, - 0x90, 0x52, 0xf5, 0x28, 0x24, 0x8c, 0xf4, 0x10, 0xce, 0x1e, 0x7a, 0xa0, 0x94, 0x93, 0x5e, 0xe3, - 0x78, 0x69, 0xf5, 0x78, 0x3c, 0x8c, 0xbd, 0x0d, 0x73, 0x63, 0x77, 0xe9, 0x7b, 0x49, 0xcf, 0x24, - 0x5a, 0xba, 0x74, 0x1c, 0x1a, 0x46, 0xfd, 0x0a, 0x8c, 0x09, 0xc7, 0x75, 0x75, 0x52, 0x4e, 0x71, - 0x8b, 0x52, 0xfd, 0x24, 0x8b, 0x78, 0x4d, 0x0e, 0x9d, 0x53, 0xe5, 0xc3, 0xb9, 0x25, 0xa2, 0xaf, - 0x1e, 0x8f, 0x87, 0xb1, 0x9b, 0x90, 0x0b, 0x27, 0x6a, 0x29, 0xe9, 0x33, 0xd2, 0x97, 0xca, 0x93, - 0xf5, 0x61, 0x8c, 0x7b, 0x50, 0x4c, 0x8c, 0x43, 0x29, 0x69, 0x1f, 0xc7, 0x4a, 0xb5, 0xa3, 0xb1, - 0x51, 0xbc, 0xe6, 0xe6, 0xf3, 0x61, 0x39, 0xf5, 0x62, 0x58, 0x4e, 0xfd, 0x35, 0x2c, 0xa7, 0xbe, - 0x7f, 0x59, 0x9e, 0x7a, 0xf1, 0xb2, 0x3c, 0xf5, 0xc7, 0xcb, 0xf2, 0xd4, 0x43, 0xeb, 0xc4, 0x5f, - 0x24, 0x4f, 0xf4, 0x6f, 0x62, 0xf5, 0x74, 0xd8, 0xc9, 0x4a, 0x8b, 0x0f, 0xff, 0x0b, 0x00, 0x00, - 0xff, 0xff, 0x62, 0xaf, 0x8d, 0x67, 0x69, 0x0f, 0x00, 0x00, + // 1250 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x57, 0x4d, 0x6f, 0xdb, 0x46, + 0x13, 0x36, 0x2d, 0x59, 0x11, 0x47, 0xb2, 0x1c, 0x33, 0xb1, 0x4d, 0x31, 0x6f, 0x24, 0xbd, 0x42, + 0x60, 0x28, 0x29, 0x22, 0x26, 0x6e, 0x51, 0x20, 0xee, 0x29, 0x72, 0xd2, 0xd6, 0x68, 0x94, 0x06, + 0x74, 0x72, 0x09, 0x50, 0xa8, 0x2b, 0x72, 0x43, 0x13, 0x11, 0x49, 0x95, 0xbb, 0x72, 0xec, 0x6b, + 0x8f, 0xbd, 0xb4, 0xfd, 0x07, 0x41, 0x8f, 0x3d, 0xe5, 0xd0, 0xfe, 0x84, 0x02, 0x39, 0x06, 0xed, + 0xa5, 0x27, 0xb5, 0x90, 0x51, 0xa4, 0xbf, 0xa1, 0xa7, 0x82, 0xbb, 0x2b, 0x7e, 0xc8, 0x92, 0x3f, + 0x82, 0x34, 0x17, 0x9b, 0x33, 0xcf, 0xb3, 0xc3, 0xe1, 0x3c, 0x33, 0xbb, 0x2b, 0x50, 0xfc, 0x00, + 0x99, 0x3d, 0xac, 0xef, 0xdd, 0xd4, 0xe9, 0x7e, 0xb3, 0x1f, 0xf8, 0xd4, 0x57, 0x64, 0xee, 0x6b, + 0xee, 0xdd, 0xd4, 0x2e, 0xda, 0xbe, 0xed, 0x33, 0xaf, 0x1e, 0x3e, 0x71, 0x82, 0xb6, 0x1a, 0x2f, + 0x12, 0x54, 0xee, 0xaf, 0x98, 0x3e, 0x71, 0x7d, 0xa2, 0x77, 0x11, 0x09, 0xc1, 0x2e, 0xa6, 0xe8, + 0xa6, 0x6e, 0xfa, 0x8e, 0x27, 0xf0, 0x32, 0xc7, 0x3b, 0x3c, 0x20, 0x37, 0x04, 0xb4, 0x26, 0x96, + 0xba, 0xc4, 0x0e, 0xc3, 0xba, 0xc4, 0x16, 0xc0, 0x32, 0x72, 0x1d, 0xcf, 0xd7, 0xd9, 0x5f, 0xee, + 0xaa, 0xff, 0x9c, 0x85, 0x52, 0x9b, 0xd8, 0x06, 0xfe, 0x6a, 0x80, 0x09, 0xbd, 0x83, 0x28, 0x52, + 0xee, 0xc3, 0x79, 0x9e, 0x49, 0x87, 0x98, 0x81, 0xd3, 0xa7, 0x1d, 0xc7, 0x52, 0xa5, 0x9a, 0xd4, + 0xc8, 0xb6, 0xae, 0x8c, 0x86, 0xd5, 0xd2, 0xe7, 0x0c, 0xdb, 0x61, 0xd0, 0xf6, 0x9d, 0x7f, 0x8e, + 0x78, 0x8c, 0x92, 0x9f, 0xb4, 0x2d, 0x45, 0x83, 0xbc, 0x89, 0x7a, 0x3d, 0x0b, 0x51, 0xa4, 0xce, + 0xd7, 0xa4, 0x46, 0xd1, 0x88, 0x6c, 0xe5, 0x12, 0xc8, 0x88, 0x3c, 0xed, 0x98, 0xfe, 0xc0, 0xa3, + 0x6a, 0x26, 0x7c, 0x89, 0x91, 0x47, 0xe4, 0xe9, 0x56, 0x68, 0x87, 0xa0, 0xeb, 0x78, 0x02, 0xcc, + 0x72, 0xd0, 0x75, 0x3c, 0x0e, 0x5e, 0x05, 0xd9, 0xec, 0x39, 0xd8, 0x63, 0xe9, 0x2d, 0xd4, 0xa4, + 0x86, 0xdc, 0x2a, 0x8e, 0x86, 0xd5, 0xfc, 0x16, 0x73, 0x6e, 0xdf, 0x31, 0xf2, 0x1c, 0xde, 0xb6, + 0x94, 0x5d, 0x90, 0x9f, 0x60, 0xdc, 0xe9, 0x39, 0xae, 0x43, 0xd5, 0x5c, 0x2d, 0xd3, 0x28, 0x6c, + 0x94, 0x9b, 0xa2, 0x62, 0x61, 0x79, 0x9b, 0xa2, 0xbc, 0xcd, 0x2d, 0xdf, 0xf1, 0x5a, 0x37, 0x5e, + 0x0e, 0xab, 0x73, 0x3f, 0xfe, 0x51, 0x6d, 0xd8, 0x0e, 0xdd, 0x1d, 0x74, 0x9b, 0xa6, 0xef, 0x8a, + 0xf2, 0x8a, 0x7f, 0xd7, 0x89, 0xf5, 0x54, 0xa7, 0x07, 0x7d, 0x4c, 0xd8, 0x02, 0x62, 0xe4, 0x9f, + 0x60, 0x7c, 0x2f, 0x0c, 0xae, 0x54, 0xa1, 0xd0, 0x0f, 0x70, 0x1f, 0x05, 0xb8, 0x63, 0x23, 0xa2, + 0x9e, 0x63, 0x39, 0x83, 0x70, 0x7d, 0x82, 0x48, 0x48, 0xc0, 0xfb, 0xd8, 0x1c, 0x50, 0x4e, 0xc8, + 0x73, 0x82, 0x70, 0x85, 0x84, 0x1b, 0x90, 0x23, 0xd8, 0xb3, 0x70, 0xa0, 0xca, 0xec, 0x9b, 0xd4, + 0x5f, 0x7f, 0xba, 0x7e, 0x51, 0xe4, 0x7a, 0xdb, 0xb2, 0x02, 0x4c, 0xc8, 0x0e, 0x0d, 0x1c, 0xcf, + 0x36, 0x04, 0x4f, 0x79, 0x00, 0x4b, 0x94, 0x90, 0x0e, 0xf6, 0x4c, 0xdf, 0xc2, 0x9d, 0x30, 0x2f, + 0x15, 0x6a, 0x52, 0xa3, 0xb4, 0xb1, 0xd2, 0x8c, 0x7a, 0xaf, 0x79, 0x97, 0xa1, 0x0f, 0x0f, 0xfa, + 0xb8, 0xb5, 0x3c, 0x1a, 0x56, 0x17, 0x1f, 0xee, 0xec, 0xc4, 0x2e, 0x63, 0x91, 0x12, 0x12, 0x9b, + 0x9b, 0xf5, 0xbf, 0x9f, 0x57, 0xa5, 0xaf, 0x5f, 0xbf, 0xb8, 0x26, 0x5e, 0xf1, 0xcd, 0xeb, 0x17, + 0xd7, 0x84, 0xa8, 0xba, 0x68, 0x94, 0xba, 0x0a, 0xab, 0xe9, 0xb6, 0x31, 0x30, 0xe9, 0xfb, 0x1e, + 0xc1, 0xf5, 0xbf, 0x24, 0x58, 0x64, 0x50, 0xdf, 0x0f, 0x78, 0x43, 0xdd, 0x02, 0x08, 0x38, 0x31, + 0x6e, 0x25, 0x6d, 0x34, 0xac, 0xca, 0x62, 0x39, 0xeb, 0xa2, 0xd8, 0x30, 0x64, 0xc1, 0xde, 0xb6, + 0x94, 0x8f, 0xa0, 0x10, 0xa0, 0x67, 0x9d, 0x80, 0x05, 0x23, 0xea, 0x3c, 0x13, 0xef, 0x62, 0xe2, + 0xc3, 0x0c, 0xf4, 0x8c, 0xbf, 0xa9, 0x95, 0x0d, 0x75, 0x33, 0x20, 0x18, 0x3b, 0x88, 0xf2, 0x21, + 0xc8, 0x7b, 0xa8, 0xe7, 0x58, 0x88, 0xfa, 0x01, 0x6b, 0xae, 0xe3, 0xca, 0x19, 0x53, 0x37, 0xaf, + 0x8c, 0xbf, 0x3f, 0xf6, 0x85, 0x25, 0x58, 0x8c, 0x4a, 0x10, 0x86, 0xaf, 0xaf, 0xc1, 0x4a, 0xea, + 0x33, 0xa3, 0x02, 0x7c, 0x9b, 0x81, 0x0b, 0x6d, 0x62, 0x6f, 0x05, 0x18, 0x51, 0x1c, 0x22, 0x3b, + 0xfe, 0x20, 0x30, 0xb1, 0xa2, 0x40, 0xd6, 0x43, 0x2e, 0x66, 0x05, 0x90, 0x0d, 0xf6, 0xac, 0xd4, + 0xa0, 0x60, 0x61, 0x3e, 0x66, 0x8e, 0xef, 0xb1, 0xf1, 0x90, 0x8d, 0xa4, 0x4b, 0xa9, 0x80, 0x68, + 0x0f, 0xd4, 0xed, 0x61, 0xf6, 0x15, 0x45, 0x23, 0xe1, 0x51, 0xbe, 0x80, 0xcc, 0x13, 0x8c, 0xd5, + 0xec, 0xdb, 0x6f, 0xeb, 0x30, 0xae, 0xf2, 0x01, 0xe4, 0x69, 0x80, 0x11, 0x19, 0x04, 0x07, 0x62, + 0xca, 0x66, 0x97, 0x30, 0x62, 0x2a, 0x4d, 0x58, 0xf0, 0x9f, 0x79, 0x38, 0x50, 0x73, 0x27, 0x2c, + 0xe1, 0xb4, 0x44, 0xd7, 0x9f, 0x3b, 0x5d, 0xd7, 0x6f, 0xbe, 0x37, 0xa5, 0x47, 0xd7, 0x84, 0x40, + 0x93, 0x95, 0xaf, 0x5f, 0x86, 0x4b, 0x53, 0x04, 0x89, 0x04, 0xfb, 0x2d, 0x03, 0xcb, 0x6d, 0x62, + 0xdf, 0xb5, 0x1c, 0x9a, 0x90, 0xeb, 0x63, 0x28, 0x85, 0x5b, 0x54, 0x87, 0x30, 0x33, 0xee, 0xdc, + 0xda, 0x68, 0x58, 0x2d, 0xc6, 0x3c, 0xd6, 0xbc, 0x29, 0xdb, 0x28, 0x5a, 0xb1, 0x65, 0x45, 0xb2, + 0xcf, 0xcf, 0x96, 0x3d, 0x73, 0x92, 0xec, 0xd9, 0x59, 0xb2, 0x2f, 0xbc, 0x03, 0xd9, 0x73, 0x67, + 0x97, 0xfd, 0xdc, 0x59, 0x65, 0xcf, 0x9f, 0x52, 0xf6, 0xab, 0x53, 0x64, 0x5f, 0x11, 0xb2, 0xa7, + 0xf5, 0xab, 0x5f, 0x82, 0xf2, 0x11, 0x51, 0x23, 0xc9, 0x7f, 0x99, 0x67, 0xd3, 0xcb, 0x5b, 0x22, + 0x79, 0x7e, 0xbd, 0xe1, 0x94, 0xae, 0x42, 0x8e, 0x98, 0xbb, 0xd8, 0x45, 0x42, 0x4b, 0x61, 0x29, + 0xb7, 0x60, 0x49, 0xf4, 0x0f, 0xdb, 0x9d, 0x07, 0x41, 0x8f, 0x69, 0x29, 0xf3, 0x5d, 0x98, 0x27, + 0xb5, 0xe5, 0x5b, 0xf8, 0x91, 0x71, 0xcf, 0x58, 0x24, 0xb1, 0x19, 0xf4, 0xc2, 0x44, 0xc2, 0x35, + 0x6c, 0xea, 0x8a, 0x06, 0x7b, 0x7e, 0x07, 0x73, 0x75, 0x7d, 0x4a, 0x81, 0xcb, 0xa9, 0xb9, 0x4a, + 0x56, 0xab, 0x5e, 0x85, 0xcb, 0x53, 0xcb, 0x18, 0x15, 0xfa, 0x7b, 0xbe, 0x19, 0x86, 0x32, 0xa4, + 0xca, 0xfc, 0xb6, 0x2f, 0x19, 0x6f, 0x36, 0x65, 0xb1, 0x6c, 0xd9, 0x93, 0x64, 0x5b, 0x38, 0xa3, + 0x6c, 0xb9, 0x69, 0xb2, 0xfd, 0x67, 0x73, 0x71, 0xdc, 0x76, 0x38, 0x59, 0x7b, 0xb1, 0x1d, 0x4e, + 0xba, 0x23, 0xc9, 0x5c, 0x28, 0xb4, 0x89, 0x7d, 0xdb, 0xa4, 0xce, 0x1e, 0xa2, 0x38, 0x7d, 0x8a, + 0x4a, 0xa7, 0x3f, 0x45, 0xd7, 0xa7, 0x9f, 0xa2, 0x4b, 0x22, 0xab, 0x71, 0xfc, 0xfa, 0x0a, 0x6b, + 0x90, 0xb1, 0x19, 0x65, 0xf1, 0x83, 0x04, 0x4b, 0x6d, 0x62, 0x3f, 0xea, 0x5b, 0x88, 0xe2, 0x07, + 0x28, 0x40, 0x2e, 0x3b, 0xd0, 0xd1, 0x80, 0xee, 0xfa, 0x81, 0x43, 0x0f, 0x4e, 0x4e, 0x25, 0xa2, + 0x2a, 0x3a, 0xe4, 0xfa, 0x2c, 0x02, 0x6b, 0x8f, 0xc2, 0xc6, 0x72, 0xe2, 0x02, 0xc1, 0x43, 0x8b, + 0xdb, 0x83, 0xa0, 0x6d, 0xae, 0xb3, 0xbc, 0xa3, 0x00, 0x61, 0xde, 0x17, 0x44, 0xde, 0xc9, 0x84, + 0xea, 0x65, 0x58, 0x9b, 0xc8, 0x71, 0x9c, 0xff, 0xc6, 0xf3, 0x05, 0xc8, 0xb4, 0x89, 0xad, 0x7c, + 0x06, 0x85, 0xe4, 0xe5, 0xba, 0x9c, 0x78, 0x75, 0xfa, 0x02, 0xa5, 0xfd, 0x7f, 0x26, 0x34, 0x0e, + 0xaa, 0x7c, 0x0a, 0x90, 0xb8, 0x57, 0xa9, 0x93, 0x0b, 0xc6, 0x88, 0x56, 0x9b, 0x85, 0x44, 0x91, + 0x1e, 0xc3, 0xf9, 0x23, 0x17, 0x94, 0x4a, 0x7a, 0xd5, 0x24, 0xae, 0xad, 0x1f, 0x8f, 0x47, 0xb1, + 0x1f, 0x42, 0x69, 0xe2, 0x2c, 0xfd, 0x5f, 0x7a, 0x65, 0x1a, 0xd5, 0xae, 0x1c, 0x87, 0x46, 0x51, + 0xbf, 0x04, 0x65, 0xca, 0x76, 0x5d, 0x9b, 0x96, 0x53, 0x92, 0xa1, 0x35, 0x4e, 0x62, 0x24, 0x6b, + 0x72, 0x64, 0x9f, 0xaa, 0x1c, 0xcd, 0x2d, 0x15, 0x7d, 0xfd, 0x78, 0x3c, 0x8a, 0xdd, 0x82, 0x7c, + 0x34, 0x51, 0xab, 0xe9, 0x35, 0x63, 0xbf, 0x56, 0x99, 0xee, 0x8f, 0x62, 0xdc, 0x87, 0x62, 0x6a, + 0x1c, 0xb4, 0x34, 0x3f, 0x89, 0x69, 0xf5, 0xd9, 0xd8, 0x38, 0x5e, 0x6b, 0xfb, 0xe5, 0xa8, 0x22, + 0xbd, 0x1a, 0x55, 0xa4, 0x3f, 0x47, 0x15, 0xe9, 0xbb, 0xc3, 0xca, 0xdc, 0xab, 0xc3, 0xca, 0xdc, + 0xef, 0x87, 0x95, 0xb9, 0xc7, 0x7a, 0xe2, 0xb6, 0xd0, 0x45, 0x9e, 0xc5, 0x7e, 0x2b, 0x9a, 0x7e, + 0x4f, 0x37, 0x77, 0x91, 0xe3, 0xe9, 0x7b, 0x1b, 0xfa, 0xbe, 0xf8, 0xb5, 0xca, 0xaf, 0x0e, 0xdd, + 0x1c, 0x63, 0xbc, 0xff, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xae, 0xe1, 0x07, 0x87, 0x03, 0x0f, + 0x00, 0x00, } func (this *MsgRequestData) Equal(that interface{}) bool { @@ -1235,9 +1223,6 @@ func (this *MsgRequestData) Equal(that interface{}) bool { if this.Sender != that1.Sender { return false } - if this.TSSGroupID != that1.TSSGroupID { - return false - } if this.TSSEncodeType != that1.TSSEncodeType { return false } @@ -1864,11 +1849,6 @@ func (m *MsgRequestData) MarshalToSizedBuffer(dAtA []byte) (int, error) { if m.TSSEncodeType != 0 { i = encodeVarintTx(dAtA, i, uint64(m.TSSEncodeType)) i-- - dAtA[i] = 0x58 - } - if m.TSSGroupID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.TSSGroupID)) - i-- dAtA[i] = 0x50 } if len(m.Sender) > 0 { @@ -2599,9 +2579,6 @@ func (m *MsgRequestData) Size() (n int) { if l > 0 { n += 1 + l + sovTx(uint64(l)) } - if m.TSSGroupID != 0 { - n += 1 + sovTx(uint64(m.TSSGroupID)) - } if m.TSSEncodeType != 0 { n += 1 + sovTx(uint64(m.TSSEncodeType)) } @@ -3151,25 +3128,6 @@ func (m *MsgRequestData) Unmarshal(dAtA []byte) error { m.Sender = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 10: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TSSGroupID", wireType) - } - m.TSSGroupID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TSSGroupID |= github_com_bandprotocol_chain_v2_pkg_tss.GroupID(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 11: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field TSSEncodeType", wireType) } diff --git a/x/tss/README.md b/x/tss/README.md index 6ed9325bf..fc5ae8d3f 100644 --- a/x/tss/README.md +++ b/x/tss/README.md @@ -102,7 +102,7 @@ var ( DEStoreKeyPrefix = []byte{0x0c} DEQueueStoreKeyPrefix = []byte{0x0d} SigningStoreKeyPrefix = []byte{0x0e} - SigCountStoreKeyPrefix = []byte{0x0f} + PartialSignatureCountStoreKeyPrefix = []byte{0x0f} PartialSignatureStoreKeyPrefix = []byte{0x10} ParamsKeyPrefix = []byte{0x11} ) diff --git a/x/tss/client/cli/query.go b/x/tss/client/cli/query.go index b5b941f32..139427e4f 100644 --- a/x/tss/client/cli/query.go +++ b/x/tss/client/cli/query.go @@ -61,7 +61,7 @@ func GetQueryCmdCounts() *cobra.Command { return cmd } -// GetQueryCmdGroup creates a CLI command for Query/Group. +// GetQueryCmdGroup creates a CLI command for querying group information. func GetQueryCmdGroup() *cobra.Command { cmd := &cobra.Command{ Use: "group [id]", @@ -96,7 +96,7 @@ func GetQueryCmdGroup() *cobra.Command { return cmd } -// GetQueryCmdMembers creates a CLI command for Query/Members. +// GetQueryCmdMembers creates a CLI command for querying list of members from the given group ID. func GetQueryCmdMembers() *cobra.Command { cmd := &cobra.Command{ Use: "members [group-id]", @@ -131,7 +131,7 @@ func GetQueryCmdMembers() *cobra.Command { return cmd } -// GetQueryCmdIsGrantee creates a CLI command for Query/IsGrantee. +// GetQueryCmdIsGrantee creates a CLI command for query whether the grantee is granted by a granter. func GetQueryCmdIsGrantee() *cobra.Command { cmd := &cobra.Command{ Use: "is-grantee [granter_address] [grantee_address]", @@ -192,7 +192,7 @@ func GetQueryCmdDE() *cobra.Command { return cmd } -// GetQueryCmdPendingSignings creates a CLI command for Query/PendingSignings. +// GetQueryCmdPendingSignings creates a CLI command for querying pending signings of the given address. func GetQueryCmdPendingSignings() *cobra.Command { cmd := &cobra.Command{ Use: "pending-signings [address]", @@ -222,7 +222,7 @@ func GetQueryCmdPendingSignings() *cobra.Command { return cmd } -// GetQueryCmdSigning creates a CLI command for Query/Signing. +// GetQueryCmdSigning creates a CLI command for querying signing information from the given ID. func GetQueryCmdSigning() *cobra.Command { cmd := &cobra.Command{ Use: "signing [id]", diff --git a/x/tss/client/cli/tx.go b/x/tss/client/cli/tx.go index 34a22b410..0a7dacd29 100644 --- a/x/tss/client/cli/tx.go +++ b/x/tss/client/cli/tx.go @@ -20,7 +20,6 @@ import ( const ( flagExpiration = "expiration" - flagFeeLimit = "fee-limit" ) // GetTxCmd returns a root CLI command handler for all x/tss transaction commands. @@ -61,7 +60,7 @@ $ %s tx tss add-grantees band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun band1m5lq9u version.AppName, ), ), - RunE: grant.AddGranteeCmd(types.GetTSSGrantMsgTypes(), flagExpiration), + RunE: grant.AddGranteeCmd(types.TSSGrantMsgTypes, flagExpiration), } cmd.Flags(). @@ -85,7 +84,7 @@ $ %s tx tss remove-grantees band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun band1m5l version.AppName, ), ), - RunE: grant.RemoveGranteeCmd(types.GetTSSGrantMsgTypes()), + RunE: grant.RemoveGranteeCmd(types.TSSGrantMsgTypes), } flags.AddTxFlagsToCmd(cmd) @@ -93,7 +92,7 @@ $ %s tx tss remove-grantees band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun band1m5l return cmd } -// GetTxCmdSubmitDKGRound1 creates a CLI command for CLI command for Msg/SubmitDKGRound1. +// GetTxCmdSubmitDKGRound1 creates a CLI command for submitting DKG round 1 information. func GetTxCmdSubmitDKGRound1() *cobra.Command { cmd := &cobra.Command{ Use: "submit-dkg-round1 [group_id] [member_id] [one_time_pub_key] [a0_sign] [one_time_sign] [coefficients-commit1] [coefficients-commit2] ...", @@ -169,7 +168,7 @@ func GetTxCmdSubmitDKGRound1() *cobra.Command { return cmd } -// GetTxCmdSubmitDKGRound2 creates a CLI command for CLI command for Msg/SubmitDKGRound2. +// GetTxCmdSubmitDKGRound2 creates a CLI command for submitting DKG round 2 information. func GetTxCmdSubmitDKGRound2() *cobra.Command { cmd := &cobra.Command{ Use: "submit-dkg-round2 [group_id] [member_id] [encrypted-secret-share1,encrypted-secret-share2,...]", @@ -224,7 +223,7 @@ func GetTxCmdSubmitDKGRound2() *cobra.Command { return cmd } -// GetTxCmdComplain creates a CLI command for CLI command for Msg/Complaint. +// GetTxCmdComplain creates a CLI command for submitting complaint message. func GetTxCmdComplain() *cobra.Command { cmd := &cobra.Command{ Use: "complain [group_id] [complaints-json-file]", @@ -278,7 +277,7 @@ Where complaints.json contains: return cmd } -// GetTxCmdConfirm creates a CLI command for CLI command for Msg/Confirm. +// GetTxCmdConfirm creates a CLI command for submitting confirm message. func GetTxCmdConfirm() *cobra.Command { cmd := &cobra.Command{ Use: "confirm [group_id] [member_id] [own_pub_key_sig]", @@ -324,7 +323,7 @@ func GetTxCmdConfirm() *cobra.Command { return cmd } -// GetTxCmdSubmitDEs creates a CLI command for CLI command for Msg/SubmitDEPairs. +// GetTxCmdSubmitDEs creates a CLI command for submitting DE message. func GetTxCmdSubmitDEs() *cobra.Command { cmd := &cobra.Command{ Use: "submit-multi-de [d,e] [d,e] ...", @@ -373,7 +372,7 @@ func GetTxCmdSubmitDEs() *cobra.Command { return cmd } -// GetTxCmdSubmitSignature creates a CLI command for CLI command for Msg/SubmitSignature. +// GetTxCmdSubmitSignature creates a CLI command for submitting a signature. func GetTxCmdSubmitSignature() *cobra.Command { cmd := &cobra.Command{ Use: "submit-signature [signing_id] [member_id] [signature]", diff --git a/x/tss/client/cli/utils.go b/x/tss/client/cli/utils.go index b9bb77825..241161697 100644 --- a/x/tss/client/cli/utils.go +++ b/x/tss/client/cli/utils.go @@ -3,65 +3,10 @@ package cli import ( "encoding/json" "os" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/authz" "github.com/bandprotocol/chain/v2/x/tss/types" ) -// combineGrantMsgs combines multiple grant messages into a single slice of messages. -func combineGrantMsgs( - granter sdk.AccAddress, - grantee sdk.AccAddress, - msgGrants []string, - expiration *time.Time, -) ([]sdk.Msg, error) { - msgs := []sdk.Msg{} - - for _, msgGrant := range msgGrants { - msg, err := authz.NewMsgGrant( - granter, - grantee, - authz.NewGenericAuthorization(msgGrant), - expiration, - ) - if err != nil { - return nil, err - } - - if err = msg.ValidateBasic(); err != nil { - return nil, err - } - - msgs = append(msgs, msg) - } - - return msgs, nil -} - -// combineRevokeMsgs combines multiple revoke messages into a single slice of messages. -func combineRevokeMsgs(granter sdk.AccAddress, grantee sdk.AccAddress, msgRevokes []string) ([]sdk.Msg, error) { - msgs := []sdk.Msg{} - - for _, msgRevoke := range msgRevokes { - msg := authz.NewMsgRevoke( - granter, - grantee, - msgRevoke, - ) - - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - msgs = append(msgs, &msg) - } - - return msgs, nil -} - type Complaints struct { Complaints []types.Complaint `json:"complaints"` } diff --git a/x/tss/client/cli/utils_test.go b/x/tss/client/cli/utils_test.go index 83795e929..5eb06c221 100644 --- a/x/tss/client/cli/utils_test.go +++ b/x/tss/client/cli/utils_test.go @@ -3,60 +3,13 @@ package cli import ( "os" "testing" - "time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/authz" "github.com/stretchr/testify/require" "github.com/bandprotocol/chain/v2/pkg/tss/testutil" "github.com/bandprotocol/chain/v2/x/tss/types" ) -func TestCombineGrantMsgs(t *testing.T) { - granter := sdk.AccAddress([]byte("granter")) - grantee := sdk.AccAddress([]byte("grantee")) - msgGrants := types.GetTSSGrantMsgTypes() - expiration := time.Now() - - msgs, err := combineGrantMsgs(granter, grantee, msgGrants, &expiration) - require.NoError(t, err) - require.Len(t, msgs, len(msgGrants)) - - for i, msg := range msgs { - // cast type - msgGrant, ok := msg.(*authz.MsgGrant) - require.True(t, ok) - - authorization, err := msgGrant.GetAuthorization() - require.NoError(t, err) - - require.Equal(t, msgGrants[i], authorization.MsgTypeURL()) - require.Equal(t, granter.String(), msgGrant.Granter) - require.Equal(t, grantee.String(), msgGrant.Grantee) - require.Equal(t, expiration, *msgGrant.Grant.Expiration) - } -} - -func TestCombineRevokeMsgs(t *testing.T) { - granter := sdk.AccAddress([]byte("granter")) - grantee := sdk.AccAddress([]byte("grantee")) - msgRevokes := []string{"revoke1", "revoke2"} - - msgs, err := combineRevokeMsgs(granter, grantee, msgRevokes) - require.NoError(t, err) - require.Len(t, msgs, len(msgRevokes)) - - for i, msg := range msgs { - // cast type - msgRevoke, ok := msg.(*authz.MsgRevoke) - require.True(t, ok) - require.Equal(t, granter.String(), msgRevoke.Granter) - require.Equal(t, grantee.String(), msgRevoke.Grantee) - require.Equal(t, msgRevokes[i], msgRevoke.MsgTypeUrl) - } -} - func TestParseComplaints(t *testing.T) { // 1. Test with empty string complaints, err := parseComplaints("") diff --git a/x/tss/client/signature_order_handler.go b/x/tss/client/signature_order_handler.go deleted file mode 100644 index 1b351cfae..000000000 --- a/x/tss/client/signature_order_handler.go +++ /dev/null @@ -1,20 +0,0 @@ -package client - -import ( - "github.com/spf13/cobra" -) - -// function to create the cli handler -type CLIHandlerFn func() *cobra.Command - -// SignatureOrderHandler wraps CLIHandlerFn -type SignatureOrderHandler struct { - CLIHandler CLIHandlerFn -} - -// NewSignatureOrderHandler creates a new SignatureOrderHandler object -func NewSignatureOrderHandler(cliHandler CLIHandlerFn) SignatureOrderHandler { - return SignatureOrderHandler{ - CLIHandler: cliHandler, - } -} diff --git a/x/tss/genesis.go b/x/tss/genesis.go index d8968f7ee..f605de087 100644 --- a/x/tss/genesis.go +++ b/x/tss/genesis.go @@ -1,6 +1,8 @@ package tss import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bandprotocol/chain/v2/x/tss/keeper" @@ -18,22 +20,33 @@ func InitGenesis(ctx sdk.Context, k *keeper.Keeper, data *types.GenesisState) { k.SetGroup(ctx, group) } - for _, member := range data.Members { - k.SetMember(ctx, member) - } + k.SetMembers(ctx, data.Members) k.SetSigningCount(ctx, data.SigningCount) for _, signing := range data.Signings { k.SetSigning(ctx, signing) } - for _, deq := range data.DEQueues { - k.SetDEQueue(ctx, deq) + desMapping := make(map[string][]types.DE) + for _, deq := range data.DEsGenesis { + desMapping[deq.Address] = append(desMapping[deq.Address], deq.DE) } - for _, de := range data.DEsGenesis { - address := sdk.MustAccAddressFromBech32(de.Address) - k.SetDE(ctx, address, de.Index, de.DE) + for addr, des := range desMapping { + if uint64(len(des)) > data.Params.MaxDESize { + panic(fmt.Sprintf("DEsGenesis of %s size exceeds MaxDESize", addr)) + } + + k.SetDEQueue(ctx, types.DEQueue{ + Address: addr, + Head: 0, + Tail: uint64(len(des)), + }) + + acc := sdk.MustAccAddressFromBech32(addr) + for i, de := range des { + k.SetDE(ctx, acc, uint64(i), de) + } } } @@ -46,7 +59,6 @@ func ExportGenesis(ctx sdk.Context, k *keeper.Keeper) *types.GenesisState { Members: k.GetMembers(ctx), SigningCount: k.GetSigningCount(ctx), Signings: k.GetSignings(ctx), - DEQueues: k.GetDEQueues(ctx), DEsGenesis: k.GetDEsGenesis(ctx), } } diff --git a/x/tss/genesis_test.go b/x/tss/genesis_test.go new file mode 100644 index 000000000..094bac66b --- /dev/null +++ b/x/tss/genesis_test.go @@ -0,0 +1,87 @@ +package tss_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + bandtesting "github.com/bandprotocol/chain/v2/testing" + "github.com/bandprotocol/chain/v2/x/tss" + "github.com/bandprotocol/chain/v2/x/tss/testutil" + "github.com/bandprotocol/chain/v2/x/tss/types" +) + +func TestExportGenesis(t *testing.T) { + s := testutil.NewTestSuite(t) + ctx, k := s.Ctx, s.Keeper + + addr1 := bandtesting.Alice.Address + addr2 := bandtesting.Bob.Address + + data := types.GenesisState{ + Params: types.DefaultParams(), + GroupCount: 1, + Groups: []types.Group{ + { + ID: 1, + Size_: 1, + Threshold: 1, + PubKey: nil, + Status: types.GROUP_STATUS_ROUND_1, + }, + }, + Members: []types.Member{ + { + ID: 1, + GroupID: 1, + Address: addr1.String(), + PubKey: nil, + IsMalicious: false, + IsActive: true, + }, + }, + SigningCount: 0, + Signings: []types.Signing{}, + DEsGenesis: []types.DEGenesis{ + { + Address: addr1.String(), + DE: types.DE{ + PubD: []byte("pubD"), + PubE: []byte("pubE"), + }, + }, + { + Address: addr1.String(), + DE: types.DE{ + PubD: []byte("pubD2"), + PubE: []byte("pubE2"), + }, + }, + { + Address: addr2.String(), + DE: types.DE{ + PubD: []byte("pubD3"), + PubE: []byte("pubE3"), + }, + }, + }, + } + + tss.InitGenesis(ctx, k, &data) + + exported := tss.ExportGenesis(ctx, k) + require.Equal(t, data.Params, exported.Params) + require.Equal(t, data.DEsGenesis, exported.DEsGenesis) + + require.Equal(t, uint64(2), k.GetDECount(ctx, addr1)) + de, err := k.GetDE(ctx, addr1, 1) + require.NoError(t, err) + require.Equal( + t, + types.DE{ + PubD: []byte("pubD2"), + PubE: []byte("pubE2"), + }, + de, + ) +} diff --git a/x/tss/keeper/de.go b/x/tss/keeper/de.go index ec9c0371b..fc1519ee9 100644 --- a/x/tss/keeper/de.go +++ b/x/tss/keeper/de.go @@ -3,8 +3,8 @@ package keeper import ( "fmt" - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/bandprotocol/chain/v2/x/tss/types" ) @@ -51,10 +51,10 @@ func (k Keeper) GetDEQueues(ctx sdk.Context) []types.DEQueue { // GetDECount retrieves the current count of DE for a given address from the context's KVStore. func (k Keeper) GetDECount(ctx sdk.Context, address sdk.AccAddress) uint64 { deQueue := k.GetDEQueue(ctx, address) - if deQueue.Head <= deQueue.Tail { return deQueue.Tail - deQueue.Head } + return k.GetParams(ctx).MaxDESize - (deQueue.Head - deQueue.Tail) } @@ -68,8 +68,7 @@ func (k Keeper) SetDE(ctx sdk.Context, address sdk.AccAddress, index uint64, de func (k Keeper) GetDE(ctx sdk.Context, address sdk.AccAddress, index uint64) (types.DE, error) { bz := ctx.KVStore(k.storeKey).Get(types.DEIndexStoreKey(address, index)) if bz == nil { - return types.DE{}, errors.Wrapf( - types.ErrDENotFound, + return types.DE{}, types.ErrDENotFound.Wrapf( "failed to get DE with address %s index %d", address, index, @@ -98,10 +97,9 @@ func (k Keeper) GetDEsGenesis(ctx sdk.Context) []types.DEGenesis { for ; iterator.Valid(); iterator.Next() { var de types.DE k.cdc.MustUnmarshal(iterator.Value(), &de) - address, index := types.AddressAndIndexFromDEStoreKey(iterator.Key()) + address, _ := types.AddressAndIndexFromDEStoreKey(iterator.Key()) des = append(des, types.DEGenesis{ Address: address.String(), - Index: index, DE: de, }) } @@ -151,38 +149,26 @@ func (k Keeper) PollDE(ctx sdk.Context, address sdk.AccAddress) (types.DE, error return de, nil } -// HandleAssignedMembersPollDE function handles the polling of DE for the assigned members. -// It takes a list of member IDs (mids) and members information (members) and returns the assigned members. -func (k Keeper) HandleAssignedMembersPollDE( - ctx sdk.Context, - members []types.Member, -) (types.AssignedMembers, error) { - var assignedMembers types.AssignedMembers +// PollDEs handles the polling of DE from the selected members. It takes a list of member IDs (mids) +// and members information (members) and returns the list of selected DEs ordered by selected members. +func (k Keeper) PollDEs(ctx sdk.Context, members []types.Member) ([]types.DE, error) { + des := make([]types.DE, 0, len(members)) for _, member := range members { // Convert the address from Bech32 format to AccAddress format accMember, err := sdk.AccAddressFromBech32(member.Address) if err != nil { - return nil, types.ErrInvalidAccAddressFormat.Wrapf("invalid account address: %s", err) + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid account address: %s", err) } de, err := k.PollDE(ctx, accMember) if err != nil { return nil, err } - - assignedMembers = append(assignedMembers, types.AssignedMember{ - MemberID: member.ID, - Address: member.Address, - PubKey: member.PubKey, - PubD: de.PubD, - PubE: de.PubE, - BindingFactor: nil, - PubNonce: nil, - }) + des = append(des, de) } - return assignedMembers, nil + return des, nil } // FilterMembersHaveDEs function retrieves all members that have DEs in the store. @@ -192,10 +178,7 @@ func (k Keeper) FilterMembersHaveDE(ctx sdk.Context, members []types.Member) ([] // Convert the address from Bech32 format to AccAddress format accMember, err := sdk.AccAddressFromBech32(member.Address) if err != nil { - return nil, errors.Wrapf( - types.ErrInvalidAccAddressFormat, - "invalid account address: %s", err, - ) + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid account address: %s", err) } count := k.GetDECount(ctx, accMember) diff --git a/x/tss/keeper/de_test.go b/x/tss/keeper/de_test.go index 55c58f83d..eb8ba2c07 100644 --- a/x/tss/keeper/de_test.go +++ b/x/tss/keeper/de_test.go @@ -113,7 +113,6 @@ func (s *KeeperTestSuite) TestGetDEsGenesis() { if q.Address == string(address) { s.Require().Equal(types.DEGenesis{ Address: address.String(), - Index: index, DE: de, }, q) } @@ -246,24 +245,16 @@ func (s *KeeperTestSuite) TestHandlePollDEForAssignedMembers() { s.Require().NoError(err) } - assignedMembers, err := k.HandleAssignedMembersPollDE(ctx, members) + des, err := k.PollDEs(ctx, members) s.Require().NoError(err) - s.Require().Equal(types.AssignedMembers{ + s.Require().Equal([]types.DE{ { - MemberID: 1, - Address: members[0].Address, - PubD: des[0].PubD, - PubE: des[0].PubE, - BindingFactor: nil, - PubNonce: nil, + PubD: des[0].PubD, + PubE: des[0].PubE, }, { - MemberID: 2, - Address: members[1].Address, - PubD: des[0].PubD, - PubE: des[0].PubE, - BindingFactor: nil, - PubNonce: nil, + PubD: des[0].PubD, + PubE: des[0].PubE, }, - }, assignedMembers) + }, des) } diff --git a/x/tss/keeper/groups.go b/x/tss/keeper/groups.go index e50a06ba1..db561c78f 100644 --- a/x/tss/keeper/groups.go +++ b/x/tss/keeper/groups.go @@ -10,6 +10,100 @@ import ( "github.com/bandprotocol/chain/v2/x/tss/types" ) +// SetGroupCount sets the number of group count to the given value. +func (k Keeper) SetGroupCount(ctx sdk.Context, count uint64) { + ctx.KVStore(k.storeKey).Set(types.GroupCountStoreKey, sdk.Uint64ToBigEndian(count)) +} + +// GetGroupCount returns the current number of all groups ever existed. +func (k Keeper) GetGroupCount(ctx sdk.Context) uint64 { + return sdk.BigEndianToUint64(ctx.KVStore(k.storeKey).Get(types.GroupCountStoreKey)) +} + +// GetNextGroupID increments the group count and returns the current number of groups. +func (k Keeper) GetNextGroupID(ctx sdk.Context) tss.GroupID { + groupNumber := k.GetGroupCount(ctx) + k.SetGroupCount(ctx, groupNumber+1) + return tss.GroupID(groupNumber + 1) +} + +// CreateNewGroup creates a new group in the store and returns the id of the group. +func (k Keeper) CreateNewGroup(ctx sdk.Context, group types.Group) tss.GroupID { + group.ID = k.GetNextGroupID(ctx) + group.CreatedHeight = uint64(ctx.BlockHeight()) + k.SetGroup(ctx, group) + + return group.ID +} + +// GetGroup retrieves a group from the store. +func (k Keeper) GetGroup(ctx sdk.Context, groupID tss.GroupID) (types.Group, error) { + bz := ctx.KVStore(k.storeKey).Get(types.GroupStoreKey(groupID)) + if bz == nil { + return types.Group{}, types.ErrGroupNotFound.Wrapf("failed to get group with groupID: %d", groupID) + } + + group := types.Group{} + k.cdc.MustUnmarshal(bz, &group) + return group, nil +} + +// MustGetGroup returns the group for the given ID. Panics error if not exists. +func (k Keeper) MustGetGroup(ctx sdk.Context, groupID tss.GroupID) types.Group { + group, err := k.GetGroup(ctx, groupID) + if err != nil { + panic(err) + } + return group +} + +// SetGroup set a group in the store. +func (k Keeper) SetGroup(ctx sdk.Context, group types.Group) { + ctx.KVStore(k.storeKey).Set(types.GroupStoreKey(group.ID), k.cdc.MustMarshal(&group)) +} + +// GetGroupsIterator gets an iterator all group. +func (k Keeper) GetGroupsIterator(ctx sdk.Context) sdk.Iterator { + return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.GroupStoreKeyPrefix) +} + +// GetGroups retrieves all group of the store. +func (k Keeper) GetGroups(ctx sdk.Context) []types.Group { + var groups []types.Group + iterator := k.GetGroupsIterator(ctx) + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var group types.Group + k.cdc.MustUnmarshal(iterator.Value(), &group) + groups = append(groups, group) + } + return groups +} + +// DeleteGroup removes the group from the store. +func (k Keeper) DeleteGroup(ctx sdk.Context, groupID tss.GroupID) { + ctx.KVStore(k.storeKey).Delete(types.GroupStoreKey(groupID)) +} + +// SetDKGContext sets DKG context for a group in the store. +func (k Keeper) SetDKGContext(ctx sdk.Context, groupID tss.GroupID, dkgContext []byte) { + ctx.KVStore(k.storeKey).Set(types.DKGContextStoreKey(groupID), dkgContext) +} + +// GetDKGContext retrieves DKG context of a group from the store. +func (k Keeper) GetDKGContext(ctx sdk.Context, groupID tss.GroupID) ([]byte, error) { + bz := ctx.KVStore(k.storeKey).Get(types.DKGContextStoreKey(groupID)) + if bz == nil { + return nil, types.ErrDKGContextNotFound.Wrapf("failed to get dkg-context with groupID: %d", groupID) + } + return bz, nil +} + +// DeleteDKGContext removes the DKG context data of a group from the store. +func (k Keeper) DeleteDKGContext(ctx sdk.Context, groupID tss.GroupID) { + ctx.KVStore(k.storeKey).Delete(types.DKGContextStoreKey(groupID)) +} + // CreateGroup creates a new group with the given members and threshold. func (k Keeper) CreateGroup( ctx sdk.Context, diff --git a/x/tss/keeper/groups_endblock.go b/x/tss/keeper/groups_endblock.go new file mode 100644 index 000000000..08a831d62 --- /dev/null +++ b/x/tss/keeper/groups_endblock.go @@ -0,0 +1,182 @@ +package keeper + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/bandprotocol/chain/v2/x/tss/types" +) + +// ===================================== +// Process fully-submitted group creation message +// ===================================== + +// AddPendingProcessGroup adds a new pending process group to the store. +func (k Keeper) AddPendingProcessGroup(ctx sdk.Context, groupID tss.GroupID) { + pgs := k.GetPendingProcessGroups(ctx) + pgs = append(pgs, groupID) + k.SetPendingProcessGroups(ctx, types.PendingProcessGroups{ + GroupIDs: pgs, + }) +} + +// SetPendingProcessGroups sets the given pending process groups in the store. +func (k Keeper) SetPendingProcessGroups(ctx sdk.Context, pgs types.PendingProcessGroups) { + ctx.KVStore(k.storeKey).Set(types.PendingProcessGroupsStoreKey, k.cdc.MustMarshal(&pgs)) +} + +// GetPendingProcessGroups retrieves the list of pending process groups from the store. +// It returns an empty list if the key does not exist in the store. +func (k Keeper) GetPendingProcessGroups(ctx sdk.Context) []tss.GroupID { + bz := ctx.KVStore(k.storeKey).Get(types.PendingProcessGroupsStoreKey) + if len(bz) == 0 { + // Return an empty list if the key does not exist in the store. + return []tss.GroupID{} + } + pgs := types.PendingProcessGroups{} + k.cdc.MustUnmarshal(bz, &pgs) + return pgs.GroupIDs +} + +// HandleProcessGroup handles the pending process group based on its status. +// It updates the group status and emits appropriate events. +func (k Keeper) HandleProcessGroup(ctx sdk.Context, groupID tss.GroupID) { + group := k.MustGetGroup(ctx, groupID) + switch group.Status { + case types.GROUP_STATUS_ROUND_1: + group.Status = types.GROUP_STATUS_ROUND_2 + group.PubKey = k.GetAccumulatedCommit(ctx, groupID, 0) + k.SetGroup(ctx, group) + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeRound1Success, + sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), + sdk.NewAttribute(types.AttributeKeyStatus, group.Status.String()), + ), + ) + case types.GROUP_STATUS_ROUND_2: + group.Status = types.GROUP_STATUS_ROUND_3 + k.SetGroup(ctx, group) + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeRound2Success, + sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), + sdk.NewAttribute(types.AttributeKeyStatus, group.Status.String()), + ), + ) + case types.GROUP_STATUS_FALLEN: + group.Status = types.GROUP_STATUS_FALLEN + k.SetGroup(ctx, group) + + // Handle the hooks when group creation is fallen; this shouldn't return any error. + if err := k.Hooks().AfterCreatingGroupFailed(ctx, group); err != nil { + panic(err) + } + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeRound3Failed, + sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), + sdk.NewAttribute(types.AttributeKeyStatus, group.Status.String()), + ), + ) + case types.GROUP_STATUS_ROUND_3: + // Get members to check malicious + members := k.MustGetMembers(ctx, group.ID) + if !types.Members(members).HaveMalicious() { + group.Status = types.GROUP_STATUS_ACTIVE + k.SetGroup(ctx, group) + + // Handle the hooks when group is ready. this shouldn't return any error. + if err := k.Hooks().AfterCreatingGroupCompleted(ctx, group); err != nil { + panic(err) + } + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeRound3Success, + sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), + sdk.NewAttribute(types.AttributeKeyStatus, group.Status.String()), + ), + ) + } else { + group.Status = types.GROUP_STATUS_FALLEN + k.SetGroup(ctx, group) + + // Handle the hooks when group creation is fallen; this shouldn't return any error. + if err := k.Hooks().AfterCreatingGroupFailed(ctx, group); err != nil { + panic(err) + } + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeRound3Failed, + sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), + sdk.NewAttribute(types.AttributeKeyStatus, group.Status.String()), + ), + ) + } + } +} + +// ===================================== +// Process expired group +// ===================================== + +// SetLastExpiredGroupID sets the last expired group ID in the store. +func (k Keeper) SetLastExpiredGroupID(ctx sdk.Context, groupID tss.GroupID) { + ctx.KVStore(k.storeKey).Set(types.LastExpiredGroupIDStoreKey, sdk.Uint64ToBigEndian(uint64(groupID))) +} + +// GetLastExpiredGroupID retrieves the last expired group ID from the store. +func (k Keeper) GetLastExpiredGroupID(ctx sdk.Context) tss.GroupID { + bz := ctx.KVStore(k.storeKey).Get(types.LastExpiredGroupIDStoreKey) + return tss.GroupID(sdk.BigEndianToUint64(bz)) +} + +// HandleExpiredGroups cleans up expired groups and removes them from the store. +func (k Keeper) HandleExpiredGroups(ctx sdk.Context) { + // Get the current group ID to start processing from + currentGroupID := k.GetLastExpiredGroupID(ctx) + 1 + + // Get the last group ID in the store + lastGroupID := tss.GroupID(k.GetGroupCount(ctx)) + + // Process each group starting from currentGroupID + for ; currentGroupID <= lastGroupID; currentGroupID++ { + // Get the group + group := k.MustGetGroup(ctx, currentGroupID) + + // Check if the group is still within the expiration period + if group.CreatedHeight+k.GetParams(ctx).CreatingPeriod > uint64(ctx.BlockHeight()) { + break + } + + // Check group is not active + if group.Status != types.GROUP_STATUS_ACTIVE && group.Status != types.GROUP_STATUS_FALLEN { + // Handle the hooks before setting group to be expired; this shouldn't return any error. + if err := k.Hooks().BeforeSetGroupExpired(ctx, group); err != nil { + panic(err) + } + + // Update group status + group.Status = types.GROUP_STATUS_EXPIRED + k.SetGroup(ctx, group) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeExpiredGroup, + sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", group.ID)), + ), + ) + } + + // Cleanup all interim data associated with the group + k.DeleteAllDKGInterimData(ctx, currentGroupID) + + // Set the last expired group ID to the current group ID + k.SetLastExpiredGroupID(ctx, currentGroupID) + } +} diff --git a/x/tss/keeper/groups_test.go b/x/tss/keeper/groups_test.go new file mode 100644 index 000000000..3375a160f --- /dev/null +++ b/x/tss/keeper/groups_test.go @@ -0,0 +1,245 @@ +package keeper_test + +import ( + "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/bandprotocol/chain/v2/x/tss/types" +) + +func (s *KeeperTestSuite) TestGetSetGroupCount() { + ctx, k := s.ctx, s.app.TSSKeeper + k.SetGroupCount(ctx, 1) + + groupCount := k.GetGroupCount(ctx) + s.Require().Equal(uint64(1), groupCount) +} + +func (s *KeeperTestSuite) TestGetNextGroupID() { + ctx, k := s.ctx, s.app.TSSKeeper + + // Initial group count + k.SetGroupCount(ctx, 0) + + groupID1 := k.GetNextGroupID(ctx) + s.Require().Equal(tss.GroupID(1), groupID1) + groupID2 := k.GetNextGroupID(ctx) + s.Require().Equal(tss.GroupID(2), groupID2) +} + +func (s *KeeperTestSuite) TestGetGroups() { + ctx, k := s.ctx, s.app.TSSKeeper + group := types.Group{ + ID: 1, + Size_: 5, + Threshold: 3, + PubKey: nil, + Status: types.GROUP_STATUS_ROUND_1, + } + + // Set new group + k.SetGroup(ctx, group) + + // Get group from chain state + got := k.GetGroups(ctx) + s.Require().Equal([]types.Group{group}, got) +} + +func (s *KeeperTestSuite) TestDeleteGroup() { + ctx, k := s.ctx, s.app.TSSKeeper + + // Create a sample group ID + groupID := tss.GroupID(123) + + // Set up a sample group in the store + group := types.Group{ + ID: groupID, + // Set other fields as needed + } + k.SetGroup(ctx, group) + + // Delete the group + k.DeleteGroup(ctx, groupID) + + // Verify that the group is deleted + _, err := k.GetGroup(ctx, groupID) + s.Require().Error(err) +} + +func (s *KeeperTestSuite) TestGetSetDKGContext() { + ctx, k := s.ctx, s.app.TSSKeeper + + dkgContext := []byte("dkg-context sample") + k.SetDKGContext(ctx, 1, dkgContext) + + got, err := k.GetDKGContext(ctx, 1) + s.Require().NoError(err) + s.Require().Equal(dkgContext, got) +} + +func (s *KeeperTestSuite) TestCreateNewGroup() { + ctx, k := s.ctx, s.app.TSSKeeper + + group := types.Group{ + Size_: 5, + Threshold: 3, + PubKey: nil, + Status: types.GROUP_STATUS_ROUND_1, + } + + // Create new group + groupID := k.CreateNewGroup(ctx, group) + + // init group ID + group.ID = groupID + + // Get group by id + got, err := k.GetGroup(ctx, groupID) + s.Require().NoError(err) + s.Require().Equal(group, got) +} + +func (s *KeeperTestSuite) TestSetGroup() { + ctx, k := s.ctx, s.app.TSSKeeper + group := types.Group{ + Size_: 5, + Threshold: 3, + PubKey: nil, + Status: types.GROUP_STATUS_ROUND_1, + } + + // Set new group + groupID := k.CreateNewGroup(ctx, group) + + // Update group size value + group.Size_ = 6 + + // Add group ID + group.ID = groupID + + k.SetGroup(ctx, group) + + // Get group from chain state + got, err := k.GetGroup(ctx, groupID) + + // Validate group size value + s.Require().NoError(err) + s.Require().Equal(group.Size_, got.Size_) +} + +func (s *KeeperTestSuite) TestSetLastExpiredGroupID() { + ctx, k := s.ctx, s.app.TSSKeeper + groupID := tss.GroupID(1) + k.SetLastExpiredGroupID(ctx, groupID) + + got := k.GetLastExpiredGroupID(ctx) + s.Require().Equal(groupID, got) +} + +func (s *KeeperTestSuite) TestGetSetLastExpiredGroupID() { + ctx, k := s.ctx, s.app.TSSKeeper + + // Set the last expired group ID + groupID := tss.GroupID(98765) + k.SetLastExpiredGroupID(ctx, groupID) + + // Get the last expired group ID + got := k.GetLastExpiredGroupID(ctx) + + // Assert equality + s.Require().Equal(groupID, got) +} + +func (s *KeeperTestSuite) TestProcessExpiredGroups() { + ctx, k := s.ctx, s.app.TSSKeeper + + // Create group + groupID := k.CreateNewGroup(ctx, types.Group{}) + k.SetMember(ctx, types.Member{ + ID: 1, + GroupID: groupID, + Address: "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun", + PubKey: nil, + IsMalicious: false, + }) + + // Set the current block height + blockHeight := int64(30001) + ctx = ctx.WithBlockHeight(blockHeight) + + // Handle expired groups + k.HandleExpiredGroups(ctx) + + // Assert that the last expired group ID is updated correctly + lastExpiredGroupID := k.GetLastExpiredGroupID(ctx) + s.Require().Equal(groupID, lastExpiredGroupID) +} + +func (s *KeeperTestSuite) TestGetSetPendingProcessGroups() { + ctx, k := s.ctx, s.app.TSSKeeper + groupID := tss.GroupID(1) + + // Set the pending process group in the store + k.SetPendingProcessGroups(ctx, types.PendingProcessGroups{ + GroupIDs: []tss.GroupID{groupID}, + }) + + got := k.GetPendingProcessGroups(ctx) + + // Check if the retrieved pending process groups match the original sample + s.Require().Len(got, 1) + s.Require().Equal(groupID, got[0]) +} + +func (s *KeeperTestSuite) TestHandleProcessGroup() { + ctx, k := s.ctx, s.app.TSSKeeper + groupID, memberID := tss.GroupID(1), tss.MemberID(1) + member := types.Member{ + ID: memberID, + GroupID: groupID, + IsMalicious: false, + } + + k.SetMember(ctx, member) + + k.SetGroup(ctx, types.Group{ + ID: groupID, + Status: types.GROUP_STATUS_ROUND_1, + }) + k.HandleProcessGroup(ctx, groupID) + group := k.MustGetGroup(ctx, groupID) + s.Require().Equal(types.GROUP_STATUS_ROUND_2, group.Status) + + k.SetGroup(ctx, types.Group{ + ID: groupID, + Status: types.GROUP_STATUS_ROUND_2, + }) + k.HandleProcessGroup(ctx, groupID) + group = k.MustGetGroup(ctx, groupID) + s.Require().Equal(types.GROUP_STATUS_ROUND_3, group.Status) + + k.SetGroup(ctx, types.Group{ + ID: groupID, + Status: types.GROUP_STATUS_FALLEN, + }) + k.HandleProcessGroup(ctx, groupID) + group = k.MustGetGroup(ctx, groupID) + s.Require().Equal(types.GROUP_STATUS_FALLEN, group.Status) + + k.SetGroup(ctx, types.Group{ + ID: groupID, + Status: types.GROUP_STATUS_ROUND_3, + }) + k.HandleProcessGroup(ctx, groupID) + group = k.MustGetGroup(ctx, groupID) + s.Require().Equal(types.GROUP_STATUS_ACTIVE, group.Status) + + // if member is malicious + k.SetGroup(ctx, types.Group{ + ID: groupID, + Status: types.GROUP_STATUS_ROUND_3, + }) + member.IsMalicious = true + k.SetMember(ctx, member) + k.HandleProcessGroup(ctx, groupID) + group = k.MustGetGroup(ctx, groupID) + s.Require().Equal(types.GROUP_STATUS_FALLEN, group.Status) +} diff --git a/x/tss/keeper/grpc_query.go b/x/tss/keeper/grpc_query.go index f973d9402..cb32eb69d 100644 --- a/x/tss/keeper/grpc_query.go +++ b/x/tss/keeper/grpc_query.go @@ -3,10 +3,10 @@ package keeper import ( "context" - "cosmossdk.io/errors" tmbytes "github.com/cometbft/cometbft/libs/bytes" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/query" "github.com/bandprotocol/chain/v2/pkg/tss" @@ -30,7 +30,7 @@ func (q queryServer) Counts(c context.Context, req *types.QueryCountsRequest) (* }, nil } -// Group function handles the request to fetch information about a group. +// Group queries information about a group. func (q queryServer) Group(goCtx context.Context, req *types.QueryGroupRequest) (*types.QueryGroupResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) groupID := tss.GroupID(req.GroupId) @@ -68,7 +68,7 @@ func (q queryServer) Group(goCtx context.Context, req *types.QueryGroupRequest) }, nil } -// Members function handles the request to get members of a group. +// Members queries members of a group. func (q queryServer) Members( goCtx context.Context, req *types.QueryMembersRequest, @@ -86,7 +86,7 @@ func (q queryServer) Members( }, nil } -// IsGrantee function handles the request to check if a specific address is a grantee of another. +// IsGrantee queries if a specific address is a grantee of another. func (q queryServer) IsGrantee( goCtx context.Context, req *types.QueryIsGranteeRequest, @@ -96,12 +96,12 @@ func (q queryServer) IsGrantee( // Convert granter and grantee addresses from Bech32 to AccAddress granter, err := sdk.AccAddressFromBech32(req.Granter) if err != nil { - return nil, errors.Wrapf(types.ErrInvalidAccAddressFormat, err.Error()) + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid granter address: %s", err) } grantee, err := sdk.AccAddressFromBech32(req.Grantee) if err != nil { - return nil, errors.Wrapf(types.ErrInvalidAccAddressFormat, err.Error()) + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid grantee address: %s", err) } return &types.QueryIsGranteeResponse{ @@ -109,14 +109,14 @@ func (q queryServer) IsGrantee( }, nil } -// DE function handles the request to get DEs of a given address. +// DE queries DEs of a given address. func (q queryServer) DE(goCtx context.Context, req *types.QueryDERequest) (*types.QueryDEResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // Convert the address from Bech32 format to AccAddress format accAddress, err := sdk.AccAddressFromBech32(req.Address) if err != nil { - return nil, errors.Wrapf(types.ErrInvalidAccAddressFormat, "invalid account address: %s", err) + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } // Get DEs and paginate the result @@ -129,7 +129,7 @@ func (q queryServer) DE(goCtx context.Context, req *types.QueryDERequest) (*type return nil }) if err != nil { - return nil, errors.Wrapf(types.ErrInvalidArgument, "paginate: %v", err) + return nil, types.ErrInvalidArgument.Wrapf("paginate: %v", err) } return &types.QueryDEResponse{ @@ -138,7 +138,7 @@ func (q queryServer) DE(goCtx context.Context, req *types.QueryDERequest) (*type }, nil } -// PendingGroups function handles the request to get pending groups of a given address. +// PendingGroups queries pending groups creation that waits a given address to submit a message. func (q queryServer) PendingGroups( goCtx context.Context, req *types.QueryPendingGroupsRequest, @@ -205,7 +205,7 @@ func (q queryServer) PendingGroups( }, nil } -// PendingSignings function handles the request to get pending signs of a given address. +// PendingSignings queries signings that waits a given address to sign. func (q queryServer) PendingSignings( goCtx context.Context, req *types.QueryPendingSigningsRequest, @@ -214,7 +214,7 @@ func (q queryServer) PendingSignings( address, err := sdk.AccAddressFromBech32(req.Address) if err != nil { - return nil, errors.Wrapf(types.ErrInvalidAccAddressFormat, err.Error()) + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } // Get pending signs. @@ -225,7 +225,7 @@ func (q queryServer) PendingSignings( }, nil } -// Signing function handles the request to get signing of a given ID. +// Signing queries signing of a given ID. func (q queryServer) Signing( goCtx context.Context, req *types.QuerySigningRequest, diff --git a/x/tss/keeper/grpc_query_test.go b/x/tss/keeper/grpc_query_test.go index c2bd92682..9e9fc86e4 100644 --- a/x/tss/keeper/grpc_query_test.go +++ b/x/tss/keeper/grpc_query_test.go @@ -382,7 +382,7 @@ func (s *KeeperTestSuite) TestGRPCQueryIsGrantee() { granter, _ := sdk.AccAddressFromBech32("band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun") // Save grant msgs to grantee - for _, m := range types.GetTSSGrantMsgTypes() { + for _, m := range types.TSSGrantMsgTypes { err := authzKeeper.SaveGrant(s.ctx, grantee, granter, authz.NewGenericAuthorization(m), &expTime) s.Require().NoError(err) } diff --git a/x/tss/keeper/keeper.go b/x/tss/keeper/keeper.go index 278679aac..e0b198b39 100644 --- a/x/tss/keeper/keeper.go +++ b/x/tss/keeper/keeper.go @@ -3,14 +3,12 @@ package keeper import ( "fmt" - "cosmossdk.io/errors" "github.com/cometbft/cometbft/libs/log" "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/x/tss/types" ) @@ -52,26 +50,9 @@ func (k Keeper) GetAuthority() string { return k.authority } -// SetGroupCount sets the number of group count to the given value. -func (k Keeper) SetGroupCount(ctx sdk.Context, count uint64) { - ctx.KVStore(k.storeKey).Set(types.GroupCountStoreKey, sdk.Uint64ToBigEndian(count)) -} - -// GetGroupCount returns the current number of all groups ever existed. -func (k Keeper) GetGroupCount(ctx sdk.Context) uint64 { - return sdk.BigEndianToUint64(ctx.KVStore(k.storeKey).Get(types.GroupCountStoreKey)) -} - -// GetNextGroupID increments the group count and returns the current number of groups. -func (k Keeper) GetNextGroupID(ctx sdk.Context) tss.GroupID { - groupNumber := k.GetGroupCount(ctx) - k.SetGroupCount(ctx, groupNumber+1) - return tss.GroupID(groupNumber + 1) -} - // CheckIsGrantee checks if the granter granted permissions to the grantee. func (k Keeper) CheckIsGrantee(ctx sdk.Context, granter sdk.AccAddress, grantee sdk.AccAddress) bool { - for _, msg := range types.GetTSSGrantMsgTypes() { + for _, msg := range types.TSSGrantMsgTypes { cap, _ := k.authzKeeper.GetAuthorization( ctx, grantee, @@ -87,427 +68,6 @@ func (k Keeper) CheckIsGrantee(ctx sdk.Context, granter sdk.AccAddress, grantee return true } -// CreateNewGroup creates a new group in the store and returns the id of the group. -func (k Keeper) CreateNewGroup(ctx sdk.Context, group types.Group) tss.GroupID { - group.ID = k.GetNextGroupID(ctx) - group.CreatedHeight = uint64(ctx.BlockHeight()) - k.SetGroup(ctx, group) - - return group.ID -} - -// GetGroup retrieves a group from the store. -func (k Keeper) GetGroup(ctx sdk.Context, groupID tss.GroupID) (types.Group, error) { - bz := ctx.KVStore(k.storeKey).Get(types.GroupStoreKey(groupID)) - if bz == nil { - return types.Group{}, types.ErrGroupNotFound.Wrapf("failed to get group with groupID: %d", groupID) - } - - group := types.Group{} - k.cdc.MustUnmarshal(bz, &group) - return group, nil -} - -// MustGetGroup returns the group for the given ID. Panics error if not exists. -func (k Keeper) MustGetGroup(ctx sdk.Context, groupID tss.GroupID) types.Group { - group, err := k.GetGroup(ctx, groupID) - if err != nil { - panic(err) - } - return group -} - -// SetGroup set a group in the store. -func (k Keeper) SetGroup(ctx sdk.Context, group types.Group) { - ctx.KVStore(k.storeKey).Set(types.GroupStoreKey(group.ID), k.cdc.MustMarshal(&group)) -} - -// GetGroupsIterator gets an iterator all group. -func (k Keeper) GetGroupsIterator(ctx sdk.Context) sdk.Iterator { - return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.GroupStoreKeyPrefix) -} - -// GetGroups retrieves all group of the store. -func (k Keeper) GetGroups(ctx sdk.Context) []types.Group { - var groups []types.Group - iterator := k.GetGroupsIterator(ctx) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var group types.Group - k.cdc.MustUnmarshal(iterator.Value(), &group) - groups = append(groups, group) - } - return groups -} - -// DeleteGroup removes the group from the store. -func (k Keeper) DeleteGroup(ctx sdk.Context, groupID tss.GroupID) { - ctx.KVStore(k.storeKey).Delete(types.GroupStoreKey(groupID)) -} - -// SetDKGContext sets DKG context for a group in the store. -func (k Keeper) SetDKGContext(ctx sdk.Context, groupID tss.GroupID, dkgContext []byte) { - ctx.KVStore(k.storeKey).Set(types.DKGContextStoreKey(groupID), dkgContext) -} - -// GetDKGContext retrieves DKG context of a group from the store. -func (k Keeper) GetDKGContext(ctx sdk.Context, groupID tss.GroupID) ([]byte, error) { - bz := ctx.KVStore(k.storeKey).Get(types.DKGContextStoreKey(groupID)) - if bz == nil { - return nil, errors.Wrapf(types.ErrDKGContextNotFound, "failed to get dkg-context with groupID: %d", groupID) - } - return bz, nil -} - -// DeleteDKGContext removes the DKG context data of a group from the store. -func (k Keeper) DeleteDKGContext(ctx sdk.Context, groupID tss.GroupID) { - ctx.KVStore(k.storeKey).Delete(types.DKGContextStoreKey(groupID)) -} - -// SetMember sets a member of a group in the store. -func (k Keeper) SetMember(ctx sdk.Context, member types.Member) { - ctx.KVStore(k.storeKey).Set(types.MemberOfGroupKey(member.GroupID, member.ID), k.cdc.MustMarshal(&member)) -} - -// SetMembers sets members of a group in the store. -func (k Keeper) SetMembers(ctx sdk.Context, members []types.Member) { - for _, member := range members { - k.SetMember(ctx, member) - } -} - -// GetMemberByAddress function retrieves a member of a group from the store by using address. -func (k Keeper) GetMemberByAddress(ctx sdk.Context, groupID tss.GroupID, address string) (types.Member, error) { - members, err := k.GetGroupMembers(ctx, groupID) - if err != nil { - return types.Member{}, err - } - - for _, member := range members { - if member.Verify(address) { - return member, nil - } - } - - return types.Member{}, errors.Wrapf( - types.ErrMemberNotFound, - "failed to get member with groupID: %d and address: %s", - groupID, - address, - ) -} - -// GetMember function retrieves a member of a group from the store. -func (k Keeper) GetMember(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) (types.Member, error) { - bz := ctx.KVStore(k.storeKey).Get(types.MemberOfGroupKey(groupID, memberID)) - if bz == nil { - return types.Member{}, errors.Wrapf( - types.ErrMemberNotFound, - "failed to get member with groupID: %d and memberID: %d", - groupID, - memberID, - ) - } - - member := types.Member{} - k.cdc.MustUnmarshal(bz, &member) - return member, nil -} - -// MustGetMember returns the member for the given groupID and memberID. Panics error if not exists. -func (k Keeper) MustGetMember(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) types.Member { - member, err := k.GetMember(ctx, groupID, memberID) - if err != nil { - panic(err) - } - return member -} - -// GetGroupMembersIterator gets an iterator over all members of a group. -func (k Keeper) GetGroupMembersIterator(ctx sdk.Context, groupID tss.GroupID) sdk.Iterator { - return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.MembersStoreKey(groupID)) -} - -// GetGroupMembers retrieves all members of a group from the store. -func (k Keeper) GetGroupMembers(ctx sdk.Context, groupID tss.GroupID) ([]types.Member, error) { - var members []types.Member - iterator := k.GetGroupMembersIterator(ctx, groupID) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var member types.Member - k.cdc.MustUnmarshal(iterator.Value(), &member) - members = append(members, member) - } - if len(members) == 0 { - return nil, errors.Wrapf(types.ErrMemberNotFound, "failed to get members with groupID: %d", groupID) - } - return members, nil -} - -// GetMembers retrieves all members from store. -func (k Keeper) GetMembers(ctx sdk.Context) []types.Member { - var members []types.Member - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.MemberStoreKeyPrefix) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var member types.Member - k.cdc.MustUnmarshal(iterator.Value(), &member) - members = append(members, member) - } - - return members -} - -// DeleteGroupMembers removes all members in the group -func (k Keeper) DeleteGroupMembers(ctx sdk.Context, groupID tss.GroupID) error { - members, err := k.GetGroupMembers(ctx, groupID) - if err != nil { - return err - } - - for _, member := range members { - k.DeleteMember(ctx, member) - } - - return nil -} - -// DeleteMember removes a member -func (k Keeper) DeleteMember(ctx sdk.Context, member types.Member) { - ctx.KVStore(k.storeKey).Delete(types.MemberOfGroupKey(member.GroupID, member.ID)) -} - -// MustGetMembers retrieves all members of a group from the store. Panics error if not exists. -func (k Keeper) MustGetMembers(ctx sdk.Context, groupID tss.GroupID) []types.Member { - members, err := k.GetGroupMembers(ctx, groupID) - if err != nil { - panic(err) - } - return members -} - -// GetAvailableMembers retrieves all active members of a group from the store. -func (k Keeper) GetAvailableMembers(ctx sdk.Context, groupID tss.GroupID) ([]types.Member, error) { - var activeMembers []types.Member - iterator := k.GetGroupMembersIterator(ctx, groupID) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var member types.Member - k.cdc.MustUnmarshal(iterator.Value(), &member) - - if member.IsActive { - activeMembers = append(activeMembers, member) - } - } - - // Filter members that have DE left - filteredMembers, err := k.FilterMembersHaveDE(ctx, activeMembers) - if err != nil { - return nil, err - } - - if len(filteredMembers) == 0 { - return nil, types.ErrNoActiveMember.Wrapf("no active member in groupID: %d", groupID) - } - return filteredMembers, nil -} - -// SetLastExpiredGroupID sets the last expired group ID in the store. -func (k Keeper) SetLastExpiredGroupID(ctx sdk.Context, groupID tss.GroupID) { - ctx.KVStore(k.storeKey).Set(types.LastExpiredGroupIDStoreKey, sdk.Uint64ToBigEndian(uint64(groupID))) -} - -// SetMemberIsActive sets a boolean flag represent activeness of the user. -func (k Keeper) SetMemberIsActive(ctx sdk.Context, groupID tss.GroupID, address sdk.AccAddress, status bool) error { - members := k.MustGetMembers(ctx, groupID) - for _, m := range members { - if m.Address == address.String() { - m.IsActive = status - k.SetMember(ctx, m) - return nil - } - } - - return types.ErrMemberNotFound.Wrapf( - "failed to set member active status with groupID: %d and address: %s", - groupID, - address, - ) -} - -// ActivateMember sets a boolean flag represent activeness of the user to true. -func (k Keeper) ActivateMember(ctx sdk.Context, groupID tss.GroupID, address sdk.AccAddress) error { - return k.SetMemberIsActive(ctx, groupID, address, true) -} - -// DeactivateMember sets a boolean flag represent activeness of the user to false. -func (k Keeper) DeactivateMember(ctx sdk.Context, groupID tss.GroupID, address sdk.AccAddress) error { - return k.SetMemberIsActive(ctx, groupID, address, false) -} - -// GetLastExpiredGroupID retrieves the last expired group ID from the store. -func (k Keeper) GetLastExpiredGroupID(ctx sdk.Context) tss.GroupID { - bz := ctx.KVStore(k.storeKey).Get(types.LastExpiredGroupIDStoreKey) - return tss.GroupID(sdk.BigEndianToUint64(bz)) -} - -// HandleExpiredGroups cleans up expired groups and removes them from the store. -func (k Keeper) HandleExpiredGroups(ctx sdk.Context) { - // Get the current group ID to start processing from - currentGroupID := k.GetLastExpiredGroupID(ctx) + 1 - - // Get the last group ID in the store - lastGroupID := tss.GroupID(k.GetGroupCount(ctx)) - - // Get the group signature creating period - creatingPeriod := k.GetParams(ctx).CreatingPeriod - - // Process each group starting from currentGroupID - for ; currentGroupID <= lastGroupID; currentGroupID++ { - // Get the group - group := k.MustGetGroup(ctx, currentGroupID) - - // Check if the group is still within the expiration period - if group.CreatedHeight+creatingPeriod > uint64(ctx.BlockHeight()) { - break - } - - // Check group is not active - if group.Status != types.GROUP_STATUS_ACTIVE && group.Status != types.GROUP_STATUS_FALLEN { - // Handle the hooks before setting group to be expired. - // this shouldn't return any error. - if err := k.Hooks().BeforeSetGroupExpired(ctx, group); err != nil { - panic(err) - } - - // Update group status - group.Status = types.GROUP_STATUS_EXPIRED - k.SetGroup(ctx, group) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeExpiredGroup, - sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", group.ID)), - ), - ) - } - - // Cleanup all interim data associated with the group - k.DeleteAllDKGInterimData(ctx, currentGroupID) - - // Set the last expired group ID to the current group ID - k.SetLastExpiredGroupID(ctx, currentGroupID) - } -} - -// AddPendingProcessGroup adds a new pending process group to the store. -func (k Keeper) AddPendingProcessGroup(ctx sdk.Context, groupID tss.GroupID) { - pgs := k.GetPendingProcessGroups(ctx) - pgs = append(pgs, groupID) - k.SetPendingProcessGroups(ctx, types.PendingProcessGroups{ - GroupIDs: pgs, - }) -} - -// SetPendingProcessGroups sets the given pending process groups in the store. -func (k Keeper) SetPendingProcessGroups(ctx sdk.Context, pgs types.PendingProcessGroups) { - ctx.KVStore(k.storeKey).Set(types.PendingProcessGroupsStoreKey, k.cdc.MustMarshal(&pgs)) -} - -// GetPendingProcessGroups retrieves the list of pending process groups from the store. -// It returns an empty list if the key does not exist in the store. -func (k Keeper) GetPendingProcessGroups(ctx sdk.Context) []tss.GroupID { - bz := ctx.KVStore(k.storeKey).Get(types.PendingProcessGroupsStoreKey) - if len(bz) == 0 { - // Return an empty list if the key does not exist in the store. - return []tss.GroupID{} - } - pgs := types.PendingProcessGroups{} - k.cdc.MustUnmarshal(bz, &pgs) - return pgs.GroupIDs -} - -// HandleProcessGroup handles the pending process group based on its status. -// It updates the group status and emits appropriate events. -func (k Keeper) HandleProcessGroup(ctx sdk.Context, groupID tss.GroupID) { - group := k.MustGetGroup(ctx, groupID) - switch group.Status { - case types.GROUP_STATUS_ROUND_1: - group.Status = types.GROUP_STATUS_ROUND_2 - group.PubKey = k.GetAccumulatedCommit(ctx, groupID, 0) - k.SetGroup(ctx, group) - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeRound1Success, - sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), - sdk.NewAttribute(types.AttributeKeyStatus, group.Status.String()), - ), - ) - case types.GROUP_STATUS_ROUND_2: - group.Status = types.GROUP_STATUS_ROUND_3 - k.SetGroup(ctx, group) - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeRound2Success, - sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), - sdk.NewAttribute(types.AttributeKeyStatus, group.Status.String()), - ), - ) - case types.GROUP_STATUS_FALLEN: - group.Status = types.GROUP_STATUS_FALLEN - k.SetGroup(ctx, group) - - // Handle the hooks when group creation is fallen; this shouldn't return any error. - if err := k.Hooks().AfterCreatingGroupFailed(ctx, group); err != nil { - panic(err) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeRound3Failed, - sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), - sdk.NewAttribute(types.AttributeKeyStatus, group.Status.String()), - ), - ) - case types.GROUP_STATUS_ROUND_3: - // Get members to check malicious - members := k.MustGetMembers(ctx, group.ID) - if !types.Members(members).HaveMalicious() { - group.Status = types.GROUP_STATUS_ACTIVE - k.SetGroup(ctx, group) - - // Handle the hooks when group is ready. this shouldn't return any error. - if err := k.Hooks().AfterCreatingGroupCompleted(ctx, group); err != nil { - panic(err) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeRound3Success, - sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), - sdk.NewAttribute(types.AttributeKeyStatus, group.Status.String()), - ), - ) - } else { - group.Status = types.GROUP_STATUS_FALLEN - k.SetGroup(ctx, group) - - // Handle the hooks when group creation is fallen; this shouldn't return any error. - if err := k.Hooks().AfterCreatingGroupFailed(ctx, group); err != nil { - panic(err) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeRound3Failed, - sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), - sdk.NewAttribute(types.AttributeKeyStatus, group.Status.String()), - ), - ) - } - } -} - func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } diff --git a/x/tss/keeper/keeper_test.go b/x/tss/keeper/keeper_test.go index 2f7dae662..ba565885c 100644 --- a/x/tss/keeper/keeper_test.go +++ b/x/tss/keeper/keeper_test.go @@ -182,26 +182,6 @@ func (s *KeeperTestSuite) SetupGroup(groupStatus types.GroupStatus) { } } -func (s *KeeperTestSuite) TestGetSetGroupCount() { - ctx, k := s.ctx, s.app.TSSKeeper - k.SetGroupCount(ctx, 1) - - groupCount := k.GetGroupCount(ctx) - s.Require().Equal(uint64(1), groupCount) -} - -func (s *KeeperTestSuite) TestGetNextGroupID() { - ctx, k := s.ctx, s.app.TSSKeeper - - // Initial group count - k.SetGroupCount(ctx, 0) - - groupID1 := k.GetNextGroupID(ctx) - s.Require().Equal(tss.GroupID(1), groupID1) - groupID2 := k.GetNextGroupID(ctx) - s.Require().Equal(tss.GroupID(2), groupID2) -} - func (s *KeeperTestSuite) TestIsGrantee() { ctx, k := s.ctx, s.app.TSSKeeper expTime := time.Unix(0, 0) @@ -213,7 +193,7 @@ func (s *KeeperTestSuite) TestIsGrantee() { granter, _ := sdk.AccAddressFromBech32("band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun") // Save grant msgs to grantee - for _, m := range types.GetTSSGrantMsgTypes() { + for _, m := range types.TSSGrantMsgTypes { err := s.app.AuthzKeeper.SaveGrant(ctx, grantee, granter, authz.NewGenericAuthorization(m), &expTime) s.Require().NoError(err) } @@ -222,306 +202,6 @@ func (s *KeeperTestSuite) TestIsGrantee() { s.Require().True(isGrantee) } -func (s *KeeperTestSuite) TestCreateNewGroup() { - ctx, k := s.ctx, s.app.TSSKeeper - - group := types.Group{ - Size_: 5, - Threshold: 3, - PubKey: nil, - Status: types.GROUP_STATUS_ROUND_1, - } - - // Create new group - groupID := k.CreateNewGroup(ctx, group) - - // init group ID - group.ID = groupID - - // Get group by id - got, err := k.GetGroup(ctx, groupID) - s.Require().NoError(err) - s.Require().Equal(group, got) -} - -func (s *KeeperTestSuite) TestSetGroup() { - ctx, k := s.ctx, s.app.TSSKeeper - group := types.Group{ - Size_: 5, - Threshold: 3, - PubKey: nil, - Status: types.GROUP_STATUS_ROUND_1, - } - - // Set new group - groupID := k.CreateNewGroup(ctx, group) - - // Update group size value - group.Size_ = 6 - - // Add group ID - group.ID = groupID - - k.SetGroup(ctx, group) - - // Get group from chain state - got, err := k.GetGroup(ctx, groupID) - - // Validate group size value - s.Require().NoError(err) - s.Require().Equal(group.Size_, got.Size_) -} - -func (s *KeeperTestSuite) TestGetGroups() { - ctx, k := s.ctx, s.app.TSSKeeper - group := types.Group{ - ID: 1, - Size_: 5, - Threshold: 3, - PubKey: nil, - Status: types.GROUP_STATUS_ROUND_1, - } - - // Set new group - k.SetGroup(ctx, group) - - // Get group from chain state - got := k.GetGroups(ctx) - s.Require().Equal([]types.Group{group}, got) -} - -func (s *KeeperTestSuite) TestDeleteGroup() { - ctx, k := s.ctx, s.app.TSSKeeper - - // Create a sample group ID - groupID := tss.GroupID(123) - - // Set up a sample group in the store - group := types.Group{ - ID: groupID, - // Set other fields as needed - } - k.SetGroup(ctx, group) - - // Delete the group - k.DeleteGroup(ctx, groupID) - - // Verify that the group is deleted - _, err := k.GetGroup(ctx, groupID) - s.Require().Error(err) -} - -func (s *KeeperTestSuite) TestGetSetDKGContext() { - ctx, k := s.ctx, s.app.TSSKeeper - - dkgContext := []byte("dkg-context sample") - k.SetDKGContext(ctx, 1, dkgContext) - - got, err := k.GetDKGContext(ctx, 1) - s.Require().NoError(err) - s.Require().Equal(dkgContext, got) -} - -func (s *KeeperTestSuite) TestGetSetMember() { - ctx, k := s.ctx, s.app.TSSKeeper - groupID, memberID := tss.GroupID(1), tss.MemberID(1) - member := types.Member{ - ID: 1, - GroupID: groupID, - Address: "band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", - PubKey: nil, - IsMalicious: false, - } - k.SetMember(ctx, member) - - got, err := k.GetMember(ctx, groupID, memberID) - s.Require().NoError(err) - s.Require().Equal(member, got) -} - -func (s *KeeperTestSuite) TestGetMembers() { - ctx, k := s.ctx, s.app.TSSKeeper - groupID := tss.GroupID(1) - members := []types.Member{ - { - ID: 1, - GroupID: groupID, - Address: "band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", - PubKey: nil, - IsMalicious: false, - }, - { - ID: 2, - GroupID: groupID, - Address: "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun", - PubKey: nil, - IsMalicious: false, - }, - } - - // Set members - for _, m := range members { - k.SetMember(ctx, m) - } - - got, err := k.GetGroupMembers(ctx, groupID) - s.Require().NoError(err) - s.Require().Equal(members, got) -} - -func (s *KeeperTestSuite) TestGetSetMemberIsActive() { - ctx, k := s.ctx, s.app.TSSKeeper - - groupID := tss.GroupID(10) - address := sdk.MustAccAddressFromBech32("band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs") - k.SetMember(ctx, types.Member{ - ID: tss.MemberID(1), - GroupID: groupID, - Address: address.String(), - PubKey: nil, - IsActive: true, - }) - - // check when being set to active - members, err := k.GetGroupMembers(ctx, groupID) - s.Require().NoError(err) - s.Require().Len(members, 1) - - for _, member := range members { - s.Require().True(member.IsActive) - } - - err = k.SetMemberIsActive(ctx, groupID, address, false) - s.Require().NoError(err) - - members, err = k.GetGroupMembers(ctx, groupID) - s.Require().NoError(err) - s.Require().Len(members, 1) - - for _, member := range members { - s.Require().False(member.IsActive) - } -} - -func (s *KeeperTestSuite) TestSetLastExpiredGroupID() { - ctx, k := s.ctx, s.app.TSSKeeper - groupID := tss.GroupID(1) - k.SetLastExpiredGroupID(ctx, groupID) - - got := k.GetLastExpiredGroupID(ctx) - s.Require().Equal(groupID, got) -} - -func (s *KeeperTestSuite) TestGetSetLastExpiredGroupID() { - ctx, k := s.ctx, s.app.TSSKeeper - - // Set the last expired group ID - groupID := tss.GroupID(98765) - k.SetLastExpiredGroupID(ctx, groupID) - - // Get the last expired group ID - got := k.GetLastExpiredGroupID(ctx) - - // Assert equality - s.Require().Equal(groupID, got) -} - -func (s *KeeperTestSuite) TestProcessExpiredGroups() { - ctx, k := s.ctx, s.app.TSSKeeper - - // Create group - groupID := k.CreateNewGroup(ctx, types.Group{}) - k.SetMember(ctx, types.Member{ - ID: 1, - GroupID: groupID, - Address: "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun", - PubKey: nil, - IsMalicious: false, - }) - - // Set the current block height - blockHeight := int64(30001) - ctx = ctx.WithBlockHeight(blockHeight) - - // Handle expired groups - k.HandleExpiredGroups(ctx) - - // Assert that the last expired group ID is updated correctly - lastExpiredGroupID := k.GetLastExpiredGroupID(ctx) - s.Require().Equal(groupID, lastExpiredGroupID) -} - -func (s *KeeperTestSuite) TestGetSetPendingProcessGroups() { - ctx, k := s.ctx, s.app.TSSKeeper - groupID := tss.GroupID(1) - - // Set the pending process group in the store - k.SetPendingProcessGroups(ctx, types.PendingProcessGroups{ - GroupIDs: []tss.GroupID{groupID}, - }) - - got := k.GetPendingProcessGroups(ctx) - - // Check if the retrieved pending process groups match the original sample - s.Require().Len(got, 1) - s.Require().Equal(groupID, got[0]) -} - -func (s *KeeperTestSuite) TestHandleProcessGroup() { - ctx, k := s.ctx, s.app.TSSKeeper - groupID, memberID := tss.GroupID(1), tss.MemberID(1) - member := types.Member{ - ID: memberID, - GroupID: groupID, - IsMalicious: false, - } - - k.SetMember(ctx, member) - - k.SetGroup(ctx, types.Group{ - ID: groupID, - Status: types.GROUP_STATUS_ROUND_1, - }) - k.HandleProcessGroup(ctx, groupID) - group := k.MustGetGroup(ctx, groupID) - s.Require().Equal(types.GROUP_STATUS_ROUND_2, group.Status) - - k.SetGroup(ctx, types.Group{ - ID: groupID, - Status: types.GROUP_STATUS_ROUND_2, - }) - k.HandleProcessGroup(ctx, groupID) - group = k.MustGetGroup(ctx, groupID) - s.Require().Equal(types.GROUP_STATUS_ROUND_3, group.Status) - - k.SetGroup(ctx, types.Group{ - ID: groupID, - Status: types.GROUP_STATUS_FALLEN, - }) - k.HandleProcessGroup(ctx, groupID) - group = k.MustGetGroup(ctx, groupID) - s.Require().Equal(types.GROUP_STATUS_FALLEN, group.Status) - - k.SetGroup(ctx, types.Group{ - ID: groupID, - Status: types.GROUP_STATUS_ROUND_3, - }) - k.HandleProcessGroup(ctx, groupID) - group = k.MustGetGroup(ctx, groupID) - s.Require().Equal(types.GROUP_STATUS_ACTIVE, group.Status) - - // if member is malicious - k.SetGroup(ctx, types.Group{ - ID: groupID, - Status: types.GROUP_STATUS_ROUND_3, - }) - member.IsMalicious = true - k.SetMember(ctx, member) - k.HandleProcessGroup(ctx, groupID) - group = k.MustGetGroup(ctx, groupID) - s.Require().Equal(types.GROUP_STATUS_FALLEN, group.Status) -} - func (s *KeeperTestSuite) TestParams() { k := s.app.TSSKeeper diff --git a/x/tss/keeper/member.go b/x/tss/keeper/member.go new file mode 100644 index 000000000..adac408bf --- /dev/null +++ b/x/tss/keeper/member.go @@ -0,0 +1,182 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/bandprotocol/chain/v2/x/tss/types" +) + +// SetMember sets a member of a group in the store. +func (k Keeper) SetMember(ctx sdk.Context, member types.Member) { + ctx.KVStore(k.storeKey).Set(types.MemberOfGroupKey(member.GroupID, member.ID), k.cdc.MustMarshal(&member)) +} + +// SetMembers sets members of a group in the store. +func (k Keeper) SetMembers(ctx sdk.Context, members []types.Member) { + for _, member := range members { + k.SetMember(ctx, member) + } +} + +// GetMemberByAddress function retrieves a member of a group from the store by using address. +func (k Keeper) GetMemberByAddress(ctx sdk.Context, groupID tss.GroupID, address string) (types.Member, error) { + members, err := k.GetGroupMembers(ctx, groupID) + if err != nil { + return types.Member{}, err + } + + for _, member := range members { + if member.Verify(address) { + return member, nil + } + } + + return types.Member{}, types.ErrMemberNotFound.Wrapf( + "failed to get member with groupID: %d and address: %s", + groupID, + address, + ) +} + +// GetMember function retrieves a member of a group from the store. +func (k Keeper) GetMember(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) (types.Member, error) { + bz := ctx.KVStore(k.storeKey).Get(types.MemberOfGroupKey(groupID, memberID)) + if bz == nil { + return types.Member{}, types.ErrMemberNotFound.Wrapf( + "failed to get member with groupID: %d and memberID: %d", + groupID, + memberID, + ) + } + + member := types.Member{} + k.cdc.MustUnmarshal(bz, &member) + return member, nil +} + +// MustGetMember returns the member for the given groupID and memberID. Panics error if not exists. +func (k Keeper) MustGetMember(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) types.Member { + member, err := k.GetMember(ctx, groupID, memberID) + if err != nil { + panic(err) + } + return member +} + +// GetGroupMembersIterator gets an iterator over all members of a group. +func (k Keeper) GetGroupMembersIterator(ctx sdk.Context, groupID tss.GroupID) sdk.Iterator { + return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.MembersStoreKey(groupID)) +} + +// GetGroupMembers retrieves all members of a group from the store. +func (k Keeper) GetGroupMembers(ctx sdk.Context, groupID tss.GroupID) ([]types.Member, error) { + var members []types.Member + iterator := k.GetGroupMembersIterator(ctx, groupID) + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var member types.Member + k.cdc.MustUnmarshal(iterator.Value(), &member) + members = append(members, member) + } + if len(members) == 0 { + return nil, types.ErrMemberNotFound.Wrapf("failed to get members with groupID: %d", groupID) + } + return members, nil +} + +// GetMembers retrieves all members from store. +func (k Keeper) GetMembers(ctx sdk.Context) []types.Member { + var members []types.Member + iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.MemberStoreKeyPrefix) + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var member types.Member + k.cdc.MustUnmarshal(iterator.Value(), &member) + members = append(members, member) + } + + return members +} + +// DeleteGroupMembers removes all members in the group +func (k Keeper) DeleteGroupMembers(ctx sdk.Context, groupID tss.GroupID) error { + members, err := k.GetGroupMembers(ctx, groupID) + if err != nil { + return err + } + + for _, member := range members { + k.DeleteMember(ctx, member) + } + + return nil +} + +// DeleteMember removes a member +func (k Keeper) DeleteMember(ctx sdk.Context, member types.Member) { + ctx.KVStore(k.storeKey).Delete(types.MemberOfGroupKey(member.GroupID, member.ID)) +} + +// MustGetMembers retrieves all members of a group from the store. Panics error if not exists. +func (k Keeper) MustGetMembers(ctx sdk.Context, groupID tss.GroupID) []types.Member { + members, err := k.GetGroupMembers(ctx, groupID) + if err != nil { + panic(err) + } + return members +} + +// GetAvailableMembers retrieves all active members of a group from the store. +func (k Keeper) GetAvailableMembers(ctx sdk.Context, groupID tss.GroupID) ([]types.Member, error) { + var activeMembers []types.Member + iterator := k.GetGroupMembersIterator(ctx, groupID) + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + var member types.Member + k.cdc.MustUnmarshal(iterator.Value(), &member) + + if member.IsActive { + activeMembers = append(activeMembers, member) + } + } + + // Filter members that have DE left + filteredMembers, err := k.FilterMembersHaveDE(ctx, activeMembers) + if err != nil { + return nil, err + } + + if len(filteredMembers) == 0 { + return nil, types.ErrNoActiveMember.Wrapf("no active member in groupID: %d", groupID) + } + return filteredMembers, nil +} + +// SetMemberIsActive sets a boolean flag represent activeness of the user. +func (k Keeper) SetMemberIsActive(ctx sdk.Context, groupID tss.GroupID, address sdk.AccAddress, status bool) error { + members := k.MustGetMembers(ctx, groupID) + for _, m := range members { + if m.Address == address.String() { + m.IsActive = status + k.SetMember(ctx, m) + return nil + } + } + + return types.ErrMemberNotFound.Wrapf( + "failed to set member active status with groupID: %d and address: %s", + groupID, + address, + ) +} + +// ActivateMember sets a boolean flag represent activeness of the user to true. +func (k Keeper) ActivateMember(ctx sdk.Context, groupID tss.GroupID, address sdk.AccAddress) error { + return k.SetMemberIsActive(ctx, groupID, address, true) +} + +// DeactivateMember sets a boolean flag represent activeness of the user to false. +func (k Keeper) DeactivateMember(ctx sdk.Context, groupID tss.GroupID, address sdk.AccAddress) error { + return k.SetMemberIsActive(ctx, groupID, address, false) +} diff --git a/x/tss/keeper/member_test.go b/x/tss/keeper/member_test.go new file mode 100644 index 000000000..83a7b91f8 --- /dev/null +++ b/x/tss/keeper/member_test.go @@ -0,0 +1,86 @@ +package keeper_test + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/bandprotocol/chain/v2/x/tss/types" +) + +func (s *KeeperTestSuite) TestGetSetMember() { + ctx, k := s.ctx, s.app.TSSKeeper + groupID, memberID := tss.GroupID(1), tss.MemberID(1) + member := types.Member{ + ID: 1, + GroupID: groupID, + Address: "band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", + PubKey: nil, + IsMalicious: false, + } + k.SetMember(ctx, member) + + got, err := k.GetMember(ctx, groupID, memberID) + s.Require().NoError(err) + s.Require().Equal(member, got) +} + +func (s *KeeperTestSuite) TestGetGroupMembers() { + ctx, k := s.ctx, s.app.TSSKeeper + groupID := tss.GroupID(1) + members := []types.Member{ + { + ID: 1, + GroupID: groupID, + Address: "band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", + PubKey: nil, + IsMalicious: false, + }, + { + ID: 2, + GroupID: groupID, + Address: "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun", + PubKey: nil, + IsMalicious: false, + }, + } + + k.SetMembers(ctx, members) + + got, err := k.GetGroupMembers(ctx, groupID) + s.Require().NoError(err) + s.Require().Equal(members, got) +} + +func (s *KeeperTestSuite) TestGetSetMemberIsActive() { + ctx, k := s.ctx, s.app.TSSKeeper + + groupID := tss.GroupID(10) + address := sdk.MustAccAddressFromBech32("band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs") + k.SetMember(ctx, types.Member{ + ID: tss.MemberID(1), + GroupID: groupID, + Address: address.String(), + PubKey: nil, + IsActive: true, + }) + + // check when being set to active + members, err := k.GetGroupMembers(ctx, groupID) + s.Require().NoError(err) + s.Require().Len(members, 1) + + for _, member := range members { + s.Require().True(member.IsActive) + } + + err = k.SetMemberIsActive(ctx, groupID, address, false) + s.Require().NoError(err) + + members, err = k.GetGroupMembers(ctx, groupID) + s.Require().NoError(err) + s.Require().Len(members, 1) + + for _, member := range members { + s.Require().False(member.IsActive) + } +} diff --git a/x/tss/keeper/msg_server.go b/x/tss/keeper/msg_server.go index 1fc7f4725..6cdcc2123 100644 --- a/x/tss/keeper/msg_server.go +++ b/x/tss/keeper/msg_server.go @@ -5,8 +5,8 @@ import ( "encoding/hex" "fmt" - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/bandprotocol/chain/v2/pkg/tss" @@ -17,8 +17,7 @@ type msgServer struct { *Keeper } -// NewMsgServerImpl returns an implementation of the MsgServer interface -// for the provided Keeper. +// NewMsgServerImpl returns an implementation of the MsgServer interface for the provided Keeper. func NewMsgServerImpl(keeper *Keeper) types.MsgServer { return &msgServer{Keeper: keeper} } @@ -27,8 +26,8 @@ var _ types.MsgServer = msgServer{} // SubmitDKGRound1 validates the group status, member, coefficients commit length, one-time // signature, and A0 signature for a group's round 1. If all checks pass, it updates the -// accumulated commits, stores the Round1Info, emits an event, and if necessary, updates the -// group status to round 2. +// accumulated commits, stores the Round1Info, emits an event, and if necessary, add to the +// pending process group for processing group status to round 2. func (k msgServer) SubmitDKGRound1( goCtx context.Context, req *types.MsgSubmitDKGRound1, @@ -37,27 +36,22 @@ func (k msgServer) SubmitDKGRound1( groupID := req.GroupID memberID := req.Round1Info.MemberID - // Get group + // Get group and check group status group, err := k.GetGroup(ctx, groupID) if err != nil { return nil, err } - - // Check round status if group.Status != types.GROUP_STATUS_ROUND_1 { - return nil, errors.Wrap(types.ErrInvalidStatus, "group status is not round 1") + return nil, types.ErrInvalidStatus.Wrap("group status is not round 1") } - // Get member + // Get member and verify if the sender is in the group member, err := k.GetMember(ctx, groupID, memberID) if err != nil { return nil, err } - - // Verify address if !member.Verify(req.Address) { - return nil, errors.Wrapf( - types.ErrMemberNotAuthorized, + return nil, types.ErrMemberNotAuthorized.Wrapf( "memberID %d address %s is not match in this group", memberID, req.Address, @@ -65,23 +59,19 @@ func (k msgServer) SubmitDKGRound1( } // Check previous submit - _, err = k.GetRound1Info(ctx, groupID, req.Round1Info.MemberID) - if err == nil { - return nil, errors.Wrap(types.ErrMemberAlreadySubmit, "this member already submit round 1") + if k.HasRound1Info(ctx, groupID, req.Round1Info.MemberID) { + return nil, types.ErrMemberAlreadySubmit.Wrap("this member already submit round 1") } // Check coefficients commit length if uint64(len(req.Round1Info.CoefficientCommits)) != group.Threshold { - return nil, errors.Wrap( - types.ErrInvalidLengthCoefCommits, - "number of coefficients commit is invalid", - ) + return nil, types.ErrInvalidLengthCoefCommits } // Get dkg-context dkgContext, err := k.GetDKGContext(ctx, groupID) if err != nil { - return nil, errors.Wrap(types.ErrDKGContextNotFound, "dkg-context is not found") + return nil, types.ErrDKGContextNotFound.Wrap("dkg-context is not found") } // Verify one time signature @@ -92,7 +82,7 @@ func (k msgServer) SubmitDKGRound1( req.Round1Info.OneTimePubKey, ) if err != nil { - return nil, errors.Wrap(types.ErrVerifyOneTimeSignatureFailed, err.Error()) + return nil, types.ErrVerifyOneTimeSignatureFailed.Wrap(err.Error()) } // Verify A0 signature @@ -103,13 +93,12 @@ func (k msgServer) SubmitDKGRound1( req.Round1Info.CoefficientCommits[0], ) if err != nil { - return nil, errors.Wrap(types.ErrVerifyA0SignatureFailed, err.Error()) + return nil, types.ErrVerifyA0SignatureFailed.Wrap(err.Error()) } // Add commits to calculate accumulated commits for each index - err = k.AddCommits(ctx, groupID, req.Round1Info.CoefficientCommits) - if err != nil { - return nil, errors.Wrap(types.ErrAddCoefCommit, err.Error()) + if err = k.AddCommits(ctx, groupID, req.Round1Info.CoefficientCommits); err != nil { + return nil, types.ErrAddCoeffCommit.Wrap(err.Error()) } // Add round 1 info @@ -128,19 +117,20 @@ func (k msgServer) SubmitDKGRound1( ), ) + // Add to the pending process group if members submit their information. count := k.GetRound1InfoCount(ctx, groupID) if count == group.Size_ { - // Add the pending process group to the list of pending process groups to be processed at the endblock. k.AddPendingProcessGroup(ctx, groupID) } return &types.MsgSubmitDKGRound1Response{}, nil } -// SubmitDKGRound2 checks the group status, member, and whether the member has already submitted round 2 info. -// It verifies the member, checks the length of encrypted secret shares, computes and stores the member's own public key, -// sets the round 2 info, and emits appropriate events. If all members have submitted round 2 info, -// it updates the group status to round 3. +// SubmitDKGRound2 checks the group status, member, and whether the member has already +// submitted round 2 info. It verifies the member, checks the length of encrypted secret shares, +// computes and stores the member's own public key, sets the round 2 info, and emits appropriate events. +// If all members have submitted round 2 info, add to the pending process group for processing +// group status to round 3. func (k msgServer) SubmitDKGRound2( goCtx context.Context, req *types.MsgSubmitDKGRound2, @@ -149,27 +139,22 @@ func (k msgServer) SubmitDKGRound2( groupID := req.GroupID memberID := req.Round2Info.MemberID - // Get group + // Get group and check group status group, err := k.GetGroup(ctx, groupID) if err != nil { return nil, err } - - // Check round status if group.Status != types.GROUP_STATUS_ROUND_2 { - return nil, errors.Wrap(types.ErrInvalidStatus, "group status is not round 2") + return nil, types.ErrInvalidStatus.Wrap("group status is not round 2") } - // Get member + // Get member and verify if the sender is in the group member, err := k.GetMember(ctx, groupID, memberID) if err != nil { return nil, err } - - // Verify address if !member.Verify(req.Address) { - return nil, errors.Wrapf( - types.ErrMemberNotAuthorized, + return nil, types.ErrMemberNotAuthorized.Wrapf( "memberID %d address %s is not match in this group", memberID, req.Address, @@ -177,28 +162,20 @@ func (k msgServer) SubmitDKGRound2( } // Check previous submit - _, err = k.GetRound2Info(ctx, groupID, memberID) - if err == nil { - return nil, errors.Wrap(types.ErrMemberAlreadySubmit, "this member already submit round 2") + if k.HasRound2Info(ctx, groupID, memberID) { + return nil, types.ErrMemberAlreadySubmit.Wrap("this member already submit round 2") } // Check encrypted secret shares length if uint64(len(req.Round2Info.EncryptedSecretShares)) != group.Size_-1 { - return nil, errors.Wrap( - types.ErrInvalidLengthEncryptedSecretShares, - "number of encrypted secret shares is invalid", - ) + return nil, types.ErrInvalidLengthEncryptedSecretShares } // Compute own public key accCommits := k.GetAllAccumulatedCommits(ctx, groupID) ownPubKey, err := tss.ComputeOwnPublicKey(accCommits, memberID) if err != nil { - return nil, errors.Wrapf( - types.ErrComputeOwnPubKeyFailed, - "compute own public key failed; %s", - err, - ) + return nil, types.ErrComputeOwnPubKeyFailed.Wrapf("compute own public key failed; %s", err) } // Update public key of the member @@ -218,9 +195,9 @@ func (k msgServer) SubmitDKGRound2( ), ) + // Add to the pending process group if members submit their information. count := k.GetRound2InfoCount(ctx, groupID) if count == group.Size_ { - // Add the pending process group to the list of pending process groups to be processed at the endblock. k.AddPendingProcessGroup(ctx, groupID) } @@ -235,27 +212,22 @@ func (k msgServer) Complain(goCtx context.Context, req *types.MsgComplain) (*typ groupID := req.GroupID memberID := req.Complaints[0].Complainant - // Get group + // Get group and check group status group, err := k.GetGroup(ctx, groupID) if err != nil { return nil, err } - - // Check round status if group.Status != types.GROUP_STATUS_ROUND_3 { - return nil, errors.Wrap(types.ErrInvalidStatus, "group status is not round 3") + return nil, types.ErrInvalidStatus.Wrap("group status is not round 3") } - // Get member + // Get member and verify if the sender is in the group member, err := k.GetMember(ctx, groupID, memberID) if err != nil { return nil, err } - - // Verify address if !member.Verify(req.Address) { - return nil, errors.Wrapf( - types.ErrMemberNotAuthorized, + return nil, types.ErrMemberNotAuthorized.Wrapf( "memberID %d address %s is not match in this group", memberID, req.Address, @@ -263,12 +235,11 @@ func (k msgServer) Complain(goCtx context.Context, req *types.MsgComplain) (*typ } // Check already confirm or complain - err = k.checkConfirmOrComplain(ctx, groupID, memberID) - if err != nil { + if err := k.checkConfirmOrComplain(ctx, groupID, memberID); err != nil { return nil, err } - // Verify complaint + // Verify complaint if fail to verify, mark complainant as malicious instead. var complaintsWithStatus []types.ComplaintWithStatus for _, c := range req.Complaints { err := k.HandleVerifyComplaint(ctx, groupID, c) @@ -331,12 +302,9 @@ func (k msgServer) Complain(goCtx context.Context, req *types.MsgComplain) (*typ ComplaintsWithStatus: complaintsWithStatus, }) - // Get confirm complain count + // Add to the pending process group if everyone sends confirm or complain already confirmComplainCount := k.GetConfirmComplainCount(ctx, groupID) - - // Handle fallen group if everyone sends confirm or complain already if confirmComplainCount == group.Size_ { - // Add the pending process group to the list of pending process groups to be processed at the endblock. k.AddPendingProcessGroup(ctx, groupID) } @@ -355,27 +323,22 @@ func (k msgServer) Confirm( groupID := req.GroupID memberID := req.MemberID - // Get group + // Get group and check group status group, err := k.GetGroup(ctx, groupID) if err != nil { return nil, err } - - // Check round status if group.Status != types.GROUP_STATUS_ROUND_3 { - return nil, errors.Wrap(types.ErrInvalidStatus, "group status is not round 3") + return nil, types.ErrInvalidStatus.Wrap("group status is not round 3") } - // Get member + // Get member and verify if the sender is in the group member, err := k.GetMember(ctx, groupID, memberID) if err != nil { return nil, err } - - // Verify address if !member.Verify(req.Address) { - return nil, errors.Wrapf( - types.ErrMemberNotAuthorized, + return nil, types.ErrMemberNotAuthorized.Wrapf( "memberID %d address %s is not match in this group", memberID, req.Address, @@ -383,20 +346,15 @@ func (k msgServer) Confirm( } // Check already confirm or complain - err = k.checkConfirmOrComplain(ctx, groupID, memberID) - if err != nil { + if err := k.checkConfirmOrComplain(ctx, groupID, memberID); err != nil { return nil, err } // Verify OwnPubKeySig - err = k.HandleVerifyOwnPubKeySig(ctx, groupID, memberID, req.OwnPubKeySig) - if err != nil { + if err := k.HandleVerifyOwnPubKeySig(ctx, groupID, memberID, req.OwnPubKeySig); err != nil { return nil, err } - // Get confirm complain count - confirmComplainCount := k.GetConfirmComplainCount(ctx, groupID) - // Add confirm k.AddConfirm(ctx, groupID, types.Confirm{ MemberID: memberID, @@ -414,9 +372,9 @@ func (k msgServer) Confirm( ), ) - // Handle fallen group if everyone sends confirm or complain already - if confirmComplainCount+1 == group.Size_ { - // Add the pending process group to the list of pending process groups to be processed at the endblock. + // Add to the pending process group if everyone sends confirm or complain already + confirmComplainCount := k.GetConfirmComplainCount(ctx, groupID) + if confirmComplainCount == group.Size_ { k.AddPendingProcessGroup(ctx, groupID) } @@ -424,17 +382,15 @@ func (k msgServer) Confirm( } // SubmitDEs receives a member's request containing Distributed Key Generation (DKG) shares (DEs). -// It converts the member's address from Bech32 to AccAddress format and then delegates the task of setting the DEs to the HandleSetDEs function. +// It converts the member's address from Bech32 to AccAddress format and then delegates the task of +// setting the DEs to the HandleSetDEs function. func (k msgServer) SubmitDEs(goCtx context.Context, req *types.MsgSubmitDEs) (*types.MsgSubmitDEsResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // Convert the address from Bech32 format to AccAddress format member, err := sdk.AccAddressFromBech32(req.Address) if err != nil { - return nil, errors.Wrapf( - types.ErrInvalidAccAddressFormat, - "invalid account address: %s", err, - ) + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid account address: %s", err) } err = k.HandleSetDEs(ctx, member, req.DEs) @@ -445,50 +401,46 @@ func (k msgServer) SubmitDEs(goCtx context.Context, req *types.MsgSubmitDEs) (*t return &types.MsgSubmitDEsResponse{}, nil } -// SubmitSignature verifies that the member and signing process are valid, and that the member hasn't already signed. -// It checks the correctness of the signature and if the threshold is met, it combines all partial signatures into a group signature. -// It then updates the signing record, deletes all interim data, and emits appropriate events. +// SubmitSignature verifies that the member and signing process are valid, and that the member +// hasn't already signed. It checks the correctness of the signature and if the threshold is met, +// it combines all partial signatures into a group signature. It then updates the signing record, +// deletes all interim data, and emits appropriate events. func (k msgServer) SubmitSignature( goCtx context.Context, req *types.MsgSubmitSignature, ) (*types.MsgSubmitSignatureResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - // Get signing + // Get signing and check signing is still waiting for signature signing, err := k.GetSigning(ctx, req.SigningID) if err != nil { return nil, err } - - // Check signing is still waiting for signature if signing.Status != types.SIGNING_STATUS_WAITING { - return nil, errors.Wrapf( - types.ErrSigningAlreadySuccess, "signing ID: %d is not in waiting state", req.SigningID, + return nil, types.ErrSigningAlreadySuccess.Wrapf( + "signing ID: %d is not in waiting state", req.SigningID, ) } - // Check sender not in assigned member + // Check if sender not in assigned member am, found := signing.AssignedMembers.FindAssignedMember(req.MemberID, req.Address) if !found { - return nil, errors.Wrapf( - types.ErrMemberNotAssigned, "member ID/Address: %d is not in assigned members", req.MemberID, + return nil, types.ErrMemberNotAssigned.Wrapf( + "member ID/Address: %d is not in assigned members", req.MemberID, ) } // Verify signature R if !signing.AssignedMembers.VerifySignatureR(req.MemberID, req.Signature.R()) { - return nil, errors.Wrapf( - types.ErrPubNonceNotEqualToSigR, + return nil, types.ErrPubNonceNotEqualToSigR.Wrapf( "public nonce from member ID: %d is not equal signature r", req.MemberID, ) } // Check member is already signed - _, err = k.GetPartialSignature(ctx, req.SigningID, req.MemberID) - if err == nil { - return nil, errors.Wrapf( - types.ErrAlreadySigned, + if k.HasPartialSignature(ctx, req.SigningID, req.MemberID) { + return nil, types.ErrAlreadySigned.Wrapf( "member ID: %d is already signed on signing ID: %d", req.MemberID, req.SigningID, @@ -498,7 +450,7 @@ func (k msgServer) SubmitSignature( // Compute lagrange coefficient lagrange, err := tss.ComputeLagrangeCoefficient(req.MemberID, signing.AssignedMembers.MemberIDs()) if err != nil { - return nil, errors.Wrapf(types.ErrInvalidArgument, err.Error()) + return nil, types.ErrInvalidArgument.Wrap(err.Error()) } // Verify signing signature @@ -511,13 +463,14 @@ func (k msgServer) SubmitSignature( am.PubKey, ) if err != nil { - return nil, errors.Wrapf(types.ErrVerifySigningSigFailed, err.Error()) + return nil, types.ErrVerifySigningSigFailed.Wrap(err.Error()) } // Add partial signature k.AddPartialSignature(ctx, req.SigningID, req.MemberID, req.Signature) - sigCount := k.GetSignatureCount(ctx, req.SigningID) + // Check if the threshold is met, if so, add to the pending process signing. + sigCount := k.GetPartialSignatureCount(ctx, req.SigningID) if sigCount == uint64(len(signing.AssignedMembers)) { k.AddPendingProcessSigning(ctx, req.SigningID) } @@ -544,8 +497,7 @@ func (k Keeper) UpdateParams( req *types.MsgUpdateParams, ) (*types.MsgUpdateParamsResponse, error) { if k.authority != req.Authority { - return nil, errors.Wrapf( - govtypes.ErrInvalidSigner, + return nil, govtypes.ErrInvalidSigner.Wrapf( "invalid authority; expected %s, got %s", k.authority, req.Authority, @@ -560,21 +512,19 @@ func (k Keeper) UpdateParams( return &types.MsgUpdateParamsResponse{}, nil } -// checkConfirmOrComplain checks whether a specific member has already sent a "Confirm" or "Complaint" message in a given group. -// If either a confirm or a complain message from the member is found, an error is returned. +// checkConfirmOrComplain checks whether a specific member has already sent a "Confirm" or +// "Complaint" message in a given group. If either a confirm or a complain message from the member +// is found, an error is returned. func (k Keeper) checkConfirmOrComplain(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) error { - _, err := k.GetConfirm(ctx, groupID, memberID) - if err == nil { - return errors.Wrapf( - types.ErrMemberIsAlreadyComplainOrConfirm, + if k.HasConfirm(ctx, groupID, memberID) { + return types.ErrMemberIsAlreadyComplainOrConfirm.Wrapf( "memberID %d already send confirm message", memberID, ) } - _, err = k.GetComplaintsWithStatus(ctx, groupID, memberID) - if err == nil { - return errors.Wrapf( - types.ErrMemberIsAlreadyComplainOrConfirm, + + if k.HasComplaintsWithStatus(ctx, groupID, memberID) { + return types.ErrMemberIsAlreadyComplainOrConfirm.Wrapf( "memberID %d already send complain message", memberID, ) diff --git a/x/tss/keeper/params.go b/x/tss/keeper/params.go index e9d4a9be9..d59fdc2c7 100644 --- a/x/tss/keeper/params.go +++ b/x/tss/keeper/params.go @@ -8,8 +8,7 @@ import ( // GetParams returns the current x/tss module parameters. func (k Keeper) GetParams(ctx sdk.Context) (p types.Params) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ParamsKeyPrefix) + bz := ctx.KVStore(k.storeKey).Get(types.ParamsKeyPrefix) if bz == nil { return p } @@ -24,9 +23,7 @@ func (k Keeper) SetParams(ctx sdk.Context, p types.Params) error { return err } - store := ctx.KVStore(k.storeKey) - bz := k.cdc.MustMarshal(&p) - store.Set(types.ParamsKeyPrefix, bz) + ctx.KVStore(k.storeKey).Set(types.ParamsKeyPrefix, k.cdc.MustMarshal(&p)) return nil } diff --git a/x/tss/keeper/round1.go b/x/tss/keeper/round1.go index 6de92df03..19a0266d6 100644 --- a/x/tss/keeper/round1.go +++ b/x/tss/keeper/round1.go @@ -1,7 +1,6 @@ package keeper import ( - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bandprotocol/chain/v2/pkg/tss" @@ -14,19 +13,23 @@ func (k Keeper) AddRound1Info(ctx sdk.Context, groupID tss.GroupID, round1Info t k.SetRound1Info(ctx, groupID, round1Info) } -// SetRound1Info sets round 1 info for a member of a group. +// SetRound1Info sets round1Info for a member of a group. func (k Keeper) SetRound1Info(ctx sdk.Context, groupID tss.GroupID, round1Info types.Round1Info) { ctx.KVStore(k.storeKey). Set(types.Round1InfoMemberStoreKey(groupID, round1Info.MemberID), k.cdc.MustMarshal(&round1Info)) } -// GetRound1Info retrieves round 1 info of a member from the store. +// HasRound1Info checks if a round1Info of a member exists in the store. +func (k Keeper) HasRound1Info(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) bool { + return ctx.KVStore(k.storeKey).Has(types.Round1InfoMemberStoreKey(groupID, memberID)) +} + +// GetRound1Info retrieves round1Info of a member from the store. func (k Keeper) GetRound1Info(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) (types.Round1Info, error) { bz := ctx.KVStore(k.storeKey).Get(types.Round1InfoMemberStoreKey(groupID, memberID)) if bz == nil { - return types.Round1Info{}, errors.Wrapf( - types.ErrRound1InfoNotFound, - "failed to get round 1 info with groupID: %d and memberID %d", + return types.Round1Info{}, types.ErrRound1InfoNotFound.Wrapf( + "failed to get round1Info with groupID: %d and memberID %d", groupID, memberID, ) @@ -36,12 +39,12 @@ func (k Keeper) GetRound1Info(ctx sdk.Context, groupID tss.GroupID, memberID tss return r1, nil } -// GetRound1InfoIterator gets an iterator over all round 1 info of a group. +// GetRound1InfoIterator gets an iterator over all round1Info of a group. func (k Keeper) GetRound1InfoIterator(ctx sdk.Context, groupID tss.GroupID) sdk.Iterator { return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.Round1InfoStoreKey(groupID)) } -// GetRound1Infos retrieves round 1 infos for a group from the store. +// GetRound1Infos retrieves round1Infos for a group from the store. func (k Keeper) GetRound1Infos(ctx sdk.Context, groupID tss.GroupID) []types.Round1Info { var round1Infos []types.Round1Info iterator := k.GetRound1InfoIterator(ctx, groupID) @@ -54,12 +57,12 @@ func (k Keeper) GetRound1Infos(ctx sdk.Context, groupID tss.GroupID) []types.Rou return round1Infos } -// DeleteRound1Info removes the round 1 info of a group member from the store. +// DeleteRound1Info removes the round1Info of a group member from the store. func (k Keeper) DeleteRound1Info(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) { ctx.KVStore(k.storeKey).Delete(types.Round1InfoMemberStoreKey(groupID, memberID)) } -// DeleteRound1Infos removes all round 1 info associated with a specific group ID from the store. +// DeleteRound1Infos removes all round1Info associated with a specific group ID from the store. func (k Keeper) DeleteRound1Infos(ctx sdk.Context, groupID tss.GroupID) { iterator := k.GetRound1InfoIterator(ctx, groupID) defer iterator.Close() @@ -70,24 +73,24 @@ func (k Keeper) DeleteRound1Infos(ctx sdk.Context, groupID tss.GroupID) { } } -// SetRound1InfoCount sets the count of round 1 info for a group in the store. +// SetRound1InfoCount sets the count of round1Info for a group in the store. func (k Keeper) SetRound1InfoCount(ctx sdk.Context, groupID tss.GroupID, count uint64) { ctx.KVStore(k.storeKey).Set(types.Round1InfoCountStoreKey(groupID), sdk.Uint64ToBigEndian(count)) } -// GetRound1InfoCount retrieves the count of round 1 info for a group from the store. +// GetRound1InfoCount retrieves the count of round1Info for a group from the store. func (k Keeper) GetRound1InfoCount(ctx sdk.Context, groupID tss.GroupID) uint64 { bz := ctx.KVStore(k.storeKey).Get(types.Round1InfoCountStoreKey(groupID)) return sdk.BigEndianToUint64(bz) } -// AddRound1InfoCount increments the count of round 1 info for a group in the store. +// AddRound1InfoCount increments the count of round1Info for a group in the store. func (k Keeper) AddRound1InfoCount(ctx sdk.Context, groupID tss.GroupID) { count := k.GetRound1InfoCount(ctx, groupID) k.SetRound1InfoCount(ctx, groupID, count+1) } -// DeleteRound1InfoCount remove the round 1 info count data of a group from the store. +// DeleteRound1InfoCount remove the round1Info count data of a group from the store. func (k Keeper) DeleteRound1InfoCount(ctx sdk.Context, groupID tss.GroupID) { ctx.KVStore(k.storeKey).Delete(types.Round1InfoCountStoreKey(groupID)) } diff --git a/x/tss/keeper/round2.go b/x/tss/keeper/round2.go index fc2e6814d..6baf7a999 100644 --- a/x/tss/keeper/round2.go +++ b/x/tss/keeper/round2.go @@ -1,7 +1,6 @@ package keeper import ( - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bandprotocol/chain/v2/pkg/tss" @@ -9,31 +8,27 @@ import ( ) // AddRound2Info adds the round2Info of a member in the store and increments the count of round2Info. -func (k Keeper) AddRound2Info( - ctx sdk.Context, - groupID tss.GroupID, - round2Info types.Round2Info, -) { +func (k Keeper) AddRound2Info(ctx sdk.Context, groupID tss.GroupID, round2Info types.Round2Info) { k.AddRound2InfoCount(ctx, groupID) k.SetRound2Info(ctx, groupID, round2Info) } // SetRound2Info sets the round2Info of a member in the store and increments the count of round2Info. -func (k Keeper) SetRound2Info( - ctx sdk.Context, - groupID tss.GroupID, - round2Info types.Round2Info, -) { +func (k Keeper) SetRound2Info(ctx sdk.Context, groupID tss.GroupID, round2Info types.Round2Info) { ctx.KVStore(k.storeKey). Set(types.Round2InfoMemberStoreKey(groupID, round2Info.MemberID), k.cdc.MustMarshal(&round2Info)) } +// HasRound2Info checks if the round2Info of a member exists in the store. +func (k Keeper) HasRound2Info(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) bool { + return ctx.KVStore(k.storeKey).Has(types.Round2InfoMemberStoreKey(groupID, memberID)) +} + // GetRound2Info retrieves the round2Info of a member from the store. func (k Keeper) GetRound2Info(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) (types.Round2Info, error) { bz := ctx.KVStore(k.storeKey).Get(types.Round2InfoMemberStoreKey(groupID, memberID)) if bz == nil { - return types.Round2Info{}, errors.Wrapf( - types.ErrRound2InfoNotFound, + return types.Round2Info{}, types.ErrRound2InfoNotFound.Wrapf( "failed to get round2Info with groupID: %d, memberID: %d", groupID, memberID, @@ -49,7 +44,7 @@ func (k Keeper) DeleteRound2Info(ctx sdk.Context, groupID tss.GroupID, memberID ctx.KVStore(k.storeKey).Delete(types.Round2InfoMemberStoreKey(groupID, memberID)) } -// DeleteRound2Infos removes all round 2 info associated with a specific group ID from the store. +// DeleteRound2Infos removes all round2Info associated with a specific group ID from the store. func (k Keeper) DeleteRound2Infos(ctx sdk.Context, groupID tss.GroupID) { iterator := k.GetRound2InfoIterator(ctx, groupID) defer iterator.Close() @@ -77,12 +72,12 @@ func (k Keeper) AddRound2InfoCount(ctx sdk.Context, groupID tss.GroupID) { k.SetRound2InfoCount(ctx, groupID, count+1) } -// DeleteRound2InfoCount remove the round 2 info count data of a group from the store. +// DeleteRound2InfoCount remove the round2Info count data of a group from the store. func (k Keeper) DeleteRound2InfoCount(ctx sdk.Context, groupID tss.GroupID) { ctx.KVStore(k.storeKey).Delete(types.Round2InfoCountStoreKey(groupID)) } -// Getround2InfoIterator gets an iterator over all round 2 info of a group. +// Getround2InfoIterator gets an iterator over all round2Info of a group. func (k Keeper) GetRound2InfoIterator(ctx sdk.Context, groupID tss.GroupID) sdk.Iterator { return sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.Round2InfoStoreKey(groupID)) } diff --git a/x/tss/keeper/round3.go b/x/tss/keeper/round3.go index d76057182..121393472 100644 --- a/x/tss/keeper/round3.go +++ b/x/tss/keeper/round3.go @@ -1,7 +1,6 @@ package keeper import ( - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bandprotocol/chain/v2/pkg/tss" @@ -14,19 +13,19 @@ func (k Keeper) HandleVerifyComplaint( groupID tss.GroupID, complaint types.Complaint, ) error { - // Get round 1 info from member Complainant + // Get round1Info from member Complainant round1Complainant, err := k.GetRound1Info(ctx, groupID, complaint.Complainant) if err != nil { return err } - // Get round 1 info from member Respondent + // Get round1Info from member Respondent round1Respondent, err := k.GetRound1Info(ctx, groupID, complaint.Respondent) if err != nil { return err } - // Get round 2 info from member Respondent + // Get round2Info from member Respondent round2Respondent, err := k.GetRound2Info(ctx, groupID, complaint.Respondent) if err != nil { return err @@ -37,8 +36,7 @@ func (k Keeper) HandleVerifyComplaint( // Return error if the slot exceeds length of shares if int(complainantIndex) >= len(round2Respondent.EncryptedSecretShares) { - return errors.Wrapf( - types.ErrComplainFailed, + return types.ErrComplainFailed.Wrapf( "No encrypted secret share from MemberID(%d) to MemberID(%d)", complaint.Respondent, complaint.Complainant, @@ -56,8 +54,7 @@ func (k Keeper) HandleVerifyComplaint( round1Respondent.CoefficientCommits, ) if err != nil { - return errors.Wrapf( - types.ErrComplainFailed, + return types.ErrComplainFailed.Wrapf( "failed to complaint member: %d with groupID: %d; %s", complaint.Respondent, groupID, @@ -90,8 +87,7 @@ func (k Keeper) HandleVerifyOwnPubKeySig( // Verify own public key sig err = tss.VerifyOwnPubKeySignature(memberID, dkgContext, ownPubKeySig, member.PubKey) if err != nil { - return errors.Wrapf( - types.ErrConfirmFailed, + return types.ErrConfirmFailed.Wrapf( "failed to verify own public key with memberID: %d; %s", memberID, err, @@ -117,8 +113,15 @@ func (k Keeper) SetComplaintsWithStatus( groupID tss.GroupID, complaintsWithStatus types.ComplaintsWithStatus, ) { - ctx.KVStore(k.storeKey). - Set(types.ComplainsWithStatusMemberStoreKey(groupID, complaintsWithStatus.MemberID), k.cdc.MustMarshal(&complaintsWithStatus)) + ctx.KVStore(k.storeKey).Set( + types.ComplainsWithStatusMemberStoreKey(groupID, complaintsWithStatus.MemberID), + k.cdc.MustMarshal(&complaintsWithStatus), + ) +} + +// HasComplaintsWithStatus checks if the complaints with status exists for a specific groupID and memberID in the store. +func (k Keeper) HasComplaintsWithStatus(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) bool { + return ctx.KVStore(k.storeKey).Has(types.ComplainsWithStatusMemberStoreKey(groupID, memberID)) } // GetComplaintsWithStatus retrieves the complaints with status for a specific groupID and memberID from the store. @@ -129,8 +132,7 @@ func (k Keeper) GetComplaintsWithStatus( ) (types.ComplaintsWithStatus, error) { bz := ctx.KVStore(k.storeKey).Get(types.ComplainsWithStatusMemberStoreKey(groupID, memberID)) if bz == nil { - return types.ComplaintsWithStatus{}, errors.Wrapf( - types.ErrComplaintsWithStatusNotFound, + return types.ComplaintsWithStatus{}, types.ErrComplaintsWithStatusNotFound.Wrapf( "failed to get complaints with status with groupID %d memberID %d", groupID, memberID, @@ -195,6 +197,11 @@ func (k Keeper) SetConfirm( Set(types.ConfirmMemberStoreKey(groupID, confirm.MemberID), k.cdc.MustMarshal(&confirm)) } +// HasConfirm checks if a confirm exists for a specific groupID and memberID in the store. +func (k Keeper) HasConfirm(ctx sdk.Context, groupID tss.GroupID, memberID tss.MemberID) bool { + return ctx.KVStore(k.storeKey).Has(types.ConfirmMemberStoreKey(groupID, memberID)) +} + // GetConfirm retrieves the confirm for a specific groupID and memberID from the store. func (k Keeper) GetConfirm( ctx sdk.Context, @@ -203,8 +210,7 @@ func (k Keeper) GetConfirm( ) (types.Confirm, error) { bz := ctx.KVStore(k.storeKey).Get(types.ConfirmMemberStoreKey(groupID, memberID)) if bz == nil { - return types.Confirm{}, errors.Wrapf( - types.ErrConfirmNotFound, + return types.Confirm{}, types.ErrConfirmNotFound.Wrapf( "failed to get confirm with groupID %d memberID %d", groupID, memberID, @@ -294,13 +300,13 @@ func (k Keeper) DeleteAllDKGInterimData( ) { // Delete DKG context k.DeleteDKGContext(ctx, groupID) - // Delete round 1 infos + // Delete round1Infos k.DeleteRound1Infos(ctx, groupID) - // Delete round 1 info count + // Delete round1InfoCount k.DeleteRound1InfoCount(ctx, groupID) - // Delete round 2 infos + // Delete round2Infos k.DeleteRound2Infos(ctx, groupID) - // Delete round 2 info count + // Delete round2InfoCount k.DeleteRound2InfoCount(ctx, groupID) // Delete all complaint with status k.DeleteAllComplainsWithStatus(ctx, groupID) diff --git a/x/tss/keeper/signing.go b/x/tss/keeper/signing.go index 0816e2ee6..aa4426981 100644 --- a/x/tss/keeper/signing.go +++ b/x/tss/keeper/signing.go @@ -4,18 +4,21 @@ import ( "bytes" "encoding/hex" "fmt" + "slices" "sort" - "cosmossdk.io/errors" tmbytes "github.com/cometbft/cometbft/libs/bytes" sdk "github.com/cosmos/cosmos-sdk/types" - "golang.org/x/exp/slices" "github.com/bandprotocol/chain/v2/pkg/bandrng" "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/x/tss/types" ) +// ================================== +// Signing Information Store +// ================================== + // SetSigningCount sets the number of signing count to the given value. func (k Keeper) SetSigningCount(ctx sdk.Context, count uint64) { ctx.KVStore(k.storeKey).Set(types.SigningCountStoreKey, sdk.Uint64ToBigEndian(count)) @@ -33,12 +36,12 @@ func (k Keeper) GetNextSigningID(ctx sdk.Context) tss.SigningID { return tss.SigningID(signingNumber) } -// SetSigning sets the signing data for a given signing ID. +// SetSigning sets the signing data of a given signing ID. func (k Keeper) SetSigning(ctx sdk.Context, signing types.Signing) { ctx.KVStore(k.storeKey).Set(types.SigningStoreKey(signing.ID), k.cdc.MustMarshal(&signing)) } -// GetSigning retrieves the signing data for a given signing ID from the store. +// GetSigning retrieves the signing data of a given signing ID from the store. func (k Keeper) GetSigning(ctx sdk.Context, signingID tss.SigningID) (types.Signing, error) { bz := ctx.KVStore(k.storeKey).Get(types.SigningStoreKey(signingID)) if bz == nil { @@ -52,7 +55,7 @@ func (k Keeper) GetSigning(ctx sdk.Context, signingID tss.SigningID) (types.Sign return signing, nil } -// MustGetSigning returns the signing for the given ID. Panics error if not exists. +// MustGetSigning returns the signing of the given ID. Panics error if not exists. func (k Keeper) MustGetSigning(ctx sdk.Context, signingID tss.SigningID) types.Signing { signing, err := k.GetSigning(ctx, signingID) if err != nil { @@ -88,116 +91,57 @@ func (k Keeper) AddSigning(ctx sdk.Context, signing types.Signing) tss.SigningID return signing.ID } -// DeleteSigning deletes the signing data for a given signing ID from the store. +// DeleteSigning deletes the signing data of a given signing ID from the store. func (k Keeper) DeleteSigning(ctx sdk.Context, signingID tss.SigningID) { ctx.KVStore(k.storeKey).Delete(types.SigningStoreKey(signingID)) } -// DeleteAssignedMembers deletes the assigned members for a given signing ID from the store. +// DeleteAssignedMembers deletes the assigned members of a given signing ID from the store. func (k Keeper) DeleteAssignedMembers(ctx sdk.Context, signingID tss.SigningID) { signing := k.MustGetSigning(ctx, signingID) signing.AssignedMembers = nil k.SetSigning(ctx, signing) } -// GetPendingSignings retrieves the pending signing objects associated with the given account address. -func (k Keeper) GetPendingSignings(ctx sdk.Context, address sdk.AccAddress) []uint64 { - // Get the ID of the last expired signing - lastExpired := k.GetLastExpiredSigningID(ctx) - - // Get the total signing count - signingCount := k.GetSigningCount(ctx) - - var pendingSignings []uint64 - for sid := lastExpired + 1; uint64(sid) <= signingCount; sid++ { - // Retrieve the signing object - signing := k.MustGetSigning(ctx, sid) - - // Ignore if it's successful already - if signing.Status == types.SIGNING_STATUS_SUCCESS { - continue - } - - // Check if address is assigned for signing - for _, am := range signing.AssignedMembers { - if am.Address == address.String() { - // Add the signing to the pendingSignings if there is no partial sig of the member yet. - if _, err := k.GetPartialSignature(ctx, sid, am.MemberID); err != nil { - pendingSignings = append(pendingSignings, uint64(signing.ID)) - } - } - } - } +// ================================== +// Partial Signature information Store +// ================================== - return pendingSignings +// SetPartialSignatureCount sets the count of partial signatures of a given signing ID in the store. +func (k Keeper) SetPartialSignatureCount(ctx sdk.Context, signingID tss.SigningID, count uint64) { + ctx.KVStore(k.storeKey).Set(types.PartialSignatureCountStoreKey(signingID), sdk.Uint64ToBigEndian(count)) } -// GetPendingSigningsByPubKey retrieves the pending signing objects associated with the given tss public key. -func (k Keeper) GetPendingSigningsByPubKey(ctx sdk.Context, pubKey tss.Point) []uint64 { - // Get the ID of the last expired signing - lastExpired := k.GetLastExpiredSigningID(ctx) - - // Get the total signing count - signingCount := k.GetSigningCount(ctx) - - var pendingSignings []uint64 - for sid := lastExpired + 1; uint64(sid) <= signingCount; sid++ { - // Retrieve the signing object - signing := k.MustGetSigning(ctx, sid) - - // Ignore if it's successful already - if signing.Status == types.SIGNING_STATUS_SUCCESS { - continue - } - - // Check if address is assigned for signing - for _, am := range signing.AssignedMembers { - if bytes.Equal(am.PubKey, pubKey) { - // Add the signing to the pendingSignings if there is no partial sig of the member yet. - if _, err := k.GetPartialSignature(ctx, sid, am.MemberID); err != nil { - pendingSignings = append(pendingSignings, uint64(signing.ID)) - } - } - } - } - - return pendingSignings -} - -// SetSignatureCount sets the count of signature data for a sign in the store. -func (k Keeper) SetSignatureCount(ctx sdk.Context, signingID tss.SigningID, count uint64) { - ctx.KVStore(k.storeKey).Set(types.SigCountStoreKey(signingID), sdk.Uint64ToBigEndian(count)) -} - -// GetSignatureCount retrieves the count of signature data for a sign from the store. -func (k Keeper) GetSignatureCount(ctx sdk.Context, signingID tss.SigningID) uint64 { - bz := ctx.KVStore(k.storeKey).Get(types.SigCountStoreKey(signingID)) +// GetPartialSignatureCount retrieves the count of partial signatures of a given signing ID from the store. +func (k Keeper) GetPartialSignatureCount(ctx sdk.Context, signingID tss.SigningID) uint64 { + bz := ctx.KVStore(k.storeKey).Get(types.PartialSignatureCountStoreKey(signingID)) return sdk.BigEndianToUint64(bz) } -// AddSignatureCount increments the count of signature data for a sign in the store. -func (k Keeper) AddSignatureCount(ctx sdk.Context, signingID tss.SigningID) { - count := k.GetSignatureCount(ctx, signingID) - k.SetSignatureCount(ctx, signingID, count+1) +// AddPartialSignatureCount increments the count of partial signatures of a given signing ID in the store. +func (k Keeper) AddPartialSignatureCount(ctx sdk.Context, signingID tss.SigningID) { + count := k.GetPartialSignatureCount(ctx, signingID) + k.SetPartialSignatureCount(ctx, signingID, count+1) } -// DeleteSignatureCount delete the signature count data of a sign from the store. -func (k Keeper) DeleteSignatureCount(ctx sdk.Context, signingID tss.SigningID) { - ctx.KVStore(k.storeKey).Delete(types.SigCountStoreKey(signingID)) +// DeletePartialSignatureCount delete the signature count data of a sign from the store. +func (k Keeper) DeletePartialSignatureCount(ctx sdk.Context, signingID tss.SigningID) { + ctx.KVStore(k.storeKey).Delete(types.PartialSignatureCountStoreKey(signingID)) } -// AddPartialSignature adds the partial signature for a specific signing ID and member ID and increments the count of signature data. +// AddPartialSignature adds the partial signature of a specific signing ID from the given member ID +// and increments the count of partial signature. func (k Keeper) AddPartialSignature( ctx sdk.Context, signingID tss.SigningID, memberID tss.MemberID, signature tss.Signature, ) { - k.AddSignatureCount(ctx, signingID) + k.AddPartialSignatureCount(ctx, signingID) k.SetPartialSignature(ctx, signingID, memberID, signature) } -// SetPartialSignature sets the partial signature for a specific signing ID and member ID. +// SetPartialSignature sets the partial signature of a specific signing ID and member ID. func (k Keeper) SetPartialSignature( ctx sdk.Context, signingID tss.SigningID, @@ -207,7 +151,12 @@ func (k Keeper) SetPartialSignature( ctx.KVStore(k.storeKey).Set(types.PartialSignatureMemberStoreKey(signingID, memberID), signature) } -// GetPartialSignature retrieves the partial signature for a specific signing ID and member ID from the store. +// HasPartialSignature checks if the partial signature of a specific signing ID and member ID exists in the store. +func (k Keeper) HasPartialSignature(ctx sdk.Context, signingID tss.SigningID, memberID tss.MemberID) bool { + return ctx.KVStore(k.storeKey).Has(types.PartialSignatureMemberStoreKey(signingID, memberID)) +} + +// GetPartialSignature retrieves the partial signature of a specific signing ID and member ID from the store. func (k Keeper) GetPartialSignature( ctx sdk.Context, signingID tss.SigningID, @@ -215,8 +164,7 @@ func (k Keeper) GetPartialSignature( ) (tss.Signature, error) { bz := ctx.KVStore(k.storeKey).Get(types.PartialSignatureMemberStoreKey(signingID, memberID)) if bz == nil { - return nil, errors.Wrapf( - types.ErrPartialSignatureNotFound, + return nil, types.ErrPartialSignatureNotFound.Wrapf( "failed to get partial signature with signingID: %d memberID: %d", signingID, memberID, @@ -256,7 +204,8 @@ func (k Keeper) GetPartialSignatures(ctx sdk.Context, signingID tss.SigningID) t return pzs } -// GetPartialSignaturesWithKey retrieves all partial signatures for a specific signing ID from the store along with their corresponding member IDs. +// GetPartialSignaturesWithKey retrieves all partial signatures for a specific signing ID +// from the store along with their corresponding member IDs. func (k Keeper) GetPartialSignaturesWithKey(ctx sdk.Context, signingID tss.SigningID) []types.PartialSignature { var pzs []types.PartialSignature iterator := k.GetPartialSignatureIterator(ctx, signingID) @@ -270,14 +219,25 @@ func (k Keeper) GetPartialSignaturesWithKey(ctx sdk.Context, signingID tss.Signi return pzs } -// GetRandomAssignedMembers generates a random selection of assigned members for a signing process. -// It selects 't' assigned members out of 'members size' assigned members using a deterministic random number generator (DRBG). +// ================================== +// Create Signing +// ================================== + +// GetRandomAssignedMembers select a random assigned members for a signing process. +// It selects 't' assigned members out of the available members in the given group using +// a deterministic random number generator (DRBG). func (k Keeper) GetRandomAssignedMembers( ctx sdk.Context, + groupID tss.GroupID, signingID uint64, - members []types.Member, t uint64, ) ([]types.Member, error) { + // Get available members + members, err := k.GetAvailableMembers(ctx, groupID) + if err != nil { + return nil, err + } + members_size := uint64(len(members)) if t > members_size { return nil, types.ErrUnexpectedThreshold.Wrapf("t must less than or equal to size") @@ -312,30 +272,22 @@ func (k Keeper) GetRandomAssignedMembers( return selected, nil } -// HandleAssignedMembers handles the assignment of members for a group signature process. -func (k Keeper) HandleAssignedMembers( +// AssignMembers handles the assignment of members for a group signature process. +func (k Keeper) AssignMembers( ctx sdk.Context, group types.Group, msg []byte, ) (types.AssignedMembers, error) { // Check group status if group.Status != types.GROUP_STATUS_ACTIVE { - return types.AssignedMembers{}, types.ErrGroupIsNotActive.Wrap( - "group status is not active", - ) - } - - // Get available members - members, err := k.GetAvailableMembers(ctx, group.ID) - if err != nil { - return types.AssignedMembers{}, err + return types.AssignedMembers{}, types.ErrGroupIsNotActive.Wrap("group status is not active") } // Random assigning members selectedMembers, err := k.GetRandomAssignedMembers( ctx, + group.ID, k.GetSigningCount(ctx)+1, - members, group.Threshold, ) if err != nil { @@ -343,12 +295,25 @@ func (k Keeper) HandleAssignedMembers( } // Handle assigned members by polling DE and retrieve assigned members information. - assignedMembers, err := k.HandleAssignedMembersPollDE(ctx, selectedMembers) + des, err := k.PollDEs(ctx, selectedMembers) if err != nil { return types.AssignedMembers{}, err } - // Compute commitment from mids, public D and public E + var assignedMembers types.AssignedMembers + for i, member := range selectedMembers { + assignedMembers = append(assignedMembers, types.AssignedMember{ + MemberID: member.ID, + Address: member.Address, + PubKey: member.PubKey, + PubD: des[i].PubD, + PubE: des[i].PubE, + BindingFactor: nil, + PubNonce: nil, + }) + } + + // Compute commitment from mids, public D, and public E commitment, err := tss.ComputeCommitment( types.Members(selectedMembers).GetIDs(), assignedMembers.PubDs(), @@ -379,175 +344,8 @@ func (k Keeper) HandleAssignedMembers( return assignedMembers, nil } -// SetLastExpiredSigningID sets the last expired signing ID in the store. -func (k Keeper) SetLastExpiredSigningID(ctx sdk.Context, signingID tss.SigningID) { - ctx.KVStore(k.storeKey).Set(types.LastExpiredSigningIDStoreKey, sdk.Uint64ToBigEndian(uint64(signingID))) -} - -// GetLastExpiredSigningID retrieves the last expired signing ID from the store. -func (k Keeper) GetLastExpiredSigningID(ctx sdk.Context) tss.SigningID { - bz := ctx.KVStore(k.storeKey).Get(types.LastExpiredSigningIDStoreKey) - return tss.SigningID(sdk.BigEndianToUint64(bz)) -} - -// AddPendingProcessSigning adds a new pending process signing to the store. -func (k Keeper) AddPendingProcessSigning(ctx sdk.Context, signingID tss.SigningID) { - pss := k.GetPendingProcessSignings(ctx) - pss = append(pss, signingID) - k.SetPendingProcessSignings(ctx, types.PendingProcessSignings{ - SigningIDs: pss, - }) -} - -// SetPendingProcessSignings sets the given pending process signings in the store. -func (k Keeper) SetPendingProcessSignings(ctx sdk.Context, pgs types.PendingProcessSignings) { - ctx.KVStore(k.storeKey).Set(types.PendingSigningsStoreKey, k.cdc.MustMarshal(&pgs)) -} - -// GetPendingProcessSignings retrieves the list of pending process signings from the store. -// It returns an empty list if the key does not exist in the store. -func (k Keeper) GetPendingProcessSignings(ctx sdk.Context) []tss.SigningID { - bz := ctx.KVStore(k.storeKey).Get(types.PendingSigningsStoreKey) - if len(bz) == 0 { - // Return an empty list if the key does not exist in the store. - return []tss.SigningID{} - } - pss := types.PendingProcessSignings{} - k.cdc.MustUnmarshal(bz, &pss) - return pss.SigningIDs -} - -// HandleExpiredSignings cleans up expired signings and removes them from the store. -func (k Keeper) HandleExpiredSignings(ctx sdk.Context) { - // Get the current signing ID to start processing from - currentSigningID := k.GetLastExpiredSigningID(ctx) + 1 - - // Get the last signing ID in the store - lastSigningID := tss.SigningID(k.GetSigningCount(ctx)) - - // Process each signing starting from currentSigningID - for ; currentSigningID <= lastSigningID; currentSigningID++ { - // Get the signing - signing := k.MustGetSigning(ctx, currentSigningID) - - // Check if the signing is still within the expiration period - if signing.CreatedHeight+k.GetParams(ctx).SigningPeriod > uint64(ctx.BlockHeight()) { - break - } - - // Set the signing status to expired - if signing.Status != types.SIGNING_STATUS_FALLEN && signing.Status != types.SIGNING_STATUS_SUCCESS { - // Handle hooks before setting signing to be expired; this shouldn't return any error. - if err := k.Hooks().BeforeSetSigningExpired(ctx, signing); err != nil { - panic(err) - } - - signing.Status = types.SIGNING_STATUS_EXPIRED - k.SetSigning(ctx, signing) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeExpiredSigning, - sdk.NewAttribute(types.AttributeKeySigningID, fmt.Sprintf("%d", signing.ID)), - ), - ) - } - - // Remove assigned members from the signing - k.DeleteAssignedMembers(ctx, signing.ID) - - // Remove all partial signatures from the store - k.DeletePartialSignatures(ctx, signing.ID) - - // Set the last expired signing ID to the current signing ID - k.SetLastExpiredSigningID(ctx, currentSigningID) - } -} - -// GetPenalizedMembersExpiredSigning get assigned members that do not sign a request. -func (k Keeper) GetPenalizedMembersExpiredSigning(ctx sdk.Context, signing types.Signing) ([]sdk.AccAddress, error) { - pzs := k.GetPartialSignaturesWithKey(ctx, signing.ID) - var penalizedMembers []sdk.AccAddress - - mids := signing.AssignedMembers.MemberIDs() - for _, mid := range mids { - // Check if the member sends partial signature. If found, skip this member. - found := slices.ContainsFunc(pzs, func(pz types.PartialSignature) bool { return pz.MemberID == mid }) - if found { - continue - } - - member := k.MustGetMember(ctx, signing.GroupID, mid) - accAddress, err := sdk.AccAddressFromBech32(member.Address) - if err != nil { - return nil, err - } - penalizedMembers = append(penalizedMembers, accAddress) - } - - return penalizedMembers, nil -} - -// HandleProcessSigning combine and verify group signature. -func (k Keeper) HandleProcessSigning(ctx sdk.Context, signingID tss.SigningID) { - signing := k.MustGetSigning(ctx, signingID) - pzs := k.GetPartialSignatures(ctx, signingID) - - sig, err := tss.CombineSignatures(pzs...) - if err != nil { - k.handleFailedSigning(ctx, signing, err.Error()) - return - } - - err = tss.VerifyGroupSigningSignature(signing.GroupPubKey, signing.Message, sig) - if err != nil { - k.handleFailedSigning(ctx, signing, err.Error()) - return - } - - // Set signing with signature - signing.Signature = sig - // Set signing status - signing.Status = types.SIGNING_STATUS_SUCCESS - k.SetSigning(ctx, signing) - - // Handle hooks after signing completed; this shouldn't return any error. - if err := k.Hooks().AfterSigningCompleted(ctx, signing); err != nil { - panic(err) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSigningSuccess, - sdk.NewAttribute(types.AttributeKeySigningID, fmt.Sprintf("%d", signingID)), - sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", signing.GroupID)), - sdk.NewAttribute(types.AttributeKeySignature, hex.EncodeToString(sig)), - ), - ) -} - -func (k Keeper) handleFailedSigning(ctx sdk.Context, signing types.Signing, reason string) { - // Set signing status - signing.Status = types.SIGNING_STATUS_FALLEN - k.SetSigning(ctx, signing) - - // Handle hooks after signing failed - if err := k.Hooks().AfterSigningFailed(ctx, signing); err != nil { - panic(err) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSigningFailed, - sdk.NewAttribute(types.AttributeKeySigningID, fmt.Sprintf("%d", signing.ID)), - sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", signing.GroupID)), - sdk.NewAttribute(types.AttributeKeyReason, reason), - ), - ) -} - -// HandleSigningContent convert content to message bytes by the registered router. -func (k Keeper) HandleSigningContent( +// ConvertContentToBytes convert content to message bytes by the registered router. +func (k Keeper) ConvertContentToBytes( ctx sdk.Context, content types.Content, ) ([]byte, error) { @@ -573,8 +371,8 @@ func (k Keeper) CreateSigning( group types.Group, message []byte, ) (*types.Signing, error) { - // Handle assigned members within the context of the group. - assignedMembers, err := k.HandleAssignedMembers(ctx, group, message) + // assigned members within the context of the group. + assignedMembers, err := k.AssignMembers(ctx, group, message) if err != nil { return nil, err } @@ -601,17 +399,12 @@ func (k Keeper) CreateSigning( return nil, err } - k.emitCreateSigningEvent(ctx, message, signing) - - return &signing, nil -} - -func (k Keeper) emitCreateSigningEvent(ctx sdk.Context, msg []byte, signing types.Signing) { + // emit an event. event := sdk.NewEvent( types.EventTypeRequestSignature, sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", signing.GroupID)), sdk.NewAttribute(types.AttributeKeySigningID, fmt.Sprintf("%d", signing.ID)), - sdk.NewAttribute(types.AttributeKeyMessage, hex.EncodeToString(msg)), + sdk.NewAttribute(types.AttributeKeyMessage, hex.EncodeToString(message)), sdk.NewAttribute(types.AttributeKeyGroupPubNonce, hex.EncodeToString(signing.GroupPubNonce)), ) for _, am := range signing.AssignedMembers { @@ -625,8 +418,14 @@ func (k Keeper) emitCreateSigningEvent(ctx sdk.Context, msg []byte, signing type ) } ctx.EventManager().EmitEvent(event) + + return &signing, nil } +// ===================================== +// Query signing-related information +// ===================================== + // GetSigningResult returns the signing result of the given tss signingID. func (k Keeper) GetSigningResult(ctx sdk.Context, signingID tss.SigningID) (*types.SigningResult, error) { tssSigning, err := k.GetSigning(ctx, signingID) @@ -634,7 +433,7 @@ func (k Keeper) GetSigningResult(ctx sdk.Context, signingID tss.SigningID) (*typ return nil, err } - pzs := k.GetPartialSignaturesWithKey(ctx, signingID) + partialSigs := k.GetPartialSignaturesWithKey(ctx, signingID) var evmSignature *types.EVMSignature if tssSigning.Signature != nil { @@ -652,6 +451,79 @@ func (k Keeper) GetSigningResult(ctx sdk.Context, signingID tss.SigningID) (*typ return &types.SigningResult{ Signing: tssSigning, EVMSignature: evmSignature, - ReceivedPartialSignatures: pzs, + ReceivedPartialSignatures: partialSigs, }, nil } + +// GetPenalizedMembersExpiredSigning get assigned members that haven't signed a request. +func (k Keeper) GetPenalizedMembersExpiredSigning(ctx sdk.Context, signing types.Signing) ([]sdk.AccAddress, error) { + partialSigs := k.GetPartialSignaturesWithKey(ctx, signing.ID) + var penalizedMembers []sdk.AccAddress + + mids := signing.AssignedMembers.MemberIDs() + for _, mid := range mids { + // Check if the member sends partial signature. If found, skip this member. + found := slices.ContainsFunc(partialSigs, func(pz types.PartialSignature) bool { return pz.MemberID == mid }) + if found { + continue + } + + member := k.MustGetMember(ctx, signing.GroupID, mid) + penalizedMembers = append(penalizedMembers, sdk.MustAccAddressFromBech32(member.Address)) + } + + return penalizedMembers, nil +} + +// GetPendingSignings retrieves the pending signing objects associated with the given account address. +func (k Keeper) GetPendingSignings(ctx sdk.Context, address sdk.AccAddress) []uint64 { + filterFunc := func(am types.AssignedMember) bool { + return am.Address == address.String() + } + + return k.getPendingSigningByFilterFunc(ctx, filterFunc) +} + +// GetPendingSigningsByPubKey retrieves the pending signing objects associated with the given tss public key. +func (k Keeper) GetPendingSigningsByPubKey(ctx sdk.Context, pubKey tss.Point) []uint64 { + filterFunc := func(am types.AssignedMember) bool { + return bytes.Equal(am.PubKey, pubKey) + } + + return k.getPendingSigningByFilterFunc(ctx, filterFunc) +} + +// getPendingSigningByFilterFunc retrieves the pending signing objects associated with the given filter function. +func (k Keeper) getPendingSigningByFilterFunc( + ctx sdk.Context, + filterFunc func(m types.AssignedMember) bool, +) []uint64 { + // Get the ID of the last expired signing + lastExpired := k.GetLastExpiredSigningID(ctx) + + // Get the total signing count + signingCount := k.GetSigningCount(ctx) + + var pendingSignings []uint64 + for sid := lastExpired + 1; uint64(sid) <= signingCount; sid++ { + // Retrieve the signing object + signing := k.MustGetSigning(ctx, sid) + + // Ignore if it's successful already + if signing.Status == types.SIGNING_STATUS_SUCCESS { + continue + } + + // Check if address is assigned for signing + for _, am := range signing.AssignedMembers { + if filterFunc(am) { + // Add the signing to the pendingSignings if there is no partial sig of the member yet. + if _, err := k.GetPartialSignature(ctx, sid, am.MemberID); err != nil { + pendingSignings = append(pendingSignings, uint64(signing.ID)) + } + } + } + } + + return pendingSignings +} diff --git a/x/tss/keeper/signing_endblock.go b/x/tss/keeper/signing_endblock.go new file mode 100644 index 000000000..ef9e440fe --- /dev/null +++ b/x/tss/keeper/signing_endblock.go @@ -0,0 +1,163 @@ +package keeper + +import ( + "encoding/hex" + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/bandprotocol/chain/v2/x/tss/types" +) + +// ===================================== +// Process fully-signed signing +// ===================================== + +// AddPendingProcessSigning adds a new pending process signing to the store. +func (k Keeper) AddPendingProcessSigning(ctx sdk.Context, signingID tss.SigningID) { + pss := k.GetPendingProcessSignings(ctx) + pss = append(pss, signingID) + k.SetPendingProcessSignings(ctx, types.PendingProcessSignings{ + SigningIDs: pss, + }) +} + +// SetPendingProcessSignings sets the given pending process signings in the store. +func (k Keeper) SetPendingProcessSignings(ctx sdk.Context, pgs types.PendingProcessSignings) { + ctx.KVStore(k.storeKey).Set(types.PendingSigningsStoreKey, k.cdc.MustMarshal(&pgs)) +} + +// GetPendingProcessSignings retrieves the list of pending process signings from the store. +// It returns an empty list if the key does not exist in the store. +func (k Keeper) GetPendingProcessSignings(ctx sdk.Context) []tss.SigningID { + bz := ctx.KVStore(k.storeKey).Get(types.PendingSigningsStoreKey) + if len(bz) == 0 { + // Return an empty list if the key does not exist in the store. + return []tss.SigningID{} + } + pss := types.PendingProcessSignings{} + k.cdc.MustUnmarshal(bz, &pss) + return pss.SigningIDs +} + +// HandleProcessSigning combine and verify group signature. It will be triggered at endblock. +func (k Keeper) HandleProcessSigning(ctx sdk.Context, signingID tss.SigningID) { + signing := k.MustGetSigning(ctx, signingID) + partialSigs := k.GetPartialSignatures(ctx, signingID) + + sig, err := tss.CombineSignatures(partialSigs...) + if err != nil { + k.handleFailedSigning(ctx, signing, err.Error()) + return + } + + if err = tss.VerifyGroupSigningSignature(signing.GroupPubKey, signing.Message, sig); err != nil { + k.handleFailedSigning(ctx, signing, err.Error()) + return + } + + // Set signing with signature and success status + signing.Signature = sig + signing.Status = types.SIGNING_STATUS_SUCCESS + k.SetSigning(ctx, signing) + + // Handle hooks after signing completed; this shouldn't return any error. + if err := k.Hooks().AfterSigningCompleted(ctx, signing); err != nil { + panic(err) + } + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeSigningSuccess, + sdk.NewAttribute(types.AttributeKeySigningID, fmt.Sprintf("%d", signingID)), + sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", signing.GroupID)), + sdk.NewAttribute(types.AttributeKeySignature, hex.EncodeToString(sig)), + ), + ) +} + +// handleFailedSigning handles the failed signing process by setting the signing status to fallen +// and emitting an event. +func (k Keeper) handleFailedSigning(ctx sdk.Context, signing types.Signing, reason string) { + // Set signing status + signing.Status = types.SIGNING_STATUS_FALLEN + k.SetSigning(ctx, signing) + + // Handle hooks after signing failed; this shouldn't return any error. + if err := k.Hooks().AfterSigningFailed(ctx, signing); err != nil { + panic(err) + } + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeSigningFailed, + sdk.NewAttribute(types.AttributeKeySigningID, fmt.Sprintf("%d", signing.ID)), + sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", signing.GroupID)), + sdk.NewAttribute(types.AttributeKeyReason, reason), + ), + ) +} + +// ===================================== +// Process expired signature +// ===================================== + +// SetLastExpiredSigningID sets the last expired signing ID in the store. +func (k Keeper) SetLastExpiredSigningID(ctx sdk.Context, signingID tss.SigningID) { + ctx.KVStore(k.storeKey).Set(types.LastExpiredSigningIDStoreKey, sdk.Uint64ToBigEndian(uint64(signingID))) +} + +// GetLastExpiredSigningID retrieves the last expired signing ID from the store. +func (k Keeper) GetLastExpiredSigningID(ctx sdk.Context) tss.SigningID { + bz := ctx.KVStore(k.storeKey).Get(types.LastExpiredSigningIDStoreKey) + return tss.SigningID(sdk.BigEndianToUint64(bz)) +} + +// HandleExpiredSignings cleans up expired signings and removes assigned members and their partial +// signature information from the store. It will be triggered at endblock. +func (k Keeper) HandleExpiredSignings(ctx sdk.Context) { + // Get the current signing ID to start processing from + currentSigningID := k.GetLastExpiredSigningID(ctx) + 1 + + // Get the last signing ID in the store + lastSigningID := tss.SigningID(k.GetSigningCount(ctx)) + + // Process each signing starting from currentSigningID + for ; currentSigningID <= lastSigningID; currentSigningID++ { + // Get the signing + signing := k.MustGetSigning(ctx, currentSigningID) + + // Check if the signing is still within the expiration period + if signing.CreatedHeight+k.GetParams(ctx).SigningPeriod > uint64(ctx.BlockHeight()) { + break + } + + // Set the signing status to expired + if signing.Status != types.SIGNING_STATUS_FALLEN && signing.Status != types.SIGNING_STATUS_SUCCESS { + // Handle hooks before setting signing to be expired; this shouldn't return any error. + if err := k.Hooks().BeforeSetSigningExpired(ctx, signing); err != nil { + panic(err) + } + + signing.Status = types.SIGNING_STATUS_EXPIRED + k.SetSigning(ctx, signing) + + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeExpiredSigning, + sdk.NewAttribute(types.AttributeKeySigningID, fmt.Sprintf("%d", signing.ID)), + ), + ) + } + + // Remove assigned members from the signing + k.DeleteAssignedMembers(ctx, signing.ID) + + // Remove all partial signatures from the store + k.DeletePartialSignatures(ctx, signing.ID) + + // Set the last expired signing ID to the current signing ID + k.SetLastExpiredSigningID(ctx, currentSigningID) + } +} diff --git a/x/tss/keeper/signing_test.go b/x/tss/keeper/signing_test.go index 547def3d2..e13625326 100644 --- a/x/tss/keeper/signing_test.go +++ b/x/tss/keeper/signing_test.go @@ -210,10 +210,10 @@ func (s *KeeperTestSuite) TestSetGetSignatureCount() { // Set initial SigCount initialCount := uint64(5) - k.SetSignatureCount(ctx, signingID, initialCount) + k.SetPartialSignatureCount(ctx, signingID, initialCount) // Get and check SigCount - gotCount := k.GetSignatureCount(ctx, signingID) + gotCount := k.GetPartialSignatureCount(ctx, signingID) s.Require().Equal(initialCount, gotCount) } @@ -223,13 +223,13 @@ func (s *KeeperTestSuite) TestAddSignatureCount() { // Set initial SigCount initialCount := uint64(5) - k.SetSignatureCount(ctx, signingID, initialCount) + k.SetPartialSignatureCount(ctx, signingID, initialCount) // Add to SigCount - k.AddSignatureCount(ctx, signingID) + k.AddPartialSignatureCount(ctx, signingID) // Get and check incremented SigCount - gotCount := k.GetSignatureCount(ctx, signingID) + gotCount := k.GetPartialSignatureCount(ctx, signingID) s.Require().Equal(initialCount+1, gotCount) } @@ -239,13 +239,13 @@ func (s *KeeperTestSuite) TestDeleteSignatureCount() { // Set initial SigCount initialCount := uint64(5) - k.SetSignatureCount(ctx, signingID, initialCount) + k.SetPartialSignatureCount(ctx, signingID, initialCount) // Delete SigCount - k.DeleteSignatureCount(ctx, signingID) + k.DeletePartialSignatureCount(ctx, signingID) // Get and check SigCount after deletion - gotCount := k.GetSignatureCount(ctx, signingID) + gotCount := k.GetPartialSignatureCount(ctx, signingID) s.Require().Equal(uint64(0), gotCount) // usually, Get on a non-existing key will return the zero value of the type } @@ -277,7 +277,7 @@ func (s *KeeperTestSuite) TestAddPartialSignature() { gotSig, err := k.GetPartialSignature(ctx, signingID, memberID) s.Require().NoError(err) s.Require().Equal(sig, gotSig) - gotCount := k.GetSignatureCount(ctx, signingID) + gotCount := k.GetPartialSignatureCount(ctx, signingID) s.Require().Equal(uint64(1), gotCount) } @@ -361,6 +361,7 @@ func (s *KeeperTestSuite) TestGetRandomAssigningParticipants() { Address: "band1m5lq9u533qaya4q3nfyl6ulzqkpkhge9q8tpzs", PubKey: nil, IsMalicious: false, + IsActive: true, }, { ID: 2, @@ -368,12 +369,23 @@ func (s *KeeperTestSuite) TestGetRandomAssigningParticipants() { Address: "band1p40yh3zkmhcv0ecqp3mcazy83sa57rgjp07dun", PubKey: nil, IsMalicious: false, + IsActive: true, }, } t := uint64(1) + de := types.DE{ + PubD: []byte("D"), + PubE: []byte("E"), + } + + for _, m := range members { + k.SetMember(ctx, m) + k.SetDE(ctx, sdk.MustAccAddressFromBech32(m.Address), 1, de) + k.SetDEQueue(ctx, types.DEQueue{Address: m.Address, Head: 0, Tail: 1}) + } // Generate random assigned members - ams, err := k.GetRandomAssignedMembers(ctx, signingID, members, t) + ams, err := k.GetRandomAssignedMembers(ctx, tss.GroupID(1), signingID, t) s.Require().NoError(err) // Check that the number of assigned members is correct @@ -391,20 +403,20 @@ func (s *KeeperTestSuite) TestGetRandomAssigningParticipants() { s.Require().Equal([]types.Member{members[1]}, ams) // Test that it returns an error if t > size - _, err = k.GetRandomAssignedMembers(ctx, signingID, members, uint64(len(members)+1)) + _, err = k.GetRandomAssignedMembers(ctx, tss.GroupID(1), signingID, uint64(len(members)+1)) s.Require().Error(err) } -func (s *KeeperTestSuite) TestHandleAssignedMembers() { +func (s *KeeperTestSuite) TestAssignedMembers() { ctx, k := s.ctx, s.app.TSSKeeper s.SetupGroup(types.GROUP_STATUS_ACTIVE) group := k.MustGetGroup(ctx, 1) - // Execute HandleAssignedMembers + // Execute AssignedMembers msg := []byte("test message") // or any other sample message data - assignedMembers, err := k.HandleAssignedMembers(ctx, group, msg) + assignedMembers, err := k.AssignMembers(ctx, group, msg) s.Require().NoError(err) // Assert that assigned members have the expected properties @@ -428,7 +440,7 @@ func (s *KeeperTestSuite) TestCreateSigning() { content := types.NewTextSignatureOrder([]byte("example")) // execute HandleRequestSign - msg, err := k.HandleSigningContent(ctx, content) + msg, err := k.ConvertContentToBytes(ctx, content) s.Require().NoError(err) signing, err := k.CreateSigning(ctx, group, msg) diff --git a/x/tss/testutil/mock_expected_keepers.go b/x/tss/testutil/mock_expected_keepers.go new file mode 100644 index 000000000..9be8918e3 --- /dev/null +++ b/x/tss/testutil/mock_expected_keepers.go @@ -0,0 +1,216 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: x/tss/types/expected_keepers.go +// +// Generated by this command: +// +// mockgen -source x/tss/types/expected_keepers.go -package testutil -destination x/tss/testutil/mock_expected_keepers.go +// + +// Package testutil is a generated GoMock package. +package testutil + +import ( + reflect "reflect" + time "time" + + types "github.com/bandprotocol/chain/v2/x/tss/types" + types0 "github.com/cosmos/cosmos-sdk/types" + authz "github.com/cosmos/cosmos-sdk/x/authz" + gomock "go.uber.org/mock/gomock" +) + +// MockAuthzKeeper is a mock of AuthzKeeper interface. +type MockAuthzKeeper struct { + ctrl *gomock.Controller + recorder *MockAuthzKeeperMockRecorder +} + +// MockAuthzKeeperMockRecorder is the mock recorder for MockAuthzKeeper. +type MockAuthzKeeperMockRecorder struct { + mock *MockAuthzKeeper +} + +// NewMockAuthzKeeper creates a new mock instance. +func NewMockAuthzKeeper(ctrl *gomock.Controller) *MockAuthzKeeper { + mock := &MockAuthzKeeper{ctrl: ctrl} + mock.recorder = &MockAuthzKeeperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockAuthzKeeper) EXPECT() *MockAuthzKeeperMockRecorder { + return m.recorder +} + +// GetAuthorization mocks base method. +func (m *MockAuthzKeeper) GetAuthorization(ctx types0.Context, grantee, granter types0.AccAddress, msgType string) (authz.Authorization, *time.Time) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAuthorization", ctx, grantee, granter, msgType) + ret0, _ := ret[0].(authz.Authorization) + ret1, _ := ret[1].(*time.Time) + return ret0, ret1 +} + +// GetAuthorization indicates an expected call of GetAuthorization. +func (mr *MockAuthzKeeperMockRecorder) GetAuthorization(ctx, grantee, granter, msgType any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAuthorization", reflect.TypeOf((*MockAuthzKeeper)(nil).GetAuthorization), ctx, grantee, granter, msgType) +} + +// SaveGrant mocks base method. +func (m *MockAuthzKeeper) SaveGrant(ctx types0.Context, grantee, granter types0.AccAddress, authorization authz.Authorization, expiration *time.Time) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SaveGrant", ctx, grantee, granter, authorization, expiration) + ret0, _ := ret[0].(error) + return ret0 +} + +// SaveGrant indicates an expected call of SaveGrant. +func (mr *MockAuthzKeeperMockRecorder) SaveGrant(ctx, grantee, granter, authorization, expiration any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveGrant", reflect.TypeOf((*MockAuthzKeeper)(nil).SaveGrant), ctx, grantee, granter, authorization, expiration) +} + +// MockRollingseedKeeper is a mock of RollingseedKeeper interface. +type MockRollingseedKeeper struct { + ctrl *gomock.Controller + recorder *MockRollingseedKeeperMockRecorder +} + +// MockRollingseedKeeperMockRecorder is the mock recorder for MockRollingseedKeeper. +type MockRollingseedKeeperMockRecorder struct { + mock *MockRollingseedKeeper +} + +// NewMockRollingseedKeeper creates a new mock instance. +func NewMockRollingseedKeeper(ctrl *gomock.Controller) *MockRollingseedKeeper { + mock := &MockRollingseedKeeper{ctrl: ctrl} + mock.recorder = &MockRollingseedKeeperMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockRollingseedKeeper) EXPECT() *MockRollingseedKeeperMockRecorder { + return m.recorder +} + +// GetRollingSeed mocks base method. +func (m *MockRollingseedKeeper) GetRollingSeed(ctx types0.Context) []byte { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRollingSeed", ctx) + ret0, _ := ret[0].([]byte) + return ret0 +} + +// GetRollingSeed indicates an expected call of GetRollingSeed. +func (mr *MockRollingseedKeeperMockRecorder) GetRollingSeed(ctx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRollingSeed", reflect.TypeOf((*MockRollingseedKeeper)(nil).GetRollingSeed), ctx) +} + +// MockTSSHooks is a mock of TSSHooks interface. +type MockTSSHooks struct { + ctrl *gomock.Controller + recorder *MockTSSHooksMockRecorder +} + +// MockTSSHooksMockRecorder is the mock recorder for MockTSSHooks. +type MockTSSHooksMockRecorder struct { + mock *MockTSSHooks +} + +// NewMockTSSHooks creates a new mock instance. +func NewMockTSSHooks(ctrl *gomock.Controller) *MockTSSHooks { + mock := &MockTSSHooks{ctrl: ctrl} + mock.recorder = &MockTSSHooksMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockTSSHooks) EXPECT() *MockTSSHooksMockRecorder { + return m.recorder +} + +// AfterCreatingGroupCompleted mocks base method. +func (m *MockTSSHooks) AfterCreatingGroupCompleted(ctx types0.Context, group types.Group) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AfterCreatingGroupCompleted", ctx, group) + ret0, _ := ret[0].(error) + return ret0 +} + +// AfterCreatingGroupCompleted indicates an expected call of AfterCreatingGroupCompleted. +func (mr *MockTSSHooksMockRecorder) AfterCreatingGroupCompleted(ctx, group any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AfterCreatingGroupCompleted", reflect.TypeOf((*MockTSSHooks)(nil).AfterCreatingGroupCompleted), ctx, group) +} + +// AfterCreatingGroupFailed mocks base method. +func (m *MockTSSHooks) AfterCreatingGroupFailed(ctx types0.Context, group types.Group) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AfterCreatingGroupFailed", ctx, group) + ret0, _ := ret[0].(error) + return ret0 +} + +// AfterCreatingGroupFailed indicates an expected call of AfterCreatingGroupFailed. +func (mr *MockTSSHooksMockRecorder) AfterCreatingGroupFailed(ctx, group any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AfterCreatingGroupFailed", reflect.TypeOf((*MockTSSHooks)(nil).AfterCreatingGroupFailed), ctx, group) +} + +// AfterSigningCompleted mocks base method. +func (m *MockTSSHooks) AfterSigningCompleted(ctx types0.Context, signing types.Signing) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AfterSigningCompleted", ctx, signing) + ret0, _ := ret[0].(error) + return ret0 +} + +// AfterSigningCompleted indicates an expected call of AfterSigningCompleted. +func (mr *MockTSSHooksMockRecorder) AfterSigningCompleted(ctx, signing any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AfterSigningCompleted", reflect.TypeOf((*MockTSSHooks)(nil).AfterSigningCompleted), ctx, signing) +} + +// AfterSigningFailed mocks base method. +func (m *MockTSSHooks) AfterSigningFailed(ctx types0.Context, signing types.Signing) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AfterSigningFailed", ctx, signing) + ret0, _ := ret[0].(error) + return ret0 +} + +// AfterSigningFailed indicates an expected call of AfterSigningFailed. +func (mr *MockTSSHooksMockRecorder) AfterSigningFailed(ctx, signing any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AfterSigningFailed", reflect.TypeOf((*MockTSSHooks)(nil).AfterSigningFailed), ctx, signing) +} + +// BeforeSetGroupExpired mocks base method. +func (m *MockTSSHooks) BeforeSetGroupExpired(ctx types0.Context, group types.Group) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BeforeSetGroupExpired", ctx, group) + ret0, _ := ret[0].(error) + return ret0 +} + +// BeforeSetGroupExpired indicates an expected call of BeforeSetGroupExpired. +func (mr *MockTSSHooksMockRecorder) BeforeSetGroupExpired(ctx, group any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BeforeSetGroupExpired", reflect.TypeOf((*MockTSSHooks)(nil).BeforeSetGroupExpired), ctx, group) +} + +// BeforeSetSigningExpired mocks base method. +func (m *MockTSSHooks) BeforeSetSigningExpired(ctx types0.Context, signing types.Signing) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BeforeSetSigningExpired", ctx, signing) + ret0, _ := ret[0].(error) + return ret0 +} + +// BeforeSetSigningExpired indicates an expected call of BeforeSetSigningExpired. +func (mr *MockTSSHooksMockRecorder) BeforeSetSigningExpired(ctx, signing any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BeforeSetSigningExpired", reflect.TypeOf((*MockTSSHooks)(nil).BeforeSetSigningExpired), ctx, signing) +} diff --git a/x/tss/testutil/mock_keeper.go b/x/tss/testutil/mock_keeper.go new file mode 100644 index 000000000..17c09e7c3 --- /dev/null +++ b/x/tss/testutil/mock_keeper.go @@ -0,0 +1,75 @@ +package testutil + +import ( + "testing" + "time" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cosmos/cosmos-sdk/codec" + sdktestutil "github.com/cosmos/cosmos-sdk/testutil" + sdk "github.com/cosmos/cosmos-sdk/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + "go.uber.org/mock/gomock" + + "github.com/bandprotocol/chain/v2/x/tss" + "github.com/bandprotocol/chain/v2/x/tss/keeper" + "github.com/bandprotocol/chain/v2/x/tss/types" +) + +// TestSuite is a struct that embeds a *testing.T and provides a setup for a mock keeper +type TestSuite struct { + t *testing.T + Keeper *keeper.Keeper + QueryServer types.QueryServer + Hook types.TSSHooks + + MockAuthzKeeper *MockAuthzKeeper + MockRollingseedKeeper *MockRollingseedKeeper + + Authority sdk.AccAddress + Ctx sdk.Context +} + +// NewTestSuite returns a new TestSuite object +func NewTestSuite(t *testing.T) TestSuite { + ctrl := gomock.NewController(t) + key := sdk.NewKVStoreKey(types.StoreKey) + testCtx := sdktestutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) + encCfg := moduletestutil.MakeTestEncodingConfig(tss.AppModuleBasic{}) + ctx := testCtx.Ctx.WithBlockHeader(tmproto.Header{Time: time.Now().UTC()}) + + authzKeeper := NewMockAuthzKeeper(ctrl) + rollingseedKeeper := NewMockRollingseedKeeper(ctrl) + tssRouter := types.NewRouter() + + authority := authtypes.NewModuleAddress(govtypes.ModuleName) + tssKeeper := keeper.NewKeeper( + encCfg.Codec.(codec.BinaryCodec), + key, + paramtypes.Subspace{}, + authzKeeper, + rollingseedKeeper, + tssRouter, + authority.String(), + ) + + queryServer := keeper.NewQueryServer(tssKeeper) + + return TestSuite{ + Keeper: tssKeeper, + MockAuthzKeeper: authzKeeper, + MockRollingseedKeeper: rollingseedKeeper, + Ctx: ctx, + Authority: authority, + QueryServer: queryServer, + Hook: tssKeeper.Hooks(), + t: t, + } +} + +func (s *TestSuite) T() *testing.T { + return s.t +} diff --git a/x/tss/types/tss_test.go b/x/tss/types/assigned_members_test.go similarity index 100% rename from x/tss/types/tss_test.go rename to x/tss/types/assigned_members_test.go diff --git a/x/tss/types/codec.go b/x/tss/types/codec.go index 71adda608..fc692374a 100644 --- a/x/tss/types/codec.go +++ b/x/tss/types/codec.go @@ -7,21 +7,21 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// RegisterLegacyAminoCodec registers the necessary x/bandtss interfaces and concrete types +// RegisterLegacyAminoCodec registers the necessary x/tss interfaces and concrete types // on the provided LegacyAmino codec. These types are used for Amino JSON serialization. func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - legacy.RegisterAminoMsg(cdc, &MsgSubmitDKGRound1{}, "tss/SubmitDKGRound1") - legacy.RegisterAminoMsg(cdc, &MsgSubmitDKGRound2{}, "tss/SubmitDKGRound2") - legacy.RegisterAminoMsg(cdc, &MsgComplain{}, "tss/Complaint") - legacy.RegisterAminoMsg(cdc, &MsgConfirm{}, "tss/Confirm") - legacy.RegisterAminoMsg(cdc, &MsgSubmitDEs{}, "tss/SubmitDEs") - legacy.RegisterAminoMsg(cdc, &MsgSubmitSignature{}, "tss/SubmitSignature") - legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "tss/UpdateParams") + legacy.RegisterAminoMsg(cdc, &MsgSubmitDKGRound1{}, "tss/MsgSubmitDKGRound1") + legacy.RegisterAminoMsg(cdc, &MsgSubmitDKGRound2{}, "tss/MsgSubmitDKGRound2") + legacy.RegisterAminoMsg(cdc, &MsgComplain{}, "tss/MsgComplaint") + legacy.RegisterAminoMsg(cdc, &MsgConfirm{}, "tss/MsgConfirm") + legacy.RegisterAminoMsg(cdc, &MsgSubmitDEs{}, "tss/MsgSubmitDEs") + legacy.RegisterAminoMsg(cdc, &MsgSubmitSignature{}, "tss/MsgSubmitSignature") + legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "tss/MsgUpdateParams") cdc.RegisterConcrete(&TextSignatureOrder{}, "tss/TextSignatureOrder", nil) } -// RegisterInterfaces register the bandtss module interfaces to protobuf Any. +// RegisterInterfaces register the tss module interfaces to protobuf Any. func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { registry.RegisterImplementations((*sdk.Msg)(nil), &MsgSubmitDKGRound1{}, diff --git a/x/tss/types/constants.go b/x/tss/types/constants.go index aac3e09c9..647b856bb 100644 --- a/x/tss/types/constants.go +++ b/x/tss/types/constants.go @@ -4,18 +4,15 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// GetTSSGrantMsgTypes get message types that can be granted. -func GetTSSGrantMsgTypes() []string { - return []string{ - sdk.MsgTypeURL(&MsgSubmitDKGRound1{}), - sdk.MsgTypeURL(&MsgSubmitDKGRound2{}), - sdk.MsgTypeURL(&MsgComplain{}), - sdk.MsgTypeURL(&MsgConfirm{}), - sdk.MsgTypeURL(&MsgSubmitDEs{}), - sdk.MsgTypeURL(&MsgSubmitSignature{}), - } -} - const ( uint64Len = 8 ) + +var TSSGrantMsgTypes = []string{ + sdk.MsgTypeURL(&MsgSubmitDKGRound1{}), + sdk.MsgTypeURL(&MsgSubmitDKGRound2{}), + sdk.MsgTypeURL(&MsgComplain{}), + sdk.MsgTypeURL(&MsgConfirm{}), + sdk.MsgTypeURL(&MsgSubmitDEs{}), + sdk.MsgTypeURL(&MsgSubmitSignature{}), +} diff --git a/x/tss/types/errors.go b/x/tss/types/errors.go index e68ac80c1..cc01e2782 100644 --- a/x/tss/types/errors.go +++ b/x/tss/types/errors.go @@ -1,66 +1,62 @@ package types -import "cosmossdk.io/errors" +import errorsmod "cosmossdk.io/errors" // x/tss module sentinel errors var ( - ErrInvalidAccAddressFormat = errors.Register(ModuleName, 2, "account address format is invalid") - ErrGroupSizeTooLarge = errors.Register(ModuleName, 3, "group size is too large") - ErrGroupNotFound = errors.Register(ModuleName, 4, "group not found") - ErrMemberNotFound = errors.Register(ModuleName, 5, "member not found") - ErrNoActiveMember = errors.Register(ModuleName, 6, "no active member in this group") - ErrMemberAlreadySubmit = errors.Register(ModuleName, 7, "member is already submit message") - ErrRound1InfoNotFound = errors.Register(ModuleName, 8, "round 1 info not found") - ErrDKGContextNotFound = errors.Register(ModuleName, 9, "dkg context not found") - ErrMemberNotAuthorized = errors.Register( + ErrGroupSizeTooLarge = errorsmod.Register(ModuleName, 2, "group size is too large") + ErrGroupNotFound = errorsmod.Register(ModuleName, 3, "group not found") + ErrMemberNotFound = errorsmod.Register(ModuleName, 4, "member not found") + ErrNoActiveMember = errorsmod.Register(ModuleName, 5, "no active member in this group") + ErrMemberAlreadySubmit = errorsmod.Register(ModuleName, 6, "member is already submit message") + ErrRound1InfoNotFound = errorsmod.Register(ModuleName, 7, "round 1 info not found") + ErrDKGContextNotFound = errorsmod.Register(ModuleName, 8, "dkg context not found") + ErrMemberNotAuthorized = errorsmod.Register( ModuleName, - 10, + 9, "member is not authorized for this group", ) - ErrInvalidStatus = errors.Register(ModuleName, 11, "invalid status") - ErrGroupExpired = errors.Register(ModuleName, 12, "group expired") - ErrVerifyOneTimeSignatureFailed = errors.Register(ModuleName, 13, "failed to verify one time sign") - ErrVerifyA0SignatureFailed = errors.Register(ModuleName, 14, "failed to verify a0 sign") - ErrAddCoefCommit = errors.Register(ModuleName, 15, "failed to add coefficient commit") - ErrInvalidLengthCoefCommits = errors.Register( + ErrInvalidStatus = errorsmod.Register(ModuleName, 10, "invalid status") + ErrVerifyOneTimeSignatureFailed = errorsmod.Register(ModuleName, 11, "failed to verify one time sign") + ErrVerifyA0SignatureFailed = errorsmod.Register(ModuleName, 12, "failed to verify a0 sign") + ErrAddCoeffCommit = errorsmod.Register(ModuleName, 13, "failed to add coefficient commit") + ErrInvalidLengthCoefCommits = errorsmod.Register( ModuleName, - 16, + 14, "coefficients commit length is invalid", ) - ErrRound2InfoNotFound = errors.Register(ModuleName, 17, "round 2 info not found") - ErrInvalidLengthEncryptedSecretShares = errors.Register( + ErrRound2InfoNotFound = errorsmod.Register(ModuleName, 15, "round 2 info not found") + ErrInvalidLengthEncryptedSecretShares = errorsmod.Register( ModuleName, - 18, + 16, "encrypted secret shares length is invalid ", ) - ErrComputeOwnPubKeyFailed = errors.Register(ModuleName, 19, "failed to compute own public key") - ErrMemberIsAlreadyComplainOrConfirm = errors.Register(ModuleName, 20, "member is already complain or confirm") - ErrEncryptedSecretShareNotFound = errors.Register(ModuleName, 21, "encrypted secret share not found") - ErrComplainFailed = errors.Register(ModuleName, 22, "failed to complain") - ErrConfirmFailed = errors.Register(ModuleName, 23, "failed to confirm") - ErrConfirmNotFound = errors.Register(ModuleName, 24, "confirm not found") - ErrComplaintsWithStatusNotFound = errors.Register(ModuleName, 25, "complaints with status not found") - ErrDENotFound = errors.Register(ModuleName, 26, "de not found") - ErrGroupIsNotActive = errors.Register(ModuleName, 27, "group is not active") - ErrUnexpectedThreshold = errors.Register(ModuleName, 28, "threshold value is unexpected") - ErrBadDrbgInitialization = errors.Register(ModuleName, 29, "bad drbg initialization") - ErrPartialSignatureNotFound = errors.Register(ModuleName, 30, "partial signature not found") - ErrInvalidArgument = errors.Register(ModuleName, 31, "invalid argument") - ErrSigningNotFound = errors.Register(ModuleName, 32, "signing not found") - ErrAlreadySigned = errors.Register(ModuleName, 33, "already signed") - ErrSigningAlreadySuccess = errors.Register(ModuleName, 34, "signing already success") - ErrPubNonceNotEqualToSigR = errors.Register(ModuleName, 35, "public nonce not equal to signature r") - ErrMemberNotAssigned = errors.Register(ModuleName, 36, "member is not assigned") - ErrVerifySigningSigFailed = errors.Register(ModuleName, 37, "failed to verify signing signature") - ErrCombineSigsFailed = errors.Register(ModuleName, 38, "failed to combine signatures") - ErrVerifyGroupSigningSigFailed = errors.Register( - ModuleName, - 39, - "failed to verify group signing signature", - ) - ErrDEQueueFull = errors.Register(ModuleName, 40, "de queue is full") - ErrSigningExpired = errors.Register(ModuleName, 41, "signing expired") - ErrStatusNotFound = errors.Register(ModuleName, 42, "status not found") - ErrHandleSignatureOrderFailed = errors.Register(ModuleName, 43, "failed to handle signature order") - ErrNoSignatureOrderHandlerExists = errors.Register(ModuleName, 44, "no handler exists for signature order type") + ErrComputeOwnPubKeyFailed = errorsmod.Register(ModuleName, 17, "failed to compute own public key") + ErrMemberIsAlreadyComplainOrConfirm = errorsmod.Register(ModuleName, 18, "member is already complain or confirm") + ErrComplainFailed = errorsmod.Register(ModuleName, 19, "failed to complain") + ErrConfirmFailed = errorsmod.Register(ModuleName, 20, "failed to confirm") + ErrConfirmNotFound = errorsmod.Register(ModuleName, 21, "confirm not found") + ErrComplaintsWithStatusNotFound = errorsmod.Register(ModuleName, 22, "complaints with status not found") + ErrDENotFound = errorsmod.Register(ModuleName, 23, "de not found") + ErrGroupIsNotActive = errorsmod.Register(ModuleName, 24, "group is not active") + ErrUnexpectedThreshold = errorsmod.Register(ModuleName, 25, "threshold value is unexpected") + ErrBadDrbgInitialization = errorsmod.Register(ModuleName, 26, "bad drbg initialization") + ErrPartialSignatureNotFound = errorsmod.Register(ModuleName, 27, "partial signature not found") + ErrInvalidArgument = errorsmod.Register(ModuleName, 28, "invalid argument") + ErrSigningNotFound = errorsmod.Register(ModuleName, 29, "signing not found") + ErrAlreadySigned = errorsmod.Register(ModuleName, 30, "already signed") + ErrSigningAlreadySuccess = errorsmod.Register(ModuleName, 31, "signing already success") + ErrPubNonceNotEqualToSigR = errorsmod.Register(ModuleName, 32, "public nonce not equal to signature r") + ErrMemberNotAssigned = errorsmod.Register(ModuleName, 33, "member is not assigned") + ErrVerifySigningSigFailed = errorsmod.Register(ModuleName, 34, "failed to verify signing signature") + ErrDEQueueFull = errorsmod.Register(ModuleName, 35, "de queue is full") + ErrHandleSignatureOrderFailed = errorsmod.Register(ModuleName, 36, "failed to handle signature order") + ErrNoSignatureOrderHandlerExists = errorsmod.Register(ModuleName, 37, "no handler exists for signature order type") + ErrInvalidCoefficientCommit = errorsmod.Register(ModuleName, 38, "invalid coefficient commit") + ErrInvalidPublicKey = errorsmod.Register(ModuleName, 39, "invalid public key") + ErrInvalidSignature = errorsmod.Register(ModuleName, 40, "invalid signature") + ErrInvalidSecretShare = errorsmod.Register(ModuleName, 41, "invalid secret share") + ErrInvalidComplaint = errorsmod.Register(ModuleName, 42, "invalid complaint") + ErrInvalidSymmetricKey = errorsmod.Register(ModuleName, 43, "invalid symmetric key") + ErrInvalidDE = errorsmod.Register(ModuleName, 44, "invalid de") ) diff --git a/x/tss/types/events.go b/x/tss/types/events.go index b00c2bd39..b1dea9d04 100644 --- a/x/tss/types/events.go +++ b/x/tss/types/events.go @@ -18,32 +18,28 @@ const ( EventTypeExpiredSigning = "expired_signing" EventTypeSubmitSignature = "submit_signature" - AttributeKeyGroupID = "group_id" - AttributeKeyMemberID = "member_id" - AttributeKeyAddress = "address" - AttributeKeySize = "size" - AttributeKeyThreshold = "threshold" - AttributeKeyPubKey = "pub_key" - AttributeKeyStatus = "status" - AttributeKeyFee = "fee" - AttributeKeyDKGContext = "dkg_context" - AttributeKeyModuleOwner = "module_owner" - AttributeKeyRound1Info = "round1_info" - AttributeKeyRound2Info = "round2_info" - AttributeKeyComplainantID = "complainant_id" - AttributeKeyRespondentID = "respondent_id" - AttributeKeyKeySym = "key_sym" - AttributeKeySignature = "signature" - AttributeKeyGroupPubKey = "group_pub_key" - AttributeKeyOwnPubKeySig = "own_pub_key_sig" - AttributeKeySigningID = "signing_id" - AttributeKeyReason = "reason" - AttributeKeyMessage = "message" - AttributeKeyGroupPubNonce = "group_pub_nonce" - AttributeKeyPubNonce = "pub_nonce" - AttributeKeyBindingFactor = "binding_factor" - AttributeKeyPubD = "pub_d" - AttributeKeyPubE = "pub_e" - AttributeKeyCurrentGroupID = "current_group_id" - AttributeKeyNewGroupID = "new_group_id" + AttributeKeyGroupID = "group_id" + AttributeKeyMemberID = "member_id" + AttributeKeyAddress = "address" + AttributeKeySize = "size" + AttributeKeyThreshold = "threshold" + AttributeKeyPubKey = "pub_key" + AttributeKeyStatus = "status" + AttributeKeyDKGContext = "dkg_context" + AttributeKeyModuleOwner = "module_owner" + AttributeKeyRound1Info = "round1_info" + AttributeKeyRound2Info = "round2_info" + AttributeKeyComplainantID = "complainant_id" + AttributeKeyRespondentID = "respondent_id" + AttributeKeyKeySym = "key_sym" + AttributeKeySignature = "signature" + AttributeKeyOwnPubKeySig = "own_pub_key_sig" + AttributeKeySigningID = "signing_id" + AttributeKeyReason = "reason" + AttributeKeyMessage = "message" + AttributeKeyGroupPubNonce = "group_pub_nonce" + AttributeKeyPubNonce = "pub_nonce" + AttributeKeyBindingFactor = "binding_factor" + AttributeKeyPubD = "pub_d" + AttributeKeyPubE = "pub_e" ) diff --git a/x/tss/types/expected_keepers.go b/x/tss/types/expected_keepers.go index 34d3fe905..20ff84e94 100644 --- a/x/tss/types/expected_keepers.go +++ b/x/tss/types/expected_keepers.go @@ -4,7 +4,6 @@ import ( "time" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/authz" ) @@ -29,29 +28,21 @@ type RollingseedKeeper interface { GetRollingSeed(ctx sdk.Context) []byte } -// AccountKeeper defines the expected account keeper (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) types.ModuleAccountI -} - // TSSHooks event hooks for tss validator object (noalias) type TSSHooks interface { // Must be called when a group is created successfully. AfterCreatingGroupCompleted(ctx sdk.Context, group Group) error - // Must be called when a group creation. + // Must be called after members fails to create a group. AfterCreatingGroupFailed(ctx sdk.Context, group Group) error // Must be called before setting group status to expired. BeforeSetGroupExpired(ctx sdk.Context, group Group) error - // Must be called when a signing request is unsuccessfully signed. + // Must be called after a signing request is unsuccessfully signed. AfterSigningFailed(ctx sdk.Context, signing Signing) error - // Must be called when a signing request is successfully signed by selected members. + // Must be called after a signing request is successfully signed by selected members. AfterSigningCompleted(ctx sdk.Context, signing Signing) error // Must be called before setting signing status to expired. diff --git a/x/tss/types/genesis.go b/x/tss/types/genesis.go index 6ae9e086d..f621c979e 100644 --- a/x/tss/types/genesis.go +++ b/x/tss/types/genesis.go @@ -8,7 +8,6 @@ func NewGenesisState( members []Member, signingCount uint64, signings []Signing, - deQueues []DEQueue, desGenesis []DEGenesis, ) *GenesisState { return &GenesisState{ @@ -18,7 +17,6 @@ func NewGenesisState( Members: members, SigningCount: signingCount, Signings: signings, - DEQueues: deQueues, DEsGenesis: desGenesis, } } @@ -32,7 +30,6 @@ func DefaultGenesisState() *GenesisState { []Member{}, 0, []Signing{}, - []DEQueue{}, []DEGenesis{}, ) } diff --git a/x/tss/types/genesis.pb.go b/x/tss/types/genesis.pb.go index 78a116f44..e64a45697 100644 --- a/x/tss/types/genesis.pb.go +++ b/x/tss/types/genesis.pb.go @@ -39,10 +39,8 @@ type GenesisState struct { SigningCount uint64 `protobuf:"varint,5,opt,name=signing_count,json=signingCount,proto3" json:"signing_count,omitempty"` // signings is an array containing information about each signing. Signings []Signing `protobuf:"bytes,6,rep,name=signings,proto3" json:"signings"` - // de_queues is an array containing the de queues of all the addressres. - DEQueues []DEQueue `protobuf:"bytes,7,rep,name=de_queues,json=deQueues,proto3" json:"de_queues"` // des_genesis is an array containing the des of all the addressres. - DEsGenesis []DEGenesis `protobuf:"bytes,8,rep,name=des_genesis,json=desGenesis,proto3" json:"des_genesis"` + DEsGenesis []DEGenesis `protobuf:"bytes,7,rep,name=des_genesis,json=desGenesis,proto3" json:"des_genesis"` } func (m *GenesisState) Reset() { *m = GenesisState{} } @@ -120,13 +118,6 @@ func (m *GenesisState) GetSignings() []Signing { return nil } -func (m *GenesisState) GetDEQueues() []DEQueue { - if m != nil { - return m.DEQueues - } - return nil -} - func (m *GenesisState) GetDEsGenesis() []DEGenesis { if m != nil { return m.DEsGenesis @@ -211,10 +202,8 @@ func (m *Params) GetSigningPeriod() uint64 { type DEGenesis struct { // address is the address of the de holder. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // index is the index for store de of the address - Index uint64 `protobuf:"varint,2,opt,name=index,proto3" json:"index,omitempty"` // de defines the difference de this balance holds. - DE DE `protobuf:"bytes,3,opt,name=de,proto3" json:"de"` + DE DE `protobuf:"bytes,2,opt,name=de,proto3" json:"de"` } func (m *DEGenesis) Reset() { *m = DEGenesis{} } @@ -257,13 +246,6 @@ func (m *DEGenesis) GetAddress() string { return "" } -func (m *DEGenesis) GetIndex() uint64 { - if m != nil { - return m.Index - } - return 0 -} - func (m *DEGenesis) GetDE() DE { if m != nil { return m.DE @@ -280,43 +262,40 @@ func init() { func init() { proto.RegisterFile("tss/v1beta1/genesis.proto", fileDescriptor_eb5f1c2be1950e47) } var fileDescriptor_eb5f1c2be1950e47 = []byte{ - // 564 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x53, 0xc1, 0x6e, 0xd3, 0x4c, - 0x10, 0x8e, 0x93, 0x34, 0x4d, 0xc6, 0xfd, 0xdb, 0x5f, 0x4b, 0x40, 0x6e, 0x0f, 0x4e, 0x55, 0x40, - 0x54, 0x02, 0x62, 0x92, 0x4a, 0xdc, 0x71, 0x13, 0x7a, 0x40, 0x48, 0xc5, 0xb9, 0x71, 0xb1, 0xd6, - 0xde, 0xc1, 0xb5, 0x54, 0x7b, 0x83, 0x77, 0x5d, 0x85, 0x1e, 0x79, 0x02, 0xde, 0x80, 0x97, 0xe0, - 0xc0, 0x23, 0xf4, 0x58, 0x71, 0xe2, 0x54, 0xa1, 0xe4, 0x45, 0x90, 0x77, 0xd7, 0x55, 0x53, 0x71, - 0x9b, 0xf9, 0xbe, 0x6f, 0x3e, 0x7d, 0x9e, 0xf1, 0xc2, 0xae, 0x14, 0xc2, 0xbb, 0x18, 0x45, 0x28, - 0xe9, 0xc8, 0x4b, 0x30, 0x47, 0x91, 0x8a, 0xe1, 0xbc, 0xe0, 0x92, 0x13, 0x5b, 0x0a, 0x31, 0x34, - 0xd4, 0x5e, 0x3f, 0xe1, 0x09, 0x57, 0xb8, 0x57, 0x55, 0x5a, 0xb2, 0xe7, 0x26, 0x9c, 0x27, 0xe7, - 0xe8, 0xa9, 0x2e, 0x2a, 0x3f, 0x79, 0xac, 0x2c, 0xa8, 0x4c, 0x79, 0x6e, 0xf8, 0x87, 0x77, 0xdd, - 0x2b, 0x3b, 0x0d, 0xef, 0xc6, 0x5c, 0x64, 0x5c, 0x84, 0xda, 0x4f, 0x37, 0x9a, 0x3a, 0xf8, 0xd9, - 0x82, 0xad, 0x13, 0x1d, 0x63, 0x26, 0xa9, 0x44, 0x32, 0x82, 0xce, 0x9c, 0x16, 0x34, 0x13, 0x8e, - 0xb5, 0x6f, 0x1d, 0xda, 0xe3, 0x07, 0xc3, 0x3b, 0xb1, 0x86, 0xa7, 0x8a, 0xf2, 0xdb, 0x57, 0x37, - 0x83, 0x46, 0x60, 0x84, 0x64, 0x00, 0x76, 0x52, 0xf0, 0x72, 0x1e, 0xc6, 0xbc, 0xcc, 0xa5, 0xd3, - 0xdc, 0xb7, 0x0e, 0xdb, 0x01, 0x28, 0xe8, 0xb8, 0x42, 0xc8, 0x2b, 0xe8, 0xa8, 0x4e, 0x38, 0xad, - 0xfd, 0xd6, 0xa1, 0x3d, 0x26, 0x6b, 0x9e, 0x27, 0x15, 0x55, 0x5b, 0x6a, 0x1d, 0x39, 0x82, 0xcd, - 0x0c, 0xb3, 0x08, 0x0b, 0xe1, 0xb4, 0xd5, 0xc8, 0x7a, 0x8c, 0xf7, 0x8a, 0x33, 0x33, 0xb5, 0x92, - 0x3c, 0x86, 0xff, 0x44, 0x9a, 0xe4, 0x69, 0x9e, 0x98, 0x24, 0x1b, 0x2a, 0xc9, 0x96, 0x01, 0x75, - 0x96, 0xd7, 0xd0, 0x35, 0xbd, 0x70, 0x3a, 0xca, 0xba, 0xbf, 0x66, 0x3d, 0xd3, 0xa4, 0xf1, 0xbe, - 0xd5, 0x92, 0x63, 0xe8, 0x31, 0x0c, 0x3f, 0x97, 0x58, 0xa2, 0x70, 0x36, 0xff, 0x31, 0x38, 0x99, - 0x7e, 0xa8, 0x48, 0xff, 0xff, 0x6a, 0x70, 0x79, 0x33, 0xe8, 0x1a, 0x40, 0x04, 0x5d, 0x86, 0xba, - 0x22, 0xef, 0xc0, 0x66, 0x28, 0x42, 0x73, 0x77, 0xa7, 0xab, 0x6c, 0x1e, 0xdd, 0xb3, 0x31, 0xe7, - 0xf0, 0x89, 0x31, 0x82, 0xc9, 0x54, 0x18, 0x2c, 0x00, 0x86, 0x75, 0x7d, 0xf0, 0xdd, 0x82, 0x8e, - 0xbe, 0x07, 0x79, 0x02, 0xdb, 0x19, 0x5d, 0x84, 0xfa, 0x0a, 0x22, 0xbd, 0x44, 0x75, 0xbc, 0x76, - 0xb0, 0x95, 0xd1, 0x85, 0x5a, 0xef, 0x2c, 0xbd, 0x44, 0x32, 0x80, 0xaa, 0x0f, 0x59, 0x88, 0x5a, - 0xa3, 0x0f, 0xd5, 0xcb, 0xe8, 0x62, 0x32, 0x55, 0x82, 0x67, 0xb0, 0x13, 0x17, 0x48, 0x65, 0xb5, - 0xc1, 0x39, 0x16, 0x29, 0x67, 0x4e, 0x4b, 0x69, 0xb6, 0x6b, 0xf8, 0x54, 0xa1, 0xe4, 0x29, 0x6c, - 0xd7, 0x9b, 0x36, 0xba, 0xb6, 0xd2, 0xd5, 0xfb, 0xd7, 0xb2, 0x83, 0xaf, 0x16, 0xf4, 0x6e, 0xbf, - 0x87, 0x8c, 0x61, 0x93, 0x32, 0x56, 0xa0, 0xd0, 0xbf, 0x56, 0xcf, 0x77, 0x7e, 0xfd, 0x78, 0xd9, - 0x37, 0x7f, 0xe3, 0x1b, 0xcd, 0xcc, 0x64, 0x91, 0xe6, 0x49, 0x50, 0x0b, 0x49, 0x1f, 0x36, 0xd2, - 0x9c, 0xe1, 0xc2, 0x64, 0xd5, 0x0d, 0x79, 0x0e, 0x4d, 0x86, 0x2a, 0x9a, 0x3d, 0xde, 0xb9, 0xb7, - 0x3d, 0x1f, 0xcc, 0xda, 0x9a, 0x93, 0x69, 0xd0, 0x64, 0xe8, 0xbf, 0xbd, 0x5a, 0xba, 0xd6, 0xf5, - 0xd2, 0xb5, 0xfe, 0x2c, 0x5d, 0xeb, 0xdb, 0xca, 0x6d, 0x5c, 0xaf, 0xdc, 0xc6, 0xef, 0x95, 0xdb, - 0xf8, 0xf8, 0x22, 0x49, 0xe5, 0x59, 0x19, 0x0d, 0x63, 0x9e, 0x79, 0x11, 0xcd, 0x99, 0x7a, 0x11, - 0x31, 0x3f, 0xf7, 0xe2, 0x33, 0x9a, 0xe6, 0xde, 0xc5, 0xd8, 0x5b, 0x54, 0x8f, 0xc8, 0x93, 0x5f, - 0xe6, 0x28, 0xa2, 0x8e, 0xa2, 0x8f, 0xfe, 0x06, 0x00, 0x00, 0xff, 0xff, 0x6e, 0xa5, 0xc3, 0x8c, - 0xc2, 0x03, 0x00, 0x00, + // 520 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x5c, 0x52, 0x41, 0x6e, 0xd3, 0x40, + 0x14, 0x8d, 0x93, 0x90, 0x90, 0xef, 0x90, 0x4a, 0x43, 0x40, 0x6e, 0x17, 0x4e, 0x14, 0x40, 0x44, + 0x02, 0x62, 0x92, 0x4a, 0xec, 0x09, 0x09, 0x5d, 0x20, 0xa4, 0xca, 0xd9, 0xb1, 0xb1, 0xc6, 0x9e, + 0x61, 0x3a, 0x52, 0xec, 0x89, 0x3c, 0xe3, 0x2a, 0xf4, 0x14, 0xdc, 0x80, 0x4b, 0x70, 0x88, 0x2e, + 0x2b, 0x56, 0xac, 0x2a, 0x94, 0x1c, 0x81, 0x0b, 0x20, 0xcf, 0x8c, 0xab, 0x86, 0x9d, 0xff, 0x7b, + 0xef, 0x3f, 0xbd, 0x79, 0xfe, 0x70, 0xac, 0xa4, 0x0c, 0x2e, 0xa7, 0x31, 0x55, 0x78, 0x1a, 0x30, + 0x9a, 0x51, 0xc9, 0xe5, 0x64, 0x93, 0x0b, 0x25, 0x90, 0xab, 0xa4, 0x9c, 0x58, 0xea, 0xa4, 0xcf, + 0x04, 0x13, 0x1a, 0x0f, 0xca, 0x2f, 0x23, 0x39, 0xf1, 0x99, 0x10, 0x6c, 0x4d, 0x03, 0x3d, 0xc5, + 0xc5, 0xd7, 0x80, 0x14, 0x39, 0x56, 0x5c, 0x64, 0x96, 0x7f, 0x72, 0xdf, 0xbd, 0xb4, 0x33, 0xf0, + 0x71, 0x22, 0x64, 0x2a, 0x64, 0x64, 0xfc, 0xcc, 0x60, 0xa8, 0xd1, 0xdf, 0x3a, 0x74, 0xcf, 0x4c, + 0x8c, 0x95, 0xc2, 0x8a, 0xa2, 0x29, 0xb4, 0x36, 0x38, 0xc7, 0xa9, 0xf4, 0x9c, 0xa1, 0x33, 0x76, + 0x67, 0x8f, 0x27, 0xf7, 0x62, 0x4d, 0xce, 0x35, 0x35, 0x6f, 0x5e, 0xdf, 0x0e, 0x6a, 0xa1, 0x15, + 0xa2, 0x01, 0xb8, 0x2c, 0x17, 0xc5, 0x26, 0x4a, 0x44, 0x91, 0x29, 0xaf, 0x3e, 0x74, 0xc6, 0xcd, + 0x10, 0x34, 0xf4, 0xa1, 0x44, 0xd0, 0x5b, 0x68, 0xe9, 0x49, 0x7a, 0x8d, 0x61, 0x63, 0xec, 0xce, + 0xd0, 0x81, 0xe7, 0x59, 0x49, 0x55, 0x96, 0x46, 0x87, 0x4e, 0xa1, 0x9d, 0xd2, 0x34, 0xa6, 0xb9, + 0xf4, 0x9a, 0x7a, 0xe5, 0x30, 0xc6, 0x67, 0xcd, 0xd9, 0x9d, 0x4a, 0x89, 0x9e, 0xc1, 0x23, 0xc9, + 0x59, 0xc6, 0x33, 0x66, 0x93, 0x3c, 0xd0, 0x49, 0xba, 0x16, 0x34, 0x59, 0xde, 0xc1, 0x43, 0x3b, + 0x4b, 0xaf, 0xa5, 0xad, 0xfb, 0x07, 0xd6, 0x2b, 0x43, 0x5a, 0xef, 0x3b, 0x2d, 0xfa, 0x04, 0x2e, + 0xa1, 0x32, 0xb2, 0xbf, 0xcc, 0x6b, 0xeb, 0xd5, 0xa7, 0x07, 0xab, 0x8b, 0xa5, 0x6d, 0x72, 0x8e, + 0xca, 0xe5, 0xdd, 0xed, 0x00, 0x16, 0x4b, 0x69, 0xb1, 0x10, 0x08, 0xad, 0xbe, 0x47, 0x3f, 0x1c, + 0x68, 0x99, 0x2a, 0xd1, 0x73, 0xe8, 0xa5, 0x78, 0x1b, 0x99, 0x02, 0x25, 0xbf, 0xa2, 0xba, 0xf7, + 0x66, 0xd8, 0x4d, 0xf1, 0x56, 0x37, 0xb3, 0xe2, 0x57, 0x14, 0x0d, 0xa0, 0x9c, 0x23, 0x12, 0x51, + 0xa3, 0x31, 0x1d, 0x77, 0x52, 0xbc, 0x5d, 0x2c, 0xb5, 0xe0, 0x25, 0x1c, 0x25, 0x39, 0xc5, 0xaa, + 0x7c, 0xfc, 0x86, 0xe6, 0x5c, 0x10, 0xaf, 0xa1, 0x35, 0xbd, 0x0a, 0x3e, 0xd7, 0x28, 0x7a, 0x01, + 0xbd, 0xaa, 0x24, 0xab, 0x6b, 0x6a, 0x5d, 0x55, 0x9d, 0x91, 0x8d, 0xd6, 0xd0, 0xb9, 0x7b, 0x0e, + 0x9a, 0x41, 0x1b, 0x13, 0x92, 0x53, 0x69, 0x8e, 0xa2, 0x33, 0xf7, 0x7e, 0xfd, 0x7c, 0xd3, 0xb7, + 0x77, 0xf4, 0xde, 0x30, 0x2b, 0x95, 0xf3, 0x8c, 0x85, 0x95, 0x10, 0xbd, 0x82, 0x3a, 0x31, 0x39, + 0xdd, 0xd9, 0xd1, 0x7f, 0x35, 0xcd, 0xc1, 0xf6, 0x53, 0x5f, 0x2c, 0xc3, 0x3a, 0xa1, 0xf3, 0x8f, + 0xd7, 0x3b, 0xdf, 0xb9, 0xd9, 0xf9, 0xce, 0x9f, 0x9d, 0xef, 0x7c, 0xdf, 0xfb, 0xb5, 0x9b, 0xbd, + 0x5f, 0xfb, 0xbd, 0xf7, 0x6b, 0x5f, 0x5e, 0x33, 0xae, 0x2e, 0x8a, 0x78, 0x92, 0x88, 0x34, 0x88, + 0x71, 0x46, 0xf4, 0xd5, 0x26, 0x62, 0x1d, 0x24, 0x17, 0x98, 0x67, 0xc1, 0xe5, 0x2c, 0xd8, 0x96, + 0x87, 0x1e, 0xa8, 0x6f, 0x1b, 0x2a, 0xe3, 0x96, 0xa6, 0x4f, 0xff, 0x05, 0x00, 0x00, 0xff, 0xff, + 0x50, 0xcf, 0x81, 0xaf, 0x66, 0x03, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { @@ -350,20 +329,6 @@ func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x42 - } - } - if len(m.DEQueues) > 0 { - for iNdEx := len(m.DEQueues) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DEQueues[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- dAtA[i] = 0x3a } } @@ -504,12 +469,7 @@ func (m *DEGenesis) MarshalToSizedBuffer(dAtA []byte) (int, error) { i = encodeVarintGenesis(dAtA, i, uint64(size)) } i-- - dAtA[i] = 0x1a - if m.Index != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Index)) - i-- - dAtA[i] = 0x10 - } + dAtA[i] = 0x12 if len(m.Address) > 0 { i -= len(m.Address) copy(dAtA[i:], m.Address) @@ -563,12 +523,6 @@ func (m *GenesisState) Size() (n int) { n += 1 + l + sovGenesis(uint64(l)) } } - if len(m.DEQueues) > 0 { - for _, e := range m.DEQueues { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } if len(m.DEsGenesis) > 0 { for _, e := range m.DEsGenesis { l = e.Size() @@ -609,9 +563,6 @@ func (m *DEGenesis) Size() (n int) { if l > 0 { n += 1 + l + sovGenesis(uint64(l)) } - if m.Index != 0 { - n += 1 + sovGenesis(uint64(m.Index)) - } l = m.DE.Size() n += 1 + l + sovGenesis(uint64(l)) return n @@ -826,40 +777,6 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { } iNdEx = postIndex case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DEQueues", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DEQueues = append(m.DEQueues, DEQueue{}) - if err := m.DEQueues[len(m.DEQueues)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DEsGenesis", wireType) } @@ -1102,25 +1019,6 @@ func (m *DEGenesis) Unmarshal(dAtA []byte) error { m.Address = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) - } - m.Index = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Index |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field DE", wireType) } diff --git a/x/tss/types/handler.go b/x/tss/types/handler.go index 5a698d5e3..5d594ba1b 100644 --- a/x/tss/types/handler.go +++ b/x/tss/types/handler.go @@ -4,9 +4,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// Content defines an interface that a signature order must implement. It contains -// information such as the type and routing information for the appropriate handler to process the order. -// Content can have additional fields, which will handled by a order's Handler. +// Content defines an interface that a signature order must implement. It contains information +// such as the type and routing information for the appropriate handler to process the order. +// Content can have additional fields, which is handled by an order's Handler. type Content interface { OrderRoute() string OrderType() string diff --git a/x/tss/types/keys.go b/x/tss/types/keys.go index 62b66dcd6..7b65fdeed 100644 --- a/x/tss/types/keys.go +++ b/x/tss/types/keys.go @@ -85,125 +85,143 @@ var ( // SigningStoreKeyPrefix is the key for keeps signing data. SigningStoreKeyPrefix = []byte{0x0e} - // SigCountStoreKeyPrefix is the key for keeps signature count data. - SigCountStoreKeyPrefix = []byte{0x0f} + // PartialSignatureCountStoreKeyPrefix is the key for keeps signature count data. + PartialSignatureCountStoreKeyPrefix = []byte{0x0f} // PartialSignatureStoreKeyPrefix is the key for keeps partial signature. PartialSignatureStoreKeyPrefix = []byte{0x10} - // ParamsKeyPrefix is a prefix for keys that store TSS's parameters + // ParamsKeyPrefix is a prefix for keys that store tss's parameters ParamsKeyPrefix = []byte{0x11} ) +// GroupStoreKey returns the key for storing group information. func GroupStoreKey(groupID tss.GroupID) []byte { return append(GroupStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(groupID))...) } +// DKGContextStoreKey returns the key for storing dkg context information. func DKGContextStoreKey(groupID tss.GroupID) []byte { return append(DKGContextStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(groupID))...) } +// MembersStoreKey returns the prefix for the MemberOfGroupKey. func MembersStoreKey(groupID tss.GroupID) []byte { return append(MemberStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(groupID))...) } +// MemberOfGroupKey returns the key for storing member information. func MemberOfGroupKey(groupID tss.GroupID, memberID tss.MemberID) []byte { return append(MembersStoreKey(groupID), sdk.Uint64ToBigEndian(uint64(memberID))...) } +// Round1InfoStoreKey returns the prefix for Round1InfoMemberStoreKey. func Round1InfoStoreKey(groupID tss.GroupID) []byte { return append(Round1InfoStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(groupID))...) } +// Round1InfoCountStoreKey returns the key for storing round-1 information count. func Round1InfoCountStoreKey(groupID tss.GroupID) []byte { return append(Round1InfoCountStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(groupID))...) } +// Round1InfoMemberStoreKey returns the key for storing round-1 information of a given member. func Round1InfoMemberStoreKey(groupID tss.GroupID, memberID tss.MemberID) []byte { return append(Round1InfoStoreKey(groupID), sdk.Uint64ToBigEndian(uint64(memberID))...) } +// AccumulatedCommitStoreKey returns the prefix for AccumulatedCommitIndexStoreKey. func AccumulatedCommitStoreKey(groupID tss.GroupID) []byte { return append(AccumulatedCommitStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(groupID))...) } +// AccumulatedCommitIndexStoreKey returns the key for storing accumulated commit of a group. func AccumulatedCommitIndexStoreKey(groupID tss.GroupID, index uint64) []byte { return append(AccumulatedCommitStoreKey(groupID), sdk.Uint64ToBigEndian(index)...) } +// Round2InfoStoreKey returns the prefix for Round2InfoMemberStoreKey. func Round2InfoStoreKey(groupID tss.GroupID) []byte { return append(Round2InfoStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(groupID))...) } +// Round2InfoMemberStoreKey returns the key for storing round-2 information of a given member. func Round2InfoMemberStoreKey(groupID tss.GroupID, memberID tss.MemberID) []byte { return append(Round2InfoStoreKey(groupID), sdk.Uint64ToBigEndian(uint64(memberID))...) } +// Round2InfoCountStoreKey returns the key for storing round-2 information count. func Round2InfoCountStoreKey(groupID tss.GroupID) []byte { return append(Round2InfoCountStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(groupID))...) } +// ConfirmStoreKey returns the prefix for ConfirmMemberStoreKey. func ConfirmStoreKey(groupID tss.GroupID) []byte { return append(ConfirmStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(groupID))...) } +// ConfirmMemberStoreKey returns the key for storing confirm information of a given member. func ConfirmMemberStoreKey(groupID tss.GroupID, memberID tss.MemberID) []byte { return append(ConfirmStoreKey(groupID), sdk.Uint64ToBigEndian(uint64(memberID))...) } +// ComplainsWithStatusStoreKey returns the prefix for ComplainsWithStatusMemberStoreKey. func ComplainsWithStatusStoreKey(groupID tss.GroupID) []byte { return append(ComplainsWithStatusStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(groupID))...) } +// ComplainsWithStatusMemberStoreKey returns the key for storing complain with status of a given member. func ComplainsWithStatusMemberStoreKey(groupID tss.GroupID, memberID tss.MemberID) []byte { return append(ComplainsWithStatusStoreKey(groupID), sdk.Uint64ToBigEndian(uint64(memberID))...) } +// ConfirmComplainCountStoreKey returns the key for storing confirm complain count. func ConfirmComplainCountStoreKey(groupID tss.GroupID) []byte { return append(ConfirmComplainCountStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(groupID))...) } +// DEStoreKey returns the prefix for DEIndexStoreKey. func DEStoreKey(address sdk.AccAddress) []byte { return append(DEStoreKeyPrefix, address...) } +// DEIndexStoreKey returns the key for storing DE information. func DEIndexStoreKey(address sdk.AccAddress, index uint64) []byte { return append(DEStoreKey(address), sdk.Uint64ToBigEndian(index)...) } +// AddressAndIndexFromDEStoreKey returns the address and index that is retrieved from the key. func AddressAndIndexFromDEStoreKey(key []byte) (sdk.AccAddress, uint64) { return sdk.AccAddress(key[1 : len(key)-uint64Len]), sdk.BigEndianToUint64(key[len(key)-uint64Len:]) } +// DEQueueStoreKey returns the key for storing DEQueue information. func DEQueueKeyStoreKey(address sdk.AccAddress) []byte { return append(DEQueueStoreKeyPrefix, address...) } -func AddressFromDEQueueStoreKey(key []byte) sdk.AccAddress { - return sdk.AccAddress(key[1:]) -} - +// SigningStoreKey returns the key for storing signing information. func SigningStoreKey(signingID tss.SigningID) []byte { return append(SigningStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(signingID))...) } -func SigCountStoreKey(signingID tss.SigningID) []byte { - return append(SigCountStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(signingID))...) +// PartialSignatureCountStoreKey returns the key for storing signature count information. +func PartialSignatureCountStoreKey(signingID tss.SigningID) []byte { + return append(PartialSignatureCountStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(signingID))...) } +// PartialSignatureStoreKey returns the prefix for PartialSignatureMemberStoreKey. func PartialSignatureStoreKey(signingID tss.SigningID) []byte { return append(PartialSignatureStoreKeyPrefix, sdk.Uint64ToBigEndian(uint64(signingID))...) } +// PartialSignatureMemberStoreKey returns the key for storing partial signature information of a given member. func PartialSignatureMemberStoreKey(signingID tss.SigningID, memberID tss.MemberID) []byte { return append(PartialSignatureStoreKey(signingID), sdk.Uint64ToBigEndian(uint64(memberID))...) } +// MemberIDFromPartialSignatureMemberStoreKey returns the memberID that is retrieved from the key. func MemberIDFromPartialSignatureMemberStoreKey(key []byte) tss.MemberID { kv.AssertKeyLength(key, 1+2*uint64Len) return tss.MemberID(sdk.BigEndianToUint64(key[1+uint64Len:])) } - -func SigningIDFromPendingSignStoreKey(key []byte) uint64 { - return sdk.BigEndianToUint64(key[len(key)-uint64Len:]) -} diff --git a/x/tss/types/msgs.go b/x/tss/types/msgs.go index 540ca3d1b..266d9226b 100644 --- a/x/tss/types/msgs.go +++ b/x/tss/types/msgs.go @@ -1,17 +1,20 @@ package types import ( - "fmt" - - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/bandprotocol/chain/v2/pkg/tss" ) var ( - _, _, _, _ sdk.Msg = &MsgSubmitDKGRound1{}, &MsgSubmitDKGRound2{}, &MsgComplain{}, &MsgConfirm{} - _, _, _ sdk.Msg = &MsgSubmitDEs{}, &MsgSubmitSignature{}, &MsgUpdateParams{} + _ sdk.Msg = &MsgSubmitDKGRound1{} + _ sdk.Msg = &MsgSubmitDKGRound2{} + _ sdk.Msg = &MsgComplain{} + _ sdk.Msg = &MsgConfirm{} + _ sdk.Msg = &MsgSubmitDEs{} + _ sdk.Msg = &MsgSubmitSignature{} + _ sdk.Msg = &MsgUpdateParams{} ) // NewMsgSubmitDKGRound1 creates a new MsgSubmitDKGRound1 instance. @@ -39,31 +42,30 @@ func (m MsgSubmitDKGRound1) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data func (m MsgSubmitDKGRound1) ValidateBasic() error { // Validate member address - _, err := sdk.AccAddressFromBech32(m.Address) - if err != nil { - return errors.Wrap(err, "member") + if _, err := sdk.AccAddressFromBech32(m.Address); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) } // Validate coefficients commit for _, c := range m.Round1Info.CoefficientCommits { if err := c.Validate(); err != nil { - return errors.Wrap(err, "coefficients commit") + return ErrInvalidCoefficientCommit.Wrapf("invalid coefficient commit: %s", err) } } // Validate one time pub key if err := m.Round1Info.OneTimePubKey.Validate(); err != nil { - return errors.Wrap(err, "one time pub key") + return ErrInvalidPublicKey.Wrapf("invalid one-time public key: %s", err) } // Validate a0 signature if err := m.Round1Info.A0Signature.Validate(); err != nil { - return errors.Wrap(err, "a0 sig") + return ErrInvalidSignature.Wrapf("invalid a0 signature: %s", err) } // Validate one time signature if err := m.Round1Info.OneTimeSignature.Validate(); err != nil { - return errors.Wrap(err, "one time sig") + return ErrInvalidSignature.Wrapf("invalid one-time signature: %s", err) } return nil @@ -94,15 +96,14 @@ func (m MsgSubmitDKGRound2) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data func (m MsgSubmitDKGRound2) ValidateBasic() error { // Validate member address - _, err := sdk.AccAddressFromBech32(m.Address) - if err != nil { - return errors.Wrap(err, "member") + if _, err := sdk.AccAddressFromBech32(m.Address); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } // Validate encrypted secret shares for i, ess := range m.Round2Info.EncryptedSecretShares { if err := ess.Validate(); err != nil { - return errors.Wrap(err, fmt.Sprintf("encrypted secret shares at index: %d", i)) + return ErrInvalidSecretShare.Wrapf("encrypted secret shares at index %d: %s", i, err) } } @@ -134,14 +135,13 @@ func (m MsgComplain) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data func (m MsgComplain) ValidateBasic() error { // Validate member address - _, err := sdk.AccAddressFromBech32(m.Address) - if err != nil { - return errors.Wrap(err, "member") + if _, err := sdk.AccAddressFromBech32(m.Address); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } // Validate complaints size if len(m.Complaints) < 1 { - return errors.Wrap(fmt.Errorf("must contain at least one complaint"), "complaints") + return ErrInvalidComplaint.Wrapf("must contain at least one complaint") } // Validate complaints @@ -149,28 +149,22 @@ func (m MsgComplain) ValidateBasic() error { for i, c := range m.Complaints { // Validate member complainant if i > 0 && memberI != c.Complainant { - return errors.Wrap( - fmt.Errorf("memberID complainant in the list of complaints must be the same value"), - "complainant", - ) + return ErrInvalidComplaint.Wrapf("memberID complainant in the list of complaints must be the same value") } // Validate member complainant and respondent if c.Complainant == c.Respondent { - return errors.Wrap( - fmt.Errorf("memberID complainant and respondent can not be the same value"), - "complainant, respondent", - ) + return ErrInvalidComplaint.Wrapf("memberID complainant and respondent can not be the same value") } // Validate key sym if err := c.KeySym.Validate(); err != nil { - return errors.Wrap(err, "key sym") + return ErrInvalidSymmetricKey.Wrapf("invalid symmetric key: %s", err) } // Validate signature if err := c.Signature.Validate(); err != nil { - return errors.Wrap(err, "signature") + return ErrInvalidSignature.Wrapf("invalid signature: %s", err) } } @@ -208,14 +202,13 @@ func (m MsgConfirm) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data func (m MsgConfirm) ValidateBasic() error { // Validate member address - _, err := sdk.AccAddressFromBech32(m.Address) - if err != nil { - return errors.Wrap(err, "member") + if _, err := sdk.AccAddressFromBech32(m.Address); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } // Validate own pub key sig - if err = m.OwnPubKeySig.Validate(); err != nil { - return errors.Wrap(err, "own pub key sig") + if err := m.OwnPubKeySig.Validate(); err != nil { + return ErrInvalidPublicKey.Wrapf("invalid own public key signature: %s", err) } return nil @@ -245,21 +238,20 @@ func (m MsgSubmitDEs) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data func (m MsgSubmitDEs) ValidateBasic() error { // Validate member address - _, err := sdk.AccAddressFromBech32(m.Address) - if err != nil { - return errors.Wrap(err, "member") + if _, err := sdk.AccAddressFromBech32(m.Address); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } // Validate DEs for i, de := range m.DEs { // Validate public key D - if err = de.PubD.Validate(); err != nil { - return errors.Wrap(err, fmt.Sprintf("pub D in DE index: %d", i)) + if err := de.PubD.Validate(); err != nil { + return ErrInvalidDE.Wrapf("pub D in DE index %d: %s", i, err) } // Validate public key E - if err = de.PubE.Validate(); err != nil { - return errors.Wrap(err, fmt.Sprintf("pub E in DE index: %d", i)) + if err := de.PubE.Validate(); err != nil { + return ErrInvalidDE.Wrapf("pub E in DE index %d: %s", i, err) } } @@ -297,14 +289,13 @@ func (m MsgSubmitSignature) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data func (m MsgSubmitSignature) ValidateBasic() error { // Validate member address - _, err := sdk.AccAddressFromBech32(m.Address) - if err != nil { - return errors.Wrap(err, "member") + if _, err := sdk.AccAddressFromBech32(m.Address); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid address: %s", err) } // Validate member signature - if err = m.Signature.Validate(); err != nil { - return errors.Wrap(err, "signature") + if err := m.Signature.Validate(); err != nil { + return ErrInvalidSignature.Wrapf("invalid signature :%s", err) } return nil @@ -334,7 +325,7 @@ func (m *MsgUpdateParams) GetSigners() []sdk.AccAddress { // ValidateBasic does a sanity check on the provided data. func (m *MsgUpdateParams) ValidateBasic() error { if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { - return errors.Wrap(err, "invalid authority address") + return sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err) } if err := m.Params.Validate(); err != nil { diff --git a/x/tss/types/query.pb.go b/x/tss/types/query.pb.go index 59167e04a..07830b27c 100644 --- a/x/tss/types/query.pb.go +++ b/x/tss/types/query.pb.go @@ -574,7 +574,7 @@ func (m *QueryDEResponse) GetPagination() *query.PageResponse { // QueryPendingGroupsRequest is the request type for the Query/PendingGroups RPC method. type QueryPendingGroupsRequest struct { - // address is the address for the request. + // address is the address of the member. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` } @@ -666,7 +666,7 @@ func (m *QueryPendingGroupsResponse) GetPendingGroups() []uint64 { // QueryPendingSigningsRequest is the request type for the Query/PendingSignings RPC method. type QueryPendingSigningsRequest struct { - // address is the address for the request. + // address is the address of the member. Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` } @@ -959,15 +959,15 @@ type QueryClient interface { Group(ctx context.Context, in *QueryGroupRequest, opts ...grpc.CallOption) (*QueryGroupResponse, error) // Members queries all members in this group. Members(ctx context.Context, in *QueryMembersRequest, opts ...grpc.CallOption) (*QueryMembersResponse, error) - // IsGrantee queries grant of account on this granter. + // IsGrantee queries whether granter grants the grantee. IsGrantee(ctx context.Context, in *QueryIsGranteeRequest, opts ...grpc.CallOption) (*QueryIsGranteeResponse, error) // DE queries all de for this address. DE(ctx context.Context, in *QueryDERequest, opts ...grpc.CallOption) (*QueryDEResponse, error) - // PendingGroups queries all pending groups for this address. + // PendingGroups queries all pending groups that waits the given address to submit a message. PendingGroups(ctx context.Context, in *QueryPendingGroupsRequest, opts ...grpc.CallOption) (*QueryPendingGroupsResponse, error) - // PendingSignings queries all pending signs for this address. + // PendingSignings queries all pending requests that waits the given address to sign a message. PendingSignings(ctx context.Context, in *QueryPendingSigningsRequest, opts ...grpc.CallOption) (*QueryPendingSigningsResponse, error) - // Signing queries signing details. + // Signing queries signing details from the given id. Signing(ctx context.Context, in *QuerySigningRequest, opts ...grpc.CallOption) (*QuerySigningResponse, error) } @@ -1059,15 +1059,15 @@ type QueryServer interface { Group(context.Context, *QueryGroupRequest) (*QueryGroupResponse, error) // Members queries all members in this group. Members(context.Context, *QueryMembersRequest) (*QueryMembersResponse, error) - // IsGrantee queries grant of account on this granter. + // IsGrantee queries whether granter grants the grantee. IsGrantee(context.Context, *QueryIsGranteeRequest) (*QueryIsGranteeResponse, error) // DE queries all de for this address. DE(context.Context, *QueryDERequest) (*QueryDEResponse, error) - // PendingGroups queries all pending groups for this address. + // PendingGroups queries all pending groups that waits the given address to submit a message. PendingGroups(context.Context, *QueryPendingGroupsRequest) (*QueryPendingGroupsResponse, error) - // PendingSignings queries all pending signs for this address. + // PendingSignings queries all pending requests that waits the given address to sign a message. PendingSignings(context.Context, *QueryPendingSigningsRequest) (*QueryPendingSigningsResponse, error) - // Signing queries signing details. + // Signing queries signing details from the given id. Signing(context.Context, *QuerySigningRequest) (*QuerySigningResponse, error) } diff --git a/x/tss/types/router.go b/x/tss/types/router.go index ecfcc3e55..fffd872a8 100644 --- a/x/tss/types/router.go +++ b/x/tss/types/router.go @@ -3,7 +3,6 @@ package types import ( "fmt" - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" tsslib "github.com/bandprotocol/chain/v2/pkg/tss" @@ -64,11 +63,13 @@ func (r *Router) GetRoute(path string) Handler { return r.handlers[path] } +// wrapHandler returns a function that converts content into message bytes. +// It prefixes the message with a selector, which consists of first 4 bytes of the hashed path. func wrapHandler(path string, handler Handler) Handler { return func(ctx sdk.Context, req Content) ([]byte, error) { msg, err := handler(ctx, req) if err != nil { - return nil, errors.Wrap(ErrHandleSignatureOrderFailed, err.Error()) + return nil, ErrHandleSignatureOrderFailed.Wrap(err.Error()) } selector := tsslib.Hash([]byte(path))[:4] diff --git a/x/tss/types/signature_order.go b/x/tss/types/signature_order.go index e20e48030..9846ac8e7 100644 --- a/x/tss/types/signature_order.go +++ b/x/tss/types/signature_order.go @@ -1,7 +1,6 @@ package types import ( - "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -38,8 +37,7 @@ func NewSignatureOrderHandler() Handler { return c.Message, nil default: - return nil, errors.Wrapf( - sdkerrors.ErrUnknownRequest, + return nil, sdkerrors.ErrUnknownRequest.Wrapf( "unrecognized tss request signature message type: %s", c.OrderType(), ) diff --git a/x/tss/types/signing.go b/x/tss/types/signing.go index caeae01fc..b626f029a 100644 --- a/x/tss/types/signing.go +++ b/x/tss/types/signing.go @@ -24,8 +24,3 @@ func NewSigning( Status: status, } } - -// IsFailed check whether the signing is failed due to expired or fail within the execution. -func (s Signing) IsFailed() bool { - return s.Status == SIGNING_STATUS_EXPIRED || s.Status == SIGNING_STATUS_FALLEN -} diff --git a/yoda/executor/rest.go b/yoda/executor/rest.go index 1c3892792..a37573fb6 100644 --- a/yoda/executor/rest.go +++ b/yoda/executor/rest.go @@ -56,6 +56,7 @@ func (e *RestExec) Exec(code []byte, arg string, env interface{}) (ExecResult, e r := externalExecutionResponse{} err = resp.JSON(&r) + if err != nil { return ExecResult{}, err } From c0dbf2d90f36af9dce4785564ddcafaaa18016cc Mon Sep 17 00:00:00 2001 From: satawatnack Date: Thu, 16 May 2024 16:48:27 +0700 Subject: [PATCH 071/132] update latest version --- flusher/flusher/db.py | 23 ++++- flusher/flusher/handler.py | 132 ++++++++++++++++++++--------- flusher/flusher/tss_db.py | 85 +++++++++---------- hasura/hasura-metadata/tables.yaml | 107 ++++++++++++++++++++--- hooks/emitter/bandtss.go | 78 +++++++++++------ hooks/emitter/channel.go | 1 + hooks/emitter/handler.go | 22 ++--- hooks/emitter/oracle.go | 1 + hooks/emitter/tss.go | 32 +++---- x/bandtss/keeper/signing.go | 1 + 10 files changed, 325 insertions(+), 157 deletions(-) diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index ebe7255de..00fd391be 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -21,6 +21,13 @@ class ProposalStatus(enum.Enum): Inactive = 6 +class TSSEncodeType(enum.Enum): + Unspecified = 0 + Proto = 1 + FullABI = 2 + PartialABI = 3 + + class CustomResolveStatus(sa.types.TypeDecorator): impl = sa.Enum(ResolveStatus) @@ -35,6 +42,13 @@ def process_bind_param(self, value, dialect): return ProposalStatus(value) +class CustomTSSEncodeType(sa.types.TypeDecorator): + impl = sa.Enum(TSSEncodeType) + + def process_bind_param(self, value, dialect): + return TSSEncodeType(value) + + class CustomDateTime(sa.types.TypeDecorator): """Custom DateTime type that accepts Python nanosecond epoch int.""" @@ -179,8 +193,8 @@ def Column(*args, **kwargs): Column("prepare_gas_used", sa.Integer, default=0), Column("execute_gas", sa.Integer), Column("execute_gas_used", sa.Integer, default=0), + Column("tss_encode_type", CustomTSSEncodeType), Column("sender", sa.String, nullable=True), - Column("tss_group_id", sa.Integer, default=0), Column("client_id", sa.String), Column("request_time", sa.Integer, nullable=True, index=True), Column("resolve_status", CustomResolveStatus), @@ -627,7 +641,12 @@ def Column(*args, **kwargs): group_votes = sa.Table( "group_votes", metadata, - Column("group_proposal_id", sa.Integer, sa.ForeignKey("group_proposals.id"), primary_key=True), + Column( + "group_proposal_id", + sa.Integer, + sa.ForeignKey("group_proposals.id"), + primary_key=True, + ), Column("voter_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), Column("option", sa.String), Column("metadata", sa.String), diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index c707a13a2..fa83b836c 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -49,10 +49,12 @@ from .tss_db import ( tss_signings, tss_groups, - tss_group_members, + band_tss_groups, + tss_members, tss_assigned_members, - tss_statuses, - tss_replacements, + band_tss_members, + band_tss_signings, + band_tss_replacements, ) @@ -137,10 +139,18 @@ def get_oracle_script_id(self, id): ).scalar() def get_group_id_from_policy_address(self, address): - return self.conn.execute(select([group_policies.c.group_id]).where(group_policies.c.address == address)).scalar() + return self.conn.execute( + select([group_policies.c.group_id]).where( + group_policies.c.address == address + ) + ).scalar() def get_group_id_from_policy_address(self, address): - return self.conn.execute(select([group_policies.c.group_id]).where(group_policies.c.address == address)).scalar() + return self.conn.execute( + select([group_policies.c.group_id]).where( + group_policies.c.address == address + ) + ).scalar() def get_ibc_received_txs(self, date, port, channel, address): msg = {"date": date, "port": port, "channel": channel, "address": address} @@ -221,7 +231,9 @@ def handle_new_group_policy(self, msg): self.conn.execute(group_policies.insert(), msg) def handle_new_group_proposal(self, msg): - msg["group_id"] = self.get_group_id_from_policy_address(msg["group_policy_address"]) + msg["group_id"] = self.get_group_id_from_policy_address( + msg["group_policy_address"] + ) self.conn.execute(group_proposals.insert(), msg) def handle_new_group_vote(self, msg): @@ -234,21 +246,42 @@ def handle_update_group(self, msg): def handle_remove_group_member(self, msg): account_id = self.get_account_id(msg["address"]) - self.conn.execute(group_members.delete().where((group_members.c.group_id == msg["group_id"]) & (group_members.c.account_id == account_id))) + self.conn.execute( + group_members.delete().where( + (group_members.c.group_id == msg["group_id"]) + & (group_members.c.account_id == account_id) + ) + ) def handle_remove_group_members_by_group_id(self, msg): - self.conn.execute(group_members.delete().where(group_members.c.group_id == msg["group_id"])) + self.conn.execute( + group_members.delete().where(group_members.c.group_id == msg["group_id"]) + ) def handle_update_group_policy(self, msg): - self.conn.execute(group_policies.update().where(group_policies.c.address == msg["address"]).values(**msg)) - + self.conn.execute( + group_policies.update() + .where(group_policies.c.address == msg["address"]) + .values(**msg) + ) + def handle_update_group_proposal(self, msg): - msg["group_id"] = self.get_group_id_from_policy_address(msg["group_policy_address"]) - self.conn.execute(group_proposals.update().where(group_proposals.c.id == msg["id"]).values(**msg)) + msg["group_id"] = self.get_group_id_from_policy_address( + msg["group_policy_address"] + ) + self.conn.execute( + group_proposals.update() + .where(group_proposals.c.id == msg["id"]) + .values(**msg) + ) def handle_update_group_proposal_by_id(self, msg): - self.conn.execute(group_proposals.update().where(group_proposals.c.id == msg["id"]).values(**msg)) - + self.conn.execute( + group_proposals.update() + .where(group_proposals.c.id == msg["id"]) + .values(**msg) + ) + def handle_set_data_source(self, msg): msg["transaction_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] @@ -296,6 +329,14 @@ def handle_update_request(self, msg): if msg["tss_signing_id"] == 0: del msg["tss_signing_id"] + if "tss_signing_error_codespace" in msg: + if msg["tss_signing_error_codespace"] == "": + del msg["tss_signing_error_codespace"] + + if "tss_signing_error_code" in msg: + if msg["tss_signing_error_code"] == 0: + del msg["tss_signing_error_code"] + condition = True for col in requests.primary_key.columns.values(): condition = (col == msg[col.name]) & condition @@ -764,46 +805,59 @@ def handle_update_tss_signing(self, msg): condition = (col == msg[col.name]) & condition self.conn.execute(tss_signings.update().where(condition).values(**msg)) - def handle_set_tss_status(self, msg): - msg["account_id"] = self.get_account_id(msg["address"]) - del msg["address"] + def handle_set_band_tss_member(self, msg): + msg["requester_id"] = self.get_account_id(msg["requester"]) + del msg["requester"] - if not self.have_tss_account(msg["account_id"]): - self.conn.execute(tss_statuses.insert(), msg) - else: - condition = True - for col in tss_statuses.primary_key.columns.values(): - condition = (col == msg[col.name]) & condition - self.conn.execute(tss_statuses.update().where(condition).values(**msg)) + self.conn.execute( + insert(band_tss_signings) + .values(**msg) + .on_conflict_do_update(constraint="band_tss_signings_pkey", set_=msg) + ) def handle_set_tss_group(self, msg): - if msg["latest_replacement_id"] == 0: - msg["latest_replacement_id"] = None - self.conn.execute( insert(tss_groups) .values(**msg) .on_conflict_do_update(constraint="tss_groups_pkey", set_=msg) ) - def handle_set_tss_group_member(self, msg): + def handle_set_band_tss_group(self, msg): + self.conn.execute( + insert(band_tss_groups) + .values(**msg) + .on_conflict_do_update(constraint="band_tss_groups_pkey", set_=msg) + ) + + def handle_set_band_tss_replacement(self, msg): + self.conn.execute( + insert(band_tss_replacements) + .values(**msg) + .on_conflict_do_update(constraint="band_tss_replacements_pkey", set_=msg) + ) + + def handle_set_tss_member(self, msg): msg["account_id"] = self.get_account_id(msg["address"]) del msg["address"] self.conn.execute( - insert(tss_group_members) + insert(tss_members) .values(**msg) - .on_conflict_do_update(constraint="tss_group_members_pkey", set_=msg) + .on_conflict_do_update(constraint="tss_members_pkey", set_=msg) ) - def handle_new_tss_assigned_member(self, msg): - self.conn.execute(tss_assigned_members.insert(), msg) + def handle_set_band_tss_member(self, msg): + msg["account_id"] = self.get_account_id(msg["address"]) + del msg["address"] + + self.conn.execute( + insert(band_tss_members) + .values(**msg) + .on_conflict_do_update(constraint="band_tss_members_pkey", set_=msg) + ) - def handle_new_tss_replacement(self, msg): - self.conn.execute(tss_replacements.insert(), msg) + def handle_remove_band_tss_members(self, msg): + self.conn.execute(band_tss_members.delete()) - def handle_update_tss_replacement_status(self, msg): - condition = True - for col in tss_signings.primary_key.columns.values(): - condition = (col == msg[col.name]) & condition - self.conn.execute(tss_replacements.update().where(condition).values(**msg)) + def handle_new_tss_assigned_member(self, msg): + self.conn.execute(tss_assigned_members.insert(), msg) diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index ac25a4a06..78cd82a08 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -14,7 +14,7 @@ class SigningStatus(enum.Enum): waiting = 1 success = 2 expired = 3 - failed = 4 + fallen = 4 class GroupStatus(enum.Enum): @@ -24,22 +24,15 @@ class GroupStatus(enum.Enum): round3 = 3 active = 4 expired = 5 - failed = 6 - - -class TSSStatus(enum.Enum): - nil = 0 - active = 1 - paused = 2 - inactive = 3 - jail = 4 + fallen = 6 class ReplacementStatus(enum.Enum): nil = 0 - waiting = 1 - success = 2 - fallen = 3 + waiting_sign = 1 + waiting_replace = 2 + success = 3 + fallen = 4 class CustomSigningStatus(sa.types.TypeDecorator): @@ -56,13 +49,6 @@ def process_bind_param(self, value, dialect): return GroupStatus(value) -class CustomTSSStatus(sa.types.TypeDecorator): - impl = sa.Enum(TSSStatus) - - def process_bind_param(self, value, dialect): - return TSSStatus(value) - - class CustomReplacementStatus(sa.types.TypeDecorator): impl = sa.Enum(ReplacementStatus) @@ -79,7 +65,6 @@ def process_bind_param(self, value, dialect): Column("msg", CustomBase64), Column("group_pub_nonce", CustomBase64), Column("signature", CustomBase64, nullable=True), - Column("fee", sa.String), Column("status", CustomSigningStatus), Column("reason", sa.String, nullable=True), Column( @@ -89,43 +74,43 @@ def process_bind_param(self, value, dialect): nullable=True, index=True, ), - Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), index=True), sa.Index( "ix_group_id_group_pub_key_status", "tss_group_id", "group_pub_key", "status" ), ) +band_tss_signings = sa.Table( + "band_tss_signings", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("fee", sa.String), + Column("requester_id", sa.Integer, sa.ForeignKey("accounts.id")), + Column("current_group_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), + Column("replacing_group_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), +) + tss_groups = sa.Table( "tss_groups", metadata, Column("id", sa.Integer, primary_key=True), Column("size", sa.Integer), Column("threshold", sa.Integer), - Column("dkg_context", CustomBase64), Column("pub_key", CustomBase64, nullable=True), Column("status", CustomGroupStatus), - Column("fee", sa.String), - # if zero set it to nil - Column( - "latest_replacement_id", - sa.Integer, - sa.ForeignKey("tss_replacements.id"), - nullable=True, - ), + Column("dkg_context", CustomBase64), + Column("module_owner", sa.String), Column("created_height", sa.Integer, index=True), ) -tss_statuses = sa.Table( - "tss_statuses", +band_tss_groups = sa.Table( + "band_tss_groups", metadata, - Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), - Column("status", CustomTSSStatus), - Column("since", CustomDateTime), - Column("last_active", CustomDateTime), + Column("id", sa.Integer, primary_key=True), + Column("current_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), ) -tss_group_members = sa.Table( - "tss_group_members", +tss_members = sa.Table( + "tss_members", metadata, Column("id", sa.Integer, primary_key=True), Column( @@ -134,6 +119,16 @@ def process_bind_param(self, value, dialect): Column("account_id", sa.Integer, sa.ForeignKey("accounts.id")), Column("pub_key", CustomBase64, nullable=True), Column("is_malicious", sa.Boolean), + Column("is_active", sa.Boolean), +) + +band_tss_members = sa.Table( + "band_tss_members", + metadata, + Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), + Column("is_active", sa.Boolean), + Column("since", CustomDateTime), + Column("last_active", CustomDateTime), ) tss_assigned_members = sa.Table( @@ -145,11 +140,13 @@ def process_bind_param(self, value, dialect): Column( "tss_group_id", sa.Integer, + sa.ForeignKey("tss_groups.id"), primary_key=True, ), Column( - "tss_group_member_id", + "tss_member_id", sa.Integer, + sa.ForeignKey("tss_members.id"), primary_key=True, ), Column("pub_d", CustomBase64), @@ -157,13 +154,13 @@ def process_bind_param(self, value, dialect): Column("binding_factor", CustomBase64), Column("pub_nonce", CustomBase64), sa.ForeignKeyConstraint( - ["tss_group_id", "tss_group_member_id"], - ["tss_group_members.tss_group_id", "tss_group_members.id"], + ["tss_group_id", "tss_member_id"], + ["tss_members.tss_group_id", "tss_members.id"], ), ) -tss_replacements = sa.Table( - "tss_replacements", +band_tss_replacements = sa.Table( + "band_tss_replacements", metadata, Column("id", sa.Integer, primary_key=True), Column("tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index 810f17a4d..bc76bb9f3 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -26,6 +26,9 @@ table: name: validators schema: public + - name: band_tss_member + using: + foreign_key_constraint_on: account_id array_relationships: - name: account_transactions using: @@ -104,12 +107,19 @@ table: name: reports schema: public - - name: signing_data + - name: tss_members using: foreign_key_constraint_on: column: account_id table: - name: signing_data + name: tss_members + schema: public + - name: band_tss_signings + using: + foreign_key_constraint_on: + column: requester_id + table: + name: band_tss_signings schema: public - name: unbonding_delegations using: @@ -154,12 +164,12 @@ table: name: requests schema: public - - name: signing_data + - name: tss_signings using: foreign_key_constraint_on: column: created_height table: - name: signing_data + name: tss_signings schema: public - name: transactions using: @@ -700,7 +710,10 @@ - name: oracle_script using: foreign_key_constraint_on: oracle_script_id - - name: signing_datum + - name: group + using: + foreign_key_constraint_on: tss_group_id + - name: tss_signing using: foreign_key_constraint_on: tss_signing_id - name: transaction @@ -729,23 +742,91 @@ name: val_requests schema: public - table: - name: signing_data + name: tss_signings schema: public object_relationships: - - name: account - using: - foreign_key_constraint_on: account_id - - name: block + - name: tss_replacement using: - foreign_key_constraint_on: created_height + foreign_key_constraint_on: tss_signing_id array_relationships: - - name: requests + - name: replacing_band_tss_signing + using: + foreign_key_constraint_on: + column: replacing_group_signing_id + table: + name: band_tss_signing + schema: public + - name: current_band_tss_signing + using: + foreign_key_constraint_on: + column: current_group_signing_id + table: + name: band_tss_signing + schema: public + - name: tss_assigned_members using: foreign_key_constraint_on: column: tss_signing_id table: - name: requests + name: tss_assigned_members + schema: public + - name: tss_replacements + using: + foreign_key_constraint_on: + column: tss_signing_id + table: + name: tss_replacements + schema: public +- table: + name: tss_groups + schema: public + object_relationships: + - name: tss_group + using: + foreign_key_constraint_on: current_group_id + array_relationships: + - name: tss_members + using: + foreign_key_constraint_on: + column: tss_group_id + table: + name: tss_members schema: public + - name: tss_assigned_members + using: + foreign_key_constraint_on: + column: tss_group_id + table: + name: tss_assigned_members + schema: public + - name: tss_replacements_new_group + using: + foreign_key_constraint_on: + column: new_group_id + table: + name: tss_replacements + schema: public + - name: tss_replacements_current_group + using: + foreign_key_constraint_on: + column: current_group_id + table: + name: tss_replacements + schema: public +- table: + name: tss_members + schema: public + array_relationships: + - name: tss_assigned_members + using: + foreign_key_constraint_on: + column: tss_member_id + table: + name: tss_assigned_members + schema: public +- table: + name: tss_replacements + schema: public - table: name: tracking schema: public diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index 99a8078a5..4d7dc6344 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -4,43 +4,71 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bandprotocol/chain/v2/hooks/common" + "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/x/bandtss/types" ) -func (h *Hook) emitSetBandtssStatus(member types.Member) { - h.Write("SET_BANDTSS_STATUS", common.JsDict{ - "address": member.Address, - "is_active": member.IsActive, - "since": member.Since.UnixNano(), - "last_active": member.LastActive.UnixNano(), - }) -} - -func (h *Hook) emitNewBandtssReplacement(replacement types.Replacement) { - h.Write("NEW_BANDTSS_REPLACEMENT", common.JsDict{ +func (h *Hook) emitSetBandtssReplacement(replacement types.Replacement) { + h.Write("SET_BAND_TSS_REPLACEMENT", common.JsDict{ + "id": 1, "tss_signing_id": replacement.SigningID, "new_group_id": replacement.NewGroupID, "new_pub_key": parseBytes(replacement.NewPubKey), "current_group_id": replacement.CurrentGroupID, "current_pub_key": parseBytes(replacement.CurrentPubKey), "exec_time": replacement.ExecTime.UnixNano(), - "status": int(replacement.Status), + "status": replacement.Status, + }) +} + +func (h *Hook) emitSetBandtssGroup(gid tss.GroupID) { + h.Write("SET_BAND_TSS_GROUP", common.JsDict{ + "id": 1, + "current_group_id": gid, + }) +} + +func (h *Hook) emitSetBandtssMember(member types.Member) { + h.Write("SET_BAND_TSS_MEMBER", common.JsDict{ + "address": member.Address, + "is_active": member.IsActive, + "since": member.Since.UnixNano(), + "last_active": member.LastActive.UnixNano(), }) } -func (h *Hook) emitUpdateBandtssReplacementStatus(status types.ReplacementStatus) { - h.Write("UPDATE_BANDTSS_REPLACEMENT_STATUS", common.JsDict{ - "status": int(status), +func (h *Hook) emitRemoveBandtssMember() { + h.Write("REMOVE_BAND_TSS_MEMBERS", common.JsDict{}) +} + +func (h *Hook) emitSetBandtssSigning(signing types.Signing) { + h.Write("SET_BAND_TSS_SIGNING", common.JsDict{ + "id": signing.ID, + "fee": signing.Fee.String(), + "requester": signing.Requester, + "current_group_signing_id": signing.CurrentGroupSigningID, + "replacing_group_signing_id": signing.ReplacingGroupSigningID, }) } +// handleNewBandtssGroupActive implements emitter handler for new bandtss group active. +func (h *Hook) handleNewBandtssGroupActive(ctx sdk.Context, gid tss.GroupID) { + h.emitSetBandtssGroup(gid) + h.emitRemoveBandtssMember() + + members := h.bandtssKeeper.GetMembers(ctx) + for _, m := range members { + h.emitSetBandtssMember(m) + } +} + // handleUpdateBandtssStatus implements emitter handler for update bandtss status. func (h *Hook) handleUpdateBandtssStatus(ctx sdk.Context, address sdk.AccAddress) { member, err := h.bandtssKeeper.GetMember(ctx, address) if err != nil { panic(err) } - h.emitSetBandtssStatus(member) + h.emitSetBandtssMember(member) } // handleBandtssMsgActivate implements emitter handler for MsgActivate of bandtss. @@ -67,18 +95,14 @@ func (h *Hook) handleBandtssMsgHealthCheck( h.handleUpdateBandtssStatus(ctx, acc) } -// handleUpdateBandtssReplacementStatus implements emitter handler events related to replacements. -func (h *Hook) handleUpdateBandtssReplacementStatus(ctx sdk.Context) { - r := h.bandtssKeeper.GetReplacement(ctx) - if r.Status == types.REPLACEMENT_STATUS_SUCCESS { - h.handleSetTSSGroup(ctx, r.CurrentGroupID) - } - - h.emitUpdateBandtssReplacementStatus(r.Status) +// handleBandtssMsgRequestSignature implements emitter handler for MsgRequestSignature of bandtss. +func (h *Hook) handleEventSigningRequestCreated(ctx sdk.Context, sid types.SigningID) { + signing := h.bandtssKeeper.MustGetSigning(ctx, sid) + h.emitSetBandtssSigning(signing) } -// handleInitTSSReplacement implements emitter handler for init replacement event. -func (h *Hook) handleInitBandtssReplacement(ctx sdk.Context) { +// handleSetBandtssReplacement implements emitter handler events related to replacements. +func (h *Hook) handleSetBandtssReplacement(ctx sdk.Context) { r := h.bandtssKeeper.GetReplacement(ctx) - h.emitNewBandtssReplacement(r) + h.emitSetBandtssReplacement(r) } diff --git a/hooks/emitter/channel.go b/hooks/emitter/channel.go index 152586cd4..90785fa03 100644 --- a/hooks/emitter/channel.go +++ b/hooks/emitter/channel.go @@ -208,6 +208,7 @@ func (h *Hook) extractOracleRequestPacket( "prepare_gas_used": prepareGasUsed, "execute_gas": data.ExecuteGas, "execute_gas_used": uint64(0), + "tss_encode_type": data.TSSEncodeType, "fee_limit": data.FeeLimit.String(), "total_fees": evMap[oracletypes.EventTypeRequest+"."+oracletypes.AttributeKeyTotalFees][0], "is_ibc": req.IBCChannel != nil, diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index 9ef8ff8d9..fa273a2d4 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -132,8 +132,6 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, log sdk.AB h.handleBandtssMsgHealthCheck(ctx, msg) case *bandtsstypes.MsgRequestSignature: h.handleEventRequestSignature(ctx, evMap) - case *tsstypes.MsgSubmitDEs: - h.handleTSSMsgSubmitDEs(ctx, msg) case *group.MsgCreateGroup: h.handleGroupMsgCreateGroup(ctx, evMap) case *group.MsgCreateGroupPolicy: @@ -206,19 +204,21 @@ func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) case tsstypes.EventTypeCreateGroup, tsstypes.EventTypeRound2Success, tsstypes.EventTypeRound3Success, + tsstypes.EventTypeExpiredGroup, tsstypes.EventTypeComplainSuccess, - tsstypes.EventTypeComplainFailed, - tsstypes.EventTypeExpiredGroup: - + tsstypes.EventTypeRound3Failed: gid := tss.GroupID(common.Atoi(evMap[event.Type+"."+tsstypes.AttributeKeyGroupID][0])) h.handleSetTSSGroup(ctx, gid) + case bandtsstypes.EventTypeNewGroupActivate: + gid := tss.GroupID(common.Atoi(evMap[event.Type+"."+tsstypes.AttributeKeyGroupID][0])) + + h.handleNewBandtssGroupActive(ctx, gid) + h.handleSetBandtssReplacement(ctx) + case bandtsstypes.EventTypeSigningRequestCreated: + sid := bandtsstypes.SigningID(common.Atoi(evMap[event.Type+"."+tsstypes.AttributeKeySigningID][0])) + h.handleEventSigningRequestCreated(ctx, sid) case bandtsstypes.EventTypeReplacement: - if evMap[bandtsstypes.EventTypeReplacement+"."+bandtsstypes.AttributeKeyReplacementStatus][0] == "1" { - h.handleInitBandtssReplacement(ctx) - } else { - // TODO: check EventTypeNewGroupActivate - h.handleUpdateBandtssReplacementStatus(ctx) - } + h.handleSetBandtssReplacement(ctx) case proto.MessageName(&group.EventProposalPruned{}): h.handleGroupEventProposalPruned(ctx, evMap) default: diff --git a/hooks/emitter/oracle.go b/hooks/emitter/oracle.go index a1291fc35..5b44a5795 100644 --- a/hooks/emitter/oracle.go +++ b/hooks/emitter/oracle.go @@ -179,6 +179,7 @@ func (h *Hook) handleMsgRequestData( "prepare_gas_used": prepareGasUsed, "execute_gas": msg.ExecuteGas, "execute_gas_used": uint64(0), + "tss_encode_type": msg.TSSEncodeType, "fee_limit": msg.FeeLimit.String(), "total_fees": evMap[types.EventTypeRequest+"."+types.AttributeKeyTotalFees][0], "is_ibc": req.IBCChannel != nil, diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 80973f0e8..8aa2fa4cc 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -15,7 +15,7 @@ func (h *Hook) emitNewTSSSigning(signing types.Signing) { "group_pub_key": parseBytes(signing.GroupPubKey), "msg": parseBytes(signing.Message), "group_pub_nonce": parseBytes(signing.GroupPubNonce), - "status": int(signing.Status), + "status": signing.Status, "created_height": signing.CreatedHeight, }) } @@ -23,7 +23,7 @@ func (h *Hook) emitNewTSSSigning(signing types.Signing) { func (h *Hook) emitUpdateTSSSigningSuccess(signing types.Signing) { h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, - "status": int(signing.Status), + "status": signing.Status, "signature": parseBytes(signing.Signature), }) } @@ -31,7 +31,7 @@ func (h *Hook) emitUpdateTSSSigningSuccess(signing types.Signing) { func (h *Hook) emitUpdateTSSSigningFailed(reason string, signing types.Signing) { h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, - "status": int(signing.Status), + "status": signing.Status, "reason": reason, }) } @@ -39,7 +39,7 @@ func (h *Hook) emitUpdateTSSSigningFailed(reason string, signing types.Signing) func (h *Hook) emitUpdateTSSSigningStatus(signing types.Signing) { h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, - "status": int(signing.Status), + "status": signing.Status, }) } @@ -48,20 +48,22 @@ func (h *Hook) emitSetTSSGroup(group types.Group, dkgContext []byte) { "id": group.ID, "size": group.Size_, "threshold": group.Threshold, - "dkg_context": parseBytes(dkgContext), "pub_key": parseBytes(group.PubKey), - "status": int(group.Status), + "status": group.Status, + "dkg_context": parseBytes(dkgContext), + "module_owner": group.ModuleOwner, "created_height": group.CreatedHeight, }) } -func (h *Hook) emitSetTSSGroupMember(member types.Member) { - h.Write("SET_TSS_GROUP_MEMBER", common.JsDict{ +func (h *Hook) emitSetTSSMember(member types.Member) { + h.Write("SET_TSS_MEMBER", common.JsDict{ "id": member.ID, "tss_group_id": member.GroupID, "address": member.Address, "pub_key": parseBytes(member.PubKey), "is_malicious": member.IsMalicious, + "is_active": member.IsActive, }) } @@ -163,18 +165,6 @@ func (h *Hook) handleSetTSSGroup(ctx sdk.Context, gid tss.GroupID) { members := h.tssKeeper.MustGetMembers(ctx, gid) for _, m := range members { - h.emitSetTSSGroupMember(m) - } -} - -// handleTSSMsgSubmitDEs implements emitter handler for MsgSubmitDEs of TSS. -func (h *Hook) handleTSSMsgSubmitDEs( - ctx sdk.Context, msg *types.MsgSubmitDEs, -) { - acc, err := sdk.AccAddressFromBech32(msg.Address) - if err != nil { - panic(err) + h.emitSetTSSMember(m) } - - h.handleUpdateBandtssStatus(ctx, acc) } diff --git a/x/bandtss/keeper/signing.go b/x/bandtss/keeper/signing.go index c05d21693..e3739e114 100644 --- a/x/bandtss/keeper/signing.go +++ b/x/bandtss/keeper/signing.go @@ -205,6 +205,7 @@ func (k Keeper) HandleCreateSigning( ReplacingGroupSigningID: replacingGroupSigningID, }) + // TODO: emit AttributeKeyRequester ctx.EventManager().EmitEvent( sdk.NewEvent( types.EventTypeSigningRequestCreated, From 886a37b966be7cc6c2cb0352238786c2ce072b8b Mon Sep 17 00:00:00 2001 From: satawatnack Date: Thu, 16 May 2024 17:32:27 +0700 Subject: [PATCH 072/132] fix start docker script --- docker-config/start_docker.sh | 31 ++++++++++--------------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 346278956..2a34ea8d9 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -39,13 +39,13 @@ echo "audit silver absorb involve more aspect girl report open gather excite mir | bandd keys add relayer --recover --keyring-backend test echo "drop video mention casual soldier ostrich resemble harvest casual step design gasp grunt lab meadow buzz envelope today spy cliff column habit fall eyebrow" \ - | bandd keys add tss1 --recover --keyring-backend test + | bandd keys add account1 --recover --keyring-backend test echo "enlist electric thumb valve inherit visa ecology trust cake argue forward hidden thing analyst science treat ice lend pumpkin today ticket purchase process pioneer" \ - | bandd keys add tss2 --recover --keyring-backend test + | bandd keys add account2 --recover --keyring-backend test echo "measure fence mail fluid olive cute empower fossil ahead manage snow marble dash citizen tourist skate assist solution bonus spend tip negative try eyebrow" \ - | bandd keys add tss3 --recover --keyring-backend test + | bandd keys add account3 --recover --keyring-backend test # add accounts to genesis bandd genesis add-genesis-account validator1 10000000000000uband --keyring-backend test @@ -54,9 +54,9 @@ bandd genesis add-genesis-account validator3 10000000000000uband --keyring-backe bandd genesis add-genesis-account validator4 10000000000000uband --keyring-backend test bandd genesis add-genesis-account requester 100000000000000uband --keyring-backend test bandd genesis add-genesis-account relayer 100000000000000uband --keyring-backend test -bandd genesis add-genesis-account tss1 100000000000000uband --keyring-backend test -bandd genesis add-genesis-account tss2 100000000000000uband --keyring-backend test -bandd genesis add-genesis-account tss3 100000000000000uband --keyring-backend test +bandd genesis add-genesis-account account1 100000000000000uband --keyring-backend test +bandd genesis add-genesis-account account2 100000000000000uband --keyring-backend test +bandd genesis add-genesis-account account3 100000000000000uband --keyring-backend test # create copy of config.toml cp ~/.band/config/config.toml ~/.band/config/config.toml.temp @@ -181,28 +181,17 @@ do cylinder config random-secret "$(openssl rand -hex 32)" cylinder config active-period "12h" - # activate tss - echo "y" | bandd tx tss activate --from tss$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync - - # wait for activation transaction success - sleep 4 - for i in $(eval echo {1..1}) do # add signer key cylinder keys add signer$i done - # send band tokens to signers - echo "y" | bandd tx bank send tss$v $(cylinder keys list -a) 1000000uband --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync - - # wait for sending band tokens transaction success - sleep 4 - - # add reporter to bandchain - echo "y" | bandd tx tss add-grantees $(cylinder keys list -a) --from tss$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync + # activate tss + echo "y" | bandd tx tss add-grantees --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync + echo "y" | bandd tx bandtss add-grantees --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync - # wait for addding reporter transaction success + # wait for activating tss transaction success sleep 4 docker create --network chain_bandchain --name bandchain_cylinder${v} band-validator:latest cylinder run From 0263fd2e82c2f8a7fdd9abe31a244fc744c64ad9 Mon Sep 17 00:00:00 2001 From: satawatnack Date: Fri, 17 May 2024 09:47:59 +0700 Subject: [PATCH 073/132] update table --- hasura/hasura-metadata/tables.yaml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index bc76bb9f3..221f09542 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -817,6 +817,13 @@ name: tss_members schema: public array_relationships: + - name: tss_assigned_members + using: + foreign_key_constraint_on: + column: tss_group_id + table: + name: tss_assigned_members + schema: public - name: tss_assigned_members using: foreign_key_constraint_on: From 90adbbc34c03b129b5180f601793c8deaa8ad7fc Mon Sep 17 00:00:00 2001 From: satawatnack Date: Fri, 17 May 2024 17:12:48 +0700 Subject: [PATCH 074/132] init latest version --- flusher/flusher/handler.py | 31 +++++++++------------ flusher/flusher/tss_db.py | 15 +++++++--- hooks/emitter/bandtss.go | 7 +++-- hooks/emitter/handler.go | 8 +++--- hooks/emitter/tss.go | 14 +++++----- scripts/bandtss/proposal_replace_group.json | 2 +- x/bandtss/keeper/group.go | 14 +++++++++- x/bandtss/keeper/signing.go | 1 - 8 files changed, 53 insertions(+), 39 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index fa83b836c..110594a88 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -92,16 +92,6 @@ def get_account_id(self, address): ).scalar() return id - def have_tss_account(self, account_id): - return ( - self.conn.execute( - select([tss_statuses.c.account_id]).where( - tss_statuses.c.account_id == account_id - ) - ).scalar() - is not None - ) - def get_request_count(self, date): return self.conn.execute( select([request_count_per_days.c.count]).where( @@ -162,6 +152,12 @@ def get_ibc_received_txs(self, date, port, channel, address): select([relayer_tx_stat_days.c.ibc_received_txs]).where(condition) ).scalar() + def get_latest_band_tss_group_id(self): + result = self.conn.execute( + "SELECT id FROM band_tss_groups ORDER BY id DESC LIMIT 1" + ).fetchone() + return result[0] if result else None + def handle_new_block(self, msg): self.conn.execute(blocks.insert(), msg) @@ -795,8 +791,6 @@ def handle_set_relayer_tx_stat_days(self, port, channel, timestamp, address): ) def handle_new_tss_signing(self, msg): - msg["account_id"] = self.get_account_id(msg["requester"]) - del msg["requester"] self.conn.execute(tss_signings.insert(), msg) def handle_update_tss_signing(self, msg): @@ -805,10 +799,13 @@ def handle_update_tss_signing(self, msg): condition = (col == msg[col.name]) & condition self.conn.execute(tss_signings.update().where(condition).values(**msg)) - def handle_set_band_tss_member(self, msg): + def handle_set_band_tss_signing(self, msg): msg["requester_id"] = self.get_account_id(msg["requester"]) del msg["requester"] + if msg["replacing_group_signing_id"] == 0: + del msg["replacing_group_signing_id"] + self.conn.execute( insert(band_tss_signings) .values(**msg) @@ -823,11 +820,7 @@ def handle_set_tss_group(self, msg): ) def handle_set_band_tss_group(self, msg): - self.conn.execute( - insert(band_tss_groups) - .values(**msg) - .on_conflict_do_update(constraint="band_tss_groups_pkey", set_=msg) - ) + self.conn.execute(band_tss_groups.insert(), msg) def handle_set_band_tss_replacement(self, msg): self.conn.execute( @@ -847,6 +840,8 @@ def handle_set_tss_member(self, msg): ) def handle_set_band_tss_member(self, msg): + msg["band_tss_groups_id"] = self.get_latest_band_tss_group_id() + msg["account_id"] = self.get_account_id(msg["address"]) del msg["address"] diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index 78cd82a08..4c07ccc3b 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -86,7 +86,12 @@ def process_bind_param(self, value, dialect): Column("fee", sa.String), Column("requester_id", sa.Integer, sa.ForeignKey("accounts.id")), Column("current_group_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), - Column("replacing_group_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), + Column( + "replacing_group_signing_id", + sa.Integer, + sa.ForeignKey("tss_signings.id"), + nullable=True, + ), ) tss_groups = sa.Table( @@ -107,6 +112,7 @@ def process_bind_param(self, value, dialect): metadata, Column("id", sa.Integer, primary_key=True), Column("current_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), + Column("since", CustomDateTime), ) tss_members = sa.Table( @@ -125,6 +131,7 @@ def process_bind_param(self, value, dialect): band_tss_members = sa.Table( "band_tss_members", metadata, + Column("band_tss_groups_id", sa.ForeignKey("band_tss_groups.id"), primary_key=True), Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), Column("is_active", sa.Boolean), Column("since", CustomDateTime), @@ -146,7 +153,6 @@ def process_bind_param(self, value, dialect): Column( "tss_member_id", sa.Integer, - sa.ForeignKey("tss_members.id"), primary_key=True, ), Column("pub_d", CustomBase64), @@ -162,8 +168,9 @@ def process_bind_param(self, value, dialect): band_tss_replacements = sa.Table( "band_tss_replacements", metadata, - Column("id", sa.Integer, primary_key=True), - Column("tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), + Column( + "tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id"), primary_key=True + ), Column("new_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), Column("new_pub_key", CustomBase64), Column("current_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index 4d7dc6344..c7fb9c3bf 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -1,6 +1,8 @@ package emitter import ( + "time" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bandprotocol/chain/v2/hooks/common" @@ -10,7 +12,6 @@ import ( func (h *Hook) emitSetBandtssReplacement(replacement types.Replacement) { h.Write("SET_BAND_TSS_REPLACEMENT", common.JsDict{ - "id": 1, "tss_signing_id": replacement.SigningID, "new_group_id": replacement.NewGroupID, "new_pub_key": parseBytes(replacement.NewPubKey), @@ -23,8 +24,8 @@ func (h *Hook) emitSetBandtssReplacement(replacement types.Replacement) { func (h *Hook) emitSetBandtssGroup(gid tss.GroupID) { h.Write("SET_BAND_TSS_GROUP", common.JsDict{ - "id": 1, "current_group_id": gid, + "since": time.Now().UnixNano(), }) } @@ -101,7 +102,7 @@ func (h *Hook) handleEventSigningRequestCreated(ctx sdk.Context, sid types.Signi h.emitSetBandtssSigning(signing) } -// handleSetBandtssReplacement implements emitter handler events related to replacements. +// handleSetBandtssReplacement implements emitter handler events related to create replacements. func (h *Hook) handleSetBandtssReplacement(ctx sdk.Context) { r := h.bandtssKeeper.GetReplacement(ctx) h.emitSetBandtssReplacement(r) diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index fa273a2d4..8104a8a5b 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -132,6 +132,8 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, log sdk.AB h.handleBandtssMsgHealthCheck(ctx, msg) case *bandtsstypes.MsgRequestSignature: h.handleEventRequestSignature(ctx, evMap) + sid := bandtsstypes.SigningID(common.Atoi(evMap[bandtsstypes.EventTypeSigningRequestCreated+"."+bandtsstypes.AttributeKeySigningID][0])) + h.handleEventSigningRequestCreated(ctx, sid) case *group.MsgCreateGroup: h.handleGroupMsgCreateGroup(ctx, evMap) case *group.MsgCreateGroupPolicy: @@ -210,12 +212,10 @@ func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) gid := tss.GroupID(common.Atoi(evMap[event.Type+"."+tsstypes.AttributeKeyGroupID][0])) h.handleSetTSSGroup(ctx, gid) case bandtsstypes.EventTypeNewGroupActivate: - gid := tss.GroupID(common.Atoi(evMap[event.Type+"."+tsstypes.AttributeKeyGroupID][0])) - + gid := tss.GroupID(common.Atoi(evMap[event.Type+"."+bandtsstypes.AttributeKeyGroupID][0])) h.handleNewBandtssGroupActive(ctx, gid) - h.handleSetBandtssReplacement(ctx) case bandtsstypes.EventTypeSigningRequestCreated: - sid := bandtsstypes.SigningID(common.Atoi(evMap[event.Type+"."+tsstypes.AttributeKeySigningID][0])) + sid := bandtsstypes.SigningID(common.Atoi(evMap[event.Type+"."+bandtsstypes.AttributeKeySigningID][0])) h.handleEventSigningRequestCreated(ctx, sid) case bandtsstypes.EventTypeReplacement: h.handleSetBandtssReplacement(ctx) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 8aa2fa4cc..9c2fc960a 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -69,13 +69,13 @@ func (h *Hook) emitSetTSSMember(member types.Member) { func (h *Hook) emitNewTSSAssignedMember(sid tss.SigningID, gid tss.GroupID, am types.AssignedMember) { h.Write("NEW_TSS_ASSIGNED_MEMBER", common.JsDict{ - "tss_signing_id": sid, - "tss_group_id": gid, - "tss_group_member_id": am.MemberID, - "pub_d": parseBytes(am.PubD), - "pub_e": parseBytes(am.PubE), - "binding_factor": parseBytes(am.PubKey), - "pub_nonce": parseBytes(am.PubNonce), + "tss_signing_id": sid, + "tss_group_id": gid, + "tss_member_id": am.MemberID, + "pub_d": parseBytes(am.PubD), + "pub_e": parseBytes(am.PubE), + "binding_factor": parseBytes(am.PubKey), + "pub_nonce": parseBytes(am.PubNonce), }) } diff --git a/scripts/bandtss/proposal_replace_group.json b/scripts/bandtss/proposal_replace_group.json index 0618b0c49..9208beb5e 100644 --- a/scripts/bandtss/proposal_replace_group.json +++ b/scripts/bandtss/proposal_replace_group.json @@ -3,7 +3,7 @@ { "@type": "/bandtss.v1beta1.MsgReplaceGroup", "new_group_id": "2", - "exec_time": "2024-04-22T17:13:00+00:00", + "exec_time": "2024-05-17T10:13:00+00:00", "authority": "band10d07y265gmmuvt4z0w9aw880jnsr700jrdn8wm" } ], diff --git a/x/bandtss/keeper/group.go b/x/bandtss/keeper/group.go index f531120a2..7f648a8fe 100644 --- a/x/bandtss/keeper/group.go +++ b/x/bandtss/keeper/group.go @@ -108,7 +108,10 @@ func (k Keeper) HandleReplaceGroup(ctx sdk.Context, endBlockTime time.Time) erro sdk.NewAttribute(tsstypes.AttributeKeySigningID, fmt.Sprintf("%d", replacement.SigningID)), sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", replacement.CurrentGroupID)), sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", replacement.NewGroupID)), - sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_WAITING_REPLACE.String()), + sdk.NewAttribute( + types.AttributeKeyReplacementStatus, + types.REPLACEMENT_STATUS_WAITING_REPLACE.String(), + ), sdk.NewAttribute(types.AttributeKeyExecTime, replacement.ExecTime.Format(time.RFC3339)), ), ) @@ -161,6 +164,15 @@ func (k Keeper) ReplaceGroup(ctx sdk.Context, replacement types.Replacement) err // update replacement status and emit an event. replacement.Status = types.REPLACEMENT_STATUS_SUCCESS k.SetReplacement(ctx, replacement) + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.EventTypeReplacement, + sdk.NewAttribute(tsstypes.AttributeKeySigningID, fmt.Sprintf("%d", replacement.SigningID)), + sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", replacement.CurrentGroupID)), + sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", replacement.NewGroupID)), + sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_SUCCESS.String()), + ), + ) newGroup, err := k.tssKeeper.GetGroup(ctx, replacement.NewGroupID) if err != nil { diff --git a/x/bandtss/keeper/signing.go b/x/bandtss/keeper/signing.go index e3739e114..c05d21693 100644 --- a/x/bandtss/keeper/signing.go +++ b/x/bandtss/keeper/signing.go @@ -205,7 +205,6 @@ func (k Keeper) HandleCreateSigning( ReplacingGroupSigningID: replacingGroupSigningID, }) - // TODO: emit AttributeKeyRequester ctx.EventManager().EmitEvent( sdk.NewEvent( types.EventTypeSigningRequestCreated, From 39310ba0fc39eb1cd167ab076a2e08658ec688ed Mon Sep 17 00:00:00 2001 From: satawatnack Date: Sat, 18 May 2024 00:27:33 +0700 Subject: [PATCH 075/132] undo --- scripts/bandtss/proposal_replace_group.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/bandtss/proposal_replace_group.json b/scripts/bandtss/proposal_replace_group.json index 9208beb5e..0618b0c49 100644 --- a/scripts/bandtss/proposal_replace_group.json +++ b/scripts/bandtss/proposal_replace_group.json @@ -3,7 +3,7 @@ { "@type": "/bandtss.v1beta1.MsgReplaceGroup", "new_group_id": "2", - "exec_time": "2024-05-17T10:13:00+00:00", + "exec_time": "2024-04-22T17:13:00+00:00", "authority": "band10d07y265gmmuvt4z0w9aw880jnsr700jrdn8wm" } ], From 933c4221c281bd64be36b85834ca0eddce455684 Mon Sep 17 00:00:00 2001 From: satawatnack Date: Thu, 23 May 2024 16:12:04 +0700 Subject: [PATCH 076/132] fix reviews --- docker-config/start_docker.sh | 1 - flusher/flusher/handler.py | 2 +- hooks/emitter/bandtss.go | 7 +++++++ hooks/emitter/emitter.go | 3 +++ 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 2a34ea8d9..a28b2943b 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -189,7 +189,6 @@ do # activate tss echo "y" | bandd tx tss add-grantees --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync - echo "y" | bandd tx bandtss add-grantees --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync # wait for activating tss transaction success sleep 4 diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 110594a88..4fb7b7d0c 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -154,7 +154,7 @@ def get_ibc_received_txs(self, date, port, channel, address): def get_latest_band_tss_group_id(self): result = self.conn.execute( - "SELECT id FROM band_tss_groups ORDER BY id DESC LIMIT 1" + "SELECT id FROM band_tss_groups ORDER BY since DESC LIMIT 1" ).fetchone() return result[0] if result else None diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index c7fb9c3bf..bab7e30db 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -52,6 +52,13 @@ func (h *Hook) emitSetBandtssSigning(signing types.Signing) { }) } +// handleInitBandTSSModule implements emitter handler for init bandtss module. +func (h *Hook) handleInitBandTSSModule(ctx sdk.Context) { + for _, signing := range h.bandtssKeeper.GetSignings(ctx) { + h.emitSetBandtssSigning(signing) + } +} + // handleNewBandtssGroupActive implements emitter handler for new bandtss group active. func (h *Hook) handleNewBandtssGroupActive(ctx sdk.Context, gid tss.GroupID) { h.emitSetBandtssGroup(gid) diff --git a/hooks/emitter/emitter.go b/hooks/emitter/emitter.go index f302c486f..3f6dde489 100644 --- a/hooks/emitter/emitter.go +++ b/hooks/emitter/emitter.go @@ -290,6 +290,9 @@ func (h *Hook) AfterInitChain(ctx sdk.Context, req abci.RequestInitChain, res ab // TSS module h.handleInitTSSModule(ctx) + // BandTSS module + h.handleInitBandTSSModule(ctx) + // Oracle module var oracleState oracletypes.GenesisState h.cdc.MustUnmarshalJSON(genesisState[oracletypes.ModuleName], &oracleState) From de0c11ce0d87bf6681036cf11c551931306c458f Mon Sep 17 00:00:00 2001 From: satawatnack Date: Thu, 23 May 2024 16:21:06 +0700 Subject: [PATCH 077/132] extend timeout --- .github/workflows/golangci-lint.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 8d6e78a45..b6d14ee1f 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -13,4 +13,4 @@ jobs: uses: golangci/golangci-lint-action@v5 with: version: v1.55.2 - args: --timeout=5m0s + args: --timeout=8m0s From be8730d2cad2119eee85757e9cbd04d176cc05e9 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 4 Jun 2024 17:12:15 +0700 Subject: [PATCH 078/132] fix syntax --- docker-config/start_docker.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 72ca5b46a..23594a267 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -198,7 +198,7 @@ do docker create --network chain_bandchain --name bandchain-cylinder${v} band-validator:latest cylinder run docker cp ~/.cylinder bandchain-cylinder${v}:/root/.cylinder docker start bandchain-cylinder${v} - +done # pull latest image first docker pull bandprotocol/bothan-api:latest From ad2589c1da48643b057d10556d8ead037e813ed3 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 4 Jun 2024 17:36:20 +0700 Subject: [PATCH 079/132] fix typo --- docker-config/start_docker.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 23594a267..41fd93aa2 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -171,7 +171,7 @@ do rm -rf ~/.cylinder cylinder config node tcp://multi-validator$v-node:26657 cylinder config chain-id bandchain - cylinder config granter $(bandd keys show tss$v -a --keyring-backend test) + cylinder config granter $(bandd keys show account$v -a --keyring-backend test) cylinder config max-messages 10 cylinder config broadcast-timeout "5m" cylinder config rpc-poll-interval "1s" @@ -190,7 +190,7 @@ do done # activate tss - echo "y" | bandd tx tss add-grantees --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync + echo "y" | bandd tx tss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync # wait for activating tss transaction success sleep 4 From 46b0e3e4491fd4be92606954e2257cdbb5ff9147 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 4 Jun 2024 18:11:17 +0700 Subject: [PATCH 080/132] fix error --- app/app.go | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/app/app.go b/app/app.go index 8228f076e..77a2eba37 100644 --- a/app/app.go +++ b/app/app.go @@ -586,6 +586,14 @@ func NewBandApp( authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + app.FeedsKeeper = feedskeeper.NewKeeper( + appCodec, + keys[feedstypes.StoreKey], + app.OracleKeeper, + app.StakingKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + if emitterFlag != "" { app.hooks = append(app.hooks, emitter.NewHook( appCodec, @@ -671,13 +679,6 @@ func NewBandApp( // further handlers to be registered after the keeper is created since this // could create invalid or non-deterministic behavior. tssRouter.Seal() - app.FeedsKeeper = feedskeeper.NewKeeper( - appCodec, - keys[feedstypes.StoreKey], - app.OracleKeeper, - app.StakingKeeper, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) app.StakingKeeper.SetHooks( stakingtypes.NewMultiStakingHooks( From 233d0e122c440e92f48657e566cd793b2d344c9d Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 4 Jun 2024 21:25:06 +0700 Subject: [PATCH 081/132] fix config cylinder docker --- docker-config/start_docker.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 41fd93aa2..6053af7c6 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -176,7 +176,7 @@ do cylinder config broadcast-timeout "5m" cylinder config rpc-poll-interval "1s" cylinder config max-try 5 - cylinder config gas-prices "0.0025uband" + cylinder config gas-prices "0uband" cylinder config min-de 20 cylinder config gas-adjust-start 1.6 cylinder config gas-adjust-step 0.2 @@ -189,8 +189,12 @@ do cylinder keys add signer$i done + # send band tokens to grantees + bandd tx multi-send 1000000uband $(cylinder keys list -a) --gas-prices 0.0025uband --keyring-backend test --chain-id bandchain --from $KEY -b sync -y + # activate tss echo "y" | bandd tx tss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync + echo "y" | bandd tx bandtss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync # wait for activating tss transaction success sleep 4 From 7cf241ef998cb8dc2002b9fd4f6f2f407692014d Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 4 Jun 2024 22:02:15 +0700 Subject: [PATCH 082/132] fix metadata --- hasura/hasura-metadata/tables.yaml | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index 221f09542..20aad3846 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -816,21 +816,6 @@ - table: name: tss_members schema: public - array_relationships: - - name: tss_assigned_members - using: - foreign_key_constraint_on: - column: tss_group_id - table: - name: tss_assigned_members - schema: public - - name: tss_assigned_members - using: - foreign_key_constraint_on: - column: tss_member_id - table: - name: tss_assigned_members - schema: public - table: name: tss_replacements schema: public From b071fa1638723b47a90a1d3c5bba27e35dccd35b Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 4 Jun 2024 22:14:22 +0700 Subject: [PATCH 083/132] add slep --- docker-config/start_docker.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 6053af7c6..698f8ff4d 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -191,12 +191,13 @@ do # send band tokens to grantees bandd tx multi-send 1000000uband $(cylinder keys list -a) --gas-prices 0.0025uband --keyring-backend test --chain-id bandchain --from $KEY -b sync -y + sleep 4 # activate tss echo "y" | bandd tx tss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync - echo "y" | bandd tx bandtss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync + sleep 4 - # wait for activating tss transaction success + echo "y" | bandd tx bandtss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync sleep 4 docker create --network chain_bandchain --name bandchain-cylinder${v} band-validator:latest cylinder run From 72e7cf98b6d1065ca929742dc05f1480b20f0529 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 4 Jun 2024 22:27:11 +0700 Subject: [PATCH 084/132] fix --- docker-config/start_docker.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 698f8ff4d..523e63afb 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -190,7 +190,7 @@ do done # send band tokens to grantees - bandd tx multi-send 1000000uband $(cylinder keys list -a) --gas-prices 0.0025uband --keyring-backend test --chain-id bandchain --from $KEY -b sync -y + echo "y" | bandd tx multi-send 1000000uband $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync sleep 4 # activate tss From 0ee0808bc505043961d1df7d510049b17219389a Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 4 Jun 2024 22:34:59 +0700 Subject: [PATCH 085/132] fix table --- hasura/hasura-metadata/tables.yaml | 108 ----------------------------- 1 file changed, 108 deletions(-) diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index 20aad3846..51491dcca 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -26,9 +26,6 @@ table: name: validators schema: public - - name: band_tss_member - using: - foreign_key_constraint_on: account_id array_relationships: - name: account_transactions using: @@ -107,20 +104,6 @@ table: name: reports schema: public - - name: tss_members - using: - foreign_key_constraint_on: - column: account_id - table: - name: tss_members - schema: public - - name: band_tss_signings - using: - foreign_key_constraint_on: - column: requester_id - table: - name: band_tss_signings - schema: public - name: unbonding_delegations using: foreign_key_constraint_on: @@ -164,13 +147,6 @@ table: name: requests schema: public - - name: tss_signings - using: - foreign_key_constraint_on: - column: created_height - table: - name: tss_signings - schema: public - name: transactions using: foreign_key_constraint_on: @@ -710,12 +686,6 @@ - name: oracle_script using: foreign_key_constraint_on: oracle_script_id - - name: group - using: - foreign_key_constraint_on: tss_group_id - - name: tss_signing - using: - foreign_key_constraint_on: tss_signing_id - name: transaction using: foreign_key_constraint_on: transaction_id @@ -741,84 +711,6 @@ table: name: val_requests schema: public -- table: - name: tss_signings - schema: public - object_relationships: - - name: tss_replacement - using: - foreign_key_constraint_on: tss_signing_id - array_relationships: - - name: replacing_band_tss_signing - using: - foreign_key_constraint_on: - column: replacing_group_signing_id - table: - name: band_tss_signing - schema: public - - name: current_band_tss_signing - using: - foreign_key_constraint_on: - column: current_group_signing_id - table: - name: band_tss_signing - schema: public - - name: tss_assigned_members - using: - foreign_key_constraint_on: - column: tss_signing_id - table: - name: tss_assigned_members - schema: public - - name: tss_replacements - using: - foreign_key_constraint_on: - column: tss_signing_id - table: - name: tss_replacements - schema: public -- table: - name: tss_groups - schema: public - object_relationships: - - name: tss_group - using: - foreign_key_constraint_on: current_group_id - array_relationships: - - name: tss_members - using: - foreign_key_constraint_on: - column: tss_group_id - table: - name: tss_members - schema: public - - name: tss_assigned_members - using: - foreign_key_constraint_on: - column: tss_group_id - table: - name: tss_assigned_members - schema: public - - name: tss_replacements_new_group - using: - foreign_key_constraint_on: - column: new_group_id - table: - name: tss_replacements - schema: public - - name: tss_replacements_current_group - using: - foreign_key_constraint_on: - column: current_group_id - table: - name: tss_replacements - schema: public -- table: - name: tss_members - schema: public -- table: - name: tss_replacements - schema: public - table: name: tracking schema: public From eefa6de59d879f3929aa10b0b83104ffe0b27391 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 4 Jun 2024 22:53:02 +0700 Subject: [PATCH 086/132] fix table hasura --- hasura/hasura-metadata/tables.yaml | 299 +++++++++++++++++++++++++++++ 1 file changed, 299 insertions(+) diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index 51491dcca..b5c0aefdb 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -34,6 +34,20 @@ table: name: account_transactions schema: public + - name: band_tss_members + using: + foreign_key_constraint_on: + column: account_id + table: + name: band_tss_members + schema: public + - name: band_tss_signings + using: + foreign_key_constraint_on: + column: requester_id + table: + name: band_tss_signings + schema: public - name: delegations using: foreign_key_constraint_on: @@ -41,6 +55,13 @@ table: name: delegations schema: public + - name: delegator_signals + using: + foreign_key_constraint_on: + column: account_id + table: + name: delegator_signals + schema: public - name: deposits using: foreign_key_constraint_on: @@ -48,6 +69,13 @@ table: name: deposits schema: public + - name: feeders + using: + foreign_key_constraint_on: + column: feeder_id + table: + name: feeders + schema: public - name: group_members using: foreign_key_constraint_on: @@ -104,6 +132,13 @@ table: name: reports schema: public + - name: tss_members + using: + foreign_key_constraint_on: + column: account_id + table: + name: tss_members + schema: public - name: unbonding_delegations using: foreign_key_constraint_on: @@ -118,6 +153,57 @@ table: name: votes schema: public +- table: + name: band_tss_groups + schema: public + object_relationships: + - name: tss_group + using: + foreign_key_constraint_on: current_group_id + array_relationships: + - name: band_tss_members + using: + foreign_key_constraint_on: + column: band_tss_groups_id + table: + name: band_tss_members + schema: public +- table: + name: band_tss_members + schema: public + object_relationships: + - name: account + using: + foreign_key_constraint_on: account_id + - name: band_tss_group + using: + foreign_key_constraint_on: band_tss_groups_id +- table: + name: band_tss_replacements + schema: public + object_relationships: + - name: tssGroupByNewGroupId + using: + foreign_key_constraint_on: new_group_id + - name: tss_group + using: + foreign_key_constraint_on: current_group_id + - name: tss_signing + using: + foreign_key_constraint_on: tss_signing_id +- table: + name: band_tss_signings + schema: public + object_relationships: + - name: account + using: + foreign_key_constraint_on: requester_id + - name: tssSigningByReplacingGroupSigningId + using: + foreign_key_constraint_on: replacing_group_signing_id + - name: tss_signing + using: + foreign_key_constraint_on: current_group_signing_id - table: name: blocks schema: public @@ -154,6 +240,13 @@ table: name: transactions schema: public + - name: tss_signings + using: + foreign_key_constraint_on: + column: created_height + table: + name: tss_signings + schema: public - name: unbonding_delegations using: foreign_key_constraint_on: @@ -305,6 +398,16 @@ - table: name: delegations_view schema: public +- table: + name: delegator_signals + schema: public + object_relationships: + - name: account + using: + foreign_key_constraint_on: account_id + - name: signal_total_power + using: + foreign_key_constraint_on: signal_id - table: name: deposits schema: public @@ -318,6 +421,13 @@ - name: transaction using: foreign_key_constraint_on: tx_id +- table: + name: feeders + schema: public + object_relationships: + - name: account + using: + foreign_key_constraint_on: feeder_id - table: name: group_members schema: public @@ -532,6 +642,16 @@ - name: transaction using: foreign_key_constraint_on: tx_id +- table: + name: price_services + schema: public +- table: + name: prices + schema: public + object_relationships: + - name: signal_total_power + using: + foreign_key_constraint_on: signal_id - table: name: proposal_total_votes schema: public @@ -689,6 +809,9 @@ - name: transaction using: foreign_key_constraint_on: transaction_id + - name: tss_signing + using: + foreign_key_constraint_on: tss_signing_id array_relationships: - name: raw_requests using: @@ -711,6 +834,32 @@ table: name: val_requests schema: public +- table: + name: signal_total_powers + schema: public + object_relationships: + - name: price + using: + foreign_key_constraint_on: + column: signal_id + table: + name: prices + schema: public + array_relationships: + - name: delegator_signals + using: + foreign_key_constraint_on: + column: signal_id + table: + name: delegator_signals + schema: public + - name: validator_prices + using: + foreign_key_constraint_on: + column: signal_id + table: + name: validator_prices + schema: public - table: name: tracking schema: public @@ -785,6 +934,139 @@ table: name: votes schema: public +- table: + name: tss_assigned_members + schema: public + object_relationships: + - name: tss_group + using: + foreign_key_constraint_on: tss_group_id + - name: tss_member + using: + manual_configuration: + column_mapping: + tss_group_id: tss_group_id + tss_member_id: id + insertion_order: null + remote_table: + name: tss_members + schema: public + - name: tss_signing + using: + foreign_key_constraint_on: tss_signing_id +- table: + name: tss_groups + schema: public + array_relationships: + - name: bandTssReplacementsByNewGroupId + using: + foreign_key_constraint_on: + column: new_group_id + table: + name: band_tss_replacements + schema: public + - name: band_tss_groups + using: + foreign_key_constraint_on: + column: current_group_id + table: + name: band_tss_groups + schema: public + - name: band_tss_replacements + using: + foreign_key_constraint_on: + column: current_group_id + table: + name: band_tss_replacements + schema: public + - name: tss_assigned_members + using: + foreign_key_constraint_on: + column: tss_group_id + table: + name: tss_assigned_members + schema: public + - name: tss_members + using: + foreign_key_constraint_on: + column: tss_group_id + table: + name: tss_members + schema: public + - name: tss_signings + using: + foreign_key_constraint_on: + column: tss_group_id + table: + name: tss_signings + schema: public +- table: + name: tss_members + schema: public + object_relationships: + - name: account + using: + foreign_key_constraint_on: account_id + - name: tss_group + using: + foreign_key_constraint_on: tss_group_id + array_relationships: + - name: tss_assigned_members + using: + manual_configuration: + column_mapping: + id: tss_member_id + tss_group_id: tss_group_id + insertion_order: null + remote_table: + name: tss_assigned_members + schema: public +- table: + name: tss_signings + schema: public + object_relationships: + - name: band_tss_replacement + using: + foreign_key_constraint_on: + column: tss_signing_id + table: + name: band_tss_replacements + schema: public + - name: block + using: + foreign_key_constraint_on: created_height + - name: tss_group + using: + foreign_key_constraint_on: tss_group_id + array_relationships: + - name: bandTssSigningsByReplacingGroupSigningId + using: + foreign_key_constraint_on: + column: replacing_group_signing_id + table: + name: band_tss_signings + schema: public + - name: band_tss_signings + using: + foreign_key_constraint_on: + column: current_group_signing_id + table: + name: band_tss_signings + schema: public + - name: requests + using: + foreign_key_constraint_on: + column: tss_signing_id + table: + name: requests + schema: public + - name: tss_assigned_members + using: + foreign_key_constraint_on: + column: tss_signing_id + table: + name: tss_assigned_members + schema: public - table: name: unbonding_delegations schema: public @@ -820,6 +1102,16 @@ - table: name: validator_last_250_votes schema: public +- table: + name: validator_prices + schema: public + object_relationships: + - name: signal_total_power + using: + foreign_key_constraint_on: signal_id + - name: validator + using: + foreign_key_constraint_on: validator_id - table: name: validator_report_count schema: public @@ -909,6 +1201,13 @@ table: name: val_requests schema: public + - name: validator_prices + using: + foreign_key_constraint_on: + column: validator_id + table: + name: validator_prices + schema: public - name: validator_votes using: foreign_key_constraint_on: From 0874daaae1fe06072ef56727115b780d3904cec9 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Sun, 9 Jun 2024 20:59:59 +0700 Subject: [PATCH 087/132] remove panic --- hooks/emitter/tss.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 9c2fc960a..c0e5e5721 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -158,7 +158,7 @@ func (h *Hook) handleSetTSSGroup(ctx sdk.Context, gid tss.GroupID) { group := h.tssKeeper.MustGetGroup(ctx, gid) dkgContext, err := h.tssKeeper.GetDKGContext(ctx, gid) if err != nil { - panic(err) + dkgContext = []byte{} } h.emitSetTSSGroup(group, dkgContext) From a7d4cd351c3722fc4988d88a019a48647959faf9 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 11 Jun 2024 21:55:04 +0700 Subject: [PATCH 088/132] reject if early --- x/feeds/keeper/msg_server.go | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/x/feeds/keeper/msg_server.go b/x/feeds/keeper/msg_server.go index 6974e00e1..c65a77c3f 100644 --- a/x/feeds/keeper/msg_server.go +++ b/x/feeds/keeper/msg_server.go @@ -115,8 +115,6 @@ func (ms msgServer) SubmitPrices( supportedFeedsMap[feed.SignalID] = true } - tooEarlyPriceSubmission := 0 - for _, price := range req.Prices { if _, ok := supportedFeedsMap[price.SignalID]; !ok { return nil, types.ErrSignalIDNotSupported.Wrapf( @@ -128,7 +126,7 @@ func (ms msgServer) SubmitPrices( // check if price is not too fast valPrice, err := ms.GetValidatorPrice(ctx, price.SignalID, val) if err == nil && blockTime < valPrice.Timestamp+cooldownTime { - tooEarlyPriceSubmission++ + return nil, types.ErrPriceSubmitTooEarly } valPrice = ms.NewValidatorPrice(val, price, blockTime, blockHeight) @@ -140,10 +138,6 @@ func (ms msgServer) SubmitPrices( emitEventSubmitPrice(ctx, valPrice) } - if tooEarlyPriceSubmission > len(req.Prices)/2 { - return nil, types.ErrPriceSubmitTooEarly - } - return &types.MsgSubmitPricesResponse{}, nil } From c71aa08e32611ae4e5d281e43d8c6cd1eacb7675 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Sun, 23 Jun 2024 13:54:32 +0700 Subject: [PATCH 089/132] remove dup --- flusher/flusher/handler.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index cd617859b..3879e65a2 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -144,13 +144,6 @@ def get_group_id_from_policy_address(self, address): ) ).scalar() - def get_group_id_from_policy_address(self, address): - return self.conn.execute( - select([group_policies.c.group_id]).where( - group_policies.c.address == address - ) - ).scalar() - def get_ibc_received_txs(self, date, port, channel, address): msg = {"date": date, "port": port, "channel": channel, "address": address} condition = True From c5b171177b4e185d7e7dbf943ae0aa9069f63029 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Sun, 23 Jun 2024 13:59:17 +0700 Subject: [PATCH 090/132] merge --- x/bandtss/keeper/group.go | 9 --------- 1 file changed, 9 deletions(-) diff --git a/x/bandtss/keeper/group.go b/x/bandtss/keeper/group.go index c3558dad5..d277a687b 100644 --- a/x/bandtss/keeper/group.go +++ b/x/bandtss/keeper/group.go @@ -175,15 +175,6 @@ func (k Keeper) ReplaceGroup(ctx sdk.Context, replacement types.Replacement) err // update replacement status and emit an event. replacement.Status = types.REPLACEMENT_STATUS_SUCCESS k.SetReplacement(ctx, replacement) - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeReplacement, - sdk.NewAttribute(tsstypes.AttributeKeySigningID, fmt.Sprintf("%d", replacement.SigningID)), - sdk.NewAttribute(types.AttributeKeyCurrentGroupID, fmt.Sprintf("%d", replacement.CurrentGroupID)), - sdk.NewAttribute(types.AttributeKeyReplacingGroupID, fmt.Sprintf("%d", replacement.NewGroupID)), - sdk.NewAttribute(types.AttributeKeyReplacementStatus, types.REPLACEMENT_STATUS_SUCCESS.String()), - ), - ) ctx.EventManager().EmitEvent( sdk.NewEvent( From 71592997454c8ef27171a8ecc37336c568de6786 Mon Sep 17 00:00:00 2001 From: satawatnack Date: Mon, 24 Jun 2024 17:28:53 +0700 Subject: [PATCH 091/132] update latest bandtss --- hooks/emitter/bandtss.go | 10 ++-- hooks/emitter/decoder.go | 110 ++++++++++++++++++++++++++++++++++ hooks/emitter/decoder_test.go | 88 ++++++++++++++++++++++++++- hooks/emitter/emitter.go | 4 +- hooks/emitter/handler.go | 2 +- 5 files changed, 205 insertions(+), 9 deletions(-) diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index bab7e30db..5957e94d1 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -53,7 +53,7 @@ func (h *Hook) emitSetBandtssSigning(signing types.Signing) { } // handleInitBandTSSModule implements emitter handler for init bandtss module. -func (h *Hook) handleInitBandTSSModule(ctx sdk.Context) { +func (h *Hook) handleInitBandtssModule(ctx sdk.Context) { for _, signing := range h.bandtssKeeper.GetSignings(ctx) { h.emitSetBandtssSigning(signing) } @@ -70,8 +70,8 @@ func (h *Hook) handleNewBandtssGroupActive(ctx sdk.Context, gid tss.GroupID) { } } -// handleUpdateBandtssStatus implements emitter handler for update bandtss status. -func (h *Hook) handleUpdateBandtssStatus(ctx sdk.Context, address sdk.AccAddress) { +// handleUpdateBandtssMember implements emitter handler for update bandtss status. +func (h *Hook) handleUpdateBandtssMember(ctx sdk.Context, address sdk.AccAddress) { member, err := h.bandtssKeeper.GetMember(ctx, address) if err != nil { panic(err) @@ -88,7 +88,7 @@ func (h *Hook) handleBandtssMsgActivate( panic(err) } - h.handleUpdateBandtssStatus(ctx, acc) + h.handleUpdateBandtssMember(ctx, acc) } // handleBandtssMsgHealthCheck implements emitter handler for MsgHealthCheck of bandtss. @@ -100,7 +100,7 @@ func (h *Hook) handleBandtssMsgHealthCheck( panic(err) } - h.handleUpdateBandtssStatus(ctx, acc) + h.handleUpdateBandtssMember(ctx, acc) } // handleBandtssMsgRequestSignature implements emitter handler for MsgRequestSignature of bandtss. diff --git a/hooks/emitter/decoder.go b/hooks/emitter/decoder.go index bcb8523c0..5ca76f632 100644 --- a/hooks/emitter/decoder.go +++ b/hooks/emitter/decoder.go @@ -20,8 +20,10 @@ import ( channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" "github.com/bandprotocol/chain/v2/hooks/common" + bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" feedstypes "github.com/bandprotocol/chain/v2/x/feeds/types" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" + tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) func DecodeMsg(msg sdk.Msg, detail common.JsDict) { @@ -134,6 +136,32 @@ func DecodeMsg(msg sdk.Msg, detail common.JsDict) { DecodeMsgUpdatePriceService(msg, detail) case *feedstypes.MsgUpdateParams: DecodeMsgUpdateParams(msg, detail) + case *bandtsstypes.MsgCreateGroup: + DecodeGroupMsgCreateGroupBandtss(msg, detail) + case *bandtsstypes.MsgReplaceGroup: + DecodeGroupMsgReplaceGroup(msg, detail) + case *bandtsstypes.MsgRequestSignature: + DecodeMsgRequestSignature(msg, detail) + case *bandtsstypes.MsgActivate: + DecodeMsgActivateBandtss(msg, detail) + case *bandtsstypes.MsgHealthCheck: + DecodeMsgHealthCheck(msg, detail) + case *bandtsstypes.MsgUpdateParams: + DecodeMsgUpdateParamsBandtss(msg, detail) + case *tsstypes.MsgSubmitDKGRound1: + DecodeMsgSubmitDKGRound1(msg, detail) + case *tsstypes.MsgSubmitDKGRound2: + DecodeMsgSubmitDKGRound2(msg, detail) + case *tsstypes.MsgComplain: + DecodeMsgComplain(msg, detail) + case *tsstypes.MsgConfirm: + DecodeMsgConfirm(msg, detail) + case *tsstypes.MsgSubmitDEs: + DecodeMsgSubmitDEs(msg, detail) + case *tsstypes.MsgSubmitSignature: + DecodeMsgSubmitSignature(msg, detail) + case *tsstypes.MsgUpdateParams: + DecodeMsgUpdateParamsTss(msg, detail) case *group.MsgCreateGroup: DecodeGroupMsgCreateGroup(msg, detail) case *group.MsgCreateGroupPolicy: @@ -292,6 +320,7 @@ func DecodeMsgRequestData(msg *oracletypes.MsgRequestData, detail common.JsDict) detail["prepare_gas"] = msg.GetPrepareGas() detail["execute_gas"] = msg.GetExecuteGas() detail["sender"] = msg.GetSender() + detail["tss_encode_type"] = msg.GetTSSEncodeType() } func DecodeMsgReportData(msg *oracletypes.MsgReportData, detail common.JsDict) { @@ -690,6 +719,87 @@ func DecodeMsgUpdateParams(msg *feedstypes.MsgUpdateParams, detail common.JsDict detail["max_deviation_in_thousandth"] = params.GetMaxDeviationInThousandth() } +func DecodeGroupMsgCreateGroupBandtss(msg *bandtsstypes.MsgCreateGroup, detail common.JsDict) { + detail["members"] = msg.Members + detail["threshold"] = msg.Threshold + detail["authority"] = msg.Authority +} + +func DecodeGroupMsgReplaceGroup(msg *bandtsstypes.MsgReplaceGroup, detail common.JsDict) { + detail["new_group_id"] = msg.NewGroupID + detail["exec_time"] = msg.ExecTime.GoString() + detail["authority"] = msg.Authority +} + +func DecodeMsgUpdateParamsBandtss(msg *bandtsstypes.MsgUpdateParams, detail common.JsDict) { + params := msg.GetParams() + detail["active_duration"] = params.GetActiveDuration() + detail["reward_percentage"] = params.GetRewardPercentage() + detail["inactive_penalty_duration"] = params.GetInactivePenaltyDuration() + detail["fee"] = params.GetFee() + detail["authority"] = msg.GetAuthority() +} + +func DecodeMsgSubmitDKGRound1(msg *tsstypes.MsgSubmitDKGRound1, detail common.JsDict) { + detail["group_id"] = msg.GroupID + detail["round1_info"] = msg.Round1Info + detail["address"] = msg.Address +} + +func DecodeMsgSubmitDKGRound2(msg *tsstypes.MsgSubmitDKGRound2, detail common.JsDict) { + detail["group_id"] = msg.GroupID + detail["round2_info"] = msg.Round2Info + detail["address"] = msg.Address +} + +func DecodeMsgComplain(msg *tsstypes.MsgComplain, detail common.JsDict) { + detail["group_id"] = msg.GroupID + detail["complaints"] = msg.Complaints + detail["address"] = msg.Address +} + +func DecodeMsgConfirm(msg *tsstypes.MsgConfirm, detail common.JsDict) { + detail["group_id"] = msg.GroupID + detail["member_id"] = msg.MemberID + detail["own_pub_key_sig"] = msg.OwnPubKeySig + detail["address"] = msg.Address +} + +func DecodeMsgSubmitDEs(msg *tsstypes.MsgSubmitDEs, detail common.JsDict) { + detail["des"] = msg.DEs + detail["address"] = msg.Address +} + +func DecodeMsgSubmitSignature(msg *tsstypes.MsgSubmitSignature, detail common.JsDict) { + detail["signing_id"] = msg.SigningID + detail["member_id"] = msg.MemberID + detail["signature"] = msg.Signature + detail["address"] = msg.Address +} + +func DecodeMsgUpdateParamsTss(msg *tsstypes.MsgUpdateParams, detail common.JsDict) { + params := msg.GetParams() + detail["max_group_size"] = params.GetMaxGroupSize() + detail["max_d_e_size"] = params.GetMaxDESize() + detail["creating_period"] = params.GetCreatingPeriod() + detail["signing_period"] = params.GetSigningPeriod() + detail["authority"] = msg.GetAuthority() +} + +func DecodeMsgActivateBandtss(msg *bandtsstypes.MsgActivate, detail common.JsDict) { + detail["address"] = msg.Address +} + +func DecodeMsgHealthCheck(msg *bandtsstypes.MsgHealthCheck, detail common.JsDict) { + detail["address"] = msg.Address +} + +func DecodeMsgRequestSignature(msg *bandtsstypes.MsgRequestSignature, detail common.JsDict) { + detail["content"] = msg.Content.GetCachedValue() + detail["fee_limit"] = msg.FeeLimit + detail["sender"] = msg.Sender +} + func DecodeGroupMsgCreateGroup(msg *group.MsgCreateGroup, detail common.JsDict) { detail["admin"] = msg.Admin detail["members"] = msg.Members diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index c29749775..284755884 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -26,10 +26,13 @@ import ( "github.com/bandprotocol/chain/v2/hooks/common" "github.com/bandprotocol/chain/v2/hooks/emitter" + "github.com/bandprotocol/chain/v2/pkg/tss" bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/testing/ibctesting" + bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" feedstypes "github.com/bandprotocol/chain/v2/x/feeds/types" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" + tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) var ( @@ -55,6 +58,10 @@ var ( PubKey = newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB50") Amount = sdk.NewCoin("uband", sdk.NewInt(1)) + tssPoint = tss.Point([]byte("point")) + tssSignature = tss.Signature([]byte("signature")) + tssEncSecretShare = tss.EncSecretShare([]byte("encSecretShare")) + content, _ = govv1beta1.ContentFromProposalType("Title", "Desc", "Text") proposalMsg = banktypes.NewMsgSend(SenderAddress, ReceiverAddress, sdk.Coins{Amount}) ) @@ -200,7 +207,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgRequestData() { emitter.DecodeMsgRequestData(msg, detail) suite.testCompareJson( detail, - "{\"ask_count\":1,\"calldata\":\"Y2FsbGRhdGE=\",\"client_id\":\"cleint_id\",\"execute_gas\":300000,\"fee_limit\":[{\"denom\":\"uband\",\"amount\":\"100000000\"}],\"min_count\":1,\"oracle_script_id\":1,\"prepare_gas\":40000,\"sender\":\"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0\"}", + "{\"ask_count\":1,\"calldata\":\"Y2FsbGRhdGE=\",\"client_id\":\"cleint_id\",\"execute_gas\":300000,\"fee_limit\":[{\"denom\":\"uband\",\"amount\":\"100000000\"}],\"min_count\":1,\"oracle_script_id\":1,\"prepare_gas\":40000,\"sender\":\"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0\",\"tss_encode_type\":0}", ) } @@ -950,6 +957,85 @@ func (suite *DecoderTestSuite) TestDecodeMsgUpdatePriceService() { ) } +func (suite *DecoderTestSuite) TestDecodeGroupMsgCreateGroupBandtss() { + detail := make(common.JsDict) + + msg := bandtsstypes.MsgCreateGroup{ + Members: []string{"member1", "member2"}, + Threshold: 2, + Authority: "some-authority-id", + } + + emitter.DecodeGroupMsgCreateGroupBandtss(&msg, detail) + + expectedJSON := `{"authority":"some-authority-id","members":["member1","member2"],"threshold":2}` + suite.testCompareJson(detail, expectedJSON) +} + +func (suite *DecoderTestSuite) TestDecodeGroupMsgReplaceGroup() { + detail := make(common.JsDict) + + msg := bandtsstypes.MsgReplaceGroup{ + NewGroupID: 1, + ExecTime: time.Now(), + Authority: "authority123", + } + + emitter.DecodeGroupMsgReplaceGroup(&msg, detail) + + expectedJSON := `{"authority":"authority123","exec_time":"` + msg.ExecTime.GoString() + `","new_group_id":1}` + suite.testCompareJson(detail, expectedJSON) +} + +func (suite *DecoderTestSuite) TestDecodeMsgUpdateParamsBandtss() { + detail := make(common.JsDict) + + msg := bandtsstypes.MsgUpdateParams{ + Params: bandtsstypes.NewParams(100, 10, 50, sdk.Coins{Amount}), + } + + emitter.DecodeMsgUpdateParamsBandtss(&msg, detail) + expectedJSON := "{\"active_duration\":100,\"authority\":\"\",\"fee\":[{\"denom\":\"uband\",\"amount\":\"1\"}],\"inactive_penalty_duration\":50,\"reward_percentage\":10}" + suite.testCompareJson(detail, expectedJSON) +} + +func (suite *DecoderTestSuite) TestDecodeMsgSubmitDKGRound1() { + detail := make(common.JsDict) + + msg := tsstypes.MsgSubmitDKGRound1{ + GroupID: 1, + Round1Info: tsstypes.Round1Info{ + MemberID: 1, + CoefficientCommits: tss.Points{tssPoint, tssPoint}, + OneTimePubKey: tssPoint, + A0Signature: tssSignature, + OneTimeSignature: tssSignature, + }, + Address: "0x123", + } + + emitter.DecodeMsgSubmitDKGRound1(&msg, detail) + expectedJSON := "{\"address\":\"0x123\",\"group_id\":1,\"round1_info\":{\"member_id\":1,\"coefficient_commits\":[\"706F696E74\",\"706F696E74\"],\"one_time_pub_key\":\"706F696E74\",\"a0_signature\":\"7369676E6174757265\",\"one_time_signature\":\"7369676E6174757265\"}}" + suite.testCompareJson(detail, expectedJSON) +} + +func (suite *DecoderTestSuite) TestDecodeMsgSubmitDKGRound2() { + detail := make(common.JsDict) + + msg := tsstypes.MsgSubmitDKGRound2{ + GroupID: 1, + Round2Info: tsstypes.Round2Info{ + MemberID: 1, + EncryptedSecretShares: tss.EncSecretShares{tssEncSecretShare}, + }, + Address: "0x456", + } + + emitter.DecodeMsgSubmitDKGRound2(&msg, detail) + expectedJSON := "{\"address\":\"0x456\",\"group_id\":1,\"round2_info\":{\"member_id\":1,\"encrypted_secret_shares\":[\"656E635365637265745368617265\"]}}" + suite.testCompareJson(detail, expectedJSON) +} + func (suite *DecoderTestSuite) TestDecodeMsgUpdateParams() { detail := make(common.JsDict) diff --git a/hooks/emitter/emitter.go b/hooks/emitter/emitter.go index 519368b35..eed8c6d2c 100644 --- a/hooks/emitter/emitter.go +++ b/hooks/emitter/emitter.go @@ -295,8 +295,8 @@ func (h *Hook) AfterInitChain(ctx sdk.Context, req abci.RequestInitChain, res ab // TSS module h.handleInitTSSModule(ctx) - // BandTSS module - h.handleInitBandTSSModule(ctx) + // Bandtss module + h.handleInitBandtssModule(ctx) // Oracle module var oracleState oracletypes.GenesisState diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index 1e2502954..ae30b346e 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -209,7 +209,7 @@ func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) address := sdk.MustAccAddressFromBech32( evMap[bandtsstypes.EventTypeInactiveStatus+"."+tsstypes.AttributeKeyAddress][0], ) - h.handleUpdateBandtssStatus(ctx, address) + h.handleUpdateBandtssMember(ctx, address) case tsstypes.EventTypeCreateGroup, tsstypes.EventTypeRound2Success, tsstypes.EventTypeRound3Success, From ca8f8e9e53b5051346bf4ca4f2185a4d40b90cb6 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Fri, 30 Aug 2024 18:33:17 +0700 Subject: [PATCH 092/132] fix emitter/flusher tss/bandtss --- flusher/flusher/bandtss_db.py | 91 ++++++++ flusher/flusher/handler.py | 104 +++++---- flusher/flusher/tss_db.py | 84 +------- hasura/hasura-metadata/tables.yaml | 219 ++++++++++--------- hooks/emitter/bandtss.go | 335 +++++++++++++++++++---------- hooks/emitter/emitter.go | 16 +- hooks/emitter/event_querier.go | 35 +++ hooks/emitter/handler.go | 53 ++--- hooks/emitter/tss.go | 130 +++++++---- 9 files changed, 663 insertions(+), 404 deletions(-) create mode 100644 flusher/flusher/bandtss_db.py create mode 100644 hooks/emitter/event_querier.go diff --git a/flusher/flusher/bandtss_db.py b/flusher/flusher/bandtss_db.py new file mode 100644 index 000000000..643e145c4 --- /dev/null +++ b/flusher/flusher/bandtss_db.py @@ -0,0 +1,91 @@ +import sqlalchemy as sa +import enum + +from .db import ( + metadata, + Column, + CustomBase64, + CustomDateTime, +) + + +class GroupTransitionStatus(enum.Enum): + nil = 0 + creating_group = 1 + waiting_sign = 2 + waiting_execution = 3 + success = 4 + expired = 5 + + +class CustomGroupTransitionStatus(sa.types.TypeDecorator): + impl = sa.Enum(GroupTransitionStatus) + + def process_bind_param(self, value, dialect): + return GroupTransitionStatus(value) + + +bandtss_group_transitions = sa.Table( + "bandtss_group_transitions", + metadata, + Column("proposal_id", sa.Integer, sa.ForeignKey("proposals.id"), primary_key=True), + Column("tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), + Column("current_tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), + Column("incoming_tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), + Column("current_group_pub_key", CustomBase64), + Column("incoming_group_pub_key", CustomBase64), + Column("status", CustomGroupTransitionStatus), + Column( + "created_height", + sa.Integer, + sa.ForeignKey("blocks.height"), + nullable=True, + index=True, + ), + sa.Index( + "ix_tss_signing_id_current_tss_group_id_incoming_tss_group_id", + "tss_signing_id", + "current_tss_group_id", + "incoming_tss_group_id", + ), +) + +bandtss_current_groups = sa.Table( + "bandtss_current_groups", + metadata, + Column("proposal_id", sa.Integer, sa.ForeignKey("proposals.id"), primary_key=True), + Column("current_tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), + Column( + "transition_height", + sa.Integer, + sa.ForeignKey("blocks.height"), + nullable=True, + index=True, + ), +) + +bandtss_members = sa.Table( + "bandtss_members", + metadata, + Column( + "tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id"), primary_key=True + ), + Column("account_id", sa.Integer, sa.ForeignKey("accounts.id")), + Column("is_active", sa.Boolean), + Column("penalty_since", CustomDateTime, nullable=True), + Column("last_active", CustomDateTime, nullable=True), +) + +bandtss_signings = sa.Table( + "bandtss_signings", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("requester_account_id", sa.Integer, sa.ForeignKey("accounts.id")), + Column("fee_per_signer", sa.String), + Column( + "current_group_tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id") + ), + Column( + "incoming_group_tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id") + ), +) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 5b143445f..d57f42a9a 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -1,6 +1,6 @@ import base64 as b64 from datetime import datetime -from sqlalchemy import select +from sqlalchemy import select, func from sqlalchemy.dialects.postgresql import insert from .db import ( @@ -46,15 +46,20 @@ relayer_tx_stat_days, ) +from .bandtss_db import ( + bandtss_current_groups, + bandtss_members, + bandtss_signings, + bandtss_group_transitions, + GroupTransitionStatus, +) + + from .tss_db import ( tss_signings, tss_groups, - band_tss_groups, tss_members, tss_assigned_members, - band_tss_members, - band_tss_signings, - band_tss_replacements, ) from .feeds_db import ( @@ -792,6 +797,10 @@ def handle_set_relayer_tx_stat_days(self, port, channel, timestamp, address): ) ) + ################################## + # TSS_HANDLER + ################################## + def handle_new_tss_signing(self, msg): self.conn.execute(tss_signings.insert(), msg) @@ -801,19 +810,6 @@ def handle_update_tss_signing(self, msg): condition = (col == msg[col.name]) & condition self.conn.execute(tss_signings.update().where(condition).values(**msg)) - def handle_set_band_tss_signing(self, msg): - msg["requester_id"] = self.get_account_id(msg["requester"]) - del msg["requester"] - - if msg["replacing_group_signing_id"] == 0: - del msg["replacing_group_signing_id"] - - self.conn.execute( - insert(band_tss_signings) - .values(**msg) - .on_conflict_do_update(constraint="band_tss_signings_pkey", set_=msg) - ) - def handle_set_tss_group(self, msg): self.conn.execute( insert(tss_groups) @@ -821,16 +817,6 @@ def handle_set_tss_group(self, msg): .on_conflict_do_update(constraint="tss_groups_pkey", set_=msg) ) - def handle_set_band_tss_group(self, msg): - self.conn.execute(band_tss_groups.insert(), msg) - - def handle_set_band_tss_replacement(self, msg): - self.conn.execute( - insert(band_tss_replacements) - .values(**msg) - .on_conflict_do_update(constraint="band_tss_replacements_pkey", set_=msg) - ) - def handle_set_tss_member(self, msg): msg["account_id"] = self.get_account_id(msg["address"]) del msg["address"] @@ -841,23 +827,65 @@ def handle_set_tss_member(self, msg): .on_conflict_do_update(constraint="tss_members_pkey", set_=msg) ) - def handle_set_band_tss_member(self, msg): - msg["band_tss_groups_id"] = self.get_latest_band_tss_group_id() + def handle_new_tss_assigned_member(self, msg): + self.conn.execute(tss_assigned_members.insert(), msg) + + def handle_update_tss_assigned_member(self, msg): + condition = True + for col in tss_assigned_members.primary_key.columns.values(): + condition = (col == msg[col.name]) & condition + self.conn.execute(tss_assigned_members.update().where(condition).values(**msg)) + + ################################## + # BANDTSS_HANDLER + ################################## + + def handle_set_bandtss_group_transition(self, msg): + self.conn.execute(bandtss_group_transitions.insert(), msg) + + def update_bandtss_group_transition(self, status): + proposal_column = bandtss_group_transitions.c.proposal_id + proposal_id = self.conn.execute(select(func.max(proposal_column))).scalar() + if proposal_id is None: + proposal_id = 0 + + self.conn.execute( + bandtss_group_transitions.update() + .where(proposal_column == proposal_id) + .values(status=status) + ) + + def handle_update_bandtss_group_transition(self, msg): + self.update_bandtss_group_transition(msg["status"]) - msg["account_id"] = self.get_account_id(msg["address"]) - del msg["address"] + def handle_update_bandtss_group_transition_success(self, msg): + self.update_bandtss_group_transition(GroupTransitionStatus.success) + + def handle_update_bandtss_group_transition_failed(self, msg): + self.update_bandtss_group_transition(GroupTransitionStatus.expired) + def handle_set_bandtss_current_group(self, msg): + proposal_column = bandtss_group_transitions.c.proposal_id + proposal_id = self.conn.execute(select(func.max(proposal_column))).scalar() + if proposal_id is None: + proposal_id = 0 + + msg["proposal_id"] = proposal_id + self.conn.execute(bandtss_current_groups.insert(), msg) + + def handle_set_bandtss_member(self, msg): self.conn.execute( - insert(band_tss_members) + insert(bandtss_members) .values(**msg) - .on_conflict_do_update(constraint="band_tss_members_pkey", set_=msg) + .on_conflict_do_update(constraint="bandtss_member_pkey", set_=msg) ) - def handle_remove_band_tss_members(self, msg): - self.conn.execute(band_tss_members.delete()) + def handle_set_bandtss_signing(self, msg): + self.conn.execute(bandtss_signings.insert(), msg) - def handle_new_tss_assigned_member(self, msg): - self.conn.execute(tss_assigned_members.insert(), msg) + ################################## + # FEEDS_HANDLER + ################################## def handle_set_validator_price(self, msg): msg["validator_id"] = self.get_validator_id(msg["validator"]) diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index 4c07ccc3b..e16a4027b 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -27,14 +27,6 @@ class GroupStatus(enum.Enum): fallen = 6 -class ReplacementStatus(enum.Enum): - nil = 0 - waiting_sign = 1 - waiting_replace = 2 - success = 3 - fallen = 4 - - class CustomSigningStatus(sa.types.TypeDecorator): impl = sa.Enum(SigningStatus) @@ -49,20 +41,15 @@ def process_bind_param(self, value, dialect): return GroupStatus(value) -class CustomReplacementStatus(sa.types.TypeDecorator): - impl = sa.Enum(ReplacementStatus) - - def process_bind_param(self, value, dialect): - return ReplacementStatus(value) - - tss_signings = sa.Table( "tss_signings", metadata, Column("id", sa.Integer, primary_key=True), Column("tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), + Column("current_attempt", sa.Integer), + Column("originator", sa.String), + Column("message", CustomBase64), Column("group_pub_key", CustomBase64), - Column("msg", CustomBase64), Column("group_pub_nonce", CustomBase64), Column("signature", CustomBase64, nullable=True), Column("status", CustomSigningStatus), @@ -79,21 +66,6 @@ def process_bind_param(self, value, dialect): ), ) -band_tss_signings = sa.Table( - "band_tss_signings", - metadata, - Column("id", sa.Integer, primary_key=True), - Column("fee", sa.String), - Column("requester_id", sa.Integer, sa.ForeignKey("accounts.id")), - Column("current_group_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), - Column( - "replacing_group_signing_id", - sa.Integer, - sa.ForeignKey("tss_signings.id"), - nullable=True, - ), -) - tss_groups = sa.Table( "tss_groups", metadata, @@ -107,14 +79,6 @@ def process_bind_param(self, value, dialect): Column("created_height", sa.Integer, index=True), ) -band_tss_groups = sa.Table( - "band_tss_groups", - metadata, - Column("id", sa.Integer, primary_key=True), - Column("current_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), - Column("since", CustomDateTime), -) - tss_members = sa.Table( "tss_members", metadata, @@ -128,53 +92,25 @@ def process_bind_param(self, value, dialect): Column("is_active", sa.Boolean), ) -band_tss_members = sa.Table( - "band_tss_members", - metadata, - Column("band_tss_groups_id", sa.ForeignKey("band_tss_groups.id"), primary_key=True), - Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), - Column("is_active", sa.Boolean), - Column("since", CustomDateTime), - Column("last_active", CustomDateTime), -) - tss_assigned_members = sa.Table( "tss_assigned_members", metadata, Column( "tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id"), primary_key=True ), - Column( - "tss_group_id", - sa.Integer, - sa.ForeignKey("tss_groups.id"), - primary_key=True, - ), - Column( - "tss_member_id", - sa.Integer, - primary_key=True, - ), + Column("tss_signing_attempt", sa.Integer, primary_key=True), + Column("tss_member_id", sa.Integer, primary_key=True), + Column("tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), Column("pub_d", CustomBase64), Column("pub_e", CustomBase64), Column("binding_factor", CustomBase64), Column("pub_nonce", CustomBase64), + Column("signature", CustomBase64, nullable=True), + Column( + "submitted_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True + ), sa.ForeignKeyConstraint( ["tss_group_id", "tss_member_id"], ["tss_members.tss_group_id", "tss_members.id"], ), ) - -band_tss_replacements = sa.Table( - "band_tss_replacements", - metadata, - Column( - "tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id"), primary_key=True - ), - Column("new_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), - Column("new_pub_key", CustomBase64), - Column("current_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), - Column("current_pub_key", CustomBase64), - Column("exec_time", CustomDateTime), - Column("status", CustomReplacementStatus), -) diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index be526d6a8..e1bf4156e 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -34,19 +34,19 @@ table: name: account_transactions schema: public - - name: band_tss_members + - name: bandtss_members using: foreign_key_constraint_on: column: account_id table: - name: band_tss_members + name: bandtss_members schema: public - - name: band_tss_signings + - name: bandtss_signings using: foreign_key_constraint_on: - column: requester_id + column: requester_account_id table: - name: band_tss_signings + name: bandtss_signings schema: public - name: delegations using: @@ -104,13 +104,6 @@ table: name: groups schema: public - - name: interchain_accounts - using: - foreign_key_constraint_on: - column: account_id - table: - name: interchain_accounts - schema: public - name: proposals using: foreign_key_constraint_on: @@ -153,13 +146,6 @@ table: name: unbonding_delegations schema: public - - name: validators - using: - foreign_key_constraint_on: - column: account_id - table: - name: validators - schema: public - name: votes using: foreign_key_constraint_on: @@ -168,56 +154,60 @@ name: votes schema: public - table: - name: band_tss_groups + name: bandtss_current_groups schema: public object_relationships: - - name: tss_group + - name: block using: - foreign_key_constraint_on: current_group_id - array_relationships: - - name: band_tss_members + foreign_key_constraint_on: transition_height + - name: proposal using: - foreign_key_constraint_on: - column: band_tss_groups_id - table: - name: band_tss_members - schema: public + foreign_key_constraint_on: proposal_id + - name: tss_group + using: + foreign_key_constraint_on: current_tss_group_id - table: - name: band_tss_members + name: bandtss_group_transitions schema: public object_relationships: - - name: account + - name: block using: - foreign_key_constraint_on: account_id - - name: band_tss_group + foreign_key_constraint_on: created_height + - name: proposal using: - foreign_key_constraint_on: band_tss_groups_id -- table: - name: band_tss_replacements - schema: public - object_relationships: - - name: tssGroupByNewGroupId + foreign_key_constraint_on: proposal_id + - name: tssGroupByIncomingTssGroupId using: - foreign_key_constraint_on: new_group_id + foreign_key_constraint_on: incoming_tss_group_id - name: tss_group using: - foreign_key_constraint_on: current_group_id + foreign_key_constraint_on: current_tss_group_id - name: tss_signing using: foreign_key_constraint_on: tss_signing_id - table: - name: band_tss_signings + name: bandtss_members schema: public object_relationships: - name: account using: - foreign_key_constraint_on: requester_id - - name: tssSigningByReplacingGroupSigningId + foreign_key_constraint_on: account_id + - name: tss_group using: - foreign_key_constraint_on: replacing_group_signing_id + foreign_key_constraint_on: tss_group_id +- table: + name: bandtss_signings + schema: public + object_relationships: + - name: account + using: + foreign_key_constraint_on: requester_account_id + - name: tssSigningByIncomingGroupTssSigningId + using: + foreign_key_constraint_on: incoming_group_tss_signing_id - name: tss_signing using: - foreign_key_constraint_on: current_group_signing_id + foreign_key_constraint_on: current_group_tss_signing_id - table: name: blocks schema: public @@ -226,6 +216,20 @@ using: foreign_key_constraint_on: proposer array_relationships: + - name: bandtss_current_groups + using: + foreign_key_constraint_on: + column: transition_height + table: + name: bandtss_current_groups + schema: public + - name: bandtss_group_transitions + using: + foreign_key_constraint_on: + column: created_height + table: + name: bandtss_group_transitions + schema: public - name: incoming_packets using: foreign_key_constraint_on: @@ -254,6 +258,13 @@ table: name: transactions schema: public + - name: tss_assigned_members + using: + foreign_key_constraint_on: + column: submitted_height + table: + name: tss_assigned_members + schema: public - name: tss_signings using: foreign_key_constraint_on: @@ -367,7 +378,7 @@ name: data_sources schema: public object_relationships: - - name: request_stat + - name: data_source_request using: foreign_key_constraint_on: column: data_source_id @@ -378,13 +389,6 @@ using: foreign_key_constraint_on: transaction_id array_relationships: - - name: data_source_requests - using: - foreign_key_constraint_on: - column: data_source_id - table: - name: data_source_requests - schema: public - name: data_source_requests_per_days using: foreign_key_constraint_on: @@ -484,13 +488,6 @@ - name: group_policy using: foreign_key_constraint_on: group_policy_address - - name: group_vote - using: - foreign_key_constraint_on: - column: group_proposal_id - table: - name: group_votes - schema: public array_relationships: - name: group_votes using: @@ -578,6 +575,9 @@ - name: connection using: foreign_key_constraint_on: connection_id +- table: + name: latest_prices + schema: public - table: name: non_validator_vote_proposals_view schema: public @@ -608,7 +608,7 @@ name: oracle_scripts schema: public object_relationships: - - name: request_stat + - name: oracle_script_request using: foreign_key_constraint_on: column: oracle_script_id @@ -619,13 +619,6 @@ using: foreign_key_constraint_on: transaction_id array_relationships: - - name: oracle_script_requests - using: - foreign_key_constraint_on: - column: oracle_script_id - table: - name: oracle_script_requests - schema: public - name: oracle_script_requests_per_days using: foreign_key_constraint_on: @@ -680,6 +673,20 @@ - name: account using: foreign_key_constraint_on: proposer_id + - name: bandtss_current_group + using: + foreign_key_constraint_on: + column: proposal_id + table: + name: bandtss_current_groups + schema: public + - name: bandtss_group_transition + using: + foreign_key_constraint_on: + column: proposal_id + table: + name: bandtss_group_transitions + schema: public array_relationships: - name: deposits using: @@ -747,7 +754,7 @@ - name: account using: foreign_key_constraint_on: delegator_id - - name: validatorByValidatorDstId + - name: validator using: foreign_key_constraint_on: validator_dst_id - name: validatorByValidatorSrcId @@ -770,7 +777,7 @@ name: relayer_tx_stat_days schema: public object_relationships: - - name: channel_by_channel_port + - name: channelByChannelPort using: manual_configuration: column_mapping: @@ -936,6 +943,9 @@ name: tss_assigned_members schema: public object_relationships: + - name: block + using: + foreign_key_constraint_on: submitted_height - name: tss_group using: foreign_key_constraint_on: tss_group_id @@ -955,27 +965,35 @@ - table: name: tss_groups schema: public + object_relationships: + - name: bandtss_member + using: + foreign_key_constraint_on: + column: tss_group_id + table: + name: bandtss_members + schema: public array_relationships: - - name: bandTssReplacementsByNewGroupId + - name: bandtssGroupTransitionsByIncomingTssGroupId using: foreign_key_constraint_on: - column: new_group_id + column: incoming_tss_group_id table: - name: band_tss_replacements + name: bandtss_group_transitions schema: public - - name: band_tss_groups + - name: bandtss_current_groups using: foreign_key_constraint_on: - column: current_group_id + column: current_tss_group_id table: - name: band_tss_groups + name: bandtss_current_groups schema: public - - name: band_tss_replacements + - name: bandtss_group_transitions using: foreign_key_constraint_on: - column: current_group_id + column: current_tss_group_id table: - name: band_tss_replacements + name: bandtss_group_transitions schema: public - name: tss_assigned_members using: @@ -1023,13 +1041,6 @@ name: tss_signings schema: public object_relationships: - - name: band_tss_replacement - using: - foreign_key_constraint_on: - column: tss_signing_id - table: - name: band_tss_replacements - schema: public - name: block using: foreign_key_constraint_on: created_height @@ -1037,19 +1048,26 @@ using: foreign_key_constraint_on: tss_group_id array_relationships: - - name: bandTssSigningsByReplacingGroupSigningId + - name: bandtssSigningsByIncomingGroupTssSigningId + using: + foreign_key_constraint_on: + column: incoming_group_tss_signing_id + table: + name: bandtss_signings + schema: public + - name: bandtss_group_transitions using: foreign_key_constraint_on: - column: replacing_group_signing_id + column: tss_signing_id table: - name: band_tss_signings + name: bandtss_group_transitions schema: public - - name: band_tss_signings + - name: bandtss_signings using: foreign_key_constraint_on: - column: current_group_signing_id + column: current_group_tss_signing_id table: - name: band_tss_signings + name: bandtss_signings schema: public - name: requests using: @@ -1130,15 +1148,6 @@ - name: account using: foreign_key_constraint_on: account_id - - name: validator_report_count - using: - manual_configuration: - column_mapping: - id: validator_id - insertion_order: null - remote_table: - name: validator_report_count - schema: public array_relationships: - name: blocks using: @@ -1164,14 +1173,14 @@ - name: redelegations using: foreign_key_constraint_on: - column: validator_src_id + column: validator_dst_id table: name: redelegations schema: public - - name: redelegationsByValidatorDstId + - name: redelegationsByValidatorSrcId using: foreign_key_constraint_on: - column: validator_dst_id + column: validator_src_id table: name: redelegations schema: public diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index 8e71f5b79..4e2bd0f5e 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -1,116 +1,223 @@ package emitter -// import ( -// "time" - -// sdk "github.com/cosmos/cosmos-sdk/types" - -// "github.com/bandprotocol/chain/v2/hooks/common" -// "github.com/bandprotocol/chain/v2/pkg/tss" -// "github.com/bandprotocol/chain/v2/x/bandtss/types" -// ) - -// func (h *Hook) emitSetBandtssReplacement(replacement types.Replacement) { -// h.Write("SET_BAND_TSS_REPLACEMENT", common.JsDict{ -// "tss_signing_id": replacement.SigningID, -// "new_group_id": replacement.NewGroupID, -// "new_pub_key": parseBytes(replacement.NewPubKey), -// "current_group_id": replacement.CurrentGroupID, -// "current_pub_key": parseBytes(replacement.CurrentPubKey), -// "exec_time": replacement.ExecTime.UnixNano(), -// "status": replacement.Status, -// }) -// } - -// func (h *Hook) emitSetBandtssGroup(gid tss.GroupID) { -// h.Write("SET_BAND_TSS_GROUP", common.JsDict{ -// "current_group_id": gid, -// "since": time.Now().UnixNano(), -// }) -// } - -// func (h *Hook) emitSetBandtssMember(member types.Member) { -// h.Write("SET_BAND_TSS_MEMBER", common.JsDict{ -// "address": member.Address, -// "is_active": member.IsActive, -// "since": member.Since.UnixNano(), -// "last_active": member.LastActive.UnixNano(), -// }) -// } - -// func (h *Hook) emitRemoveBandtssMember() { -// h.Write("REMOVE_BAND_TSS_MEMBERS", common.JsDict{}) -// } - -// func (h *Hook) emitSetBandtssSigning(signing types.Signing) { -// h.Write("SET_BAND_TSS_SIGNING", common.JsDict{ -// "id": signing.ID, -// "fee": signing.Fee.String(), -// "requester": signing.Requester, -// "current_group_signing_id": signing.CurrentGroupSigningID, -// "replacing_group_signing_id": signing.ReplacingGroupSigningID, -// }) -// } - -// // handleInitBandTSSModule implements emitter handler for init bandtss module. -// func (h *Hook) handleInitBandtssModule(ctx sdk.Context) { -// for _, signing := range h.bandtssKeeper.GetSignings(ctx) { -// h.emitSetBandtssSigning(signing) -// } -// } - -// // handleNewBandtssGroupActive implements emitter handler for new bandtss group active. -// func (h *Hook) handleNewBandtssGroupActive(ctx sdk.Context, gid tss.GroupID) { -// h.emitSetBandtssGroup(gid) -// h.emitRemoveBandtssMember() - -// members := h.bandtssKeeper.GetMembers(ctx) -// for _, m := range members { -// h.emitSetBandtssMember(m) -// } -// } - -// // handleUpdateBandtssMember implements emitter handler for update bandtss status. -// func (h *Hook) handleUpdateBandtssMember(ctx sdk.Context, address sdk.AccAddress) { -// member, err := h.bandtssKeeper.GetMember(ctx, address) -// if err != nil { -// panic(err) -// } -// h.emitSetBandtssMember(member) -// } - -// // handleBandtssMsgActivate implements emitter handler for MsgActivate of bandtss. -// func (h *Hook) handleBandtssMsgActivate( -// ctx sdk.Context, msg *types.MsgActivate, -// ) { -// acc, err := sdk.AccAddressFromBech32(msg.Address) -// if err != nil { -// panic(err) -// } - -// h.handleUpdateBandtssMember(ctx, acc) -// } - -// // handleBandtssMsgHealthCheck implements emitter handler for MsgHealthCheck of bandtss. -// func (h *Hook) handleBandtssMsgHealthCheck( -// ctx sdk.Context, msg *types.MsgHealthCheck, -// ) { -// acc, err := sdk.AccAddressFromBech32(msg.Address) -// if err != nil { -// panic(err) -// } - -// h.handleUpdateBandtssMember(ctx, acc) -// } - -// // handleBandtssMsgRequestSignature implements emitter handler for MsgRequestSignature of bandtss. -// func (h *Hook) handleEventSigningRequestCreated(ctx sdk.Context, sid types.SigningID) { -// signing := h.bandtssKeeper.MustGetSigning(ctx, sid) -// h.emitSetBandtssSigning(signing) -// } - -// // handleSetBandtssReplacement implements emitter handler events related to create replacements. -// func (h *Hook) handleSetBandtssReplacement(ctx sdk.Context) { -// r := h.bandtssKeeper.GetReplacement(ctx) -// h.emitSetBandtssReplacement(r) -// } +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + + "github.com/bandprotocol/chain/v2/hooks/common" + "github.com/bandprotocol/chain/v2/pkg/tss" + "github.com/bandprotocol/chain/v2/x/bandtss/types" +) + +func (h *Hook) emitSetBandtssGroupTransition( + proposalID uint64, + transition types.GroupTransition, + createdHeight int64, +) { + h.Write("SET_BANDTSS_GROUP_TRANSITION", common.JsDict{ + "proposal_id": proposalID, + "tss_signing_id": transition.SigningID, + "current_tss_group_id": transition.CurrentGroupID, + "incoming_tss_group_id": transition.IncomingGroupID, + "current_group_pub_key": parseBytes(transition.CurrentGroupPubKey), + "incoming_group_pub_key": parseBytes(transition.IncomingGroupPubKey), + "status": transition.Status, + "exec_time": transition.ExecTime.UnixNano(), + "created_height": createdHeight, + }) +} + +func (h *Hook) emitUpdateBandtssGroupTransitionStatus(transition types.GroupTransition) { + h.Write("UPDATE_BANDTSS_GROUP_TRANSITION", common.JsDict{ + "tss_signing_id": transition.SigningID, + "current_tss_group_id": transition.CurrentGroupID, + "incoming_tss_group_id": transition.IncomingGroupID, + "status": transition.Status, + }) +} + +func (h *Hook) emitUpdateBandtssGroupTransitionStatusSuccess(transition types.GroupTransition) { + h.Write("UPDATE_BANDTSS_GROUP_TRANSITION_SUCCESS", common.JsDict{ + "tss_signing_id": transition.SigningID, + "current_tss_group_id": transition.CurrentGroupID, + "incoming_tss_group_id": transition.IncomingGroupID, + }) +} + +func (h *Hook) emitUpdateBandtssGroupTransitionStatusFailed(transition types.GroupTransition) { + h.Write("UPDATE_BANDTSS_GROUP_TRANSITION_FAILED", common.JsDict{ + "tss_signing_id": transition.SigningID, + "current_tss_group_id": transition.CurrentGroupID, + "incoming_tss_group_id": transition.IncomingGroupID, + }) +} + +func (h *Hook) emitSetBandtssCurrentGroup(gid tss.GroupID, transitionHeight int64) { + h.Write("SET_BANDTSS_CURRENT_GROUP", common.JsDict{ + "current_tss_group_id": gid, + "transition_height": transitionHeight, + }) +} + +func (h *Hook) emitSetBandtssMember(member types.Member) { + h.Write("SET_BANDTSS_MEMBER", common.JsDict{ + "address": member.Address, + "tss_group_id": member.GroupID, + "is_active": member.IsActive, + "penalty_since": member.Since.UnixNano(), + "last_active": member.LastActive.UnixNano(), + }) +} + +func (h *Hook) emitSetBandtssSigning(signing types.Signing) { + h.Write("SET_BANDTSS_SIGNING", common.JsDict{ + "id": signing.ID, + "fee_per_signer": signing.FeePerSigner.String(), + "requester": signing.Requester, + "current_group_tss_signing_id": signing.CurrentGroupSigningID, + "replacing_group_tss_signing_id": signing.IncomingGroupSigningID, + }) +} + +// handleInitBandTSSModule implements emitter handler for init bandtss module. +func (h *Hook) handleInitBandtssModule(ctx sdk.Context) { + currentGroupID := h.bandtssKeeper.GetCurrentGroupID(ctx) + if currentGroupID != 0 { + h.emitSetBandtssCurrentGroup(currentGroupID, ctx.BlockHeight()) + } + + members := h.bandtssKeeper.GetMembers(ctx) + for _, m := range members { + h.emitSetBandtssMember(m) + } +} + +// handleUpdateBandtssMember implements emitter handler for update bandtss status. +func (h *Hook) handleUpdateBandtssMember(ctx sdk.Context, address sdk.AccAddress, groupID tss.GroupID) { + member, err := h.bandtssKeeper.GetMember(ctx, address, groupID) + if err != nil { + panic(err) + } + h.emitSetBandtssMember(member) +} + +// handleBandtssMsgActivate implements emitter handler for MsgActivate of bandtss. +func (h *Hook) handleBandtssMsgActivate(ctx sdk.Context, msg *types.MsgActivate) { + acc, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + panic(err) + } + + h.handleUpdateBandtssMember(ctx, acc, msg.GroupID) +} + +// handleBandtssMsgHeartbeat implements emitter handler for MsgHeartbeat of bandtss. +func (h *Hook) handleBandtssMsgHeartbeat(ctx sdk.Context, msg *types.MsgHeartbeat) { + acc, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + panic(err) + } + + h.handleUpdateBandtssMember(ctx, acc, msg.GroupID) +} + +// handleEventInactiveStatuses implements emitter handler for inactive status event. +func (h *Hook) handleEventInactiveStatuses(ctx sdk.Context, evMap common.EvMap) { + addresses := evMap[types.EventTypeInactiveStatus+"."+types.AttributeKeyAddress] + groupIDs := evMap[types.EventTypeInactiveStatus+"."+types.AttributeKeyGroupID] + if len(addresses) != len(groupIDs) { + panic("invalid event data") + } + + for i, addr := range addresses { + acc, err := sdk.AccAddressFromBech32(addr) + if err != nil { + panic(err) + } + + groupID := tss.GroupID(common.Atoi(groupIDs[i])) + h.handleUpdateBandtssMember(ctx, acc, groupID) + } +} + +// handleEventGroupTransition implements emitter handler for group transition event. +func (h *Hook) handleEventGroupTransition(ctx sdk.Context, eventIdx int, querier *EventQuerier) { + // if transition not found, skip the process. There is a case that the transition message is signed + // at the same block as the transition can be executed. The transition status will be updated via + // another event (group_transition_success, group_transition_failed). + transition, found := h.bandtssKeeper.GetGroupTransition(ctx) + if !found { + return + } + + isNewTransition := transition.Status == types.TRANSITION_STATUS_CREATING_GROUP || + (transition.Status == types.TRANSITION_STATUS_WAITING_SIGN && transition.SigningID == 0) + + if isNewTransition { + proposalID, _ := getCurrentProposalID(eventIdx, querier) + h.emitSetBandtssGroupTransition(proposalID, transition, ctx.BlockHeight()) + } else { + h.emitUpdateBandtssGroupTransitionStatus(transition) + } +} + +// handleEventGroupTransitionSuccess implements emitter handler for group transition success event. +func (h *Hook) handleEventGroupTransitionSuccess(ctx sdk.Context, evMap common.EvMap) { + // use value from emitted event due to the transition info is removed from the store. + signingIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeySigningID] + incomingGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyIncomingGroupID] + currentGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyCurrentGroupID] + + signingID := tss.SigningID(common.Atoi(signingIDs[0])) + currentGroupID := tss.GroupID(common.Atoi(currentGroupIDs[0])) + incomingGroupID := tss.GroupID(common.Atoi(incomingGroupIDs[0])) + + h.emitUpdateBandtssGroupTransitionStatusSuccess(types.GroupTransition{ + SigningID: signingID, + CurrentGroupID: currentGroupID, + IncomingGroupID: incomingGroupID, + }) + + h.emitSetBandtssCurrentGroup(currentGroupID, ctx.BlockHeight()) +} + +// handleEventGroupTransitionFailed implements emitter handler for group transition failed event. +func (h *Hook) handleEventGroupTransitionFailed(_ sdk.Context, evMap common.EvMap) { + // use value from emitted event due to the transition info is removed from the store. + signingIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeySigningID] + incomingGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyIncomingGroupID] + currentGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyCurrentGroupID] + + h.emitUpdateBandtssGroupTransitionStatusFailed(types.GroupTransition{ + SigningID: tss.SigningID(common.Atoi(signingIDs[0])), + CurrentGroupID: tss.GroupID(common.Atoi(currentGroupIDs[0])), + IncomingGroupID: tss.GroupID(common.Atoi(incomingGroupIDs[0])), + }) +} + +// handleBandtssMsgRequestSignature implements emitter handler for MsgRequestSignature of bandtss. +func (h *Hook) handleEventSigningRequestCreated(ctx sdk.Context, evMap common.EvMap) { + signingIDs := evMap[types.EventTypeSigningRequestCreated+"."+types.AttributeKeySigningID] + + for _, sid := range signingIDs { + signing := h.bandtssKeeper.MustGetSigning(ctx, types.SigningID(uint64(common.Atoi(sid)))) + h.emitSetBandtssSigning(signing) + } +} + +// getCurrentProposalID returns the proposal ID that execute the process that emit the given event. +// If the event is triggered by the proposal, the active proposal event should be emitted next to the event. +func getCurrentProposalID(eventIdx int, querier *EventQuerier) (id uint64, found bool) { + proposalIDEvent, found := querier.FindEventWithTypeAfterIdx(govtypes.EventTypeActiveProposal, eventIdx) + if !found { + return 0, false + } + + for _, attr := range proposalIDEvent.Attributes { + if attr.Key == govtypes.AttributeKeyProposalID { + return uint64(common.Atoi(attr.Value)), true + } + } + + return 0, false +} diff --git a/hooks/emitter/emitter.go b/hooks/emitter/emitter.go index 85d3ae74e..4d2f87672 100644 --- a/hooks/emitter/emitter.go +++ b/hooks/emitter/emitter.go @@ -293,10 +293,10 @@ func (h *Hook) AfterInitChain(ctx sdk.Context, req abci.RequestInitChain, res ab } // TSS module - h.handleInitTSSModule(ctx) + h.handleInitTssModule(ctx) // Bandtss module - // h.handleInitBandtssModule(ctx) + h.handleInitBandtssModule(ctx) // Oracle module var oracleState oracletypes.GenesisState @@ -384,8 +384,10 @@ func (h *Hook) AfterBeginBlock(ctx sdk.Context, req abci.RequestBeginBlock, res "inflation": h.mintKeeper.GetMinter(ctx).Inflation.String(), "supply": totalSupply, }) - for _, event := range res.Events { - h.handleBeginBlockEndBlockEvent(ctx, event) + + eventQuerier := NewEventQuerier(res.Events) + for i, event := range res.Events { + h.handleBeginBlockEndBlockEvent(ctx, event, i, eventQuerier) } } @@ -476,9 +478,11 @@ func (h *Hook) AfterEndBlock(ctx sdk.Context, req abci.RequestEndBlock, res abci h.doUpdateGroupProposal(ctx, proposalID) } - for _, event := range res.Events { - h.handleBeginBlockEndBlockEvent(ctx, event) + eventQuerier := NewEventQuerier(res.Events) + for i, event := range res.Events { + h.handleBeginBlockEndBlockEvent(ctx, event, i, eventQuerier) } + // Update balances of all affected accounts on this block. // Index 0 is message NEW_BLOCK, we insert SET_ACCOUNT messages right after it. modifiedMsgs := []common.Message{h.msgs[0]} diff --git a/hooks/emitter/event_querier.go b/hooks/emitter/event_querier.go new file mode 100644 index 000000000..5dbd60656 --- /dev/null +++ b/hooks/emitter/event_querier.go @@ -0,0 +1,35 @@ +package emitter + +import abci "github.com/cometbft/cometbft/abci/types" + +// EventQuerier is a helper struct that helps to find the event with some conditions. +type EventQuerier struct { + events []abci.Event +} + +// NewEventQuerier creates a new EventQuerier with the given events. +func NewEventQuerier(events []abci.Event) *EventQuerier { + return &EventQuerier{events: events} +} + +// FindEventWithTypeBeforeIdx returns the last event of the given type that is emitted before the given index. +func (es *EventQuerier) FindEventWithTypeBeforeIdx(eventType string, idx int) (abci.Event, bool) { + for i := idx; i >= 0; i-- { + if es.events[i].Type == eventType { + return es.events[i], true + } + } + + return abci.Event{}, false +} + +// FindEventWithTypeAfterIdx returns the first event of the given type that is emitted after the given index. +func (es *EventQuerier) FindEventWithTypeAfterIdx(eventType string, idx int) (abci.Event, bool) { + for i := idx + 1; i < len(es.events); i++ { + if es.events[i].Type == eventType { + return es.events[i], true + } + } + + return abci.Event{}, false +} diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index 79d0a49ab..e38e41658 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -23,6 +23,7 @@ import ( "github.com/bandprotocol/chain/v2/hooks/common" "github.com/bandprotocol/chain/v2/pkg/tss" + bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" feedstypes "github.com/bandprotocol/chain/v2/x/feeds/types" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" @@ -126,14 +127,10 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, log sdk.AB h.handleMsgRevoke(msg, detail) case *authz.MsgExec: h.handleMsgExec(ctx, txHash, msg, log, detail) - // case *bandtsstypes.MsgActivate: - // h.handleBandtssMsgActivate(ctx, msg) - // case *bandtsstypes.MsgHealthCheck: - // h.handleBandtssMsgHealthCheck(ctx, msg) - // case *bandtsstypes.MsgRequestSignature: - // h.handleEventRequestSignature(ctx, evMap) - // sid := bandtsstypes.SigningID(common.Atoi(evMap[bandtsstypes.EventTypeSigningRequestCreated+"."+bandtsstypes.AttributeKeySigningID][0])) - // h.handleEventSigningRequestCreated(ctx, sid) + case *bandtsstypes.MsgActivate: + h.handleBandtssMsgActivate(ctx, msg) + case *bandtsstypes.MsgHeartbeat: + h.handleBandtssMsgHeartbeat(ctx, msg) case *feedstypes.MsgSubmitSignals: h.handleMsgSubmitSignals(ctx, msg, evMap) case *feedstypes.MsgSubmitSignalPrices: @@ -174,10 +171,25 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, log sdk.AB } } -func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) { +func (h *Hook) handleBeginBlockEndBlockEvent( + ctx sdk.Context, + event abci.Event, + eventIdx int, + eventQuerier *EventQuerier, +) { events := sdk.StringifyEvents([]abci.Event{event}) evMap := parseEvents(events) switch event.Type { + case bandtsstypes.EventTypeInactiveStatus: + h.handleEventInactiveStatuses(ctx, evMap) + case bandtsstypes.EventTypeGroupTransition: + h.handleEventGroupTransition(ctx, eventIdx, eventQuerier) + case bandtsstypes.EventTypeGroupTransitionSuccess: + h.handleEventGroupTransitionSuccess(ctx, evMap) + case bandtsstypes.EventTypeGroupTransitionFailed: + h.handleEventGroupTransitionFailed(ctx, evMap) + case bandtsstypes.EventTypeSigningRequestCreated: + h.handleEventSigningRequestCreated(ctx, evMap) case oracletypes.EventTypeResolve: h.handleEventRequestExecute(ctx, evMap) case slashingtypes.EventTypeSlash: @@ -202,29 +214,18 @@ func (h *Hook) handleBeginBlockEndBlockEvent(ctx sdk.Context, event abci.Event) h.handleEventSigningSuccess(ctx, evMap) case tsstypes.EventTypeSigningFailed: h.handleEventSigningFailed(ctx, evMap) - // case tsstypes.EventTypeExpiredSigning: - // h.handleEventExpiredSigning(ctx, evMap) - // case bandtsstypes.EventTypeInactiveStatus: - // address := sdk.MustAccAddressFromBech32( - // evMap[bandtsstypes.EventTypeInactiveStatus+"."+tsstypes.AttributeKeyAddress][0], - // ) - // h.handleUpdateBandtssMember(ctx, address) case tsstypes.EventTypeCreateGroup, tsstypes.EventTypeRound2Success, tsstypes.EventTypeRound3Success, tsstypes.EventTypeExpiredGroup, tsstypes.EventTypeComplainSuccess, tsstypes.EventTypeRound3Failed: - gid := tss.GroupID(common.Atoi(evMap[event.Type+"."+tsstypes.AttributeKeyGroupID][0])) - h.handleSetTSSGroup(ctx, gid) - // case bandtsstypes.EventTypeNewGroupActivate: - // gid := tss.GroupID(common.Atoi(evMap[event.Type+"."+bandtsstypes.AttributeKeyGroupID][0])) - // h.handleNewBandtssGroupActive(ctx, gid) - // case bandtsstypes.EventTypeSigningRequestCreated: - // sid := bandtsstypes.SigningID(common.Atoi(evMap[event.Type+"."+bandtsstypes.AttributeKeySigningID][0])) - // h.handleEventSigningRequestCreated(ctx, sid) - // case bandtsstypes.EventTypeReplacement: - // h.handleSetBandtssReplacement(ctx) + groupIDs := evMap[event.Type+"."+tsstypes.AttributeKeyGroupID] + for _, gid := range groupIDs { + h.handleSetTssGroup(ctx, tss.GroupID(common.Atoi(gid))) + } + case tsstypes.EventTypeSubmitSignature: + h.handleEventSubmitSignature(ctx, evMap) case feedstypes.EventTypeUpdatePrice: h.handleEventUpdatePrice(ctx, evMap) case proto.MessageName(&group.EventProposalPruned{}): diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index b2c782efe..26a8962d8 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -1,6 +1,8 @@ package emitter import ( + "encoding/hex" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bandprotocol/chain/v2/hooks/common" @@ -8,19 +10,21 @@ import ( "github.com/bandprotocol/chain/v2/x/tss/types" ) -func (h *Hook) emitNewTSSSigning(signing types.Signing) { +func (h *Hook) emitNewTssSigning(signing types.Signing) { h.Write("NEW_TSS_SIGNING", common.JsDict{ "id": signing.ID, + "current_attempt": signing.CurrentAttempt, "tss_group_id": signing.GroupID, + "originator": parseBytes(signing.Originator), + "message": parseBytes(signing.Message), "group_pub_key": parseBytes(signing.GroupPubKey), - "msg": parseBytes(signing.Message), "group_pub_nonce": parseBytes(signing.GroupPubNonce), "status": signing.Status, "created_height": signing.CreatedHeight, }) } -func (h *Hook) emitUpdateTSSSigningSuccess(signing types.Signing) { +func (h *Hook) emitUpdateTssSigningSuccess(signing types.Signing) { h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, "status": signing.Status, @@ -28,7 +32,7 @@ func (h *Hook) emitUpdateTSSSigningSuccess(signing types.Signing) { }) } -func (h *Hook) emitUpdateTSSSigningFailed(reason string, signing types.Signing) { +func (h *Hook) emitUpdateTssSigningFailed(reason string, signing types.Signing) { h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, "status": signing.Status, @@ -36,14 +40,7 @@ func (h *Hook) emitUpdateTSSSigningFailed(reason string, signing types.Signing) }) } -func (h *Hook) emitUpdateTSSSigningStatus(signing types.Signing) { - h.Write("UPDATE_TSS_SIGNING", common.JsDict{ - "id": signing.ID, - "status": signing.Status, - }) -} - -func (h *Hook) emitSetTSSGroup(group types.Group, dkgContext []byte) { +func (h *Hook) emitSetTssGroup(group types.Group, dkgContext []byte) { h.Write("SET_TSS_GROUP", common.JsDict{ "id": group.ID, "size": group.Size_, @@ -56,7 +53,7 @@ func (h *Hook) emitSetTSSGroup(group types.Group, dkgContext []byte) { }) } -func (h *Hook) emitSetTSSMember(member types.Member) { +func (h *Hook) emitSetTssMember(member types.Member) { h.Write("SET_TSS_MEMBER", common.JsDict{ "id": member.ID, "tss_group_id": member.GroupID, @@ -67,33 +64,63 @@ func (h *Hook) emitSetTSSMember(member types.Member) { }) } -func (h *Hook) emitNewTSSAssignedMember(sid tss.SigningID, gid tss.GroupID, am types.AssignedMember) { +func (h *Hook) emitNewTssAssignedMember( + sid tss.SigningID, + attempt uint64, + gid tss.GroupID, + am types.AssignedMember, +) { h.Write("NEW_TSS_ASSIGNED_MEMBER", common.JsDict{ - "tss_signing_id": sid, - "tss_group_id": gid, - "tss_member_id": am.MemberID, - "pub_d": parseBytes(am.PubD), - "pub_e": parseBytes(am.PubE), - "binding_factor": parseBytes(am.PubKey), - "pub_nonce": parseBytes(am.PubNonce), + "tss_signing_id": sid, + "tss_signing_attempt": attempt, + "tss_group_id": gid, + "tss_member_id": am.MemberID, + "pub_d": parseBytes(am.PubD), + "pub_e": parseBytes(am.PubE), + "binding_factor": parseBytes(am.PubKey), + "pub_nonce": parseBytes(am.PubNonce), + }) +} + +func (h *Hook) emitUpdateTssAssignedMember( + signingID tss.SigningID, + attempt uint64, + memberID tss.MemberID, + sig tss.Signature, + blockHeight int64, +) { + h.Write("UPDATE_TSS_ASSIGNED_MEMBER", common.JsDict{ + "tss_signing_id": signingID, + "tss_signing_attempt": attempt, + "tss_member_id": memberID, + "signature": parseBytes(sig), + "block_height": blockHeight, }) } // handleInitTSSModule implements emitter handler for initializing tss module. -func (h *Hook) handleInitTSSModule(ctx sdk.Context) {} +func (h *Hook) handleInitTssModule(ctx sdk.Context) { + groups := h.tssKeeper.GetGroups(ctx) + for _, group := range groups { + h.emitSetTssGroup(group, nil) // DKG data is already removed. + } +} // handleEventRequestSignature implements emitter handler for RequestSignature event. func (h *Hook) handleEventRequestSignature(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeRequestSignature+"."+types.AttributeKeySigningID] + for _, sid := range sids { id := tss.SigningID(common.Atoi(sid)) + signing := h.tssKeeper.MustGetSigning(ctx, id) - signingAttempt := h.tssKeeper.MustGetSigningAttempt(ctx, id, signing.CurrentAttempt) + attempt := signing.CurrentAttempt + attemptInfo := h.tssKeeper.MustGetSigningAttempt(ctx, id, attempt) - h.emitNewTSSSigning(signing) + h.emitNewTssSigning(signing) - for _, am := range signingAttempt.AssignedMembers { - h.emitNewTSSAssignedMember(signing.ID, signing.GroupID, am) + for _, am := range attemptInfo.AssignedMembers { + h.emitNewTssAssignedMember(signing.ID, attempt, signing.GroupID, am) } } } @@ -105,43 +132,64 @@ func (h *Hook) handleEventSigningSuccess(ctx sdk.Context, evMap common.EvMap) { id := tss.SigningID(common.Atoi(sid)) signing := h.tssKeeper.MustGetSigning(ctx, id) - h.emitUpdateTSSSigningSuccess(signing) + h.emitUpdateTssSigningSuccess(signing) } } // handleEventSigningFailed implements emitter handler for SigningSuccess event. func (h *Hook) handleEventSigningFailed(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeSigningFailed+"."+types.AttributeKeySigningID] - for _, sid := range sids { + errReasons := evMap[types.EventTypeSigningFailed+"."+types.AttributeKeyReason] + for i, sid := range sids { id := tss.SigningID(common.Atoi(sid)) signing := h.tssKeeper.MustGetSigning(ctx, id) - if reason, ok := evMap[types.EventTypeSigningFailed+"."+types.AttributeKeyReason]; ok { - h.emitUpdateTSSSigningFailed( - reason[0], - signing, - ) - } else { - h.emitUpdateTSSSigningFailed( - "failed with on reason", - signing, - ) + errReason := "failed with some reason" + if i < len(errReasons) { + errReason = errReasons[i] } + + h.emitUpdateTssSigningFailed(errReason, signing) } } // handleSetTSSGroup implements emitter handler events related to group. -func (h *Hook) handleSetTSSGroup(ctx sdk.Context, gid tss.GroupID) { +func (h *Hook) handleSetTssGroup(ctx sdk.Context, gid tss.GroupID) { group := h.tssKeeper.MustGetGroup(ctx, gid) dkgContext, err := h.tssKeeper.GetDKGContext(ctx, gid) if err != nil { dkgContext = []byte{} } - h.emitSetTSSGroup(group, dkgContext) + h.emitSetTssGroup(group, dkgContext) members := h.tssKeeper.MustGetMembers(ctx, gid) for _, m := range members { - h.emitSetTSSMember(m) + h.emitSetTssMember(m) + } +} + +func (h *Hook) handleEventSubmitSignature(ctx sdk.Context, evMap common.EvMap) { + sids := evMap[types.EventTypeSubmitSignature+"."+types.AttributeKeySigningID] + attempts := evMap[types.EventTypeSubmitSignature+"."+types.AttributeKeyAttempt] + memberIDs := evMap[types.EventTypeSubmitSignature+"."+types.AttributeKeyMemberID] + sigs := evMap[types.EventTypeSubmitSignature+"."+types.AttributeKeySignature] + + if len(sids) != len(attempts) || len(sids) != len(memberIDs) || len(sids) != len(sigs) { + panic("invalid event data") + } + + for i, sid := range sids { + signingID := tss.SigningID(common.Atoi(sid)) + attempt := uint64(common.Atoi(attempts[i])) + memberID := tss.MemberID(common.Atoi(memberIDs[i])) + + bz, err := hex.DecodeString(sigs[i]) + if err != nil { + panic("invalid signature") + } + signature := tss.Signature(bz) + + h.emitUpdateTssAssignedMember(signingID, attempt, memberID, signature, ctx.BlockHeight()) } } From 0df9b3c5ea0c8e40689532be7da296669552a9ea Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 2 Sep 2024 10:28:02 +0700 Subject: [PATCH 093/132] fix logic --- flusher/flusher/bandtss_db.py | 41 +++++++++++++++++++----- flusher/flusher/handler.py | 18 +++++++++-- hooks/emitter/bandtss.go | 59 ++++++++++++++++++++--------------- hooks/emitter/handler.go | 25 ++++++++------- hooks/emitter/tss.go | 21 +++++++------ 5 files changed, 106 insertions(+), 58 deletions(-) diff --git a/flusher/flusher/bandtss_db.py b/flusher/flusher/bandtss_db.py index 643e145c4..3d0dcf31c 100644 --- a/flusher/flusher/bandtss_db.py +++ b/flusher/flusher/bandtss_db.py @@ -29,12 +29,25 @@ def process_bind_param(self, value, dialect): "bandtss_group_transitions", metadata, Column("proposal_id", sa.Integer, sa.ForeignKey("proposals.id"), primary_key=True), - Column("tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id")), - Column("current_tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), - Column("incoming_tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), - Column("current_group_pub_key", CustomBase64), - Column("incoming_group_pub_key", CustomBase64), + Column( + "tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id"), nullable=True + ), + Column( + "current_tss_group_id", + sa.Integer, + sa.ForeignKey("tss_groups.id"), + nullable=True, + ), + Column( + "incoming_tss_group_id", + sa.Integer, + sa.ForeignKey("tss_groups.id"), + nullable=True, + ), + Column("current_group_pub_key", CustomBase64, nullable=True), + Column("incoming_group_pub_key", CustomBase64, nullable=True), Column("status", CustomGroupTransitionStatus), + Column("exec_time", CustomDateTime), Column( "created_height", sa.Integer, @@ -53,7 +66,13 @@ def process_bind_param(self, value, dialect): bandtss_current_groups = sa.Table( "bandtss_current_groups", metadata, - Column("proposal_id", sa.Integer, sa.ForeignKey("proposals.id"), primary_key=True), + Column( + "proposal_id", + sa.Integer, + sa.ForeignKey("proposals.id"), + nullable=True, + index=True, + ), Column("current_tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), Column( "transition_height", @@ -83,9 +102,15 @@ def process_bind_param(self, value, dialect): Column("requester_account_id", sa.Integer, sa.ForeignKey("accounts.id")), Column("fee_per_signer", sa.String), Column( - "current_group_tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id") + "current_group_tss_signing_id", + sa.Integer, + sa.ForeignKey("tss_signings.id"), + nullable=True, ), Column( - "incoming_group_tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id") + "incoming_group_tss_signing_id", + sa.Integer, + sa.ForeignKey("tss_signings.id"), + nullable=True, ), ) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index d57f42a9a..158cc338c 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -841,6 +841,12 @@ def handle_update_tss_assigned_member(self, msg): ################################## def handle_set_bandtss_group_transition(self, msg): + if msg["tss_signing_id"] == 0: + del msg["tss_signing_id"] + if msg["current_tss_group_id"] == 0: + del msg["current_tss_group_id"] + if msg["incoming_tss_group_id"] == 0: + del msg["incoming_tss_group_id"] self.conn.execute(bandtss_group_transitions.insert(), msg) def update_bandtss_group_transition(self, status): @@ -867,10 +873,9 @@ def handle_update_bandtss_group_transition_failed(self, msg): def handle_set_bandtss_current_group(self, msg): proposal_column = bandtss_group_transitions.c.proposal_id proposal_id = self.conn.execute(select(func.max(proposal_column))).scalar() - if proposal_id is None: - proposal_id = 0 + if proposal_id is not None: + msg["proposal_id"] = proposal_id - msg["proposal_id"] = proposal_id self.conn.execute(bandtss_current_groups.insert(), msg) def handle_set_bandtss_member(self, msg): @@ -881,6 +886,13 @@ def handle_set_bandtss_member(self, msg): ) def handle_set_bandtss_signing(self, msg): + if msg["current_group_tss_signing_id"] == 0: + del msg["current_group_tss_signing_id"] + if msg["incoming_group_tss_signing_id"] == 0: + del msg["incoming_group_tss_signing_id"] + msg["requester_account_id"] = self.get_account_id(msg["requester"]) + del msg["requester"] + self.conn.execute(bandtss_signings.insert(), msg) ################################## diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index 4e2bd0f5e..0125ba7e0 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -7,6 +7,7 @@ import ( "github.com/bandprotocol/chain/v2/hooks/common" "github.com/bandprotocol/chain/v2/pkg/tss" "github.com/bandprotocol/chain/v2/x/bandtss/types" + tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" ) func (h *Hook) emitSetBandtssGroupTransition( @@ -71,11 +72,11 @@ func (h *Hook) emitSetBandtssMember(member types.Member) { func (h *Hook) emitSetBandtssSigning(signing types.Signing) { h.Write("SET_BANDTSS_SIGNING", common.JsDict{ - "id": signing.ID, - "fee_per_signer": signing.FeePerSigner.String(), - "requester": signing.Requester, - "current_group_tss_signing_id": signing.CurrentGroupSigningID, - "replacing_group_tss_signing_id": signing.IncomingGroupSigningID, + "id": signing.ID, + "fee_per_signer": signing.FeePerSigner.String(), + "requester": signing.Requester, + "current_group_tss_signing_id": signing.CurrentGroupSigningID, + "incoming_group_tss_signing_id": signing.IncomingGroupSigningID, }) } @@ -92,8 +93,8 @@ func (h *Hook) handleInitBandtssModule(ctx sdk.Context) { } } -// handleUpdateBandtssMember implements emitter handler for update bandtss status. -func (h *Hook) handleUpdateBandtssMember(ctx sdk.Context, address sdk.AccAddress, groupID tss.GroupID) { +// handleBandtssUpdateMember implements emitter handler for update bandtss status. +func (h *Hook) handleBandtssUpdateMember(ctx sdk.Context, address sdk.AccAddress, groupID tss.GroupID) { member, err := h.bandtssKeeper.GetMember(ctx, address, groupID) if err != nil { panic(err) @@ -108,7 +109,7 @@ func (h *Hook) handleBandtssMsgActivate(ctx sdk.Context, msg *types.MsgActivate) panic(err) } - h.handleUpdateBandtssMember(ctx, acc, msg.GroupID) + h.handleBandtssUpdateMember(ctx, acc, msg.GroupID) } // handleBandtssMsgHeartbeat implements emitter handler for MsgHeartbeat of bandtss. @@ -118,11 +119,11 @@ func (h *Hook) handleBandtssMsgHeartbeat(ctx sdk.Context, msg *types.MsgHeartbea panic(err) } - h.handleUpdateBandtssMember(ctx, acc, msg.GroupID) + h.handleBandtssUpdateMember(ctx, acc, msg.GroupID) } -// handleEventInactiveStatuses implements emitter handler for inactive status event. -func (h *Hook) handleEventInactiveStatuses(ctx sdk.Context, evMap common.EvMap) { +// handleBandtssEventInactiveStatuses implements emitter handler for inactive status event. +func (h *Hook) handleBandtssEventInactiveStatuses(ctx sdk.Context, evMap common.EvMap) { addresses := evMap[types.EventTypeInactiveStatus+"."+types.AttributeKeyAddress] groupIDs := evMap[types.EventTypeInactiveStatus+"."+types.AttributeKeyGroupID] if len(addresses) != len(groupIDs) { @@ -136,12 +137,12 @@ func (h *Hook) handleEventInactiveStatuses(ctx sdk.Context, evMap common.EvMap) } groupID := tss.GroupID(common.Atoi(groupIDs[i])) - h.handleUpdateBandtssMember(ctx, acc, groupID) + h.handleBandtssUpdateMember(ctx, acc, groupID) } } -// handleEventGroupTransition implements emitter handler for group transition event. -func (h *Hook) handleEventGroupTransition(ctx sdk.Context, eventIdx int, querier *EventQuerier) { +// handleBandtssEventGroupTransition implements emitter handler for group transition event. +func (h *Hook) handleBandtssEventGroupTransition(ctx sdk.Context, eventIdx int, querier *EventQuerier) { // if transition not found, skip the process. There is a case that the transition message is signed // at the same block as the transition can be executed. The transition status will be updated via // another event (group_transition_success, group_transition_failed). @@ -150,21 +151,27 @@ func (h *Hook) handleEventGroupTransition(ctx sdk.Context, eventIdx int, querier return } - isNewTransition := transition.Status == types.TRANSITION_STATUS_CREATING_GROUP || - (transition.Status == types.TRANSITION_STATUS_WAITING_SIGN && transition.SigningID == 0) + // TODO: change logic for handling force update transition + // isNewTransition := transition.Status == types.TRANSITION_STATUS_CREATING_GROUP || + // (transition.Status == types.TRANSITION_STATUS_WAITING_EXECUTION && transition.SigningID == 0) + isNewTransition := transition.Status == types.TRANSITION_STATUS_CREATING_GROUP if isNewTransition { - proposalID, _ := getCurrentProposalID(eventIdx, querier) + proposalID, found := getCurrentProposalID(eventIdx, querier) + if !found { + panic("proposal ID not found") + } + h.emitSetBandtssGroupTransition(proposalID, transition, ctx.BlockHeight()) } else { h.emitUpdateBandtssGroupTransitionStatus(transition) } } -// handleEventGroupTransitionSuccess implements emitter handler for group transition success event. -func (h *Hook) handleEventGroupTransitionSuccess(ctx sdk.Context, evMap common.EvMap) { +// handleBandtssEventGroupTransitionSuccess implements emitter handler for group transition success event. +func (h *Hook) handleBandtssEventGroupTransitionSuccess(ctx sdk.Context, evMap common.EvMap) { // use value from emitted event due to the transition info is removed from the store. - signingIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeySigningID] + signingIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+tsstypes.AttributeKeySigningID] incomingGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyIncomingGroupID] currentGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyCurrentGroupID] @@ -178,13 +185,13 @@ func (h *Hook) handleEventGroupTransitionSuccess(ctx sdk.Context, evMap common.E IncomingGroupID: incomingGroupID, }) - h.emitSetBandtssCurrentGroup(currentGroupID, ctx.BlockHeight()) + h.emitSetBandtssCurrentGroup(incomingGroupID, ctx.BlockHeight()) } -// handleEventGroupTransitionFailed implements emitter handler for group transition failed event. -func (h *Hook) handleEventGroupTransitionFailed(_ sdk.Context, evMap common.EvMap) { +// handleBandtssEventGroupTransitionFailed implements emitter handler for group transition failed event. +func (h *Hook) handleBandtssEventGroupTransitionFailed(_ sdk.Context, evMap common.EvMap) { // use value from emitted event due to the transition info is removed from the store. - signingIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeySigningID] + signingIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+tsstypes.AttributeKeySigningID] incomingGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyIncomingGroupID] currentGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyCurrentGroupID] @@ -195,8 +202,8 @@ func (h *Hook) handleEventGroupTransitionFailed(_ sdk.Context, evMap common.EvMa }) } -// handleBandtssMsgRequestSignature implements emitter handler for MsgRequestSignature of bandtss. -func (h *Hook) handleEventSigningRequestCreated(ctx sdk.Context, evMap common.EvMap) { +// handleBandtssEventSigningRequestCreated implements emitter handler for MsgRequestSignature of bandtss. +func (h *Hook) handleBandtssEventSigningRequestCreated(ctx sdk.Context, evMap common.EvMap) { signingIDs := evMap[types.EventTypeSigningRequestCreated+"."+types.AttributeKeySigningID] for _, sid := range signingIDs { diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index e38e41658..5e784a8f8 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -131,6 +131,9 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, log sdk.AB h.handleBandtssMsgActivate(ctx, msg) case *bandtsstypes.MsgHeartbeat: h.handleBandtssMsgHeartbeat(ctx, msg) + case *bandtsstypes.MsgRequestSignature: + h.handleTssEventRequestSignature(ctx, evMap) + h.handleBandtssEventSigningRequestCreated(ctx, evMap) case *feedstypes.MsgSubmitSignals: h.handleMsgSubmitSignals(ctx, msg, evMap) case *feedstypes.MsgSubmitSignalPrices: @@ -166,6 +169,8 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, log sdk.AB h.handleGroupEventExec(ctx, evMap) case *group.MsgWithdrawProposal: h.handleGroupMsgWithdrawProposal(ctx, evMap) + case *tsstypes.MsgSubmitSignature: + h.handleTssEventSubmitSignature(ctx, evMap) default: break } @@ -181,15 +186,15 @@ func (h *Hook) handleBeginBlockEndBlockEvent( evMap := parseEvents(events) switch event.Type { case bandtsstypes.EventTypeInactiveStatus: - h.handleEventInactiveStatuses(ctx, evMap) + h.handleBandtssEventInactiveStatuses(ctx, evMap) case bandtsstypes.EventTypeGroupTransition: - h.handleEventGroupTransition(ctx, eventIdx, eventQuerier) + h.handleBandtssEventGroupTransition(ctx, eventIdx, eventQuerier) case bandtsstypes.EventTypeGroupTransitionSuccess: - h.handleEventGroupTransitionSuccess(ctx, evMap) + h.handleBandtssEventGroupTransitionSuccess(ctx, evMap) case bandtsstypes.EventTypeGroupTransitionFailed: - h.handleEventGroupTransitionFailed(ctx, evMap) + h.handleBandtssEventGroupTransitionFailed(ctx, evMap) case bandtsstypes.EventTypeSigningRequestCreated: - h.handleEventSigningRequestCreated(ctx, evMap) + h.handleBandtssEventSigningRequestCreated(ctx, evMap) case oracletypes.EventTypeResolve: h.handleEventRequestExecute(ctx, evMap) case slashingtypes.EventTypeSlash: @@ -209,11 +214,11 @@ func (h *Hook) handleBeginBlockEndBlockEvent( case channeltypes.EventTypeSendPacket: h.handleEventSendPacket(ctx, evMap) case tsstypes.EventTypeRequestSignature: - h.handleEventRequestSignature(ctx, evMap) + h.handleTssEventRequestSignature(ctx, evMap) case tsstypes.EventTypeSigningSuccess: - h.handleEventSigningSuccess(ctx, evMap) + h.handleTssEventSigningSuccess(ctx, evMap) case tsstypes.EventTypeSigningFailed: - h.handleEventSigningFailed(ctx, evMap) + h.handleTssEventSigningFailed(ctx, evMap) case tsstypes.EventTypeCreateGroup, tsstypes.EventTypeRound2Success, tsstypes.EventTypeRound3Success, @@ -222,10 +227,8 @@ func (h *Hook) handleBeginBlockEndBlockEvent( tsstypes.EventTypeRound3Failed: groupIDs := evMap[event.Type+"."+tsstypes.AttributeKeyGroupID] for _, gid := range groupIDs { - h.handleSetTssGroup(ctx, tss.GroupID(common.Atoi(gid))) + h.handleTssSetGroup(ctx, tss.GroupID(common.Atoi(gid))) } - case tsstypes.EventTypeSubmitSignature: - h.handleEventSubmitSignature(ctx, evMap) case feedstypes.EventTypeUpdatePrice: h.handleEventUpdatePrice(ctx, evMap) case proto.MessageName(&group.EventProposalPruned{}): diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 26a8962d8..88708a1c4 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -94,7 +94,7 @@ func (h *Hook) emitUpdateTssAssignedMember( "tss_signing_attempt": attempt, "tss_member_id": memberID, "signature": parseBytes(sig), - "block_height": blockHeight, + "submitted_height": blockHeight, }) } @@ -106,8 +106,8 @@ func (h *Hook) handleInitTssModule(ctx sdk.Context) { } } -// handleEventRequestSignature implements emitter handler for RequestSignature event. -func (h *Hook) handleEventRequestSignature(ctx sdk.Context, evMap common.EvMap) { +// handleTssEventRequestSignature implements emitter handler for RequestSignature event. +func (h *Hook) handleTssEventRequestSignature(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeRequestSignature+"."+types.AttributeKeySigningID] for _, sid := range sids { @@ -125,8 +125,8 @@ func (h *Hook) handleEventRequestSignature(ctx sdk.Context, evMap common.EvMap) } } -// handleEventSigningSuccess implements emitter handler for SigningSuccess event. -func (h *Hook) handleEventSigningSuccess(ctx sdk.Context, evMap common.EvMap) { +// handleTssEventSigningSuccess implements emitter handler for SigningSuccess event. +func (h *Hook) handleTssEventSigningSuccess(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeSigningSuccess+"."+types.AttributeKeySigningID] for _, sid := range sids { id := tss.SigningID(common.Atoi(sid)) @@ -136,8 +136,8 @@ func (h *Hook) handleEventSigningSuccess(ctx sdk.Context, evMap common.EvMap) { } } -// handleEventSigningFailed implements emitter handler for SigningSuccess event. -func (h *Hook) handleEventSigningFailed(ctx sdk.Context, evMap common.EvMap) { +// handleTssEventSigningFailed implements emitter handler for SigningSuccess event. +func (h *Hook) handleTssEventSigningFailed(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeSigningFailed+"."+types.AttributeKeySigningID] errReasons := evMap[types.EventTypeSigningFailed+"."+types.AttributeKeyReason] for i, sid := range sids { @@ -153,8 +153,8 @@ func (h *Hook) handleEventSigningFailed(ctx sdk.Context, evMap common.EvMap) { } } -// handleSetTSSGroup implements emitter handler events related to group. -func (h *Hook) handleSetTssGroup(ctx sdk.Context, gid tss.GroupID) { +// handleTssSetGroup implements emitter handler events related to group. +func (h *Hook) handleTssSetGroup(ctx sdk.Context, gid tss.GroupID) { group := h.tssKeeper.MustGetGroup(ctx, gid) dkgContext, err := h.tssKeeper.GetDKGContext(ctx, gid) if err != nil { @@ -169,7 +169,8 @@ func (h *Hook) handleSetTssGroup(ctx sdk.Context, gid tss.GroupID) { } } -func (h *Hook) handleEventSubmitSignature(ctx sdk.Context, evMap common.EvMap) { +// handleTssEventSubmitSignature implements emitter handler for SubmitSignature event. +func (h *Hook) handleTssEventSubmitSignature(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeSubmitSignature+"."+types.AttributeKeySigningID] attempts := evMap[types.EventTypeSubmitSignature+"."+types.AttributeKeyAttempt] memberIDs := evMap[types.EventTypeSubmitSignature+"."+types.AttributeKeyMemberID] From 4bb37f5d6ad1e936a6042253ea9125fdc47297cc Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 2 Sep 2024 13:58:39 +0700 Subject: [PATCH 094/132] fix emitter msg decoder --- hooks/emitter/decoder.go | 96 +++++++++++++++++++++------------------- 1 file changed, 51 insertions(+), 45 deletions(-) diff --git a/hooks/emitter/decoder.go b/hooks/emitter/decoder.go index c75444399..355ec426e 100644 --- a/hooks/emitter/decoder.go +++ b/hooks/emitter/decoder.go @@ -136,18 +136,18 @@ func DecodeMsg(msg sdk.Msg, detail common.JsDict) { DecodeMsgUpdateReferenceSourceConfig(msg, detail) case *feedstypes.MsgUpdateParams: DecodeMsgUpdateParams(msg, detail) - // case *bandtsstypes.MsgCreateGroup: - // DecodeGroupMsgCreateGroupBandtss(msg, detail) - // case *bandtsstypes.MsgReplaceGroup: - // DecodeGroupMsgReplaceGroup(msg, detail) - // case *bandtsstypes.MsgRequestSignature: - // DecodeMsgRequestSignature(msg, detail) - // case *bandtsstypes.MsgActivate: - // DecodeMsgActivateBandtss(msg, detail) - // case *bandtsstypes.MsgHealthCheck: - // DecodeMsgHealthCheck(msg, detail) - // case *bandtsstypes.MsgUpdateParams: - // DecodeMsgUpdateParamsBandtss(msg, detail) + case *bandtsstypes.MsgTransitionGroup: + DecodeBandtssMsgTransitionGroup(msg, detail) + case *bandtsstypes.MsgForceReplaceGroup: + DecodeBandtssMsgForceReplaceGroup(msg, detail) + case *bandtsstypes.MsgRequestSignature: + DecodeBandtssMsgRequestSignature(msg, detail) + case *bandtsstypes.MsgActivate: + DecodeBandtssMsgActivate(msg, detail) + case *bandtsstypes.MsgHeartbeat: + DecodeBandtssMsgHeartbeat(msg, detail) + case *bandtsstypes.MsgUpdateParams: + DecodeBandtssMsgUpdateParams(msg, detail) case *tsstypes.MsgSubmitDKGRound1: DecodeMsgSubmitDKGRound1(msg, detail) case *tsstypes.MsgSubmitDKGRound2: @@ -719,26 +719,45 @@ func DecodeMsgUpdateParams(msg *feedstypes.MsgUpdateParams, detail common.JsDict detail["current_feeds_update_interval"] = params.GetCurrentFeedsUpdateInterval() } -// func DecodeGroupMsgCreateGroupBandtss(msg *bandtsstypes.MsgCreateGroup, detail common.JsDict) { -// detail["members"] = msg.Members -// detail["threshold"] = msg.Threshold -// detail["authority"] = msg.Authority -// } +func DecodeBandtssMsgTransitionGroup(msg *bandtsstypes.MsgTransitionGroup, detail common.JsDict) { + detail["members"] = msg.Members + detail["threshold"] = msg.Threshold + detail["exec_time"] = msg.ExecTime.GoString() + detail["authority"] = msg.Authority +} + +func DecodeBandtssMsgForceReplaceGroup(msg *bandtsstypes.MsgForceReplaceGroup, detail common.JsDict) { + detail["incoming_group_id"] = msg.IncomingGroupID + detail["exec_time"] = msg.ExecTime.GoString() + detail["authority"] = msg.Authority +} -// func DecodeGroupMsgReplaceGroup(msg *bandtsstypes.MsgReplaceGroup, detail common.JsDict) { -// detail["new_group_id"] = msg.NewGroupID -// detail["exec_time"] = msg.ExecTime.GoString() -// detail["authority"] = msg.Authority -// } +func DecodeBandtssMsgRequestSignature(msg *bandtsstypes.MsgRequestSignature, detail common.JsDict) { + detail["content"] = msg.Content.GetCachedValue() + detail["memo"] = msg.Memo + detail["fee_limit"] = msg.FeeLimit + detail["sender"] = msg.Sender +} -// func DecodeMsgUpdateParamsBandtss(msg *bandtsstypes.MsgUpdateParams, detail common.JsDict) { -// params := msg.GetParams() -// detail["active_duration"] = params.GetActiveDuration() -// detail["reward_percentage"] = params.GetRewardPercentage() -// detail["inactive_penalty_duration"] = params.GetInactivePenaltyDuration() -// detail["fee"] = params.GetFee() -// detail["authority"] = msg.GetAuthority() -// } +func DecodeBandtssMsgActivate(msg *bandtsstypes.MsgActivate, detail common.JsDict) { + detail["sender"] = msg.Sender + detail["group_id"] = msg.GroupID +} + +func DecodeBandtssMsgHeartbeat(msg *bandtsstypes.MsgHeartbeat, detail common.JsDict) { + detail["sender"] = msg.Sender + detail["group_id"] = msg.GroupID +} + +func DecodeBandtssMsgUpdateParams(msg *bandtsstypes.MsgUpdateParams, detail common.JsDict) { + params := msg.GetParams() + detail["active_duration"] = params.GetActiveDuration() + detail["reward_percentage"] = params.GetRewardPercentage() + detail["inactive_penalty_duration"] = params.GetInactivePenaltyDuration() + detail["fee"] = params.GetFee() + detail["max_transition_duration"] = params.GetMaxTransitionDuration() + detail["authority"] = msg.GetAuthority() +} func DecodeMsgSubmitDKGRound1(msg *tsstypes.MsgSubmitDKGRound1, detail common.JsDict) { detail["group_id"] = msg.GroupID @@ -774,7 +793,7 @@ func DecodeMsgSubmitSignature(msg *tsstypes.MsgSubmitSignature, detail common.Js detail["signing_id"] = msg.SigningID detail["member_id"] = msg.MemberID detail["signature"] = msg.Signature - detail["sender"] = msg.Signer + detail["signer"] = msg.Signer } func DecodeMsgUpdateParamsTss(msg *tsstypes.MsgUpdateParams, detail common.JsDict) { @@ -785,23 +804,10 @@ func DecodeMsgUpdateParamsTss(msg *tsstypes.MsgUpdateParams, detail common.JsDic detail["max_d_e_size"] = params.GetMaxDESize() detail["creating_period"] = params.GetCreationPeriod() detail["signing_period"] = params.GetSigningPeriod() + detail["max_signing_attempt"] = params.GetMaxSigningAttempt() detail["authority"] = msg.GetAuthority() } -// func DecodeMsgActivateBandtss(msg *bandtsstypes.MsgActivate, detail common.JsDict) { -// detail["address"] = msg.Address -// } - -// func DecodeMsgHealthCheck(msg *bandtsstypes.MsgHealthCheck, detail common.JsDict) { -// detail["address"] = msg.Address -// } - -func DecodeMsgRequestSignature(msg *bandtsstypes.MsgRequestSignature, detail common.JsDict) { - detail["content"] = msg.Content.GetCachedValue() - detail["fee_limit"] = msg.FeeLimit - detail["sender"] = msg.Sender -} - func DecodeGroupMsgCreateGroup(msg *group.MsgCreateGroup, detail common.JsDict) { detail["admin"] = msg.Admin detail["members"] = msg.Members From 62195b8eb5fd779208b1ead33707f01046ec389c Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 2 Sep 2024 22:11:54 +0700 Subject: [PATCH 095/132] fix logic transition and bandtss members --- flusher/flusher/bandtss_db.py | 3 ++- flusher/flusher/handler.py | 6 +++++- hooks/emitter/bandtss.go | 21 +++++++++++++++++---- hooks/emitter/decoder.go | 10 +++++----- 4 files changed, 29 insertions(+), 11 deletions(-) diff --git a/flusher/flusher/bandtss_db.py b/flusher/flusher/bandtss_db.py index 3d0dcf31c..89e848a38 100644 --- a/flusher/flusher/bandtss_db.py +++ b/flusher/flusher/bandtss_db.py @@ -48,6 +48,7 @@ def process_bind_param(self, value, dialect): Column("incoming_group_pub_key", CustomBase64, nullable=True), Column("status", CustomGroupTransitionStatus), Column("exec_time", CustomDateTime), + Column("is_force_transition", sa.Boolean), Column( "created_height", sa.Integer, @@ -89,7 +90,7 @@ def process_bind_param(self, value, dialect): Column( "tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id"), primary_key=True ), - Column("account_id", sa.Integer, sa.ForeignKey("accounts.id")), + Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), Column("is_active", sa.Boolean), Column("penalty_since", CustomDateTime, nullable=True), Column("last_active", CustomDateTime, nullable=True), diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 158cc338c..e0faef368 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -847,6 +847,7 @@ def handle_set_bandtss_group_transition(self, msg): del msg["current_tss_group_id"] if msg["incoming_tss_group_id"] == 0: del msg["incoming_tss_group_id"] + self.conn.execute(bandtss_group_transitions.insert(), msg) def update_bandtss_group_transition(self, status): @@ -879,10 +880,13 @@ def handle_set_bandtss_current_group(self, msg): self.conn.execute(bandtss_current_groups.insert(), msg) def handle_set_bandtss_member(self, msg): + msg["account_id"] = self.get_account_id(msg["address"]) + del msg["address"] + self.conn.execute( insert(bandtss_members) .values(**msg) - .on_conflict_do_update(constraint="bandtss_member_pkey", set_=msg) + .on_conflict_do_update(constraint="bandtss_members_pkey", set_=msg) ) def handle_set_bandtss_signing(self, msg): diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index 0125ba7e0..0e1a14cb4 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -24,6 +24,7 @@ func (h *Hook) emitSetBandtssGroupTransition( "incoming_group_pub_key": parseBytes(transition.IncomingGroupPubKey), "status": transition.Status, "exec_time": transition.ExecTime.UnixNano(), + "is_force_transition": transition.IsForceTransition, "created_height": createdHeight, }) } @@ -151,10 +152,22 @@ func (h *Hook) handleBandtssEventGroupTransition(ctx sdk.Context, eventIdx int, return } - // TODO: change logic for handling force update transition - // isNewTransition := transition.Status == types.TRANSITION_STATUS_CREATING_GROUP || - // (transition.Status == types.TRANSITION_STATUS_WAITING_EXECUTION && transition.SigningID == 0) - isNewTransition := transition.Status == types.TRANSITION_STATUS_CREATING_GROUP + // set new bandtss members; better approach would be emitting addMember event. + if transition.Status == types.TRANSITION_STATUS_WAITING_EXECUTION { + tssMembers := h.tssKeeper.MustGetMembers(ctx, transition.IncomingGroupID) + for _, tssMember := range tssMembers { + addr := sdk.MustAccAddressFromBech32(tssMember.Address) + member, err := h.bandtssKeeper.GetMember(ctx, addr, transition.IncomingGroupID) + if err != nil { + panic(err) + } + h.emitSetBandtssMember(member) + } + } + + // check if it is a new transition or update the status of the existing transition. + isNewTransition := transition.Status == types.TRANSITION_STATUS_CREATING_GROUP || + (transition.IsForceTransition && transition.Status == types.TRANSITION_STATUS_WAITING_EXECUTION) if isNewTransition { proposalID, found := getCurrentProposalID(eventIdx, querier) diff --git a/hooks/emitter/decoder.go b/hooks/emitter/decoder.go index 355ec426e..c44d65ba1 100644 --- a/hooks/emitter/decoder.go +++ b/hooks/emitter/decoder.go @@ -138,8 +138,8 @@ func DecodeMsg(msg sdk.Msg, detail common.JsDict) { DecodeMsgUpdateParams(msg, detail) case *bandtsstypes.MsgTransitionGroup: DecodeBandtssMsgTransitionGroup(msg, detail) - case *bandtsstypes.MsgForceReplaceGroup: - DecodeBandtssMsgForceReplaceGroup(msg, detail) + case *bandtsstypes.MsgForceTransitionGroup: + DecodeBandtssMsgForceTransitionGroup(msg, detail) case *bandtsstypes.MsgRequestSignature: DecodeBandtssMsgRequestSignature(msg, detail) case *bandtsstypes.MsgActivate: @@ -722,13 +722,13 @@ func DecodeMsgUpdateParams(msg *feedstypes.MsgUpdateParams, detail common.JsDict func DecodeBandtssMsgTransitionGroup(msg *bandtsstypes.MsgTransitionGroup, detail common.JsDict) { detail["members"] = msg.Members detail["threshold"] = msg.Threshold - detail["exec_time"] = msg.ExecTime.GoString() + detail["exec_time"] = msg.ExecTime.UnixNano() detail["authority"] = msg.Authority } -func DecodeBandtssMsgForceReplaceGroup(msg *bandtsstypes.MsgForceReplaceGroup, detail common.JsDict) { +func DecodeBandtssMsgForceTransitionGroup(msg *bandtsstypes.MsgForceTransitionGroup, detail common.JsDict) { detail["incoming_group_id"] = msg.IncomingGroupID - detail["exec_time"] = msg.ExecTime.GoString() + detail["exec_time"] = msg.ExecTime.UnixNano() detail["authority"] = msg.Authority } From 01546e7989ecb56d9b6c9e81c0bf570e46e7b739 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 2 Sep 2024 22:17:38 +0700 Subject: [PATCH 096/132] format .py files --- flusher/flusher/db.py | 150 +++++++++++++--- flusher/flusher/handler.py | 338 +++++++++++++++++++++++++++---------- 2 files changed, 369 insertions(+), 119 deletions(-) diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index 5a084c081..712c0fbc1 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -61,6 +61,7 @@ class CustomDateTime(sa.types.TypeDecorator): def process_bind_param(self, value, dialect): return datetime.fromtimestamp(value / 1e9) if value != None else None + class CustomBase64(sa.types.TypeDecorator): """Custom LargeBinary type that accepts base64-encoded string.""" @@ -158,7 +159,9 @@ def Column(*args, **kwargs): Column("executable", CustomBase64), Column("treasury", sa.String), Column("fee", sa.String), - Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True), + Column( + "transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True + ), Column("accumulated_revenue", sa.BigInteger), Column("last_request", CustomDateTime, nullable=True), ) @@ -173,7 +176,9 @@ def Column(*args, **kwargs): Column("schema", sa.String), Column("codehash", sa.String), Column("source_code_url", sa.String), - Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True), + Column( + "transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True + ), Column("version", sa.Integer, nullable=True), Column("last_request", CustomDateTime, nullable=True), ) @@ -197,13 +202,35 @@ def Column(*args, **kwargs): Column("request_time", sa.Integer, nullable=True, index=True), Column("resolve_status", CustomResolveStatus), Column("resolve_time", sa.Integer, nullable=True), - Column("resolve_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True), + Column( + "resolve_height", + sa.Integer, + sa.ForeignKey("blocks.height"), + nullable=True, + index=True, + ), Column("reason", sa.String, nullable=True), Column("result", CustomBase64, nullable=True), Column("total_fees", sa.String), Column("is_ibc", sa.Boolean), - sa.Index("ix_requests_oracle_script_id_id", "oracle_script_id", "id", postgresql_include=['transaction_id', 'min_count', 'ask_count', 'resolve_status', 'request_time']), - sa.Index("ix_requests_oracle_script_id_resolve_status_request_time", "oracle_script_id", "resolve_status", "request_time"), + sa.Index( + "ix_requests_oracle_script_id_id", + "oracle_script_id", + "id", + postgresql_include=[ + "transaction_id", + "min_count", + "ask_count", + "resolve_status", + "request_time", + ], + ), + sa.Index( + "ix_requests_oracle_script_id_resolve_status_request_time", + "oracle_script_id", + "resolve_status", + "request_time", + ), ) raw_requests = sa.Table( @@ -214,14 +241,18 @@ def Column(*args, **kwargs): Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), index=True), Column("fee", sa.BigInteger), Column("calldata", CustomBase64), - sa.Index("ix_raw_requests_data_source_id_request_id", "data_source_id", "request_id"), + sa.Index( + "ix_raw_requests_data_source_id_request_id", "data_source_id", "request_id" + ), ) val_requests = sa.Table( "val_requests", metadata, Column("request_id", sa.Integer, sa.ForeignKey("requests.id"), primary_key=True), - Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), + Column( + "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True + ), ) reports = sa.Table( @@ -229,7 +260,9 @@ def Column(*args, **kwargs): metadata, Column("request_id", sa.Integer, sa.ForeignKey("requests.id"), primary_key=True), Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id")), - Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), + Column( + "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True + ), Column("reporter_id", sa.Integer, sa.ForeignKey("accounts.id")), sa.Index("ix_reports_validator_id_request_id", "validator_id", "request_id"), ) @@ -242,8 +275,13 @@ def Column(*args, **kwargs): Column("external_id", sa.BigInteger, primary_key=True), Column("data", CustomBase64), Column("exit_code", sa.BigInteger), - sa.ForeignKeyConstraint(["request_id", "validator_id"], ["reports.request_id", "reports.validator_id"]), - sa.ForeignKeyConstraint(["request_id", "external_id"], ["raw_requests.request_id", "raw_requests.external_id"]), + sa.ForeignKeyConstraint( + ["request_id", "validator_id"], ["reports.request_id", "reports.validator_id"] + ), + sa.ForeignKeyConstraint( + ["request_id", "external_id"], + ["raw_requests.request_id", "raw_requests.external_id"], + ), ) validators = sa.Table( @@ -275,7 +313,9 @@ def Column(*args, **kwargs): delegations = sa.Table( "delegations", metadata, - Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), + Column( + "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True + ), Column("delegator_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), Column("shares", sa.DECIMAL), Column("last_ratio", sa.DECIMAL), @@ -284,8 +324,15 @@ def Column(*args, **kwargs): validator_votes = sa.Table( "validator_votes", metadata, - Column("block_height", sa.Integer, sa.ForeignKey("blocks.height"), primary_key=True), - Column("consensus_address", sa.String, sa.ForeignKey("validators.consensus_address"), primary_key=True), + Column( + "block_height", sa.Integer, sa.ForeignKey("blocks.height"), primary_key=True + ), + Column( + "consensus_address", + sa.String, + sa.ForeignKey("validators.consensus_address"), + primary_key=True, + ), Column("voted", sa.Boolean), ) @@ -294,7 +341,9 @@ def Column(*args, **kwargs): metadata, Column("delegator_id", sa.Integer, sa.ForeignKey("accounts.id")), Column("validator_id", sa.Integer, sa.ForeignKey("validators.id")), - Column("creation_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True), + Column( + "creation_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True + ), Column("completion_time", CustomDateTime), Column("amount", sa.DECIMAL), ) @@ -312,9 +361,15 @@ def Column(*args, **kwargs): account_transactions = sa.Table( "account_transactions", metadata, - Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), primary_key=True), + Column( + "transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), primary_key=True + ), Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), - sa.Index("ix_account_transactions_account_id_transaction_id", "account_id", "transaction_id"), + sa.Index( + "ix_account_transactions_account_id_transaction_id", + "account_id", + "transaction_id", + ), ) proposals = sa.Table( @@ -364,7 +419,9 @@ def Column(*args, **kwargs): historical_bonded_token_on_validators = sa.Table( "historical_bonded_token_on_validators", metadata, - Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), + Column( + "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True + ), Column("bonded_tokens", sa.DECIMAL), Column("timestamp", CustomDateTime, primary_key=True), ) @@ -379,8 +436,15 @@ def Column(*args, **kwargs): related_data_source_oracle_scripts = sa.Table( "related_data_source_oracle_scripts", metadata, - Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True), - Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True), + Column( + "data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True + ), + Column( + "oracle_script_id", + sa.Integer, + sa.ForeignKey("oracle_scripts.id"), + primary_key=True, + ), ) historical_oracle_statuses = sa.Table( @@ -394,7 +458,9 @@ def Column(*args, **kwargs): data_source_requests = sa.Table( "data_source_requests", metadata, - Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True), + Column( + "data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True + ), Column("count", sa.Integer), ) @@ -402,14 +468,21 @@ def Column(*args, **kwargs): "data_source_requests_per_days", metadata, Column("date", CustomDate, primary_key=True), - Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True), + Column( + "data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True + ), Column("count", sa.Integer), ) oracle_script_requests = sa.Table( "oracle_script_requests", metadata, - Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True), + Column( + "oracle_script_id", + sa.Integer, + sa.ForeignKey("oracle_scripts.id"), + primary_key=True, + ), Column("count", sa.Integer), ) @@ -417,7 +490,12 @@ def Column(*args, **kwargs): "oracle_script_requests_per_days", metadata, Column("date", CustomDate, primary_key=True), - Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True), + Column( + "oracle_script_id", + sa.Integer, + sa.ForeignKey("oracle_scripts.id"), + primary_key=True, + ), Column("count", sa.Integer), ) @@ -441,7 +519,9 @@ def Column(*args, **kwargs): Column("type", sa.String, nullable=True), Column("data", sa.JSON, nullable=True), Column("acknowledgement", sa.JSON, nullable=True), - sa.ForeignKeyConstraint(["dst_port", "dst_channel"], ["channels.port", "channels.channel"]), + sa.ForeignKeyConstraint( + ["dst_port", "dst_channel"], ["channels.port", "channels.channel"] + ), ) outgoing_packets = sa.Table( @@ -457,15 +537,24 @@ def Column(*args, **kwargs): Column("type", sa.String, nullable=True), Column("data", sa.JSON, nullable=True), Column("acknowledgement", sa.JSON, nullable=True), - sa.ForeignKeyConstraint(["src_port", "src_channel"], ["channels.port", "channels.channel"]), + sa.ForeignKeyConstraint( + ["src_port", "src_channel"], ["channels.port", "channels.channel"] + ), ) -counterparty_chains = sa.Table("counterparty_chains", metadata, Column("chain_id", sa.String, primary_key=True)) +counterparty_chains = sa.Table( + "counterparty_chains", metadata, Column("chain_id", sa.String, primary_key=True) +) connections = sa.Table( "connections", metadata, - Column("counterparty_chain_id", sa.String, sa.ForeignKey("counterparty_chains.chain_id"), primary_key=True), + Column( + "counterparty_chain_id", + sa.String, + sa.ForeignKey("counterparty_chains.chain_id"), + primary_key=True, + ), Column("counterparty_connection_id", sa.String), Column("client_id", sa.String), Column("counterparty_client_id", sa.String), @@ -550,7 +639,12 @@ def Column(*args, **kwargs): group_votes = sa.Table( "group_votes", metadata, - Column("group_proposal_id", sa.Integer, sa.ForeignKey("group_proposals.id"), primary_key=True), + Column( + "group_proposal_id", + sa.Integer, + sa.ForeignKey("group_proposals.id"), + primary_key=True, + ), Column("voter_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), Column("option", sa.String), Column("metadata", sa.String), diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 876baaae8..0e322c9e3 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -61,46 +61,77 @@ def __init__(self, conn): self.conn = conn def get_transaction_id(self, tx_hash): - return self.conn.execute(select([transactions.c.id]).where(transactions.c.hash == tx_hash)).scalar() + return self.conn.execute( + select([transactions.c.id]).where(transactions.c.hash == tx_hash) + ).scalar() def get_transaction_sender(self, id): - return self.conn.execute(select([transactions.c.sender]).where(transactions.c.id == id)).scalar() + return self.conn.execute( + select([transactions.c.sender]).where(transactions.c.id == id) + ).scalar() def get_validator_id(self, val): - return self.conn.execute(select([validators.c.id]).where(validators.c.operator_address == val)).scalar() + return self.conn.execute( + select([validators.c.id]).where(validators.c.operator_address == val) + ).scalar() def get_account_id(self, address): if address is None: return None - id = self.conn.execute(select([accounts.c.id]).where(accounts.c.address == address)).scalar() + id = self.conn.execute( + select([accounts.c.id]).where(accounts.c.address == address) + ).scalar() if id is None: - self.conn.execute(accounts.insert(), {"address": address, "balance": "0uband"}) - return self.conn.execute(select([accounts.c.id]).where(accounts.c.address == address)).scalar() + self.conn.execute( + accounts.insert(), {"address": address, "balance": "0uband"} + ) + return self.conn.execute( + select([accounts.c.id]).where(accounts.c.address == address) + ).scalar() return id def get_request_count(self, date): return self.conn.execute( - select([request_count_per_days.c.count]).where(request_count_per_days.c.date == date) + select([request_count_per_days.c.count]).where( + request_count_per_days.c.date == date + ) ).scalar() def get_oracle_script_requests_count_per_day(self, date, oracle_script_id): return self.conn.execute( - select([oracle_script_requests_per_days.c.count]).where((oracle_script_requests_per_days.c.date == date) & (oracle_script_requests_per_days.c.oracle_script_id == oracle_script_id)) + select([oracle_script_requests_per_days.c.count]).where( + (oracle_script_requests_per_days.c.date == date) + & ( + oracle_script_requests_per_days.c.oracle_script_id + == oracle_script_id + ) + ) ).scalar() def get_data_source_requests_count_per_day(self, date, data_source_id): return self.conn.execute( - select([data_source_requests_per_days.c.count]).where((data_source_requests_per_days.c.date == date) & (data_source_requests_per_days.c.data_source_id == data_source_id)) + select([data_source_requests_per_days.c.count]).where( + (data_source_requests_per_days.c.date == date) + & (data_source_requests_per_days.c.data_source_id == data_source_id) + ) ).scalar() def get_data_source_id(self, id): - return self.conn.execute(select([data_sources.c.id]).where(data_sources.c.id == id)).scalar() + return self.conn.execute( + select([data_sources.c.id]).where(data_sources.c.id == id) + ).scalar() def get_oracle_script_id(self, id): - return self.conn.execute(select([oracle_scripts.c.id]).where(oracle_scripts.c.id == id)).scalar() + return self.conn.execute( + select([oracle_scripts.c.id]).where(oracle_scripts.c.id == id) + ).scalar() def get_group_id_from_policy_address(self, address): - return self.conn.execute(select([group_policies.c.group_id]).where(group_policies.c.address == address)).scalar() + return self.conn.execute( + select([group_policies.c.group_id]).where( + group_policies.c.address == address + ) + ).scalar() def get_ibc_received_txs(self, date, port, channel, address): msg = {"date": date, "port": port, "channel": channel, "address": address} @@ -108,15 +139,21 @@ def get_ibc_received_txs(self, date, port, channel, address): for col in relayer_tx_stat_days.primary_key.columns.values(): condition = (col == msg[col.name]) & condition - return self.conn.execute(select([relayer_tx_stat_days.c.ibc_received_txs]).where(condition)).scalar() + return self.conn.execute( + select([relayer_tx_stat_days.c.ibc_received_txs]).where(condition) + ).scalar() def handle_new_block(self, msg): self.conn.execute(blocks.insert(), msg) def handle_new_transaction(self, msg): - msg["fee_payer"] = msg["fee_payer"] if "fee_payer" in msg and len(msg["fee_payer"]) else None + msg["fee_payer"] = ( + msg["fee_payer"] if "fee_payer" in msg and len(msg["fee_payer"]) else None + ) self.conn.execute( - insert(transactions).values(**msg).on_conflict_do_update(constraint="transactions_pkey", set_=msg) + insert(transactions) + .values(**msg) + .on_conflict_do_update(constraint="transactions_pkey", set_=msg) ) def handle_set_related_transaction(self, msg): @@ -125,7 +162,12 @@ def handle_set_related_transaction(self, msg): for account in related_tx_accounts: self.conn.execute( insert(account_transactions) - .values({"transaction_id": tx_id, "account_id": self.get_account_id(account)}) + .values( + { + "transaction_id": tx_id, + "account_id": self.get_account_id(account), + } + ) .on_conflict_do_nothing(constraint="account_transactions_pkey") ) @@ -170,7 +212,9 @@ def handle_new_group_policy(self, msg): self.conn.execute(group_policies.insert(), msg) def handle_new_group_proposal(self, msg): - msg["group_id"] = self.get_group_id_from_policy_address(msg["group_policy_address"]) + msg["group_id"] = self.get_group_id_from_policy_address( + msg["group_policy_address"] + ) self.conn.execute(group_proposals.insert(), msg) def handle_new_group_vote(self, msg): @@ -183,21 +227,42 @@ def handle_update_group(self, msg): def handle_remove_group_member(self, msg): account_id = self.get_account_id(msg["address"]) - self.conn.execute(group_members.delete().where((group_members.c.group_id == msg["group_id"]) & (group_members.c.account_id == account_id))) + self.conn.execute( + group_members.delete().where( + (group_members.c.group_id == msg["group_id"]) + & (group_members.c.account_id == account_id) + ) + ) def handle_remove_group_members_by_group_id(self, msg): - self.conn.execute(group_members.delete().where(group_members.c.group_id == msg["group_id"])) + self.conn.execute( + group_members.delete().where(group_members.c.group_id == msg["group_id"]) + ) def handle_update_group_policy(self, msg): - self.conn.execute(group_policies.update().where(group_policies.c.address == msg["address"]).values(**msg)) - + self.conn.execute( + group_policies.update() + .where(group_policies.c.address == msg["address"]) + .values(**msg) + ) + def handle_update_group_proposal(self, msg): - msg["group_id"] = self.get_group_id_from_policy_address(msg["group_policy_address"]) - self.conn.execute(group_proposals.update().where(group_proposals.c.id == msg["id"]).values(**msg)) + msg["group_id"] = self.get_group_id_from_policy_address( + msg["group_policy_address"] + ) + self.conn.execute( + group_proposals.update() + .where(group_proposals.c.id == msg["id"]) + .values(**msg) + ) def handle_update_group_proposal_by_id(self, msg): - self.conn.execute(group_proposals.update().where(group_proposals.c.id == msg["id"]).values(**msg)) - + self.conn.execute( + group_proposals.update() + .where(group_proposals.c.id == msg["id"]) + .values(**msg) + ) + def handle_set_data_source(self, msg): msg["transaction_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] @@ -226,8 +291,12 @@ def handle_new_request(self, msg): del msg["tx_hash"] if "timestamp" in msg: self.handle_set_request_count_per_day({"date": msg["timestamp"]}) - self.handle_update_oracle_script_requests_count_per_day({"date": msg["timestamp"], "oracle_script_id": msg["oracle_script_id"]}) - self.update_oracle_script_last_request(msg["oracle_script_id"], msg["timestamp"]) + self.handle_update_oracle_script_requests_count_per_day( + {"date": msg["timestamp"], "oracle_script_id": msg["oracle_script_id"]} + ) + self.update_oracle_script_last_request( + msg["oracle_script_id"], msg["timestamp"] + ) del msg["timestamp"] self.conn.execute(requests.insert(), msg) self.increase_oracle_script_count(msg["oracle_script_id"]) @@ -245,19 +314,27 @@ def handle_update_related_ds_os(self, msg): self.conn.execute( insert(related_data_source_oracle_scripts) .values(**msg) - .on_conflict_do_nothing(constraint="related_data_source_oracle_scripts_pkey") + .on_conflict_do_nothing( + constraint="related_data_source_oracle_scripts_pkey" + ) ) def handle_new_raw_request(self, msg): self.increase_data_source_count(msg["data_source_id"]) if "timestamp" in msg: - self.handle_update_data_source_requests_count_per_day({"date": msg["timestamp"], "data_source_id": msg["data_source_id"]}) - self.update_data_source_last_request(msg["data_source_id"], msg["timestamp"]) + self.handle_update_data_source_requests_count_per_day( + {"date": msg["timestamp"], "data_source_id": msg["data_source_id"]} + ) + self.update_data_source_last_request( + msg["data_source_id"], msg["timestamp"] + ) del msg["timestamp"] self.handle_update_related_ds_os( { "oracle_script_id": self.conn.execute( - select([requests.c.oracle_script_id]).where(requests.c.id == msg["request_id"]) + select([requests.c.oracle_script_id]).where( + requests.c.id == msg["request_id"] + ) ).scalar(), "data_source_id": msg["data_source_id"], } @@ -323,7 +400,9 @@ def handle_update_validator(self, msg): ) del msg["last_update"] self.conn.execute( - validators.update().where(validators.c.operator_address == msg["operator_address"]).values(**msg) + validators.update() + .where(validators.c.operator_address == msg["operator_address"]) + .values(**msg) ) def handle_set_delegation(self, msg): @@ -332,7 +411,9 @@ def handle_set_delegation(self, msg): msg["validator_id"] = self.get_validator_id(msg["operator_address"]) del msg["operator_address"] self.conn.execute( - insert(delegations).values(**msg).on_conflict_do_update(constraint="delegations_pkey", set_=msg) + insert(delegations) + .values(**msg) + .on_conflict_do_update(constraint="delegations_pkey", set_=msg) ) def handle_update_delegation(self, msg): @@ -367,7 +448,9 @@ def handle_new_unbonding_delegation(self, msg): def handle_remove_unbonding(self, msg): self.conn.execute( - unbonding_delegations.delete().where(unbonding_delegations.c.completion_time <= msg["timestamp"]) + unbonding_delegations.delete().where( + unbonding_delegations.c.completion_time <= msg["timestamp"] + ) ) def handle_new_redelegation(self, msg): @@ -380,7 +463,11 @@ def handle_new_redelegation(self, msg): self.conn.execute(insert(redelegations).values(**msg)) def handle_remove_redelegation(self, msg): - self.conn.execute(redelegations.delete().where(redelegations.c.completion_time <= msg["timestamp"])) + self.conn.execute( + redelegations.delete().where( + redelegations.c.completion_time <= msg["timestamp"] + ) + ) def handle_new_proposal(self, msg): msg["proposer_id"] = self.get_account_id(msg["proposer"]) @@ -392,14 +479,22 @@ def handle_set_deposit(self, msg): del msg["depositor"] msg["tx_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] - self.conn.execute(insert(deposits).values(**msg).on_conflict_do_update(constraint="deposits_pkey", set_=msg)) + self.conn.execute( + insert(deposits) + .values(**msg) + .on_conflict_do_update(constraint="deposits_pkey", set_=msg) + ) def handle_set_vote_weighted(self, msg): msg["voter_id"] = self.get_account_id(msg["voter"]) del msg["voter"] msg["tx_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] - self.conn.execute(insert(votes).values(**msg).on_conflict_do_update(constraint="votes_pkey", set_=msg)) + self.conn.execute( + insert(votes) + .values(**msg) + .on_conflict_do_update(constraint="votes_pkey", set_=msg) + ) def handle_update_proposal(self, msg): condition = True @@ -413,7 +508,9 @@ def handle_set_historical_bonded_token_on_validator(self, msg): self.conn.execute( insert(historical_bonded_token_on_validators) .values(**msg) - .on_conflict_do_update(constraint="historical_bonded_token_on_validators_pkey", set_=msg) + .on_conflict_do_update( + constraint="historical_bonded_token_on_validators_pkey", set_=msg + ) ) def handle_set_reporter(self, msg): @@ -421,7 +518,11 @@ def handle_set_reporter(self, msg): del msg["validator"] msg["reporter_id"] = self.get_account_id(msg["reporter"]) del msg["reporter"] - self.conn.execute(insert(reporters).values(msg).on_conflict_do_nothing(constraint="reporters_pkey")) + self.conn.execute( + insert(reporters) + .values(msg) + .on_conflict_do_nothing(constraint="reporters_pkey") + ) def handle_remove_reporter(self, msg): msg["operator_address"] = msg["validator"] @@ -437,7 +538,9 @@ def handle_set_historical_validator_status(self, msg): self.conn.execute( insert(historical_oracle_statuses) .values(**msg) - .on_conflict_do_update(constraint="historical_oracle_statuses_pkey", set_=msg) + .on_conflict_do_update( + constraint="historical_oracle_statuses_pkey", set_=msg + ) ) def init_data_source_request_count(self, id): @@ -449,9 +552,9 @@ def init_data_source_request_count(self, id): def increase_data_source_count(self, id): self.conn.execute( - data_source_requests.update(data_source_requests.c.data_source_id == id).values( - count=data_source_requests.c.count + 1 - ) + data_source_requests.update( + data_source_requests.c.data_source_id == id + ).values(count=data_source_requests.c.count + 1) ) def init_oracle_script_request_count(self, id): @@ -465,7 +568,11 @@ def handle_update_oracle_script_request(self, msg): condition = True for col in oracle_script_requests.primary_key.columns.values(): condition = (col == msg[col.name]) & condition - self.conn.execute(oracle_script_requests.update(condition).values(count=oracle_script_requests.c.count + 1)) + self.conn.execute( + oracle_script_requests.update(condition).values( + count=oracle_script_requests.c.count + 1 + ) + ) def handle_set_request_count_per_day(self, msg): if self.get_request_count(msg["date"]) is None: @@ -476,11 +583,18 @@ def handle_set_request_count_per_day(self, msg): for col in request_count_per_days.primary_key.columns.values(): condition = (col == msg[col.name]) & condition self.conn.execute( - request_count_per_days.update(condition).values(count=request_count_per_days.c.count + 1) + request_count_per_days.update(condition).values( + count=request_count_per_days.c.count + 1 + ) ) def handle_update_oracle_script_requests_count_per_day(self, msg): - if self.get_oracle_script_requests_count_per_day(msg["date"], msg["oracle_script_id"]) is None: + if ( + self.get_oracle_script_requests_count_per_day( + msg["date"], msg["oracle_script_id"] + ) + is None + ): msg["count"] = 1 self.conn.execute(oracle_script_requests_per_days.insert(), msg) else: @@ -488,11 +602,18 @@ def handle_update_oracle_script_requests_count_per_day(self, msg): for col in oracle_script_requests_per_days.primary_key.columns.values(): condition = (col == msg[col.name]) & condition self.conn.execute( - oracle_script_requests_per_days.update(condition).values(count=oracle_script_requests_per_days.c.count + 1) + oracle_script_requests_per_days.update(condition).values( + count=oracle_script_requests_per_days.c.count + 1 + ) ) def handle_update_data_source_requests_count_per_day(self, msg): - if self.get_data_source_requests_count_per_day(msg["date"], msg["data_source_id"]) is None: + if ( + self.get_data_source_requests_count_per_day( + msg["date"], msg["data_source_id"] + ) + is None + ): msg["count"] = 1 self.conn.execute(data_source_requests_per_days.insert(), msg) else: @@ -500,37 +621,51 @@ def handle_update_data_source_requests_count_per_day(self, msg): for col in data_source_requests_per_days.primary_key.columns.values(): condition = (col == msg[col.name]) & condition self.conn.execute( - data_source_requests_per_days.update(condition).values(count=data_source_requests_per_days.c.count + 1) + data_source_requests_per_days.update(condition).values( + count=data_source_requests_per_days.c.count + 1 + ) ) def handle_new_incoming_packet(self, msg): - self.update_last_update_channel(msg["dst_port"], msg["dst_channel"], msg["block_time"]) + self.update_last_update_channel( + msg["dst_port"], msg["dst_channel"], msg["block_time"] + ) msg["tx_id"] = self.get_transaction_id(msg["hash"]) del msg["hash"] msg["sender"] = self.get_transaction_sender(msg["tx_id"]) - self.handle_set_relayer_tx_stat_days(msg["dst_port"], msg["dst_channel"], msg["block_time"], msg["sender"]) + self.handle_set_relayer_tx_stat_days( + msg["dst_port"], msg["dst_channel"], msg["block_time"], msg["sender"] + ) del msg["block_time"] del msg["sender"] self.conn.execute( - insert(incoming_packets).values(**msg).on_conflict_do_nothing(constraint="incoming_packets_pkey") + insert(incoming_packets) + .values(**msg) + .on_conflict_do_nothing(constraint="incoming_packets_pkey") ) def handle_new_outgoing_packet(self, msg): - self.update_last_update_channel(msg["src_port"], msg["src_channel"], msg["block_time"]) + self.update_last_update_channel( + msg["src_port"], msg["src_channel"], msg["block_time"] + ) del msg["block_time"] msg["tx_id"] = self.get_transaction_id(msg["hash"]) del msg["hash"] self.conn.execute( - insert(outgoing_packets).values(**msg).on_conflict_do_nothing(constraint="outgoing_packets_pkey") + insert(outgoing_packets) + .values(**msg) + .on_conflict_do_nothing(constraint="outgoing_packets_pkey") ) def handle_update_outgoing_packet(self, msg): - self.update_last_update_channel(msg["src_port"], msg["src_channel"], msg["block_time"]) + self.update_last_update_channel( + msg["src_port"], msg["src_channel"], msg["block_time"] + ) del msg["block_time"] condition = True @@ -540,9 +675,9 @@ def handle_update_outgoing_packet(self, msg): def increase_oracle_script_count(self, id): self.conn.execute( - oracle_script_requests.update(oracle_script_requests.c.oracle_script_id == id).values( - count=oracle_script_requests.c.count + 1 - ) + oracle_script_requests.update( + oracle_script_requests.c.oracle_script_id == id + ).values(count=oracle_script_requests.c.count + 1) ) def update_oracle_script_last_request(self, id, timestamp): @@ -554,16 +689,16 @@ def update_oracle_script_last_request(self, id, timestamp): def update_data_source_last_request(self, id, timestamp): self.conn.execute( - data_sources.update(data_sources.c.id == id).values( - last_request=timestamp - ) + data_sources.update(data_sources.c.id == id).values(last_request=timestamp) ) def handle_new_historical_bonded_token_on_validator(self, msg): self.conn.execute( insert(historical_bonded_token_on_validators) .values(**msg) - .on_conflict_do_update(constraint="historical_bonded_token_on_validators_pkey", set_=msg) + .on_conflict_do_update( + constraint="historical_bonded_token_on_validators_pkey", set_=msg + ) ) def handle_set_counterparty_chain(self, msg): @@ -575,11 +710,17 @@ def handle_set_counterparty_chain(self, msg): def handle_set_connection(self, msg): self.conn.execute( - insert(connections).values(**msg).on_conflict_do_update(constraint="connections_pkey", set_=msg) + insert(connections) + .values(**msg) + .on_conflict_do_update(constraint="connections_pkey", set_=msg) ) def handle_set_channel(self, msg): - self.conn.execute(insert(channels).values(**msg).on_conflict_do_update(constraint="channels_pkey", set_=msg)) + self.conn.execute( + insert(channels) + .values(**msg) + .on_conflict_do_update(constraint="channels_pkey", set_=msg) + ) def update_last_update_channel(self, port, channel, timestamp): self.conn.execute( @@ -615,67 +756,82 @@ def handle_set_relayer_tx_stat_days(self, port, channel, timestamp, address): self.conn.execute( relayer_tx_stat_days.update() .where(condition) - .values(ibc_received_txs=relayer_tx_stat_days.c.ibc_received_txs + 1, last_update_at=timestamp) + .values( + ibc_received_txs=relayer_tx_stat_days.c.ibc_received_txs + 1, + last_update_at=timestamp, + ) ) def handle_set_validator_price(self, msg): msg["validator_id"] = self.get_validator_id(msg["validator"]) - del msg["validator"] + del msg["validator"] self.conn.execute( - insert(validator_prices).values(**msg).on_conflict_do_update(constraint="validator_prices_pkey", set_=msg) + insert(validator_prices) + .values(**msg) + .on_conflict_do_update(constraint="validator_prices_pkey", set_=msg) ) - + def handle_remove_validator_prices(self, msg): self.conn.execute( - validator_prices.delete().where(validator_prices.c.signal_id == msg["signal_id"]) + validator_prices.delete().where( + validator_prices.c.signal_id == msg["signal_id"] + ) ) - + def handle_set_delegator_signal(self, msg): msg["account_id"] = self.get_account_id(msg["delegator"]) - del msg["delegator"] + del msg["delegator"] self.conn.execute( - insert(delegator_signals).values(**msg).on_conflict_do_update(constraint="delegator_signals_pkey", set_=msg) + insert(delegator_signals) + .values(**msg) + .on_conflict_do_update(constraint="delegator_signals_pkey", set_=msg) ) - + def handle_remove_delegator_signals(self, msg): self.conn.execute( - delegator_signals.delete().where(delegator_signals.c.account_id == self.get_account_id(msg["delegator"])) + delegator_signals.delete().where( + delegator_signals.c.account_id == self.get_account_id(msg["delegator"]) + ) ) - + def handle_set_signal_total_power(self, msg): self.conn.execute( - insert(signal_total_powers).values(**msg).on_conflict_do_update(constraint="signal_total_powers_pkey", set_=msg) + insert(signal_total_powers) + .values(**msg) + .on_conflict_do_update(constraint="signal_total_powers_pkey", set_=msg) ) def handle_remove_signal_total_power(self, msg): self.conn.execute( - signal_total_powers.delete().where(signal_total_powers.c.signal_id == msg["signal_id"]) + signal_total_powers.delete().where( + signal_total_powers.c.signal_id == msg["signal_id"] + ) ) - + def handle_set_price(self, msg): + self.conn.execute(insert(prices).values(**msg)) self.conn.execute( - insert(prices).values(**msg) - ) - self.conn.execute( - prices.delete().where(prices.c.timestamp < msg["timestamp"] - 60 * 60 * 24 * 7 * 10e8) + prices.delete().where( + prices.c.timestamp < msg["timestamp"] - 60 * 60 * 24 * 7 * 10e8 + ) ) def handle_remove_price(self, msg): - self.conn.execute( - prices.delete().where(prices.c.signal_id == msg["signal_id"]) - ) - + self.conn.execute(prices.delete().where(prices.c.signal_id == msg["signal_id"])) + def handle_set_reference_source_config(self, msg): - self.conn.execute( - insert(reference_source_configs).values(**msg) - ) - + self.conn.execute(insert(reference_source_configs).values(**msg)) + def handle_set_feeder(self, msg): msg["operator_address"] = msg["validator"] del msg["validator"] msg["feeder_id"] = self.get_account_id(msg["feeder"]) del msg["feeder"] - self.conn.execute(insert(feeders).values(msg).on_conflict_do_nothing(constraint="feeders_pkey")) + self.conn.execute( + insert(feeders) + .values(msg) + .on_conflict_do_nothing(constraint="feeders_pkey") + ) def handle_remove_feeder(self, msg): msg["operator_address"] = msg["validator"] From 692c70f3eff57e2898ee5db14fc3797a98cd487f Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 2 Sep 2024 23:21:58 +0700 Subject: [PATCH 097/132] fix decoder test --- hooks/emitter/decoder_test.go | 90 +++++++++++++++++++++++------------ 1 file changed, 59 insertions(+), 31 deletions(-) diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index bab84d27a..01692e0c3 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -29,6 +29,7 @@ import ( "github.com/bandprotocol/chain/v2/pkg/tss" bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/testing/ibctesting" + bandtsstypes "github.com/bandprotocol/chain/v2/x/bandtss/types" feedstypes "github.com/bandprotocol/chain/v2/x/feeds/types" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" tsstypes "github.com/bandprotocol/chain/v2/x/tss/types" @@ -957,47 +958,74 @@ func (suite *DecoderTestSuite) TestDecodeMsgUpdatePriceService() { ) } -// func (suite *DecoderTestSuite) TestDecodeGroupMsgCreateGroupBandtss() { -// detail := make(common.JsDict) +func (suite *DecoderTestSuite) TestDecodeBandtssMsgTransitionGroup() { + detail := make(common.JsDict) + + msg := bandtsstypes.MsgTransitionGroup{ + Members: []string{"member1", "member2"}, + Threshold: 2, + Authority: "some-authority-id", + ExecTime: time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC), + } + + emitter.DecodeBandtssMsgTransitionGroup(&msg, detail) + + expectedJSON := `{"authority":"some-authority-id","exec_time":1577923200000000000,"members":["member1","member2"],"threshold":2}` + suite.testCompareJson(detail, expectedJSON) +} -// msg := bandtsstypes.MsgCreateGroup{ -// Members: []string{"member1", "member2"}, -// Threshold: 2, -// Authority: "some-authority-id", -// } +func (suite *DecoderTestSuite) TestDecodeGroupMsgReplaceGroup() { + detail := make(common.JsDict) + + msg := bandtsstypes.MsgForceTransitionGroup{ + IncomingGroupID: 1, + ExecTime: time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC), + Authority: "authority123", + } + + emitter.DecodeBandtssMsgForceTransitionGroup(&msg, detail) + + expectedJSON := `{"authority":"authority123","exec_time":1577923200000000000,"incoming_group_id":1}` + suite.testCompareJson(detail, expectedJSON) +} -// emitter.DecodeGroupMsgCreateGroupBandtss(&msg, detail) +func (suite *DecoderTestSuite) TestDecodeBandtssMsgUpdateParams() { + detail := make(common.JsDict) -// expectedJSON := `{"authority":"some-authority-id","members":["member1","member2"],"threshold":2}` -// suite.testCompareJson(detail, expectedJSON) -// } + msg := bandtsstypes.MsgUpdateParams{ + Params: bandtsstypes.NewParams(100, 10, 50, sdk.Coins{Amount}), + } -// func (suite *DecoderTestSuite) TestDecodeGroupMsgReplaceGroup() { -// detail := make(common.JsDict) + emitter.DecodeBandtssMsgUpdateParams(&msg, detail) + expectedJSON := `{"active_duration":100,"authority":"","fee":[{"denom":"uband","amount":"1"}],"inactive_penalty_duration":50,"max_transition_duration":432000000000000,"reward_percentage":10}` + suite.testCompareJson(detail, expectedJSON) +} -// msg := bandtsstypes.MsgReplaceGroup{ -// NewGroupID: 1, -// ExecTime: time.Now(), -// Authority: "authority123", -// } +func (suite *DecoderTestSuite) TestDecodeBandtssMsgHeartbeat() { + detail := make(common.JsDict) -// emitter.DecodeGroupMsgReplaceGroup(&msg, detail) + msg := bandtsstypes.MsgHeartbeat{ + Sender: "0x123", + GroupID: 1, + } -// expectedJSON := `{"authority":"authority123","exec_time":"` + msg.ExecTime.GoString() + `","new_group_id":1}` -// suite.testCompareJson(detail, expectedJSON) -// } + emitter.DecodeBandtssMsgHeartbeat(&msg, detail) + expectedJSON := `{"group_id":1,"sender":"0x123"}` + suite.testCompareJson(detail, expectedJSON) +} -// func (suite *DecoderTestSuite) TestDecodeMsgUpdateParamsBandtss() { -// detail := make(common.JsDict) +func (suite *DecoderTestSuite) TestDecodeBandtssMsgActivate() { + detail := make(common.JsDict) -// msg := bandtsstypes.MsgUpdateParams{ -// Params: bandtsstypes.NewParams(100, 10, 50, sdk.Coins{Amount}), -// } + msg := bandtsstypes.MsgActivate{ + Sender: "0x123", + GroupID: 1, + } -// emitter.DecodeMsgUpdateParamsBandtss(&msg, detail) -// expectedJSON := "{\"active_duration\":100,\"authority\":\"\",\"fee\":[{\"denom\":\"uband\",\"amount\":\"1\"}],\"inactive_penalty_duration\":50,\"reward_percentage\":10}" -// suite.testCompareJson(detail, expectedJSON) -// } + emitter.DecodeBandtssMsgActivate(&msg, detail) + expectedJSON := `{"group_id":1,"sender":"0x123"}` + suite.testCompareJson(detail, expectedJSON) +} func (suite *DecoderTestSuite) TestDecodeMsgSubmitDKGRound1() { detail := make(common.JsDict) From d9e64ca068d04bb629e7e7b78b84b82eb5bb16c2 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 3 Sep 2024 10:33:19 +0700 Subject: [PATCH 098/132] fix tss signing and bandtss group transition --- flusher/flusher/handler.py | 33 +++++++++++++++++++++--------- hasura/hasura-metadata/tables.yaml | 14 +++++++++++++ hooks/emitter/bandtss.go | 8 ++++---- hooks/emitter/tss.go | 6 +++--- 4 files changed, 44 insertions(+), 17 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 436373cdd..df2ccf5a5 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -795,8 +795,12 @@ def handle_set_relayer_tx_stat_days(self, port, channel, timestamp, address): # TSS_HANDLER ################################## - def handle_new_tss_signing(self, msg): - self.conn.execute(tss_signings.insert(), msg) + def handle_set_tss_signing(self, msg): + self.conn.execute( + insert(tss_signings) + .values(**msg) + .on_conflict_do_update(constraint="tss_signings_pkey", set_=msg) + ) def handle_update_tss_signing(self, msg): condition = True @@ -835,16 +839,23 @@ def handle_update_tss_assigned_member(self, msg): ################################## def handle_set_bandtss_group_transition(self, msg): - if msg["tss_signing_id"] == 0: + if "tss_signing_id" in msg and msg["tss_signing_id"] == 0: del msg["tss_signing_id"] - if msg["current_tss_group_id"] == 0: + if "current_tss_group_id" in msg and msg["current_tss_group_id"] == 0: del msg["current_tss_group_id"] - if msg["incoming_tss_group_id"] == 0: + if "incoming_tss_group_id" in msg and msg["incoming_tss_group_id"] == 0: del msg["incoming_tss_group_id"] self.conn.execute(bandtss_group_transitions.insert(), msg) - def update_bandtss_group_transition(self, status): + def update_bandtss_group_transition(self, msg): + if "tss_signing_id" in msg and msg["tss_signing_id"] == 0: + del msg["tss_signing_id"] + if "current_tss_group_id" in msg and msg["current_tss_group_id"] == 0: + del msg["current_tss_group_id"] + if "incoming_tss_group_id" in msg and msg["incoming_tss_group_id"] == 0: + del msg["incoming_tss_group_id"] + proposal_column = bandtss_group_transitions.c.proposal_id proposal_id = self.conn.execute(select(func.max(proposal_column))).scalar() if proposal_id is None: @@ -853,17 +864,19 @@ def update_bandtss_group_transition(self, status): self.conn.execute( bandtss_group_transitions.update() .where(proposal_column == proposal_id) - .values(status=status) + .values(**msg) ) def handle_update_bandtss_group_transition(self, msg): - self.update_bandtss_group_transition(msg["status"]) + self.update_bandtss_group_transition(msg) def handle_update_bandtss_group_transition_success(self, msg): - self.update_bandtss_group_transition(GroupTransitionStatus.success) + msg = {"status": GroupTransitionStatus.success} + self.update_bandtss_group_transition(msg) def handle_update_bandtss_group_transition_failed(self, msg): - self.update_bandtss_group_transition(GroupTransitionStatus.expired) + msg = {"status": GroupTransitionStatus.expired} + self.update_bandtss_group_transition(msg) def handle_set_bandtss_current_group(self, msg): proposal_column = bandtss_group_transitions.c.proposal_id diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index e1bf4156e..f3421b918 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -688,6 +688,13 @@ name: bandtss_group_transitions schema: public array_relationships: + - name: bandtss_current_groups + using: + foreign_key_constraint_on: + column: proposal_id + table: + name: bandtss_current_groups + schema: public - name: deposits using: foreign_key_constraint_on: @@ -995,6 +1002,13 @@ table: name: bandtss_group_transitions schema: public + - name: bandtss_members + using: + foreign_key_constraint_on: + column: tss_group_id + table: + name: bandtss_members + schema: public - name: tss_assigned_members using: foreign_key_constraint_on: diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index 0e1a14cb4..2fb32e6b7 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -31,10 +31,10 @@ func (h *Hook) emitSetBandtssGroupTransition( func (h *Hook) emitUpdateBandtssGroupTransitionStatus(transition types.GroupTransition) { h.Write("UPDATE_BANDTSS_GROUP_TRANSITION", common.JsDict{ - "tss_signing_id": transition.SigningID, - "current_tss_group_id": transition.CurrentGroupID, - "incoming_tss_group_id": transition.IncomingGroupID, - "status": transition.Status, + "tss_signing_id": transition.SigningID, + "incoming_tss_group_id": transition.IncomingGroupID, + "incoming_group_pub_key": parseBytes(transition.IncomingGroupPubKey), + "status": transition.Status, }) } diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 88708a1c4..42e605865 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -10,8 +10,8 @@ import ( "github.com/bandprotocol/chain/v2/x/tss/types" ) -func (h *Hook) emitNewTssSigning(signing types.Signing) { - h.Write("NEW_TSS_SIGNING", common.JsDict{ +func (h *Hook) emitSetTssSigning(signing types.Signing) { + h.Write("SET_TSS_SIGNING", common.JsDict{ "id": signing.ID, "current_attempt": signing.CurrentAttempt, "tss_group_id": signing.GroupID, @@ -117,7 +117,7 @@ func (h *Hook) handleTssEventRequestSignature(ctx sdk.Context, evMap common.EvMa attempt := signing.CurrentAttempt attemptInfo := h.tssKeeper.MustGetSigningAttempt(ctx, id, attempt) - h.emitNewTssSigning(signing) + h.emitSetTssSigning(signing) for _, am := range attemptInfo.AssignedMembers { h.emitNewTssAssignedMember(signing.ID, attempt, signing.GroupID, am) From 55f64247dc0862576fcdabf8116b2b08604cc360 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 21 Oct 2024 10:19:33 +0700 Subject: [PATCH 099/132] fix table schema --- hasura/hasura-metadata/tables.yaml | 3 --- 1 file changed, 3 deletions(-) diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index f3421b918..0df4fc046 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -575,9 +575,6 @@ - name: connection using: foreign_key_constraint_on: connection_id -- table: - name: latest_prices - schema: public - table: name: non_validator_vote_proposals_view schema: public From ce4ee8ec99e10da2afbbd615d871f0c2fd7924a9 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Mon, 21 Oct 2024 13:56:53 +0700 Subject: [PATCH 100/132] fix mismatch --- x/feeds/keeper/keeper_price.go | 5 ----- x/oracle/types/error.go | 6 +++--- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/x/feeds/keeper/keeper_price.go b/x/feeds/keeper/keeper_price.go index d16a29d7a..c9d881648 100644 --- a/x/feeds/keeper/keeper_price.go +++ b/x/feeds/keeper/keeper_price.go @@ -96,11 +96,6 @@ func (k Keeper) SetPrice(ctx sdk.Context, price types.Price) { ctx.KVStore(k.storeKey).Set(types.PriceStoreKey(price.SignalID), k.cdc.MustMarshal(&price)) } -// DeletePrice deletes a price by signal id. -func (k Keeper) DeletePrice(ctx sdk.Context, signalID string) { - ctx.KVStore(k.storeKey).Delete(types.PriceStoreKey(signalID)) -} - // CalculatePrices calculates final prices for all supported feeds. func (k Keeper) CalculatePrices(ctx sdk.Context) { // get the current feeds diff --git a/x/oracle/types/error.go b/x/oracle/types/error.go index fcd468fc9..ea9dbc72c 100644 --- a/x/oracle/types/error.go +++ b/x/oracle/types/error.go @@ -50,9 +50,9 @@ var ( ErrInvalidOwasmGas = errorsmod.Register(ModuleName, 44, "invalid owasm gas") ErrIBCRequestDisabled = errorsmod.Register(ModuleName, 45, "sending oracle request via IBC is disabled") ErrSigningResultNotFound = errorsmod.Register(ModuleName, 46, "signing result not found") - ErrReportNotFound = errorsmod.Register(ModuleName, 47, "report not found") - ErrInvalidRequestID = errorsmod.Register(ModuleName, 48, "invalid request id") - ErrInvalidOracleEncodeType = errorsmod.Register(ModuleName, 49, "invalid oracle encode type") + ErrInvalidRequestID = errorsmod.Register(ModuleName, 47, "invalid request id") + ErrInvalidOracleEncodeType = errorsmod.Register(ModuleName, 48, "invalid oracle encode type") + ErrReportNotFound = errorsmod.Register(ModuleName, 101, "report not found") ) // WrapMaxError wraps an error message with additional info of the current and max values. From a52bab26a10b103e4af901cf2ddc2eb740d904f0 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 31 Oct 2024 18:05:41 +0700 Subject: [PATCH 101/132] fix --- flusher/flusher/handler.py | 284 +++++++++++++++---------------------- 1 file changed, 116 insertions(+), 168 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 3bdf26868..5151566f4 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -46,8 +46,6 @@ relayer_tx_stat_days, ) -from .restake_db import restake_vaults, restake_locks, restake_historical_stakes - from .feeds_db import ( PRICE_HISTORY_PERIOD, signal_prices_txs, @@ -58,6 +56,7 @@ reference_source_configs, feeders, ) +from .restake_db import restake_vaults, restake_locks, restake_historical_stakes from .bandtss_db import ( bandtss_current_groups, @@ -67,7 +66,6 @@ GroupTransitionStatus, ) - from .tss_db import ( tss_signings, tss_groups, @@ -795,171 +793,6 @@ def handle_set_relayer_tx_stat_days(self, port, channel, timestamp, address): ) ) - ################################## - # TSS_HANDLER - ################################## - - def handle_set_tss_signing(self, msg): - self.conn.execute( - insert(tss_signings) - .values(**msg) - .on_conflict_do_update(constraint="tss_signings_pkey", set_=msg) - ) - - def handle_update_tss_signing(self, msg): - condition = True - for col in tss_signings.primary_key.columns.values(): - condition = (col == msg[col.name]) & condition - self.conn.execute(tss_signings.update().where(condition).values(**msg)) - - def handle_set_tss_group(self, msg): - self.conn.execute( - insert(tss_groups) - .values(**msg) - .on_conflict_do_update(constraint="tss_groups_pkey", set_=msg) - ) - - def handle_set_tss_member(self, msg): - msg["account_id"] = self.get_account_id(msg["address"]) - del msg["address"] - - self.conn.execute( - insert(tss_members) - .values(**msg) - .on_conflict_do_update(constraint="tss_members_pkey", set_=msg) - ) - - def handle_new_tss_assigned_member(self, msg): - self.conn.execute(tss_assigned_members.insert(), msg) - - def handle_update_tss_assigned_member(self, msg): - condition = True - for col in tss_assigned_members.primary_key.columns.values(): - condition = (col == msg[col.name]) & condition - self.conn.execute(tss_assigned_members.update().where(condition).values(**msg)) - - ################################## - # BANDTSS_HANDLER - ################################## - - def handle_set_bandtss_group_transition(self, msg): - if "tss_signing_id" in msg and msg["tss_signing_id"] == 0: - del msg["tss_signing_id"] - if "current_tss_group_id" in msg and msg["current_tss_group_id"] == 0: - del msg["current_tss_group_id"] - if "incoming_tss_group_id" in msg and msg["incoming_tss_group_id"] == 0: - del msg["incoming_tss_group_id"] - - self.conn.execute(bandtss_group_transitions.insert(), msg) - - def update_bandtss_group_transition(self, msg): - if "tss_signing_id" in msg and msg["tss_signing_id"] == 0: - del msg["tss_signing_id"] - if "current_tss_group_id" in msg and msg["current_tss_group_id"] == 0: - del msg["current_tss_group_id"] - if "incoming_tss_group_id" in msg and msg["incoming_tss_group_id"] == 0: - del msg["incoming_tss_group_id"] - - proposal_column = bandtss_group_transitions.c.proposal_id - proposal_id = self.conn.execute(select(func.max(proposal_column))).scalar() - if proposal_id is None: - proposal_id = 0 - - self.conn.execute( - bandtss_group_transitions.update() - .where(proposal_column == proposal_id) - .values(**msg) - ) - - def handle_update_bandtss_group_transition(self, msg): - self.update_bandtss_group_transition(msg) - - def handle_update_bandtss_group_transition_success(self, msg): - msg = {"status": GroupTransitionStatus.success} - self.update_bandtss_group_transition(msg) - - def handle_update_bandtss_group_transition_failed(self, msg): - msg = {"status": GroupTransitionStatus.expired} - self.update_bandtss_group_transition(msg) - - def handle_set_bandtss_current_group(self, msg): - proposal_column = bandtss_group_transitions.c.proposal_id - proposal_id = self.conn.execute(select(func.max(proposal_column))).scalar() - if proposal_id is not None: - msg["proposal_id"] = proposal_id - - self.conn.execute(bandtss_current_groups.insert(), msg) - - def handle_set_bandtss_member(self, msg): - msg["account_id"] = self.get_account_id(msg["address"]) - del msg["address"] - - self.conn.execute( - insert(bandtss_members) - .values(**msg) - .on_conflict_do_update(constraint="bandtss_members_pkey", set_=msg) - ) - - def handle_set_bandtss_signing(self, msg): - if msg["current_group_tss_signing_id"] == 0: - del msg["current_group_tss_signing_id"] - if msg["incoming_group_tss_signing_id"] == 0: - del msg["incoming_group_tss_signing_id"] - msg["requester_account_id"] = self.get_account_id(msg["requester"]) - del msg["requester"] - - self.conn.execute(bandtss_signings.insert(), msg) - - ################################## - # RESTAKE_HANDLER - ################################## - - def handle_set_restake_historical_stake(self, msg): - msg["account_id"] = self.get_account_id(msg["staker_address"]) - del msg["staker_address"] - self.conn.execute( - insert(restake_historical_stakes) - .values(**msg) - .on_conflict_do_update( - constraint="restake_historical_stakes_pkey", set_=msg - ) - ) - - def handle_set_restake_lock(self, msg): - if msg["tx_hash"] is not None: - msg["transaction_id"] = self.get_transaction_id(msg["tx_hash"]) - else: - msg["transaction_id"] = None - del msg["tx_hash"] - - msg["account_id"] = self.get_account_id(msg["staker_address"]) - del msg["staker_address"] - self.conn.execute( - insert(restake_locks) - .values(**msg) - .on_conflict_do_update(constraint="restake_locks_pkey", set_=msg) - ) - - def handle_remove_restake_lock(self, msg): - msg["account_id"] = self.get_account_id(msg["staker_address"]) - del msg["staker_address"] - - condition = True - for col in restake_locks.primary_key.columns.values(): - condition = (col == msg[col.name]) & condition - self.conn.execute(restake_locks.delete().where(condition)) - - def handle_set_restake_vault(self, msg): - self.conn.execute( - insert(restake_vaults) - .values(**msg) - .on_conflict_do_update(constraint="restake_vaults_pkey", set_=msg) - ) - - ################################## - # FEEDS_HANDLER - ################################## - def handle_set_signal_prices_tx(self, msg): if msg["tx_hash"] is not None: msg["transaction_id"] = self.get_transaction_id(msg["tx_hash"]) @@ -1138,3 +971,118 @@ def handle_set_restake_vault(self, msg): .values(**msg) .on_conflict_do_update(constraint="restake_vaults_pkey", set_=msg) ) + + ################################## + # TSS_HANDLER + ################################## + + def handle_set_tss_signing(self, msg): + self.conn.execute( + insert(tss_signings) + .values(**msg) + .on_conflict_do_update(constraint="tss_signings_pkey", set_=msg) + ) + + def handle_update_tss_signing(self, msg): + condition = True + for col in tss_signings.primary_key.columns.values(): + condition = (col == msg[col.name]) & condition + self.conn.execute(tss_signings.update().where(condition).values(**msg)) + + def handle_set_tss_group(self, msg): + self.conn.execute( + insert(tss_groups) + .values(**msg) + .on_conflict_do_update(constraint="tss_groups_pkey", set_=msg) + ) + + def handle_set_tss_member(self, msg): + msg["account_id"] = self.get_account_id(msg["address"]) + del msg["address"] + + self.conn.execute( + insert(tss_members) + .values(**msg) + .on_conflict_do_update(constraint="tss_members_pkey", set_=msg) + ) + + def handle_new_tss_assigned_member(self, msg): + self.conn.execute(tss_assigned_members.insert(), msg) + + def handle_update_tss_assigned_member(self, msg): + condition = True + for col in tss_assigned_members.primary_key.columns.values(): + condition = (col == msg[col.name]) & condition + self.conn.execute(tss_assigned_members.update().where(condition).values(**msg)) + + ################################## + # BANDTSS_HANDLER + ################################## + + def handle_set_bandtss_group_transition(self, msg): + if "tss_signing_id" in msg and msg["tss_signing_id"] == 0: + del msg["tss_signing_id"] + if "current_tss_group_id" in msg and msg["current_tss_group_id"] == 0: + del msg["current_tss_group_id"] + if "incoming_tss_group_id" in msg and msg["incoming_tss_group_id"] == 0: + del msg["incoming_tss_group_id"] + + self.conn.execute(bandtss_group_transitions.insert(), msg) + + def update_bandtss_group_transition(self, msg): + if "tss_signing_id" in msg and msg["tss_signing_id"] == 0: + del msg["tss_signing_id"] + if "current_tss_group_id" in msg and msg["current_tss_group_id"] == 0: + del msg["current_tss_group_id"] + if "incoming_tss_group_id" in msg and msg["incoming_tss_group_id"] == 0: + del msg["incoming_tss_group_id"] + + proposal_column = bandtss_group_transitions.c.proposal_id + proposal_id = self.conn.execute(select(func.max(proposal_column))).scalar() + if proposal_id is None: + proposal_id = 0 + + self.conn.execute( + bandtss_group_transitions.update() + .where(proposal_column == proposal_id) + .values(**msg) + ) + + def handle_update_bandtss_group_transition(self, msg): + self.update_bandtss_group_transition(msg) + + def handle_update_bandtss_group_transition_success(self, msg): + msg = {"status": GroupTransitionStatus.success} + self.update_bandtss_group_transition(msg) + + def handle_update_bandtss_group_transition_failed(self, msg): + msg = {"status": GroupTransitionStatus.expired} + self.update_bandtss_group_transition(msg) + + def handle_set_bandtss_current_group(self, msg): + proposal_column = bandtss_group_transitions.c.proposal_id + proposal_id = self.conn.execute(select(func.max(proposal_column))).scalar() + if proposal_id is not None: + msg["proposal_id"] = proposal_id + + self.conn.execute(bandtss_current_groups.insert(), msg) + + def handle_set_bandtss_member(self, msg): + msg["account_id"] = self.get_account_id(msg["address"]) + del msg["address"] + + self.conn.execute( + insert(bandtss_members) + .values(**msg) + .on_conflict_do_update(constraint="bandtss_members_pkey", set_=msg) + ) + + def handle_set_bandtss_signing(self, msg): + if msg["current_group_tss_signing_id"] == 0: + del msg["current_group_tss_signing_id"] + if msg["incoming_group_tss_signing_id"] == 0: + del msg["incoming_group_tss_signing_id"] + msg["requester_account_id"] = self.get_account_id(msg["requester"]) + del msg["requester"] + + self.conn.execute(bandtss_signings.insert(), msg) From b5dc0ff173f29e7f98d4c175ca58168d6c62dc4f Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Thu, 31 Oct 2024 19:59:40 +0700 Subject: [PATCH 102/132] fix order --- flusher/flusher/handler.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 5151566f4..794b7ed85 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -46,6 +46,8 @@ relayer_tx_stat_days, ) +from .restake_db import restake_vaults, restake_locks, restake_historical_stakes + from .feeds_db import ( PRICE_HISTORY_PERIOD, signal_prices_txs, @@ -56,7 +58,6 @@ reference_source_configs, feeders, ) -from .restake_db import restake_vaults, restake_locks, restake_historical_stakes from .bandtss_db import ( bandtss_current_groups, From 8f4df9c676db64e08f8b249fd8f8eb8e703af324 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 12 Nov 2024 20:39:09 +0700 Subject: [PATCH 103/132] fix from comments --- docker-config/start_docker.sh | 4 ---- flusher/flusher/handler.py | 29 +++++++++++++++++------------ hooks/emitter/bandtss.go | 6 +++--- hooks/emitter/decoder.go | 15 ++------------- 4 files changed, 22 insertions(+), 32 deletions(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index a2ed4167e..0faf19c12 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -183,7 +183,6 @@ do cylinder config gas-adjust-start 1.6 cylinder config gas-adjust-step 0.2 cylinder config random-secret "$(openssl rand -hex 32)" - cylinder config active-period "12h" for i in $(eval echo {1..1}) do @@ -199,9 +198,6 @@ do echo "y" | bandd tx tss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync sleep 4 - echo "y" | bandd tx bandtss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync - sleep 4 - docker create --network chain_bandchain --name bandchain-cylinder${v} band-validator:latest cylinder run docker cp ~/.cylinder bandchain-cylinder${v}:/root/.cylinder docker start bandchain-cylinder${v} diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index b5839b6e6..3c28a2dbd 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -325,17 +325,17 @@ def handle_update_request(self, msg): msg["transaction_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] - if "tss_signing_id" in msg: - if msg["tss_signing_id"] == 0: - del msg["tss_signing_id"] + if "tss_signing_id" in msg and msg["tss_signing_id"] == 0: + del msg["tss_signing_id"] - if "tss_signing_error_codespace" in msg: - if msg["tss_signing_error_codespace"] == "": - del msg["tss_signing_error_codespace"] + if ( + "tss_signing_error_codespace" in msg + and msg["tss_signing_error_codespace"] == "" + ): + del msg["tss_signing_error_codespace"] - if "tss_signing_error_code" in msg: - if msg["tss_signing_error_code"] == 0: - del msg["tss_signing_error_code"] + if "tss_signing_error_code" in msg and msg["tss_signing_error_code"] == 0: + del msg["tss_signing_error_code"] condition = True for col in requests.primary_key.columns.values(): @@ -860,7 +860,9 @@ def handle_set_signal_total_power(self, msg): self.conn.execute( insert(feeds_signal_total_powers) .values(**msg) - .on_conflict_do_update(constraint="feeds_signal_total_powers_pkey", set_=msg) + .on_conflict_do_update( + constraint="feeds_signal_total_powers_pkey", set_=msg + ) ) def handle_remove_signal_total_power(self, msg): @@ -899,7 +901,8 @@ def handle_set_prices(self, msg): self.conn.execute( feeds_historical_prices.delete().where( - feeds_historical_prices.c.timestamp < msg["timestamp"] - PRICE_HISTORY_PERIOD + feeds_historical_prices.c.timestamp + < msg["timestamp"] - PRICE_HISTORY_PERIOD ) ) @@ -907,7 +910,9 @@ def handle_set_reference_source_config(self, msg): self.conn.execute( insert(feeds_reference_source_configs) .values(**msg) - .on_conflict_do_update(constraint="feeds_reference_source_configs_pkey", set_=msg) + .on_conflict_do_update( + constraint="feeds_reference_source_configs_pkey", set_=msg + ) ) def handle_set_feeder(self, msg): diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index d86d6c41f..42394292c 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -193,9 +193,9 @@ func (h *Hook) handleBandtssEventGroupTransitionSuccess(ctx sdk.Context, evMap c // handleBandtssEventGroupTransitionFailed implements emitter handler for group transition failed event. func (h *Hook) handleBandtssEventGroupTransitionFailed(_ sdk.Context, evMap common.EvMap) { // use value from emitted event due to the transition info is removed from the store. - signingIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+tsstypes.AttributeKeySigningID] - incomingGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyIncomingGroupID] - currentGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyCurrentGroupID] + signingIDs := evMap[types.EventTypeGroupTransitionFailed+"."+tsstypes.AttributeKeySigningID] + incomingGroupIDs := evMap[types.EventTypeGroupTransitionFailed+"."+types.AttributeKeyIncomingGroupID] + currentGroupIDs := evMap[types.EventTypeGroupTransitionFailed+"."+types.AttributeKeyCurrentGroupID] h.emitUpdateBandtssGroupTransitionStatusFailed(types.GroupTransition{ SigningID: tss.SigningID(common.Atoi(signingIDs[0])), diff --git a/hooks/emitter/decoder.go b/hooks/emitter/decoder.go index 50c966ac8..91495b113 100644 --- a/hooks/emitter/decoder.go +++ b/hooks/emitter/decoder.go @@ -744,11 +744,7 @@ func DecodeBandtssMsgActivate(msg *bandtsstypes.MsgActivate, detail common.JsDic } func DecodeBandtssMsgUpdateParams(msg *bandtsstypes.MsgUpdateParams, detail common.JsDict) { - params := msg.GetParams() - detail["reward_percentage"] = params.GetRewardPercentage() - detail["inactive_penalty_duration"] = params.GetInactivePenaltyDuration() - detail["fee"] = params.GetFee() - detail["max_transition_duration"] = params.GetMaxTransitionDuration() + detail["params"] = msg.GetParams() detail["authority"] = msg.GetAuthority() } @@ -790,14 +786,7 @@ func DecodeMsgSubmitSignature(msg *tsstypes.MsgSubmitSignature, detail common.Js } func DecodeMsgUpdateParamsTss(msg *tsstypes.MsgUpdateParams, detail common.JsDict) { - params := msg.GetParams() - detail["max_group_size"] = params.GetMaxGroupSize() - detail["max_memo_length"] = params.GetMaxMemoLength() - detail["max_message_length"] = params.GetMaxMessageLength() - detail["max_d_e_size"] = params.GetMaxDESize() - detail["creating_period"] = params.GetCreationPeriod() - detail["signing_period"] = params.GetSigningPeriod() - detail["max_signing_attempt"] = params.GetMaxSigningAttempt() + detail["params"] = msg.GetParams() detail["authority"] = msg.GetAuthority() } From f24083be4f29721be69954feaaa7c6f43487fac1 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Tue, 12 Nov 2024 20:46:56 +0700 Subject: [PATCH 104/132] fix test --- hooks/emitter/decoder_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index d077984cf..98b5474a5 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -1029,7 +1029,7 @@ func (suite *DecoderTestSuite) TestDecodeBandtssMsgUpdateParams() { } emitter.DecodeBandtssMsgUpdateParams(&msg, detail) - expectedJSON := `{"authority":"","fee":[{"denom":"uband","amount":"1"}],"inactive_penalty_duration":50,"max_transition_duration":50,"reward_percentage":10}` + expectedJSON := `{"authority":"","params":{"reward_percentage":10,"inactive_penalty_duration":50,"max_transition_duration":50,"fee":[{"denom":"uband","amount":"1"}]}}` suite.testCompareJson(detail, expectedJSON) } From 0fbc06f9894ce73ff8cfe5863c46889a5318675f Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 13 Nov 2024 01:07:39 +0700 Subject: [PATCH 105/132] add content type on decoding --- hooks/emitter/decoder.go | 1 + 1 file changed, 1 insertion(+) diff --git a/hooks/emitter/decoder.go b/hooks/emitter/decoder.go index 91495b113..a27649743 100644 --- a/hooks/emitter/decoder.go +++ b/hooks/emitter/decoder.go @@ -732,6 +732,7 @@ func DecodeBandtssMsgForceTransitionGroup(msg *bandtsstypes.MsgForceTransitionGr } func DecodeBandtssMsgRequestSignature(msg *bandtsstypes.MsgRequestSignature, detail common.JsDict) { + detail["content_type"] = msg.Content.TypeUrl detail["content"] = msg.Content.GetCachedValue() detail["memo"] = msg.Memo detail["fee_limit"] = msg.FeeLimit From a52b824603c220f13c255fda9a0d0448c38b823a Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 13 Nov 2024 01:19:49 +0700 Subject: [PATCH 106/132] fix --- docker-config/start_docker.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 0faf19c12..da706a916 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -194,7 +194,7 @@ do echo "y" | bandd tx multi-send 1000000uband $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync sleep 4 - # activate tss + # grant tss echo "y" | bandd tx tss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync sleep 4 From f65021f16aa0145f68f1005b2a07e9e5f4e71601 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 13 Nov 2024 01:38:49 +0700 Subject: [PATCH 107/132] retrack table --- hasura/hasura-metadata/tables.yaml | 45 +++++++++++++++--------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index 86eec1499..a7768146c 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -402,7 +402,7 @@ name: data_sources schema: public object_relationships: - - name: data_source_request + - name: request_stat using: foreign_key_constraint_on: column: data_source_id @@ -541,6 +541,13 @@ - name: group_policy using: foreign_key_constraint_on: group_policy_address + - name: group_vote + using: + foreign_key_constraint_on: + column: group_proposal_id + table: + name: group_votes + schema: public array_relationships: - name: group_votes using: @@ -658,7 +665,7 @@ name: oracle_scripts schema: public object_relationships: - - name: oracle_script_request + - name: request_stat using: foreign_key_constraint_on: column: oracle_script_id @@ -720,13 +727,6 @@ - name: account using: foreign_key_constraint_on: proposer_id - - name: bandtss_current_group - using: - foreign_key_constraint_on: - column: proposal_id - table: - name: bandtss_current_groups - schema: public - name: bandtss_group_transition using: foreign_key_constraint_on: @@ -808,7 +808,7 @@ - name: account using: foreign_key_constraint_on: delegator_id - - name: validator + - name: validatorByValidatorDstId using: foreign_key_constraint_on: validator_dst_id - name: validatorByValidatorSrcId @@ -828,7 +828,7 @@ name: relayer_tx_stat_days schema: public object_relationships: - - name: channelByChannelPort + - name: channel_by_channel_port using: manual_configuration: column_mapping: @@ -1058,14 +1058,6 @@ - table: name: tss_groups schema: public - object_relationships: - - name: bandtss_member - using: - foreign_key_constraint_on: - column: tss_group_id - table: - name: bandtss_members - schema: public array_relationships: - name: bandtssGroupTransitionsByIncomingTssGroupId using: @@ -1241,6 +1233,15 @@ - name: account using: foreign_key_constraint_on: account_id + - name: validator_report_count + using: + manual_configuration: + column_mapping: + id: validator_id + insertion_order: null + remote_table: + name: validator_report_count + schema: public array_relationships: - name: blocks using: @@ -1280,14 +1281,14 @@ - name: redelegations using: foreign_key_constraint_on: - column: validator_dst_id + column: validator_src_id table: name: redelegations schema: public - - name: redelegationsByValidatorSrcId + - name: redelegationsByValidatorDstId using: foreign_key_constraint_on: - column: validator_src_id + column: validator_dst_id table: name: redelegations schema: public From efa0a4fd2fc4000fbeb30a80a867226932285d1d Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 13 Nov 2024 03:03:07 +0700 Subject: [PATCH 108/132] remove track table first --- hasura/hasura-metadata/tables.yaml | 264 ----------------------------- 1 file changed, 264 deletions(-) diff --git a/hasura/hasura-metadata/tables.yaml b/hasura/hasura-metadata/tables.yaml index a7768146c..e0023f4c0 100644 --- a/hasura/hasura-metadata/tables.yaml +++ b/hasura/hasura-metadata/tables.yaml @@ -34,20 +34,6 @@ table: name: account_transactions schema: public - - name: bandtss_members - using: - foreign_key_constraint_on: - column: account_id - table: - name: bandtss_members - schema: public - - name: bandtss_signings - using: - foreign_key_constraint_on: - column: requester_account_id - table: - name: bandtss_signings - schema: public - name: delegations using: foreign_key_constraint_on: @@ -153,13 +139,6 @@ table: name: restake_locks schema: public - - name: tss_members - using: - foreign_key_constraint_on: - column: account_id - table: - name: tss_members - schema: public - name: unbonding_delegations using: foreign_key_constraint_on: @@ -174,61 +153,6 @@ table: name: votes schema: public -- table: - name: bandtss_current_groups - schema: public - object_relationships: - - name: block - using: - foreign_key_constraint_on: transition_height - - name: proposal - using: - foreign_key_constraint_on: proposal_id - - name: tss_group - using: - foreign_key_constraint_on: current_tss_group_id -- table: - name: bandtss_group_transitions - schema: public - object_relationships: - - name: block - using: - foreign_key_constraint_on: created_height - - name: proposal - using: - foreign_key_constraint_on: proposal_id - - name: tssGroupByIncomingTssGroupId - using: - foreign_key_constraint_on: incoming_tss_group_id - - name: tss_group - using: - foreign_key_constraint_on: current_tss_group_id - - name: tss_signing - using: - foreign_key_constraint_on: tss_signing_id -- table: - name: bandtss_members - schema: public - object_relationships: - - name: account - using: - foreign_key_constraint_on: account_id - - name: tss_group - using: - foreign_key_constraint_on: tss_group_id -- table: - name: bandtss_signings - schema: public - object_relationships: - - name: account - using: - foreign_key_constraint_on: requester_account_id - - name: tssSigningByIncomingGroupTssSigningId - using: - foreign_key_constraint_on: incoming_group_tss_signing_id - - name: tss_signing - using: - foreign_key_constraint_on: current_group_tss_signing_id - table: name: blocks schema: public @@ -237,20 +161,6 @@ using: foreign_key_constraint_on: proposer array_relationships: - - name: bandtss_current_groups - using: - foreign_key_constraint_on: - column: transition_height - table: - name: bandtss_current_groups - schema: public - - name: bandtss_group_transitions - using: - foreign_key_constraint_on: - column: created_height - table: - name: bandtss_group_transitions - schema: public - name: incoming_packets using: foreign_key_constraint_on: @@ -279,20 +189,6 @@ table: name: transactions schema: public - - name: tss_assigned_members - using: - foreign_key_constraint_on: - column: submitted_height - table: - name: tss_assigned_members - schema: public - - name: tss_signings - using: - foreign_key_constraint_on: - column: created_height - table: - name: tss_signings - schema: public - name: unbonding_delegations using: foreign_key_constraint_on: @@ -727,21 +623,7 @@ - name: account using: foreign_key_constraint_on: proposer_id - - name: bandtss_group_transition - using: - foreign_key_constraint_on: - column: proposal_id - table: - name: bandtss_group_transitions - schema: public array_relationships: - - name: bandtss_current_groups - using: - foreign_key_constraint_on: - column: proposal_id - table: - name: bandtss_current_groups - schema: public - name: deposits using: foreign_key_constraint_on: @@ -888,9 +770,6 @@ - name: transaction using: foreign_key_constraint_on: transaction_id - - name: tss_signing - using: - foreign_key_constraint_on: tss_signing_id array_relationships: - name: raw_requests using: @@ -1032,149 +911,6 @@ table: name: votes schema: public -- table: - name: tss_assigned_members - schema: public - object_relationships: - - name: block - using: - foreign_key_constraint_on: submitted_height - - name: tss_group - using: - foreign_key_constraint_on: tss_group_id - - name: tss_member - using: - manual_configuration: - column_mapping: - tss_group_id: tss_group_id - tss_member_id: id - insertion_order: null - remote_table: - name: tss_members - schema: public - - name: tss_signing - using: - foreign_key_constraint_on: tss_signing_id -- table: - name: tss_groups - schema: public - array_relationships: - - name: bandtssGroupTransitionsByIncomingTssGroupId - using: - foreign_key_constraint_on: - column: incoming_tss_group_id - table: - name: bandtss_group_transitions - schema: public - - name: bandtss_current_groups - using: - foreign_key_constraint_on: - column: current_tss_group_id - table: - name: bandtss_current_groups - schema: public - - name: bandtss_group_transitions - using: - foreign_key_constraint_on: - column: current_tss_group_id - table: - name: bandtss_group_transitions - schema: public - - name: bandtss_members - using: - foreign_key_constraint_on: - column: tss_group_id - table: - name: bandtss_members - schema: public - - name: tss_assigned_members - using: - foreign_key_constraint_on: - column: tss_group_id - table: - name: tss_assigned_members - schema: public - - name: tss_members - using: - foreign_key_constraint_on: - column: tss_group_id - table: - name: tss_members - schema: public - - name: tss_signings - using: - foreign_key_constraint_on: - column: tss_group_id - table: - name: tss_signings - schema: public -- table: - name: tss_members - schema: public - object_relationships: - - name: account - using: - foreign_key_constraint_on: account_id - - name: tss_group - using: - foreign_key_constraint_on: tss_group_id - array_relationships: - - name: tss_assigned_members - using: - manual_configuration: - column_mapping: - id: tss_member_id - tss_group_id: tss_group_id - insertion_order: null - remote_table: - name: tss_assigned_members - schema: public -- table: - name: tss_signings - schema: public - object_relationships: - - name: block - using: - foreign_key_constraint_on: created_height - - name: tss_group - using: - foreign_key_constraint_on: tss_group_id - array_relationships: - - name: bandtssSigningsByIncomingGroupTssSigningId - using: - foreign_key_constraint_on: - column: incoming_group_tss_signing_id - table: - name: bandtss_signings - schema: public - - name: bandtss_group_transitions - using: - foreign_key_constraint_on: - column: tss_signing_id - table: - name: bandtss_group_transitions - schema: public - - name: bandtss_signings - using: - foreign_key_constraint_on: - column: current_group_tss_signing_id - table: - name: bandtss_signings - schema: public - - name: requests - using: - foreign_key_constraint_on: - column: tss_signing_id - table: - name: requests - schema: public - - name: tss_assigned_members - using: - foreign_key_constraint_on: - column: tss_signing_id - table: - name: tss_assigned_members - schema: public - table: name: unbonding_delegations schema: public From 4d00ca24f2612a9ce4ff065d55146eb7de2bc411 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Wed, 13 Nov 2024 14:29:17 +0700 Subject: [PATCH 109/132] fix start_docker script --- docker-config/start_docker.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index da706a916..527f5c4cb 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -183,6 +183,7 @@ do cylinder config gas-adjust-start 1.6 cylinder config gas-adjust-step 0.2 cylinder config random-secret "$(openssl rand -hex 32)" + cylinder config checking-de-interval "5m" for i in $(eval echo {1..1}) do From 1a39ca9818cfa6c9dd2c5721e2dc463d33b8d3e0 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Wed, 13 Nov 2024 15:58:38 +0700 Subject: [PATCH 110/132] fix from comments --- flusher/flusher/bandtss_db.py | 11 +++++-- flusher/flusher/db.py | 19 +++++++----- flusher/flusher/handler.py | 19 +++++++----- flusher/flusher/tss_db.py | 2 +- hooks/emitter/channel.go | 2 +- hooks/emitter/decoder.go | 2 +- hooks/emitter/decoder_test.go | 2 +- hooks/emitter/oracle.go | 34 ++++++++++----------- scripts/bandtss/request_signature_oracle.sh | 4 +-- 9 files changed, 53 insertions(+), 42 deletions(-) diff --git a/flusher/flusher/bandtss_db.py b/flusher/flusher/bandtss_db.py index f7412015a..67e5f7eeb 100644 --- a/flusher/flusher/bandtss_db.py +++ b/flusher/flusher/bandtss_db.py @@ -74,13 +74,18 @@ def process_bind_param(self, value, dialect): nullable=True, index=True, ), - Column("current_tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), + Column( + "current_tss_group_id", + sa.Integer, + sa.ForeignKey("tss_groups.id"), + primary_key=True, + ), Column( "transition_height", sa.Integer, sa.ForeignKey("blocks.height"), - nullable=True, index=True, + primary_key=True, ), ) @@ -99,7 +104,7 @@ def process_bind_param(self, value, dialect): "bandtss_signings", metadata, Column("id", sa.Integer, primary_key=True), - Column("requester_account_id", sa.Integer, sa.ForeignKey("accounts.id")), + Column("account_id", sa.Integer, sa.ForeignKey("accounts.id")), Column("fee_per_signer", sa.String), Column( "current_group_tss_signing_id", diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index 00fd391be..cc7e710fa 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -21,7 +21,7 @@ class ProposalStatus(enum.Enum): Inactive = 6 -class TSSEncodeType(enum.Enum): +class TSSEncoder(enum.Enum): Unspecified = 0 Proto = 1 FullABI = 2 @@ -42,11 +42,11 @@ def process_bind_param(self, value, dialect): return ProposalStatus(value) -class CustomTSSEncodeType(sa.types.TypeDecorator): - impl = sa.Enum(TSSEncodeType) +class CustomTSSEncoder(sa.types.TypeDecorator): + impl = sa.Enum(TSSEncoder) def process_bind_param(self, value, dialect): - return TSSEncodeType(value) + return TSSEncoder(value) class CustomDateTime(sa.types.TypeDecorator): @@ -193,7 +193,7 @@ def Column(*args, **kwargs): Column("prepare_gas_used", sa.Integer, default=0), Column("execute_gas", sa.Integer), Column("execute_gas_used", sa.Integer, default=0), - Column("tss_encode_type", CustomTSSEncodeType), + Column("tss_encoder", CustomTSSEncoder), Column("sender", sa.String, nullable=True), Column("client_id", sa.String), Column("request_time", sa.Integer, nullable=True, index=True), @@ -209,10 +209,13 @@ def Column(*args, **kwargs): Column("reason", sa.String, nullable=True), Column("result", CustomBase64, nullable=True), Column( - "tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id"), nullable=True + "bandtss_signing_id", + sa.Integer, + sa.ForeignKey("bandtss_signings.id"), + nullable=True, ), - Column("tss_signing_error_codespace", sa.String, nullable=True), - Column("tss_signing_error_code", sa.Integer, nullable=True), + Column("bandtss_signing_error_codespace", sa.String, nullable=True), + Column("bandtss_signing_error_code", sa.Integer, nullable=True), Column("total_fees", sa.String), Column("is_ibc", sa.Boolean), sa.Index( diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 3c28a2dbd..4d6e4f215 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -325,17 +325,20 @@ def handle_update_request(self, msg): msg["transaction_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] - if "tss_signing_id" in msg and msg["tss_signing_id"] == 0: - del msg["tss_signing_id"] + if "bandtss_signing_id" in msg and msg["bandtss_signing_id"] == 0: + del msg["bandtss_signing_id"] if ( - "tss_signing_error_codespace" in msg - and msg["tss_signing_error_codespace"] == "" + "bandtss_signing_error_codespace" in msg + and msg["bandtss_signing_error_codespace"] == "" ): - del msg["tss_signing_error_codespace"] + del msg["bandtss_signing_error_codespace"] - if "tss_signing_error_code" in msg and msg["tss_signing_error_code"] == 0: - del msg["tss_signing_error_code"] + if ( + "bandtss_signing_error_code" in msg + and msg["bandtss_signing_error_code"] == 0 + ): + del msg["bandtss_signing_error_code"] condition = True for col in requests.primary_key.columns.values(): @@ -1088,7 +1091,7 @@ def handle_set_bandtss_signing(self, msg): del msg["current_group_tss_signing_id"] if msg["incoming_group_tss_signing_id"] == 0: del msg["incoming_group_tss_signing_id"] - msg["requester_account_id"] = self.get_account_id(msg["requester"]) + msg["account_id"] = self.get_account_id(msg["requester"]) del msg["requester"] self.conn.execute(bandtss_signings.insert(), msg) diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index e16a4027b..bc88bff6a 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -47,7 +47,7 @@ def process_bind_param(self, value, dialect): Column("id", sa.Integer, primary_key=True), Column("tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), Column("current_attempt", sa.Integer), - Column("originator", sa.String), + Column("originator", CustomBase64), Column("message", CustomBase64), Column("group_pub_key", CustomBase64), Column("group_pub_nonce", CustomBase64), diff --git a/hooks/emitter/channel.go b/hooks/emitter/channel.go index a2f3c155e..d1e5aad90 100644 --- a/hooks/emitter/channel.go +++ b/hooks/emitter/channel.go @@ -231,7 +231,7 @@ func (h *Hook) extractOracleRequestPacket( "prepare_gas_used": prepareGasUsed, "execute_gas": data.ExecuteGas, "execute_gas_used": uint64(0), - "tss_encode_type": data.TSSEncodeType, + "tss_encoder": data.TSSEncoder, "fee_limit": data.FeeLimit.String(), "total_fees": evMap[oracletypes.EventTypeRequest+"."+oracletypes.AttributeKeyTotalFees][0], "is_ibc": req.IBCChannel != nil, diff --git a/hooks/emitter/decoder.go b/hooks/emitter/decoder.go index a27649743..2d3bfb354 100644 --- a/hooks/emitter/decoder.go +++ b/hooks/emitter/decoder.go @@ -325,7 +325,7 @@ func DecodeMsgRequestData(msg *oracletypes.MsgRequestData, detail common.JsDict) detail["prepare_gas"] = msg.GetPrepareGas() detail["execute_gas"] = msg.GetExecuteGas() detail["sender"] = msg.GetSender() - detail["tss_encode_type"] = msg.GetTSSEncodeType() + detail["tss_encoder"] = msg.GetTSSEncoder() } func DecodeMsgReportData(msg *oracletypes.MsgReportData, detail common.JsDict) { diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index 98b5474a5..f5a825848 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -237,7 +237,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgRequestData() { emitter.DecodeMsgRequestData(msg, detail) suite.testCompareJson( detail, - "{\"ask_count\":1,\"calldata\":\"Y2FsbGRhdGE=\",\"client_id\":\"cleint_id\",\"execute_gas\":300000,\"fee_limit\":[{\"denom\":\"uband\",\"amount\":\"100000000\"}],\"min_count\":1,\"oracle_script_id\":1,\"prepare_gas\":40000,\"sender\":\"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0\",\"tss_encode_type\":0}", + "{\"ask_count\":1,\"calldata\":\"Y2FsbGRhdGE=\",\"client_id\":\"cleint_id\",\"execute_gas\":300000,\"fee_limit\":[{\"denom\":\"uband\",\"amount\":\"100000000\"}],\"min_count\":1,\"oracle_script_id\":1,\"prepare_gas\":40000,\"sender\":\"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0\",\"tss_encoder\":0}", ) } diff --git a/hooks/emitter/oracle.go b/hooks/emitter/oracle.go index 6b17f1174..be25eb07f 100644 --- a/hooks/emitter/oracle.go +++ b/hooks/emitter/oracle.go @@ -132,24 +132,24 @@ func (h *Hook) emitUpdateResultTSS( id types.RequestID, executeGasUsed uint64, reason string, - tssSigningID uint64, - tssSigningErrorCodespace string, - tssSigningErrorCode uint64, + bandtssSigningID uint64, + bandtssSigningErrorCodespace string, + bandtssSigningErrorCode uint64, ) { result := h.oracleKeeper.MustGetResult(ctx, id) h.Write("UPDATE_REQUEST", common.JsDict{ - "id": id, - "execute_gas_used": executeGasUsed, - "request_time": result.RequestTime, - "resolve_time": result.ResolveTime, - "resolve_status": result.ResolveStatus, - "resolve_height": ctx.BlockHeight(), - "reason": reason, - "result": parseBytes(result.Result), - "tss_signing_id": tssSigningID, - "tss_signing_error_codespace": tssSigningErrorCodespace, - "tss_signing_error_code": tssSigningErrorCode, + "id": id, + "execute_gas_used": executeGasUsed, + "request_time": result.RequestTime, + "resolve_time": result.ResolveTime, + "resolve_status": result.ResolveStatus, + "resolve_height": ctx.BlockHeight(), + "reason": reason, + "result": parseBytes(result.Result), + "bandtss_signing_id": bandtssSigningID, + "bandtss_signing_error_codespace": bandtssSigningErrorCodespace, + "bandtss_signing_error_code": bandtssSigningErrorCode, }) } @@ -180,7 +180,7 @@ func (h *Hook) handleMsgRequestData( "prepare_gas_used": prepareGasUsed, "execute_gas": msg.ExecuteGas, "execute_gas_used": uint64(0), - "tss_encode_type": msg.TSSEncodeType, + "tss_encoder": msg.TSSEncoder, "fee_limit": msg.FeeLimit.String(), "total_fees": evMap[types.EventTypeRequest+"."+types.AttributeKeyTotalFees][0], "is_ibc": req.IBCChannel != nil, @@ -266,14 +266,14 @@ func (h *Hook) handleEventRequestExecute(ctx sdk.Context, evMap common.EvMap) { executeGasUsed, reasons[0], ) - } else if tssErrCodespace, ok := evMap[types.EventTypeResolve+"."+types.AttributeKeySigningErrCodespace]; ok { + } else if bandtssErrCodespace, ok := evMap[types.EventTypeResolve+"."+types.AttributeKeySigningErrCodespace]; ok { h.emitUpdateResultTSS( ctx, rid, executeGasUsed, "", 0, - tssErrCodespace[0], + bandtssErrCodespace[0], uint64(common.Atoi(evMap[types.EventTypeResolve+"."+types.AttributeKeySigningErrCode][0])), ) } else if tssSid, ok := evMap[types.EventTypeResolve+"."+types.AttributeKeySigningID]; ok { diff --git a/scripts/bandtss/request_signature_oracle.sh b/scripts/bandtss/request_signature_oracle.sh index 907b1143f..1200c6081 100755 --- a/scripts/bandtss/request_signature_oracle.sh +++ b/scripts/bandtss/request_signature_oracle.sh @@ -2,9 +2,9 @@ export WALLET_NAME=requester export REQUEST_ID=1 -export ENCODE_TYPE=1 +export ENCODER=1 -bandd tx bandtss request-signature oracle-result $REQUEST_ID $ENCODE_TYPE \ +bandd tx bandtss request-signature oracle-result $REQUEST_ID $ENCODER \ --from requester --keyring-backend test \ --gas-prices 0.0025uband --fee-limit 100uband \ -b sync -y From 7d5ba6dce71c60a0e83c8730bb5db18371fab21a Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Wed, 13 Nov 2024 19:03:33 +0700 Subject: [PATCH 111/132] group go mod order --- go.mod | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 67a5d71db..ac791fe41 100644 --- a/go.mod +++ b/go.mod @@ -33,8 +33,6 @@ require ( github.com/cosmos/ics23/go v0.11.0 github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 github.com/ethereum/go-ethereum v1.14.8 - github.com/gin-gonic/gin v1.8.1 - github.com/go-sql-driver/mysql v1.8.1 github.com/golang/protobuf v1.5.4 github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 github.com/grpc-ecosystem/grpc-gateway v1.16.0 @@ -44,14 +42,12 @@ require ( github.com/oasisprotocol/oasis-core/go v0.2202.7 github.com/peterbourgon/diskv v2.0.1+incompatible github.com/prometheus/client_golang v1.20.5 - github.com/segmentio/kafka-go v0.4.47 github.com/spf13/cast v1.7.0 github.com/spf13/cobra v1.8.1 github.com/spf13/viper v1.19.0 github.com/stretchr/testify v1.9.0 go.uber.org/mock v0.5.0 golang.org/x/crypto v0.26.0 - golang.org/x/time v0.5.0 google.golang.org/genproto/googleapis/api v0.0.0-20241021214115-324edc3d5d38 google.golang.org/grpc v1.67.1 google.golang.org/protobuf v1.35.1 @@ -59,10 +55,14 @@ require ( // extra/rest deps require ( + github.com/gin-gonic/gin v1.8.1 + github.com/go-sql-driver/mysql v1.8.1 github.com/lib/pq v1.10.7 github.com/mattn/go-sqlite3 v1.14.22 github.com/patrickmn/go-cache v2.1.0+incompatible + github.com/segmentio/kafka-go v0.4.47 github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d + golang.org/x/time v0.5.0 gorm.io/driver/mysql v1.5.7 gorm.io/driver/postgres v1.5.9 gorm.io/driver/sqlite v1.5.6 From 862c45151f7c56c6a02dc6c65c7ec200de0749f1 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 13 Nov 2024 19:50:29 +0700 Subject: [PATCH 112/132] fix command --- docker-config/start_docker.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 527f5c4cb..9112da035 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -192,7 +192,7 @@ do done # send band tokens to grantees - echo "y" | bandd tx multi-send 1000000uband $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync + echo "y" | bandd tx bank multi-send 1000000uband $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync sleep 4 # grant tss From 17373e76b5f03b74748c32fcd85897c7c5fbb04b Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 13 Nov 2024 20:06:34 +0700 Subject: [PATCH 113/132] fix --- docker-config/start_docker.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 9112da035..fdc595452 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -192,7 +192,7 @@ do done # send band tokens to grantees - echo "y" | bandd tx bank multi-send 1000000uband $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync + echo "y" | bandd tx bank multi-send account$v $(cylinder keys list -a) 1000000uband --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband -b sync sleep 4 # grant tss From a1abbea48f5b126fa5198f008304e6c7963d7eff Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 13 Nov 2024 20:18:37 +0700 Subject: [PATCH 114/132] fix --- docker-config/start_docker.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index fdc595452..9e90573c5 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -185,7 +185,7 @@ do cylinder config random-secret "$(openssl rand -hex 32)" cylinder config checking-de-interval "5m" - for i in $(eval echo {1..1}) + for i in $(eval echo {1..4}) do # add signer key cylinder keys add signer$i From 7d13b95a3810997f1608e83a52dff5dd45e3c9f6 Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Wed, 13 Nov 2024 20:49:19 +0700 Subject: [PATCH 115/132] fix gas --- docker-config/start_docker.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 9e90573c5..99ca81878 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -196,7 +196,7 @@ do sleep 4 # grant tss - echo "y" | bandd tx tss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 350000 -b sync + echo "y" | bandd tx tss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 2000000 -b sync sleep 4 docker create --network chain_bandchain --name bandchain-cylinder${v} band-validator:latest cylinder run From f3350edcd771d2593cf7bc19072370c7938af65e Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Fri, 15 Nov 2024 16:54:20 +0700 Subject: [PATCH 116/132] fix parameter --- docker-config/start_docker.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 99ca81878..295d2848f 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -174,16 +174,16 @@ do cylinder config node tcp://multi-validator$v-node:26657 cylinder config chain-id bandchain cylinder config granter $(bandd keys show account$v -a --keyring-backend test) - cylinder config max-messages 10 + cylinder config max-messages 20 cylinder config broadcast-timeout "5m" cylinder config rpc-poll-interval "1s" cylinder config max-try 5 cylinder config gas-prices "0uband" - cylinder config min-de 20 + cylinder config min-de 100 cylinder config gas-adjust-start 1.6 cylinder config gas-adjust-step 0.2 cylinder config random-secret "$(openssl rand -hex 32)" - cylinder config checking-de-interval "5m" + cylinder config checking-de-interval "1m" for i in $(eval echo {1..4}) do @@ -196,7 +196,7 @@ do sleep 4 # grant tss - echo "y" | bandd tx tss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 2000000 -b sync + echo "y" | bandd tx tss add-grantees $(cylinder keys list -a) --from account$v --keyring-backend test --chain-id bandchain --gas-prices 0.0025uband --gas 700000 -b sync sleep 4 docker create --network chain_bandchain --name bandchain-cylinder${v} band-validator:latest cylinder run From 6bccc471b8923928263c32cd4c9c1b50be440df8 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 18 Nov 2024 10:13:16 +0700 Subject: [PATCH 117/132] fix from comments --- flusher/flusher/handler.py | 6 +- hooks/emitter/bandtss.go | 28 ++-- hooks/emitter/decoder.go | 28 ++-- hooks/emitter/decoder_test.go | 127 +++++++++++++++--- .../bandtss/proposal_transition_group.json | 2 +- 5 files changed, 144 insertions(+), 47 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 4d6e4f215..959474278 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -1028,7 +1028,7 @@ def handle_update_tss_assigned_member(self, msg): # BANDTSS_HANDLER ################################## - def handle_set_bandtss_group_transition(self, msg): + def handle_new_bandtss_group_transition(self, msg): if "tss_signing_id" in msg and msg["tss_signing_id"] == 0: del msg["tss_signing_id"] if "current_tss_group_id" in msg and msg["current_tss_group_id"] == 0: @@ -1068,7 +1068,7 @@ def handle_update_bandtss_group_transition_failed(self, msg): msg = {"status": GroupTransitionStatus.expired} self.update_bandtss_group_transition(msg) - def handle_set_bandtss_current_group(self, msg): + def handle_new_bandtss_current_group(self, msg): proposal_column = bandtss_group_transitions.c.proposal_id proposal_id = self.conn.execute(select(func.max(proposal_column))).scalar() if proposal_id is not None: @@ -1086,7 +1086,7 @@ def handle_set_bandtss_member(self, msg): .on_conflict_do_update(constraint="bandtss_members_pkey", set_=msg) ) - def handle_set_bandtss_signing(self, msg): + def handle_new_bandtss_signing(self, msg): if msg["current_group_tss_signing_id"] == 0: del msg["current_group_tss_signing_id"] if msg["incoming_group_tss_signing_id"] == 0: diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index 42394292c..670755944 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -10,12 +10,12 @@ import ( tsstypes "github.com/bandprotocol/chain/v3/x/tss/types" ) -func (h *Hook) emitSetBandtssGroupTransition( +func (h *Hook) emitNewBandtssGroupTransition( proposalID uint64, transition types.GroupTransition, createdHeight int64, ) { - h.Write("SET_BANDTSS_GROUP_TRANSITION", common.JsDict{ + h.Write("NEW_BANDTSS_GROUP_TRANSITION", common.JsDict{ "proposal_id": proposalID, "tss_signing_id": transition.SigningID, "current_tss_group_id": transition.CurrentGroupID, @@ -54,8 +54,8 @@ func (h *Hook) emitUpdateBandtssGroupTransitionStatusFailed(transition types.Gro }) } -func (h *Hook) emitSetBandtssCurrentGroup(gid tss.GroupID, transitionHeight int64) { - h.Write("SET_BANDTSS_CURRENT_GROUP", common.JsDict{ +func (h *Hook) emitNewBandtssCurrentGroup(gid tss.GroupID, transitionHeight int64) { + h.Write("NEW_BANDTSS_CURRENT_GROUP", common.JsDict{ "current_tss_group_id": gid, "transition_height": transitionHeight, }) @@ -70,8 +70,8 @@ func (h *Hook) emitSetBandtssMember(member types.Member) { }) } -func (h *Hook) emitSetBandtssSigning(signing types.Signing) { - h.Write("SET_BANDTSS_SIGNING", common.JsDict{ +func (h *Hook) emitNewBandtssSigning(signing types.Signing) { + h.Write("New_BANDTSS_SIGNING", common.JsDict{ "id": signing.ID, "fee_per_signer": signing.FeePerSigner.String(), "requester": signing.Requester, @@ -84,7 +84,7 @@ func (h *Hook) emitSetBandtssSigning(signing types.Signing) { func (h *Hook) handleInitBandtssModule(ctx sdk.Context) { currentGroupID := h.bandtssKeeper.GetCurrentGroup(ctx).GroupID if currentGroupID != 0 { - h.emitSetBandtssCurrentGroup(currentGroupID, ctx.BlockHeight()) + h.emitNewBandtssCurrentGroup(currentGroupID, ctx.BlockHeight()) } members := h.bandtssKeeper.GetMembers(ctx) @@ -141,7 +141,7 @@ func (h *Hook) handleBandtssEventGroupTransition(ctx sdk.Context, eventIdx int, return } - // set new bandtss members; better approach would be emitting addMember event. + // set new bandtss members. if transition.Status == types.TRANSITION_STATUS_WAITING_EXECUTION { tssMembers := h.tssKeeper.MustGetMembers(ctx, transition.IncomingGroupID) for _, tssMember := range tssMembers { @@ -164,7 +164,7 @@ func (h *Hook) handleBandtssEventGroupTransition(ctx sdk.Context, eventIdx int, panic("proposal ID not found") } - h.emitSetBandtssGroupTransition(proposalID, transition, ctx.BlockHeight()) + h.emitNewBandtssGroupTransition(proposalID, transition, ctx.BlockHeight()) } else { h.emitUpdateBandtssGroupTransitionStatus(transition) } @@ -174,8 +174,8 @@ func (h *Hook) handleBandtssEventGroupTransition(ctx sdk.Context, eventIdx int, func (h *Hook) handleBandtssEventGroupTransitionSuccess(ctx sdk.Context, evMap common.EvMap) { // use value from emitted event due to the transition info is removed from the store. signingIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+tsstypes.AttributeKeySigningID] - incomingGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyIncomingGroupID] currentGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyCurrentGroupID] + incomingGroupIDs := evMap[types.EventTypeGroupTransitionSuccess+"."+types.AttributeKeyIncomingGroupID] signingID := tss.SigningID(common.Atoi(signingIDs[0])) currentGroupID := tss.GroupID(common.Atoi(currentGroupIDs[0])) @@ -187,7 +187,7 @@ func (h *Hook) handleBandtssEventGroupTransitionSuccess(ctx sdk.Context, evMap c IncomingGroupID: incomingGroupID, }) - h.emitSetBandtssCurrentGroup(incomingGroupID, ctx.BlockHeight()) + h.emitNewBandtssCurrentGroup(incomingGroupID, ctx.BlockHeight()) } // handleBandtssEventGroupTransitionFailed implements emitter handler for group transition failed event. @@ -209,8 +209,8 @@ func (h *Hook) handleBandtssEventSigningRequestCreated(ctx sdk.Context, evMap co signingIDs := evMap[types.EventTypeSigningRequestCreated+"."+types.AttributeKeySigningID] for _, sid := range signingIDs { - signing := h.bandtssKeeper.MustGetSigning(ctx, types.SigningID(uint64(common.Atoi(sid)))) - h.emitSetBandtssSigning(signing) + signing := h.bandtssKeeper.MustGetSigning(ctx, types.SigningID(common.Atoui(sid))) + h.emitNewBandtssSigning(signing) } } @@ -224,7 +224,7 @@ func getCurrentProposalID(eventIdx int, querier *EventQuerier) (id uint64, found for _, attr := range proposalIDEvent.Attributes { if attr.Key == govtypes.AttributeKeyProposalID { - return uint64(common.Atoi(attr.Value)), true + return common.Atoui(attr.Value), true } } diff --git a/hooks/emitter/decoder.go b/hooks/emitter/decoder.go index 2d3bfb354..1c020e88a 100644 --- a/hooks/emitter/decoder.go +++ b/hooks/emitter/decoder.go @@ -148,19 +148,19 @@ func DecodeMsg(msg sdk.Msg, detail common.JsDict) { case *bandtsstypes.MsgUpdateParams: DecodeBandtssMsgUpdateParams(msg, detail) case *tsstypes.MsgSubmitDKGRound1: - DecodeMsgSubmitDKGRound1(msg, detail) + DecodeTssMsgSubmitDKGRound1(msg, detail) case *tsstypes.MsgSubmitDKGRound2: - DecodeMsgSubmitDKGRound2(msg, detail) + DecodeTssMsgSubmitDKGRound2(msg, detail) case *tsstypes.MsgComplain: - DecodeMsgComplain(msg, detail) + DecodeTssMsgComplain(msg, detail) case *tsstypes.MsgConfirm: - DecodeMsgConfirm(msg, detail) + DecodeTssMsgConfirm(msg, detail) case *tsstypes.MsgSubmitDEs: - DecodeMsgSubmitDEs(msg, detail) + DecodeTssMsgSubmitDEs(msg, detail) case *tsstypes.MsgSubmitSignature: - DecodeMsgSubmitSignature(msg, detail) + DecodeTssMsgSubmitSignature(msg, detail) case *tsstypes.MsgUpdateParams: - DecodeMsgUpdateParamsTss(msg, detail) + DecodeTssMsgUpdateParams(msg, detail) case *group.MsgCreateGroup: DecodeGroupMsgCreateGroup(msg, detail) case *group.MsgCreateGroupPolicy: @@ -749,44 +749,44 @@ func DecodeBandtssMsgUpdateParams(msg *bandtsstypes.MsgUpdateParams, detail comm detail["authority"] = msg.GetAuthority() } -func DecodeMsgSubmitDKGRound1(msg *tsstypes.MsgSubmitDKGRound1, detail common.JsDict) { +func DecodeTssMsgSubmitDKGRound1(msg *tsstypes.MsgSubmitDKGRound1, detail common.JsDict) { detail["group_id"] = msg.GroupID detail["round1_info"] = msg.Round1Info detail["sender"] = msg.Sender } -func DecodeMsgSubmitDKGRound2(msg *tsstypes.MsgSubmitDKGRound2, detail common.JsDict) { +func DecodeTssMsgSubmitDKGRound2(msg *tsstypes.MsgSubmitDKGRound2, detail common.JsDict) { detail["group_id"] = msg.GroupID detail["round2_info"] = msg.Round2Info detail["sender"] = msg.Sender } -func DecodeMsgComplain(msg *tsstypes.MsgComplain, detail common.JsDict) { +func DecodeTssMsgComplain(msg *tsstypes.MsgComplain, detail common.JsDict) { detail["group_id"] = msg.GroupID detail["complaints"] = msg.Complaints detail["sender"] = msg.Sender } -func DecodeMsgConfirm(msg *tsstypes.MsgConfirm, detail common.JsDict) { +func DecodeTssMsgConfirm(msg *tsstypes.MsgConfirm, detail common.JsDict) { detail["group_id"] = msg.GroupID detail["member_id"] = msg.MemberID detail["own_pub_key_sig"] = msg.OwnPubKeySig detail["sender"] = msg.Sender } -func DecodeMsgSubmitDEs(msg *tsstypes.MsgSubmitDEs, detail common.JsDict) { +func DecodeTssMsgSubmitDEs(msg *tsstypes.MsgSubmitDEs, detail common.JsDict) { detail["des"] = msg.DEs detail["sender"] = msg.Sender } -func DecodeMsgSubmitSignature(msg *tsstypes.MsgSubmitSignature, detail common.JsDict) { +func DecodeTssMsgSubmitSignature(msg *tsstypes.MsgSubmitSignature, detail common.JsDict) { detail["signing_id"] = msg.SigningID detail["member_id"] = msg.MemberID detail["signature"] = msg.Signature detail["signer"] = msg.Signer } -func DecodeMsgUpdateParamsTss(msg *tsstypes.MsgUpdateParams, detail common.JsDict) { +func DecodeTssMsgUpdateParams(msg *tsstypes.MsgUpdateParams, detail common.JsDict) { detail["params"] = msg.GetParams() detail["authority"] = msg.GetAuthority() } diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index 9fa1b8ca5..522cb97d3 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -996,28 +996,47 @@ func (suite *DecoderTestSuite) TestDecodeBandtssMsgTransitionGroup() { msg := bandtsstypes.MsgTransitionGroup{ Members: []string{"member1", "member2"}, Threshold: 2, - Authority: "some-authority-id", + Authority: AuthorityAddress.String(), ExecTime: time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC), } emitter.DecodeBandtssMsgTransitionGroup(&msg, detail) - expectedJSON := `{"authority":"some-authority-id","exec_time":1577923200000000000,"members":["member1","member2"],"threshold":2}` + expectedJSON := `{"authority":"band1g96hg6r0wf5hg7gqqqqqqqqqqqqqqqqq4rjgsx","exec_time":1577923200000000000,"members":["member1","member2"],"threshold":2}` suite.testCompareJson(detail, expectedJSON) } -func (suite *DecoderTestSuite) TestDecodeGroupMsgReplaceGroup() { +func (suite *DecoderTestSuite) TestDecodeBandtssGroupMsgForceTransitionGroup() { detail := make(common.JsDict) msg := bandtsstypes.MsgForceTransitionGroup{ IncomingGroupID: 1, ExecTime: time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC), - Authority: "authority123", + Authority: AuthorityAddress.String(), } emitter.DecodeBandtssMsgForceTransitionGroup(&msg, detail) - expectedJSON := `{"authority":"authority123","exec_time":1577923200000000000,"incoming_group_id":1}` + expectedJSON := `{"authority":"band1g96hg6r0wf5hg7gqqqqqqqqqqqqqqqqq4rjgsx","exec_time":1577923200000000000,"incoming_group_id":1}` + suite.testCompareJson(detail, expectedJSON) +} + +func (suite *DecoderTestSuite) TestDecodeBandtssRequestSignature() { + detail := make(common.JsDict) + + content := tsstypes.TextSignatureOrder{Message: []byte("test_message")} + + msg := bandtsstypes.MsgRequestSignature{ + Memo: "test_memo", + FeeLimit: sdk.NewCoins(sdk.NewCoin("uband", math.NewInt(100))), + Sender: SenderAddress.String(), + } + err := msg.SetContent(&content) + suite.Require().NoError(err) + + emitter.DecodeBandtssMsgRequestSignature(&msg, detail) + + expectedJSON := `{"content":{"message":"746573745F6D657373616765"},"content_type":"/band.tss.v1beta1.TextSignatureOrder","fee_limit":[{"denom":"uband","amount":"100"}],"memo":"test_memo","sender":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0"}` suite.testCompareJson(detail, expectedJSON) } @@ -1025,11 +1044,12 @@ func (suite *DecoderTestSuite) TestDecodeBandtssMsgUpdateParams() { detail := make(common.JsDict) msg := bandtsstypes.MsgUpdateParams{ - Params: bandtsstypes.NewParams(10, 50, 50, sdk.Coins{Amount}), + Params: bandtsstypes.NewParams(10, 50, 50, sdk.Coins{Amount}), + Authority: AuthorityAddress.String(), } emitter.DecodeBandtssMsgUpdateParams(&msg, detail) - expectedJSON := `{"authority":"","params":{"reward_percentage":10,"inactive_penalty_duration":50,"max_transition_duration":50,"fee":[{"denom":"uband","amount":"1"}]}}` + expectedJSON := `{"authority":"band1g96hg6r0wf5hg7gqqqqqqqqqqqqqqqqq4rjgsx","params":{"reward_percentage":10,"inactive_penalty_duration":50,"max_transition_duration":50,"fee":[{"denom":"uband","amount":"1"}]}}` suite.testCompareJson(detail, expectedJSON) } @@ -1037,12 +1057,12 @@ func (suite *DecoderTestSuite) TestDecodeBandtssMsgActivate() { detail := make(common.JsDict) msg := bandtsstypes.MsgActivate{ - Sender: "0x123", + Sender: SenderAddress.String(), GroupID: 1, } emitter.DecodeBandtssMsgActivate(&msg, detail) - expectedJSON := `{"group_id":1,"sender":"0x123"}` + expectedJSON := `{"group_id":1,"sender":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0"}` suite.testCompareJson(detail, expectedJSON) } @@ -1058,11 +1078,11 @@ func (suite *DecoderTestSuite) TestDecodeMsgSubmitDKGRound1() { A0Signature: tssSignature, OneTimeSignature: tssSignature, }, - Sender: "0x123", + Sender: SenderAddress.String(), } - emitter.DecodeMsgSubmitDKGRound1(&msg, detail) - expectedJSON := "{\"group_id\":1,\"round1_info\":{\"member_id\":1,\"coefficient_commits\":[\"706F696E74\",\"706F696E74\"],\"one_time_pub_key\":\"706F696E74\",\"a0_signature\":\"7369676E6174757265\",\"one_time_signature\":\"7369676E6174757265\"},\"sender\":\"0x123\"}" + emitter.DecodeTssMsgSubmitDKGRound1(&msg, detail) + expectedJSON := `{"group_id":1,"round1_info":{"member_id":1,"coefficient_commits":["706F696E74","706F696E74"],"one_time_pub_key":"706F696E74","a0_signature":"7369676E6174757265","one_time_signature":"7369676E6174757265"},"sender":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0"}` suite.testCompareJson(detail, expectedJSON) } @@ -1075,11 +1095,88 @@ func (suite *DecoderTestSuite) TestDecodeMsgSubmitDKGRound2() { MemberID: 1, EncryptedSecretShares: tss.EncSecretShares{tssEncSecretShare}, }, - Sender: "0x456", + Sender: SenderAddress.String(), + } + + emitter.DecodeTssMsgSubmitDKGRound2(&msg, detail) + expectedJSON := "{\"group_id\":1,\"round2_info\":{\"member_id\":1,\"encrypted_secret_shares\":[\"656E635365637265745368617265\"]},\"sender\":\"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0\"}" + suite.testCompareJson(detail, expectedJSON) +} + +func (suite *DecoderTestSuite) TestDecodeMsgComplain() { + detail := make(common.JsDict) + + msg := tsstypes.MsgComplain{ + GroupID: 1, + Complaints: []tsstypes.Complaint{ + { + Complainant: 1, + Respondent: 2, + KeySym: tss.Point("key_sym"), + Signature: tss.ComplaintSignature([]byte("signature")), + }, + }, + Sender: SenderAddress.String(), + } + + emitter.DecodeTssMsgComplain(&msg, detail) + expectedJSON := `{"complaints":[{"complainant":1,"respondent":2,"key_sym":"6B65795F73796D","signature":"7369676E6174757265"}],"group_id":1,"sender":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0"}` + suite.testCompareJson(detail, expectedJSON) +} + +func (suite *DecoderTestSuite) TestDecodeMsgConfirm() { + detail := make(common.JsDict) + + msg := tsstypes.MsgConfirm{ + GroupID: 1, + MemberID: 1, + OwnPubKeySig: tss.Signature([]byte("signature")), + Sender: SenderAddress.String(), + } + + emitter.DecodeTssMsgConfirm(&msg, detail) + expectedJSON := `{"group_id":1,"member_id":1,"own_pub_key_sig":"7369676E6174757265","sender":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0"}` + suite.testCompareJson(detail, expectedJSON) +} + +func (suite *DecoderTestSuite) TestDecodeMsgSubmitDE() { + detail := make(common.JsDict) + + msg := tsstypes.MsgSubmitDEs{ + DEs: []tsstypes.DE{{PubD: tss.Point([]byte("pub_d")), PubE: tss.Point("pub_e")}}, + Sender: SenderAddress.String(), + } + + emitter.DecodeTssMsgSubmitDEs(&msg, detail) + expectedJSON := `{"des":[{"pub_d":"7075625F64","pub_e":"7075625F65"}],"sender":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0"}` + suite.testCompareJson(detail, expectedJSON) +} + +func (suite *DecoderTestSuite) TestDecodeMsgSubmitSignature() { + detail := make(common.JsDict) + + msg := tsstypes.MsgSubmitSignature{ + SigningID: 1, + MemberID: 1, + Signature: tss.Signature([]byte("signature")), + Signer: SenderAddress.String(), + } + + emitter.DecodeTssMsgSubmitSignature(&msg, detail) + expectedJSON := `{"member_id":1,"signature":"7369676E6174757265","signer":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0","signing_id":1}` + suite.testCompareJson(detail, expectedJSON) +} + +func (suite *DecoderTestSuite) TestDecodeMsgUpdateParams() { + detail := make(common.JsDict) + + msg := tsstypes.MsgUpdateParams{ + Authority: AuthorityAddress.String(), + Params: tsstypes.DefaultParams(), } - emitter.DecodeMsgSubmitDKGRound2(&msg, detail) - expectedJSON := "{\"group_id\":1,\"round2_info\":{\"member_id\":1,\"encrypted_secret_shares\":[\"656E635365637265745368617265\"]},\"sender\":\"0x456\"}" + emitter.DecodeTssMsgUpdateParams(&msg, detail) + expectedJSON := `{"authority":"band1g96hg6r0wf5hg7gqqqqqqqqqqqqqqqqq4rjgsx","params":{"max_group_size":20,"max_de_size":300,"creation_period":30000,"signing_period":100,"max_signing_attempt":5,"max_memo_length":100,"max_message_length":1000}}` suite.testCompareJson(detail, expectedJSON) } diff --git a/scripts/bandtss/proposal_transition_group.json b/scripts/bandtss/proposal_transition_group.json index bf510b1a3..738054e5e 100755 --- a/scripts/bandtss/proposal_transition_group.json +++ b/scripts/bandtss/proposal_transition_group.json @@ -8,7 +8,7 @@ "band1nx0xkpnytk35wvflsg7gszf9smw3vaeauk248q" ], "threshold": "2", - "exec_time": "2024-11-06T16:40:00+00:00", + "exec_time": "2024-11-18T16:40:00+00:00", "authority": "band10d07y265gmmuvt4z0w9aw880jnsr700jrdn8wm" } ], From 45e23b48b4c0e74fa8be53888e5064520379ceb8 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 18 Nov 2024 11:21:18 +0700 Subject: [PATCH 118/132] reformat --- flusher/flusher/db.py | 149 ++++++++---------------------------------- 1 file changed, 29 insertions(+), 120 deletions(-) diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index cc7e710fa..4dbde3ee1 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -155,9 +155,7 @@ def Column(*args, **kwargs): Column("executable", CustomBase64), Column("treasury", sa.String), Column("fee", sa.String), - Column( - "transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True - ), + Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True), Column("accumulated_revenue", sa.BigInteger), Column("last_request", CustomDateTime, nullable=True), ) @@ -172,9 +170,7 @@ def Column(*args, **kwargs): Column("schema", sa.String), Column("codehash", sa.String), Column("source_code_url", sa.String), - Column( - "transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True - ), + Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), nullable=True), Column("version", sa.Integer, nullable=True), Column("last_request", CustomDateTime, nullable=True), ) @@ -199,21 +195,10 @@ def Column(*args, **kwargs): Column("request_time", sa.Integer, nullable=True, index=True), Column("resolve_status", CustomResolveStatus), Column("resolve_time", sa.Integer, nullable=True), - Column( - "resolve_height", - sa.Integer, - sa.ForeignKey("blocks.height"), - nullable=True, - index=True, - ), + Column("resolve_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True,), Column("reason", sa.String, nullable=True), Column("result", CustomBase64, nullable=True), - Column( - "bandtss_signing_id", - sa.Integer, - sa.ForeignKey("bandtss_signings.id"), - nullable=True, - ), + Column("bandtss_signing_id", sa.Integer, sa.ForeignKey("bandtss_signings.id"), nullable=True,), Column("bandtss_signing_error_codespace", sa.String, nullable=True), Column("bandtss_signing_error_code", sa.Integer, nullable=True), Column("total_fees", sa.String), @@ -222,13 +207,7 @@ def Column(*args, **kwargs): "ix_requests_oracle_script_id_id", "oracle_script_id", "id", - postgresql_include=[ - "transaction_id", - "min_count", - "ask_count", - "resolve_status", - "request_time", - ], + postgresql_include=["transaction_id", "min_count", "ask_count", "resolve_status", "request_time",], ), sa.Index( "ix_requests_oracle_script_id_resolve_status_request_time", @@ -246,18 +225,14 @@ def Column(*args, **kwargs): Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), index=True), Column("fee", sa.BigInteger), Column("calldata", CustomBase64), - sa.Index( - "ix_raw_requests_data_source_id_request_id", "data_source_id", "request_id" - ), + sa.Index("ix_raw_requests_data_source_id_request_id", "data_source_id", "request_id"), ) val_requests = sa.Table( "val_requests", metadata, Column("request_id", sa.Integer, sa.ForeignKey("requests.id"), primary_key=True), - Column( - "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True - ), + Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), ) reports = sa.Table( @@ -265,9 +240,7 @@ def Column(*args, **kwargs): metadata, Column("request_id", sa.Integer, sa.ForeignKey("requests.id"), primary_key=True), Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id")), - Column( - "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True - ), + Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), Column("reporter_id", sa.Integer, sa.ForeignKey("accounts.id")), sa.Index("ix_reports_validator_id_request_id", "validator_id", "request_id"), ) @@ -280,13 +253,8 @@ def Column(*args, **kwargs): Column("external_id", sa.BigInteger, primary_key=True), Column("data", CustomBase64), Column("exit_code", sa.BigInteger), - sa.ForeignKeyConstraint( - ["request_id", "validator_id"], ["reports.request_id", "reports.validator_id"] - ), - sa.ForeignKeyConstraint( - ["request_id", "external_id"], - ["raw_requests.request_id", "raw_requests.external_id"], - ), + sa.ForeignKeyConstraint(["request_id", "validator_id"], ["reports.request_id", "reports.validator_id"]), + sa.ForeignKeyConstraint(["request_id", "external_id"], ["raw_requests.request_id", "raw_requests.external_id"],), ) validators = sa.Table( @@ -318,9 +286,7 @@ def Column(*args, **kwargs): delegations = sa.Table( "delegations", metadata, - Column( - "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True - ), + Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), Column("delegator_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), Column("shares", sa.DECIMAL), Column("last_ratio", sa.DECIMAL), @@ -329,15 +295,8 @@ def Column(*args, **kwargs): validator_votes = sa.Table( "validator_votes", metadata, - Column( - "block_height", sa.Integer, sa.ForeignKey("blocks.height"), primary_key=True - ), - Column( - "consensus_address", - sa.String, - sa.ForeignKey("validators.consensus_address"), - primary_key=True, - ), + Column("block_height", sa.Integer, sa.ForeignKey("blocks.height"), primary_key=True), + Column("consensus_address", sa.String, sa.ForeignKey("validators.consensus_address"), primary_key=True,), Column("voted", sa.Boolean), ) @@ -346,9 +305,7 @@ def Column(*args, **kwargs): metadata, Column("delegator_id", sa.Integer, sa.ForeignKey("accounts.id")), Column("validator_id", sa.Integer, sa.ForeignKey("validators.id")), - Column( - "creation_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True - ), + Column("creation_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True), Column("completion_time", CustomDateTime), Column("amount", sa.DECIMAL), ) @@ -366,15 +323,9 @@ def Column(*args, **kwargs): account_transactions = sa.Table( "account_transactions", metadata, - Column( - "transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), primary_key=True - ), + Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), primary_key=True), Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), - sa.Index( - "ix_account_transactions_account_id_transaction_id", - "account_id", - "transaction_id", - ), + sa.Index("ix_account_transactions_account_id_transaction_id", "account_id", "transaction_id",), ) proposals = sa.Table( @@ -424,9 +375,7 @@ def Column(*args, **kwargs): historical_bonded_token_on_validators = sa.Table( "historical_bonded_token_on_validators", metadata, - Column( - "validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True - ), + Column("validator_id", sa.Integer, sa.ForeignKey("validators.id"), primary_key=True), Column("bonded_tokens", sa.DECIMAL), Column("timestamp", CustomDateTime, primary_key=True), ) @@ -441,15 +390,8 @@ def Column(*args, **kwargs): related_data_source_oracle_scripts = sa.Table( "related_data_source_oracle_scripts", metadata, - Column( - "data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True - ), - Column( - "oracle_script_id", - sa.Integer, - sa.ForeignKey("oracle_scripts.id"), - primary_key=True, - ), + Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True), + Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True,), ) historical_oracle_statuses = sa.Table( @@ -463,9 +405,7 @@ def Column(*args, **kwargs): data_source_requests = sa.Table( "data_source_requests", metadata, - Column( - "data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True - ), + Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True), Column("count", sa.Integer), ) @@ -473,21 +413,14 @@ def Column(*args, **kwargs): "data_source_requests_per_days", metadata, Column("date", CustomDate, primary_key=True), - Column( - "data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True - ), + Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True), Column("count", sa.Integer), ) oracle_script_requests = sa.Table( "oracle_script_requests", metadata, - Column( - "oracle_script_id", - sa.Integer, - sa.ForeignKey("oracle_scripts.id"), - primary_key=True, - ), + Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True,), Column("count", sa.Integer), ) @@ -495,20 +428,12 @@ def Column(*args, **kwargs): "oracle_script_requests_per_days", metadata, Column("date", CustomDate, primary_key=True), - Column( - "oracle_script_id", - sa.Integer, - sa.ForeignKey("oracle_scripts.id"), - primary_key=True, - ), + Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True,), Column("count", sa.Integer), ) request_count_per_days = sa.Table( - "request_count_per_days", - metadata, - Column("date", CustomDate, primary_key=True), - Column("count", sa.Integer), + "request_count_per_days", metadata, Column("date", CustomDate, primary_key=True), Column("count", sa.Integer), ) incoming_packets = sa.Table( @@ -524,9 +449,7 @@ def Column(*args, **kwargs): Column("type", sa.String, nullable=True), Column("data", sa.JSON, nullable=True), Column("acknowledgement", sa.JSON, nullable=True), - sa.ForeignKeyConstraint( - ["dst_port", "dst_channel"], ["channels.port", "channels.channel"] - ), + sa.ForeignKeyConstraint(["dst_port", "dst_channel"], ["channels.port", "channels.channel"]), ) outgoing_packets = sa.Table( @@ -542,24 +465,15 @@ def Column(*args, **kwargs): Column("type", sa.String, nullable=True), Column("data", sa.JSON, nullable=True), Column("acknowledgement", sa.JSON, nullable=True), - sa.ForeignKeyConstraint( - ["src_port", "src_channel"], ["channels.port", "channels.channel"] - ), + sa.ForeignKeyConstraint(["src_port", "src_channel"], ["channels.port", "channels.channel"]), ) -counterparty_chains = sa.Table( - "counterparty_chains", metadata, Column("chain_id", sa.String, primary_key=True) -) +counterparty_chains = sa.Table("counterparty_chains", metadata, Column("chain_id", sa.String, primary_key=True)) connections = sa.Table( "connections", metadata, - Column( - "counterparty_chain_id", - sa.String, - sa.ForeignKey("counterparty_chains.chain_id"), - primary_key=True, - ), + Column("counterparty_chain_id", sa.String, sa.ForeignKey("counterparty_chains.chain_id"), primary_key=True,), Column("counterparty_connection_id", sa.String), Column("client_id", sa.String), Column("counterparty_client_id", sa.String), @@ -644,12 +558,7 @@ def Column(*args, **kwargs): group_votes = sa.Table( "group_votes", metadata, - Column( - "group_proposal_id", - sa.Integer, - sa.ForeignKey("group_proposals.id"), - primary_key=True, - ), + Column("group_proposal_id", sa.Integer, sa.ForeignKey("group_proposals.id"), primary_key=True,), Column("voter_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), Column("option", sa.String), Column("metadata", sa.String), From e0a940949128857cb9e47407a4f9ae962286fce1 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 18 Nov 2024 11:22:39 +0700 Subject: [PATCH 119/132] format --- flusher/flusher/db.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/flusher/flusher/db.py b/flusher/flusher/db.py index 4dbde3ee1..cfa86f88d 100644 --- a/flusher/flusher/db.py +++ b/flusher/flusher/db.py @@ -195,10 +195,10 @@ def Column(*args, **kwargs): Column("request_time", sa.Integer, nullable=True, index=True), Column("resolve_status", CustomResolveStatus), Column("resolve_time", sa.Integer, nullable=True), - Column("resolve_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True,), + Column("resolve_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True, index=True), Column("reason", sa.String, nullable=True), Column("result", CustomBase64, nullable=True), - Column("bandtss_signing_id", sa.Integer, sa.ForeignKey("bandtss_signings.id"), nullable=True,), + Column("bandtss_signing_id", sa.Integer, sa.ForeignKey("bandtss_signings.id"), nullable=True), Column("bandtss_signing_error_codespace", sa.String, nullable=True), Column("bandtss_signing_error_code", sa.Integer, nullable=True), Column("total_fees", sa.String), @@ -254,7 +254,7 @@ def Column(*args, **kwargs): Column("data", CustomBase64), Column("exit_code", sa.BigInteger), sa.ForeignKeyConstraint(["request_id", "validator_id"], ["reports.request_id", "reports.validator_id"]), - sa.ForeignKeyConstraint(["request_id", "external_id"], ["raw_requests.request_id", "raw_requests.external_id"],), + sa.ForeignKeyConstraint(["request_id", "external_id"], ["raw_requests.request_id", "raw_requests.external_id"]), ) validators = sa.Table( @@ -296,7 +296,7 @@ def Column(*args, **kwargs): "validator_votes", metadata, Column("block_height", sa.Integer, sa.ForeignKey("blocks.height"), primary_key=True), - Column("consensus_address", sa.String, sa.ForeignKey("validators.consensus_address"), primary_key=True,), + Column("consensus_address", sa.String, sa.ForeignKey("validators.consensus_address"), primary_key=True), Column("voted", sa.Boolean), ) @@ -325,7 +325,7 @@ def Column(*args, **kwargs): metadata, Column("transaction_id", sa.Integer, sa.ForeignKey("transactions.id"), primary_key=True), Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), - sa.Index("ix_account_transactions_account_id_transaction_id", "account_id", "transaction_id",), + sa.Index("ix_account_transactions_account_id_transaction_id", "account_id", "transaction_id"), ) proposals = sa.Table( @@ -391,7 +391,7 @@ def Column(*args, **kwargs): "related_data_source_oracle_scripts", metadata, Column("data_source_id", sa.Integer, sa.ForeignKey("data_sources.id"), primary_key=True), - Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True,), + Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True), ) historical_oracle_statuses = sa.Table( @@ -420,7 +420,7 @@ def Column(*args, **kwargs): oracle_script_requests = sa.Table( "oracle_script_requests", metadata, - Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True,), + Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True), Column("count", sa.Integer), ) @@ -428,7 +428,7 @@ def Column(*args, **kwargs): "oracle_script_requests_per_days", metadata, Column("date", CustomDate, primary_key=True), - Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True,), + Column("oracle_script_id", sa.Integer, sa.ForeignKey("oracle_scripts.id"), primary_key=True), Column("count", sa.Integer), ) @@ -473,7 +473,7 @@ def Column(*args, **kwargs): connections = sa.Table( "connections", metadata, - Column("counterparty_chain_id", sa.String, sa.ForeignKey("counterparty_chains.chain_id"), primary_key=True,), + Column("counterparty_chain_id", sa.String, sa.ForeignKey("counterparty_chains.chain_id"), primary_key=True), Column("counterparty_connection_id", sa.String), Column("client_id", sa.String), Column("counterparty_client_id", sa.String), @@ -558,7 +558,7 @@ def Column(*args, **kwargs): group_votes = sa.Table( "group_votes", metadata, - Column("group_proposal_id", sa.Integer, sa.ForeignKey("group_proposals.id"), primary_key=True,), + Column("group_proposal_id", sa.Integer, sa.ForeignKey("group_proposals.id"), primary_key=True), Column("voter_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), Column("option", sa.String), Column("metadata", sa.String), From 736966da8e7af5037b639104d7ae1fe7358bf0c0 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 25 Nov 2024 13:36:14 +0700 Subject: [PATCH 120/132] fix testcase --- hooks/emitter/decoder_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index 522cb97d3..e448a310d 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -1044,12 +1044,12 @@ func (suite *DecoderTestSuite) TestDecodeBandtssMsgUpdateParams() { detail := make(common.JsDict) msg := bandtsstypes.MsgUpdateParams{ - Params: bandtsstypes.NewParams(10, 50, 50, sdk.Coins{Amount}), + Params: bandtsstypes.NewParams(10, 50, 10, 50, sdk.Coins{Amount}), Authority: AuthorityAddress.String(), } emitter.DecodeBandtssMsgUpdateParams(&msg, detail) - expectedJSON := `{"authority":"band1g96hg6r0wf5hg7gqqqqqqqqqqqqqqqqq4rjgsx","params":{"reward_percentage":10,"inactive_penalty_duration":50,"max_transition_duration":50,"fee":[{"denom":"uband","amount":"1"}]}}` + expectedJSON := `{"authority":"band1g96hg6r0wf5hg7gqqqqqqqqqqqqqqqqq4rjgsx","params":{"reward_percentage":10,"inactive_penalty_duration":50,"min_transition_duration":10,"max_transition_duration":50,"fee_per_signer":[{"denom":"uband","amount":"1"}]}}` suite.testCompareJson(detail, expectedJSON) } From 58b5fc7d2fc84f1194ecd93da87c91129d994c47 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Mon, 25 Nov 2024 14:18:02 +0700 Subject: [PATCH 121/132] add bandtss.total_fee --- flusher/flusher/bandtss_db.py | 11 ++++------- hooks/emitter/bandtss.go | 8 +++++--- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/flusher/flusher/bandtss_db.py b/flusher/flusher/bandtss_db.py index 67e5f7eeb..e9e9e5c2d 100644 --- a/flusher/flusher/bandtss_db.py +++ b/flusher/flusher/bandtss_db.py @@ -1,12 +1,8 @@ -import sqlalchemy as sa import enum -from .db import ( - metadata, - Column, - CustomBase64, - CustomDateTime, -) +import sqlalchemy as sa + +from .db import Column, CustomBase64, CustomDateTime, metadata class GroupTransitionStatus(enum.Enum): @@ -106,6 +102,7 @@ def process_bind_param(self, value, dialect): Column("id", sa.Integer, primary_key=True), Column("account_id", sa.Integer, sa.ForeignKey("accounts.id")), Column("fee_per_signer", sa.String), + Column("total_fee", sa.String), Column( "current_group_tss_signing_id", sa.Integer, diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index 670755944..d6e935686 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -70,10 +70,11 @@ func (h *Hook) emitSetBandtssMember(member types.Member) { }) } -func (h *Hook) emitNewBandtssSigning(signing types.Signing) { +func (h *Hook) emitNewBandtssSigning(signing types.Signing, totalFee string) { h.Write("New_BANDTSS_SIGNING", common.JsDict{ "id": signing.ID, "fee_per_signer": signing.FeePerSigner.String(), + "total_fee": totalFee, "requester": signing.Requester, "current_group_tss_signing_id": signing.CurrentGroupSigningID, "incoming_group_tss_signing_id": signing.IncomingGroupSigningID, @@ -207,10 +208,11 @@ func (h *Hook) handleBandtssEventGroupTransitionFailed(_ sdk.Context, evMap comm // handleBandtssEventSigningRequestCreated implements emitter handler for MsgRequestSignature of bandtss. func (h *Hook) handleBandtssEventSigningRequestCreated(ctx sdk.Context, evMap common.EvMap) { signingIDs := evMap[types.EventTypeSigningRequestCreated+"."+types.AttributeKeySigningID] + totalFees := evMap[types.EventTypeSigningRequestCreated+"."+types.AttributeKeyTotalFee] - for _, sid := range signingIDs { + for i, sid := range signingIDs { signing := h.bandtssKeeper.MustGetSigning(ctx, types.SigningID(common.Atoui(sid))) - h.emitNewBandtssSigning(signing) + h.emitNewBandtssSigning(signing, totalFees[i]) } } From 15e78aeadd6b5a2dd0da4f0af90fc1a5efa3a5ec Mon Sep 17 00:00:00 2001 From: Kitipong Sirirueangsakul Date: Tue, 26 Nov 2024 03:29:10 +0700 Subject: [PATCH 122/132] fix lint --- flusher/flusher/handler.py | 307 +++++++++---------------------------- 1 file changed, 72 insertions(+), 235 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 959474278..45ccec994 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -80,50 +80,33 @@ def __init__(self, conn): self.conn = conn def get_transaction_id(self, tx_hash): - return self.conn.execute( - select([transactions.c.id]).where(transactions.c.hash == tx_hash) - ).scalar() + return self.conn.execute(select([transactions.c.id]).where(transactions.c.hash == tx_hash)).scalar() def get_transaction_sender(self, id): - return self.conn.execute( - select([transactions.c.sender]).where(transactions.c.id == id) - ).scalar() + return self.conn.execute(select([transactions.c.sender]).where(transactions.c.id == id)).scalar() def get_validator_id(self, val): - return self.conn.execute( - select([validators.c.id]).where(validators.c.operator_address == val) - ).scalar() + return self.conn.execute(select([validators.c.id]).where(validators.c.operator_address == val)).scalar() def get_account_id(self, address): if address is None: return None - id = self.conn.execute( - select([accounts.c.id]).where(accounts.c.address == address) - ).scalar() + id = self.conn.execute(select([accounts.c.id]).where(accounts.c.address == address)).scalar() if id is None: - self.conn.execute( - accounts.insert(), {"address": address, "balance": "0uband"} - ) - return self.conn.execute( - select([accounts.c.id]).where(accounts.c.address == address) - ).scalar() + self.conn.execute(accounts.insert(), {"address": address, "balance": "0uband"}) + return self.conn.execute(select([accounts.c.id]).where(accounts.c.address == address)).scalar() return id def get_request_count(self, date): return self.conn.execute( - select([request_count_per_days.c.count]).where( - request_count_per_days.c.date == date - ) + select([request_count_per_days.c.count]).where(request_count_per_days.c.date == date) ).scalar() def get_oracle_script_requests_count_per_day(self, date, oracle_script_id): return self.conn.execute( select([oracle_script_requests_per_days.c.count]).where( (oracle_script_requests_per_days.c.date == date) - & ( - oracle_script_requests_per_days.c.oracle_script_id - == oracle_script_id - ) + & (oracle_script_requests_per_days.c.oracle_script_id == oracle_script_id) ) ).scalar() @@ -136,20 +119,14 @@ def get_data_source_requests_count_per_day(self, date, data_source_id): ).scalar() def get_data_source_id(self, id): - return self.conn.execute( - select([data_sources.c.id]).where(data_sources.c.id == id) - ).scalar() + return self.conn.execute(select([data_sources.c.id]).where(data_sources.c.id == id)).scalar() def get_oracle_script_id(self, id): - return self.conn.execute( - select([oracle_scripts.c.id]).where(oracle_scripts.c.id == id) - ).scalar() + return self.conn.execute(select([oracle_scripts.c.id]).where(oracle_scripts.c.id == id)).scalar() def get_group_id_from_policy_address(self, address): return self.conn.execute( - select([group_policies.c.group_id]).where( - group_policies.c.address == address - ) + select([group_policies.c.group_id]).where(group_policies.c.address == address) ).scalar() def get_ibc_received_txs(self, date, port, channel, address): @@ -158,21 +135,15 @@ def get_ibc_received_txs(self, date, port, channel, address): for col in relayer_tx_stat_days.primary_key.columns.values(): condition = (col == msg[col.name]) & condition - return self.conn.execute( - select([relayer_tx_stat_days.c.ibc_received_txs]).where(condition) - ).scalar() + return self.conn.execute(select([relayer_tx_stat_days.c.ibc_received_txs]).where(condition)).scalar() def handle_new_block(self, msg): self.conn.execute(blocks.insert(), msg) def handle_new_transaction(self, msg): - msg["fee_payer"] = ( - msg["fee_payer"] if "fee_payer" in msg and len(msg["fee_payer"]) else None - ) + msg["fee_payer"] = msg["fee_payer"] if "fee_payer" in msg and len(msg["fee_payer"]) else None self.conn.execute( - insert(transactions) - .values(**msg) - .on_conflict_do_update(constraint="transactions_pkey", set_=msg) + insert(transactions).values(**msg).on_conflict_do_update(constraint="transactions_pkey", set_=msg) ) def handle_set_related_transaction(self, msg): @@ -231,9 +202,7 @@ def handle_new_group_policy(self, msg): self.conn.execute(group_policies.insert(), msg) def handle_new_group_proposal(self, msg): - msg["group_id"] = self.get_group_id_from_policy_address( - msg["group_policy_address"] - ) + msg["group_id"] = self.get_group_id_from_policy_address(msg["group_policy_address"]) self.conn.execute(group_proposals.insert(), msg) def handle_new_group_vote(self, msg): @@ -248,39 +217,22 @@ def handle_remove_group_member(self, msg): account_id = self.get_account_id(msg["address"]) self.conn.execute( group_members.delete().where( - (group_members.c.group_id == msg["group_id"]) - & (group_members.c.account_id == account_id) + (group_members.c.group_id == msg["group_id"]) & (group_members.c.account_id == account_id) ) ) def handle_remove_group_members_by_group_id(self, msg): - self.conn.execute( - group_members.delete().where(group_members.c.group_id == msg["group_id"]) - ) + self.conn.execute(group_members.delete().where(group_members.c.group_id == msg["group_id"])) def handle_update_group_policy(self, msg): - self.conn.execute( - group_policies.update() - .where(group_policies.c.address == msg["address"]) - .values(**msg) - ) + self.conn.execute(group_policies.update().where(group_policies.c.address == msg["address"]).values(**msg)) def handle_update_group_proposal(self, msg): - msg["group_id"] = self.get_group_id_from_policy_address( - msg["group_policy_address"] - ) - self.conn.execute( - group_proposals.update() - .where(group_proposals.c.id == msg["id"]) - .values(**msg) - ) + msg["group_id"] = self.get_group_id_from_policy_address(msg["group_policy_address"]) + self.conn.execute(group_proposals.update().where(group_proposals.c.id == msg["id"]).values(**msg)) def handle_update_group_proposal_by_id(self, msg): - self.conn.execute( - group_proposals.update() - .where(group_proposals.c.id == msg["id"]) - .values(**msg) - ) + self.conn.execute(group_proposals.update().where(group_proposals.c.id == msg["id"]).values(**msg)) def handle_set_data_source(self, msg): msg["transaction_id"] = self.get_transaction_id(msg["tx_hash"]) @@ -313,9 +265,7 @@ def handle_new_request(self, msg): self.handle_update_oracle_script_requests_count_per_day( {"date": msg["timestamp"], "oracle_script_id": msg["oracle_script_id"]} ) - self.update_oracle_script_last_request( - msg["oracle_script_id"], msg["timestamp"] - ) + self.update_oracle_script_last_request(msg["oracle_script_id"], msg["timestamp"]) del msg["timestamp"] self.conn.execute(requests.insert(), msg) self.increase_oracle_script_count(msg["oracle_script_id"]) @@ -328,16 +278,10 @@ def handle_update_request(self, msg): if "bandtss_signing_id" in msg and msg["bandtss_signing_id"] == 0: del msg["bandtss_signing_id"] - if ( - "bandtss_signing_error_codespace" in msg - and msg["bandtss_signing_error_codespace"] == "" - ): + if "bandtss_signing_error_codespace" in msg and msg["bandtss_signing_error_codespace"] == "": del msg["bandtss_signing_error_codespace"] - if ( - "bandtss_signing_error_code" in msg - and msg["bandtss_signing_error_code"] == 0 - ): + if "bandtss_signing_error_code" in msg and msg["bandtss_signing_error_code"] == 0: del msg["bandtss_signing_error_code"] condition = True @@ -349,9 +293,7 @@ def handle_update_related_ds_os(self, msg): self.conn.execute( insert(related_data_source_oracle_scripts) .values(**msg) - .on_conflict_do_nothing( - constraint="related_data_source_oracle_scripts_pkey" - ) + .on_conflict_do_nothing(constraint="related_data_source_oracle_scripts_pkey") ) def handle_new_raw_request(self, msg): @@ -360,16 +302,12 @@ def handle_new_raw_request(self, msg): self.handle_update_data_source_requests_count_per_day( {"date": msg["timestamp"], "data_source_id": msg["data_source_id"]} ) - self.update_data_source_last_request( - msg["data_source_id"], msg["timestamp"] - ) + self.update_data_source_last_request(msg["data_source_id"], msg["timestamp"]) del msg["timestamp"] self.handle_update_related_ds_os( { "oracle_script_id": self.conn.execute( - select([requests.c.oracle_script_id]).where( - requests.c.id == msg["request_id"] - ) + select([requests.c.oracle_script_id]).where(requests.c.id == msg["request_id"]) ).scalar(), "data_source_id": msg["data_source_id"], } @@ -435,9 +373,7 @@ def handle_update_validator(self, msg): ) del msg["last_update"] self.conn.execute( - validators.update() - .where(validators.c.operator_address == msg["operator_address"]) - .values(**msg) + validators.update().where(validators.c.operator_address == msg["operator_address"]).values(**msg) ) def handle_set_delegation(self, msg): @@ -446,9 +382,7 @@ def handle_set_delegation(self, msg): msg["validator_id"] = self.get_validator_id(msg["operator_address"]) del msg["operator_address"] self.conn.execute( - insert(delegations) - .values(**msg) - .on_conflict_do_update(constraint="delegations_pkey", set_=msg) + insert(delegations).values(**msg).on_conflict_do_update(constraint="delegations_pkey", set_=msg) ) def handle_update_delegation(self, msg): @@ -483,9 +417,7 @@ def handle_new_unbonding_delegation(self, msg): def handle_remove_unbonding(self, msg): self.conn.execute( - unbonding_delegations.delete().where( - unbonding_delegations.c.completion_time <= msg["timestamp"] - ) + unbonding_delegations.delete().where(unbonding_delegations.c.completion_time <= msg["timestamp"]) ) def handle_new_redelegation(self, msg): @@ -498,11 +430,7 @@ def handle_new_redelegation(self, msg): self.conn.execute(insert(redelegations).values(**msg)) def handle_remove_redelegation(self, msg): - self.conn.execute( - redelegations.delete().where( - redelegations.c.completion_time <= msg["timestamp"] - ) - ) + self.conn.execute(redelegations.delete().where(redelegations.c.completion_time <= msg["timestamp"])) def handle_new_proposal(self, msg): msg["proposer_id"] = self.get_account_id(msg["proposer"]) @@ -514,22 +442,14 @@ def handle_set_deposit(self, msg): del msg["depositor"] msg["tx_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] - self.conn.execute( - insert(deposits) - .values(**msg) - .on_conflict_do_update(constraint="deposits_pkey", set_=msg) - ) + self.conn.execute(insert(deposits).values(**msg).on_conflict_do_update(constraint="deposits_pkey", set_=msg)) def handle_set_vote_weighted(self, msg): msg["voter_id"] = self.get_account_id(msg["voter"]) del msg["voter"] msg["tx_id"] = self.get_transaction_id(msg["tx_hash"]) del msg["tx_hash"] - self.conn.execute( - insert(votes) - .values(**msg) - .on_conflict_do_update(constraint="votes_pkey", set_=msg) - ) + self.conn.execute(insert(votes).values(**msg).on_conflict_do_update(constraint="votes_pkey", set_=msg)) def handle_update_proposal(self, msg): condition = True @@ -543,9 +463,7 @@ def handle_set_historical_bonded_token_on_validator(self, msg): self.conn.execute( insert(historical_bonded_token_on_validators) .values(**msg) - .on_conflict_do_update( - constraint="historical_bonded_token_on_validators_pkey", set_=msg - ) + .on_conflict_do_update(constraint="historical_bonded_token_on_validators_pkey", set_=msg) ) def handle_set_reporter(self, msg): @@ -553,11 +471,7 @@ def handle_set_reporter(self, msg): del msg["validator"] msg["reporter_id"] = self.get_account_id(msg["reporter"]) del msg["reporter"] - self.conn.execute( - insert(reporters) - .values(msg) - .on_conflict_do_nothing(constraint="reporters_pkey") - ) + self.conn.execute(insert(reporters).values(msg).on_conflict_do_nothing(constraint="reporters_pkey")) def handle_remove_reporter(self, msg): msg["operator_address"] = msg["validator"] @@ -573,9 +487,7 @@ def handle_set_historical_validator_status(self, msg): self.conn.execute( insert(historical_oracle_statuses) .values(**msg) - .on_conflict_do_update( - constraint="historical_oracle_statuses_pkey", set_=msg - ) + .on_conflict_do_update(constraint="historical_oracle_statuses_pkey", set_=msg) ) def init_data_source_request_count(self, id): @@ -587,9 +499,9 @@ def init_data_source_request_count(self, id): def increase_data_source_count(self, id): self.conn.execute( - data_source_requests.update( - data_source_requests.c.data_source_id == id - ).values(count=data_source_requests.c.count + 1) + data_source_requests.update(data_source_requests.c.data_source_id == id).values( + count=data_source_requests.c.count + 1 + ) ) def init_oracle_script_request_count(self, id): @@ -603,11 +515,7 @@ def handle_update_oracle_script_request(self, msg): condition = True for col in oracle_script_requests.primary_key.columns.values(): condition = (col == msg[col.name]) & condition - self.conn.execute( - oracle_script_requests.update(condition).values( - count=oracle_script_requests.c.count + 1 - ) - ) + self.conn.execute(oracle_script_requests.update(condition).values(count=oracle_script_requests.c.count + 1)) def handle_set_request_count_per_day(self, msg): if self.get_request_count(msg["date"]) is None: @@ -618,18 +526,11 @@ def handle_set_request_count_per_day(self, msg): for col in request_count_per_days.primary_key.columns.values(): condition = (col == msg[col.name]) & condition self.conn.execute( - request_count_per_days.update(condition).values( - count=request_count_per_days.c.count + 1 - ) + request_count_per_days.update(condition).values(count=request_count_per_days.c.count + 1) ) def handle_update_oracle_script_requests_count_per_day(self, msg): - if ( - self.get_oracle_script_requests_count_per_day( - msg["date"], msg["oracle_script_id"] - ) - is None - ): + if self.get_oracle_script_requests_count_per_day(msg["date"], msg["oracle_script_id"]) is None: msg["count"] = 1 self.conn.execute(oracle_script_requests_per_days.insert(), msg) else: @@ -643,12 +544,7 @@ def handle_update_oracle_script_requests_count_per_day(self, msg): ) def handle_update_data_source_requests_count_per_day(self, msg): - if ( - self.get_data_source_requests_count_per_day( - msg["date"], msg["data_source_id"] - ) - is None - ): + if self.get_data_source_requests_count_per_day(msg["date"], msg["data_source_id"]) is None: msg["count"] = 1 self.conn.execute(data_source_requests_per_days.insert(), msg) else: @@ -656,51 +552,37 @@ def handle_update_data_source_requests_count_per_day(self, msg): for col in data_source_requests_per_days.primary_key.columns.values(): condition = (col == msg[col.name]) & condition self.conn.execute( - data_source_requests_per_days.update(condition).values( - count=data_source_requests_per_days.c.count + 1 - ) + data_source_requests_per_days.update(condition).values(count=data_source_requests_per_days.c.count + 1) ) def handle_new_incoming_packet(self, msg): - self.update_last_update_channel( - msg["dst_port"], msg["dst_channel"], msg["block_time"] - ) + self.update_last_update_channel(msg["dst_port"], msg["dst_channel"], msg["block_time"]) msg["tx_id"] = self.get_transaction_id(msg["hash"]) del msg["hash"] msg["sender"] = self.get_transaction_sender(msg["tx_id"]) - self.handle_set_relayer_tx_stat_days( - msg["dst_port"], msg["dst_channel"], msg["block_time"], msg["sender"] - ) + self.handle_set_relayer_tx_stat_days(msg["dst_port"], msg["dst_channel"], msg["block_time"], msg["sender"]) del msg["block_time"] del msg["sender"] self.conn.execute( - insert(incoming_packets) - .values(**msg) - .on_conflict_do_nothing(constraint="incoming_packets_pkey") + insert(incoming_packets).values(**msg).on_conflict_do_nothing(constraint="incoming_packets_pkey") ) def handle_new_outgoing_packet(self, msg): - self.update_last_update_channel( - msg["src_port"], msg["src_channel"], msg["block_time"] - ) + self.update_last_update_channel(msg["src_port"], msg["src_channel"], msg["block_time"]) del msg["block_time"] msg["tx_id"] = self.get_transaction_id(msg["hash"]) del msg["hash"] self.conn.execute( - insert(outgoing_packets) - .values(**msg) - .on_conflict_do_nothing(constraint="outgoing_packets_pkey") + insert(outgoing_packets).values(**msg).on_conflict_do_nothing(constraint="outgoing_packets_pkey") ) def handle_update_outgoing_packet(self, msg): - self.update_last_update_channel( - msg["src_port"], msg["src_channel"], msg["block_time"] - ) + self.update_last_update_channel(msg["src_port"], msg["src_channel"], msg["block_time"]) del msg["block_time"] condition = True @@ -710,30 +592,22 @@ def handle_update_outgoing_packet(self, msg): def increase_oracle_script_count(self, id): self.conn.execute( - oracle_script_requests.update( - oracle_script_requests.c.oracle_script_id == id - ).values(count=oracle_script_requests.c.count + 1) + oracle_script_requests.update(oracle_script_requests.c.oracle_script_id == id).values( + count=oracle_script_requests.c.count + 1 + ) ) def update_oracle_script_last_request(self, id, timestamp): - self.conn.execute( - oracle_scripts.update(oracle_scripts.c.id == id).values( - last_request=timestamp - ) - ) + self.conn.execute(oracle_scripts.update(oracle_scripts.c.id == id).values(last_request=timestamp)) def update_data_source_last_request(self, id, timestamp): - self.conn.execute( - data_sources.update(data_sources.c.id == id).values(last_request=timestamp) - ) + self.conn.execute(data_sources.update(data_sources.c.id == id).values(last_request=timestamp)) def handle_new_historical_bonded_token_on_validator(self, msg): self.conn.execute( insert(historical_bonded_token_on_validators) .values(**msg) - .on_conflict_do_update( - constraint="historical_bonded_token_on_validators_pkey", set_=msg - ) + .on_conflict_do_update(constraint="historical_bonded_token_on_validators_pkey", set_=msg) ) def handle_set_counterparty_chain(self, msg): @@ -745,17 +619,11 @@ def handle_set_counterparty_chain(self, msg): def handle_set_connection(self, msg): self.conn.execute( - insert(connections) - .values(**msg) - .on_conflict_do_update(constraint="connections_pkey", set_=msg) + insert(connections).values(**msg).on_conflict_do_update(constraint="connections_pkey", set_=msg) ) def handle_set_channel(self, msg): - self.conn.execute( - insert(channels) - .values(**msg) - .on_conflict_do_update(constraint="channels_pkey", set_=msg) - ) + self.conn.execute(insert(channels).values(**msg).on_conflict_do_update(constraint="channels_pkey", set_=msg)) def update_last_update_channel(self, port, channel, timestamp): self.conn.execute( @@ -854,25 +722,19 @@ def handle_set_voter_signal(self, msg): def handle_remove_voter_signals(self, msg): self.conn.execute( - feeds_voter_signals.delete().where( - feeds_voter_signals.c.account_id == self.get_account_id(msg["voter"]) - ) + feeds_voter_signals.delete().where(feeds_voter_signals.c.account_id == self.get_account_id(msg["voter"])) ) def handle_set_signal_total_power(self, msg): self.conn.execute( insert(feeds_signal_total_powers) .values(**msg) - .on_conflict_do_update( - constraint="feeds_signal_total_powers_pkey", set_=msg - ) + .on_conflict_do_update(constraint="feeds_signal_total_powers_pkey", set_=msg) ) def handle_remove_signal_total_power(self, msg): self.conn.execute( - feeds_signal_total_powers.delete().where( - feeds_signal_total_powers.c.signal_id == msg["signal_id"] - ) + feeds_signal_total_powers.delete().where(feeds_signal_total_powers.c.signal_id == msg["signal_id"]) ) def handle_set_prices(self, msg): @@ -904,8 +766,7 @@ def handle_set_prices(self, msg): self.conn.execute( feeds_historical_prices.delete().where( - feeds_historical_prices.c.timestamp - < msg["timestamp"] - PRICE_HISTORY_PERIOD + feeds_historical_prices.c.timestamp < msg["timestamp"] - PRICE_HISTORY_PERIOD ) ) @@ -913,9 +774,7 @@ def handle_set_reference_source_config(self, msg): self.conn.execute( insert(feeds_reference_source_configs) .values(**msg) - .on_conflict_do_update( - constraint="feeds_reference_source_configs_pkey", set_=msg - ) + .on_conflict_do_update(constraint="feeds_reference_source_configs_pkey", set_=msg) ) def handle_set_feeder(self, msg): @@ -923,11 +782,7 @@ def handle_set_feeder(self, msg): del msg["validator"] msg["feeder_id"] = self.get_account_id(msg["feeder"]) del msg["feeder"] - self.conn.execute( - insert(feeds_feeders) - .values(msg) - .on_conflict_do_nothing(constraint="feeds_feeders_pkey") - ) + self.conn.execute(insert(feeds_feeders).values(msg).on_conflict_do_nothing(constraint="feeds_feeders_pkey")) def handle_remove_feeder(self, msg): msg["operator_address"] = msg["validator"] @@ -945,9 +800,7 @@ def handle_set_restake_historical_stake(self, msg): self.conn.execute( insert(restake_historical_stakes) .values(**msg) - .on_conflict_do_update( - constraint="restake_historical_stakes_pkey", set_=msg - ) + .on_conflict_do_update(constraint="restake_historical_stakes_pkey", set_=msg) ) def handle_set_restake_lock(self, msg): @@ -960,9 +813,7 @@ def handle_set_restake_lock(self, msg): msg["account_id"] = self.get_account_id(msg["staker_address"]) del msg["staker_address"] self.conn.execute( - insert(restake_locks) - .values(**msg) - .on_conflict_do_update(constraint="restake_locks_pkey", set_=msg) + insert(restake_locks).values(**msg).on_conflict_do_update(constraint="restake_locks_pkey", set_=msg) ) def handle_remove_restake_lock(self, msg): @@ -976,9 +827,7 @@ def handle_remove_restake_lock(self, msg): def handle_set_restake_vault(self, msg): self.conn.execute( - insert(restake_vaults) - .values(**msg) - .on_conflict_do_update(constraint="restake_vaults_pkey", set_=msg) + insert(restake_vaults).values(**msg).on_conflict_do_update(constraint="restake_vaults_pkey", set_=msg) ) ################################## @@ -987,9 +836,7 @@ def handle_set_restake_vault(self, msg): def handle_set_tss_signing(self, msg): self.conn.execute( - insert(tss_signings) - .values(**msg) - .on_conflict_do_update(constraint="tss_signings_pkey", set_=msg) + insert(tss_signings).values(**msg).on_conflict_do_update(constraint="tss_signings_pkey", set_=msg) ) def handle_update_tss_signing(self, msg): @@ -1000,9 +847,7 @@ def handle_update_tss_signing(self, msg): def handle_set_tss_group(self, msg): self.conn.execute( - insert(tss_groups) - .values(**msg) - .on_conflict_do_update(constraint="tss_groups_pkey", set_=msg) + insert(tss_groups).values(**msg).on_conflict_do_update(constraint="tss_groups_pkey", set_=msg) ) def handle_set_tss_member(self, msg): @@ -1010,9 +855,7 @@ def handle_set_tss_member(self, msg): del msg["address"] self.conn.execute( - insert(tss_members) - .values(**msg) - .on_conflict_do_update(constraint="tss_members_pkey", set_=msg) + insert(tss_members).values(**msg).on_conflict_do_update(constraint="tss_members_pkey", set_=msg) ) def handle_new_tss_assigned_member(self, msg): @@ -1051,11 +894,7 @@ def update_bandtss_group_transition(self, msg): if proposal_id is None: proposal_id = 0 - self.conn.execute( - bandtss_group_transitions.update() - .where(proposal_column == proposal_id) - .values(**msg) - ) + self.conn.execute(bandtss_group_transitions.update().where(proposal_column == proposal_id).values(**msg)) def handle_update_bandtss_group_transition(self, msg): self.update_bandtss_group_transition(msg) @@ -1081,9 +920,7 @@ def handle_set_bandtss_member(self, msg): del msg["address"] self.conn.execute( - insert(bandtss_members) - .values(**msg) - .on_conflict_do_update(constraint="bandtss_members_pkey", set_=msg) + insert(bandtss_members).values(**msg).on_conflict_do_update(constraint="bandtss_members_pkey", set_=msg) ) def handle_new_bandtss_signing(self, msg): From bacac4e5b115a5ab7ddabc29de12a3bb711a2eda Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Wed, 27 Nov 2024 01:35:38 +0700 Subject: [PATCH 123/132] add tss content emitter --- docker-config/start_docker.sh | 1 + flusher/flusher/handler.py | 31 ++++++++++ flusher/flusher/test_util.py | 35 ++++++++++++ flusher/flusher/tss_db.py | 11 +++- flusher/flusher/util.py | 15 +++++ hooks/emitter/handler.go | 3 + hooks/emitter/tss.go | 36 ++++++++++++ .../bandtss/proposal_transition_group.json | 2 +- x/tss/keeper/keeper_signing.go | 7 ++- x/tss/types/events.go | 56 ++++++++++--------- x/tss/types/originator.go | 10 ++++ 11 files changed, 175 insertions(+), 32 deletions(-) create mode 100644 flusher/flusher/test_util.py create mode 100644 flusher/flusher/util.py diff --git a/docker-config/start_docker.sh b/docker-config/start_docker.sh index 295d2848f..c6251dd11 100755 --- a/docker-config/start_docker.sh +++ b/docker-config/start_docker.sh @@ -121,6 +121,7 @@ bandd genesis collect-gentxs cp ~/.band/config/genesis.json $DIR/genesis.json cat <<< $(jq '.app_state.gov.params.voting_period = "60s"' $DIR/genesis.json) > $DIR/genesis.json cat <<< $(jq '.app_state.feeds.params.current_feeds_update_interval = "10"' $DIR/genesis.json) > $DIR/genesis.json +cat <<< $(jq '.app_state.bandtss.params.min_transition_duration = "60s"' $DIR/genesis.json) > $DIR/genesis.json cat <<< $(jq --arg addr "$(bandd keys show requester -a --keyring-backend test)" '.app_state.feeds.params.admin = $addr' $DIR/genesis.json) > $DIR/genesis.json cat <<< $(jq '.app_state.restake.params.allowed_denoms = ["uband"]' $DIR/genesis.json) > $DIR/genesis.json diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 5b8a872bb..ee3bbdd8a 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -1,4 +1,5 @@ import base64 as b64 +import json from datetime import datetime from sqlalchemy import select, func, tuple_ from sqlalchemy.dialects.postgresql import insert @@ -72,8 +73,11 @@ tss_groups, tss_members, tss_assigned_members, + tss_signing_contents, ) +from .util import convert_proto_str_to_object + class Handler(object): def __init__(self, conn): @@ -845,6 +849,33 @@ def handle_set_tss_signing(self, msg): insert(tss_signings).values(**msg).on_conflict_do_update(constraint="tss_signings_pkey", set_=msg) ) + def handle_set_tss_signing_content(self, msg): + content_obj = {} + originator_obj = {} + + try: + content_info_text = b64.b64decode(msg["content_info"]).decode() + content_obj = convert_proto_str_to_object(content_info_text) + content_obj["content_type"] = b64.b64decode(msg["content_type"]).decode() + + originator_info_text = b64.b64decode(msg["originator_info"]).decode() + originator_obj = convert_proto_str_to_object(originator_info_text) + originator_obj["originator_type"] = b64.b64decode(msg["originator_type"]).decode() + except Exception as e: + print("An error occurred:", e) + + new_msg = { + "id": msg["id"], + "content_info": b64.b64encode(json.dumps(content_obj).encode()).decode(), + "originator_info": b64.b64encode(json.dumps(originator_obj).encode()).decode(), + } + + self.conn.execute( + insert(tss_signing_contents) + .values(**new_msg) + .on_conflict_do_update(constraint="tss_signing_contents_pkey", set_=new_msg) + ) + def handle_update_tss_signing(self, msg): condition = True for col in tss_signings.primary_key.columns.values(): diff --git a/flusher/flusher/test_util.py b/flusher/flusher/test_util.py new file mode 100644 index 000000000..89ad4d247 --- /dev/null +++ b/flusher/flusher/test_util.py @@ -0,0 +1,35 @@ + +import pytest + +from .util import convert_proto_str_to_object + + +# Test Cases +@pytest.mark.parametrize( + "input_str, expected", + [ + # Simple input with double quotes and unquoted value + ( + 'signal_id:"test value" encoder:ENCODER_FIXED_POINT_ABI ', + {"signal_id": "test value", "encoder": "ENCODER_FIXED_POINT_ABI"}, + ), + # Unquoted values + ( + "key1:value1 key2:value2 ", + {"key1": "value1", "key2": "value2"}, + ), + # Multiple types of quotes + ( + 'key1:value1 key2:"value 2" key3:\'value 3\' key4:value4', + {"key1": "value1", "key2": "value 2", "key3": "value 3", "key4": "value4"}, + ), + # Empty input + ( + "", + {}, + ), + ], +) + +def test_convert_proto_str_to_object(input_str, expected): + assert convert_proto_str_to_object(input_str) == expected diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index bc88bff6a..bb7b23db9 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -39,8 +39,7 @@ class CustomGroupStatus(sa.types.TypeDecorator): def process_bind_param(self, value, dialect): return GroupStatus(value) - - + tss_signings = sa.Table( "tss_signings", metadata, @@ -66,6 +65,14 @@ def process_bind_param(self, value, dialect): ), ) +tss_signing_contents = sa.Table( + "tss_signing_contents", + metadata, + Column("id", sa.Integer, primary_key=True), + Column("content_info", CustomBase64), + Column("originator_info", CustomBase64), +) + tss_groups = sa.Table( "tss_groups", metadata, diff --git a/flusher/flusher/util.py b/flusher/flusher/util.py new file mode 100644 index 000000000..2a61bb6ab --- /dev/null +++ b/flusher/flusher/util.py @@ -0,0 +1,15 @@ +import re + + +# convert_proto_str_to_object convert input string to object +def convert_proto_str_to_object(s: str) -> object: + pattern = r'(\w+):(?:([^\s"\']+)|["\']([^"\']*)["\'])' + matches = re.findall(pattern, s) + + result = {} + for key, unquoted_value, quoted_value in matches: + result[key] = quoted_value if quoted_value else unquoted_value + return result + + + diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index b58326fef..27537aeef 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -136,6 +136,7 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, events []a h.handleBandtssMsgActivate(ctx, msg) case *bandtsstypes.MsgRequestSignature: h.handleTssEventRequestSignature(ctx, evMap) + h.handleTssEventCreateSigning(ctx, evMap) h.handleBandtssEventSigningRequestCreated(ctx, evMap) case *feedstypes.MsgVote: h.handleFeedsMsgVote(ctx, msg, evMap) @@ -235,6 +236,8 @@ func (h *Hook) handleBeginBlockEndBlockEvent( h.handleEventTypeTransfer(evMap) case channeltypes.EventTypeSendPacket: h.handleEventSendPacket(ctx, evMap) + case tsstypes.EventTypeCreateSigning: + h.handleTssEventCreateSigning(ctx, evMap) case tsstypes.EventTypeRequestSignature: h.handleTssEventRequestSignature(ctx, evMap) case tsstypes.EventTypeSigningSuccess: diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 0cf3271c7..2b676526b 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -10,6 +10,22 @@ import ( "github.com/bandprotocol/chain/v3/x/tss/types" ) +func (h *Hook) emitSetTssSigningContent( + signingID tss.SigningID, + contentType []byte, + content []byte, + originatorType []byte, + originator []byte, +) { + h.Write("SET_TSS_SIGNING_CONTENT", common.JsDict{ + "id": signingID, + "content_type": parseBytes(contentType), + "content_info": parseBytes(content), + "originator_type": parseBytes(originatorType), + "originator_info": parseBytes(originator), + }) +} + func (h *Hook) emitSetTssSigning(signing types.Signing) { h.Write("SET_TSS_SIGNING", common.JsDict{ "id": signing.ID, @@ -106,6 +122,26 @@ func (h *Hook) handleInitTssModule(ctx sdk.Context) { } } +// handleTssEventCreateGroup implements emitter handler for CreateGroup event. +func (h *Hook) handleTssEventCreateSigning(_ sdk.Context, evMap common.EvMap) { + sids := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeySigningID] + contentTypes := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyContentType] + contentInfos := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyContentInfo] + originatorTypes := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyOriginatorType] + originatorInfos := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyOriginatorInfo] + + for i, sid := range sids { + signingID := tss.SigningID(common.Atoui(sid)) + h.emitSetTssSigningContent( + signingID, + []byte(contentTypes[i]), + []byte(contentInfos[i]), + []byte(originatorTypes[i]), + []byte(originatorInfos[i]), + ) + } +} + // handleTssEventRequestSignature implements emitter handler for RequestSignature event. func (h *Hook) handleTssEventRequestSignature(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeRequestSignature+"."+types.AttributeKeySigningID] diff --git a/scripts/bandtss/proposal_transition_group.json b/scripts/bandtss/proposal_transition_group.json index 738054e5e..59b32a0e8 100755 --- a/scripts/bandtss/proposal_transition_group.json +++ b/scripts/bandtss/proposal_transition_group.json @@ -8,7 +8,7 @@ "band1nx0xkpnytk35wvflsg7gszf9smw3vaeauk248q" ], "threshold": "2", - "exec_time": "2024-11-18T16:40:00+00:00", + "exec_time": "2024-11-27T19:50:00+00:00", "authority": "band10d07y265gmmuvt4z0w9aw880jnsr700jrdn8wm" } ], diff --git a/x/tss/keeper/keeper_signing.go b/x/tss/keeper/keeper_signing.go index ba426f7da..494037f31 100644 --- a/x/tss/keeper/keeper_signing.go +++ b/x/tss/keeper/keeper_signing.go @@ -56,12 +56,15 @@ func (k Keeper) RequestSigning( return 0, err } + contentType := fmt.Sprintf("%s/%s", content.OrderRoute(), content.OrderType()) ctx.EventManager().EmitEvent(sdk.NewEvent( types.EventTypeCreateSigning, sdk.NewAttribute(types.AttributeKeySigningID, fmt.Sprintf("%d", signingID)), sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), - sdk.NewAttribute(types.AttributeKeyContent, content.String()), - sdk.NewAttribute(types.AttributeKeyOriginator, originator.String()), + sdk.NewAttribute(types.AttributeKeyContentType, contentType), + sdk.NewAttribute(types.AttributeKeyContentInfo, content.String()), + sdk.NewAttribute(types.AttributeKeyOriginatorType, originator.Type()), + sdk.NewAttribute(types.AttributeKeyOriginatorInfo, originator.String()), )) return signingID, nil diff --git a/x/tss/types/events.go b/x/tss/types/events.go index e7f09dc45..5127e18ea 100644 --- a/x/tss/types/events.go +++ b/x/tss/types/events.go @@ -18,31 +18,33 @@ const ( EventTypeSigningFailed = "signing_failed" EventTypeSubmitSignature = "submit_signature" - AttributeKeyGroupID = "group_id" - AttributeKeyMemberID = "member_id" - AttributeKeyAddress = "address" - AttributeKeySize = "size" - AttributeKeyThreshold = "threshold" - AttributeKeyPubKey = "pub_key" - AttributeKeyStatus = "status" - AttributeKeyDKGContext = "dkg_context" - AttributeKeyModuleOwner = "module_owner" - AttributeKeyRound1Info = "round1_info" - AttributeKeyRound2Info = "round2_info" - AttributeKeyComplainantID = "complainant_id" - AttributeKeyRespondentID = "respondent_id" - AttributeKeyKeySym = "key_sym" - AttributeKeySignature = "signature" - AttributeKeyOwnPubKeySig = "own_pub_key_sig" - AttributeKeySigningID = "signing_id" - AttributeKeyReason = "reason" - AttributeKeyMessage = "message" - AttributeKeyGroupPubNonce = "group_pub_nonce" - AttributeKeyAttempt = "attempt" - AttributeKeyPubNonce = "pub_nonce" - AttributeKeyBindingFactor = "binding_factor" - AttributeKeyPubD = "pub_d" - AttributeKeyPubE = "pub_e" - AttributeKeyContent = "content" - AttributeKeyOriginator = "originator" + AttributeKeyGroupID = "group_id" + AttributeKeyMemberID = "member_id" + AttributeKeyAddress = "address" + AttributeKeySize = "size" + AttributeKeyThreshold = "threshold" + AttributeKeyPubKey = "pub_key" + AttributeKeyStatus = "status" + AttributeKeyDKGContext = "dkg_context" + AttributeKeyModuleOwner = "module_owner" + AttributeKeyRound1Info = "round1_info" + AttributeKeyRound2Info = "round2_info" + AttributeKeyComplainantID = "complainant_id" + AttributeKeyRespondentID = "respondent_id" + AttributeKeyKeySym = "key_sym" + AttributeKeySignature = "signature" + AttributeKeyOwnPubKeySig = "own_pub_key_sig" + AttributeKeySigningID = "signing_id" + AttributeKeyReason = "reason" + AttributeKeyMessage = "message" + AttributeKeyGroupPubNonce = "group_pub_nonce" + AttributeKeyAttempt = "attempt" + AttributeKeyPubNonce = "pub_nonce" + AttributeKeyBindingFactor = "binding_factor" + AttributeKeyPubD = "pub_d" + AttributeKeyPubE = "pub_e" + AttributeKeyContentInfo = "content_info" + AttributeKeyContentType = "content_type" + AttributeKeyOriginatorInfo = "originator_info" + AttributeKeyOriginatorType = "originator_type" ) diff --git a/x/tss/types/originator.go b/x/tss/types/originator.go index afd879920..94195fae6 100644 --- a/x/tss/types/originator.go +++ b/x/tss/types/originator.go @@ -27,6 +27,7 @@ type Originator interface { Encode() ([]byte, error) Validate(p Params) error + Type() string } // ==================================== @@ -71,6 +72,11 @@ func (o DirectOriginator) Encode() ([]byte, error) { return bz, nil } +// Type returns the type of the originator. +func (o DirectOriginator) Type() string { + return "DirectOriginator" +} + // ==================================== // TunnelOriginator // ==================================== @@ -123,3 +129,7 @@ func (o TunnelOriginator) Encode() ([]byte, error) { return bz, nil } + +func (o TunnelOriginator) Type() string { + return "TunnelOriginator" +} From fa99b5f34bbb53255e6e4a785d58e530e28823cd Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Wed, 27 Nov 2024 01:48:39 +0700 Subject: [PATCH 124/132] fix import order --- flusher/flusher/handler.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index ee3bbdd8a..6905dd191 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -47,8 +47,6 @@ relayer_tx_stat_days, ) -from .restake_db import restake_vaults, restake_locks, restake_historical_stakes - from .feeds_db import ( PRICE_HISTORY_PERIOD, feeds_signal_prices_txs, @@ -59,7 +57,7 @@ feeds_reference_source_configs, feeds_feeders, ) - +from .restake_db import restake_vaults, restake_locks, restake_historical_stakes from .bandtss_db import ( bandtss_current_groups, bandtss_members, @@ -67,7 +65,6 @@ bandtss_group_transitions, GroupTransitionStatus, ) - from .tss_db import ( tss_signings, tss_groups, @@ -75,7 +72,6 @@ tss_assigned_members, tss_signing_contents, ) - from .util import convert_proto_str_to_object From 582491f0d9eec03941116dff95b99f1113d19414 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Wed, 27 Nov 2024 15:14:51 +0700 Subject: [PATCH 125/132] group content into signing table --- flusher/flusher/handler.py | 25 +++++-------- flusher/flusher/tss_db.py | 29 +++++---------- hooks/emitter/handler.go | 2 +- hooks/emitter/tss.go | 36 +++++++++++-------- .../bandtss/proposal_transition_group.json | 2 +- x/tss/keeper/keeper_signing.go | 10 +++--- 6 files changed, 44 insertions(+), 60 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 6905dd191..feea5a89c 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -70,7 +70,6 @@ tss_groups, tss_members, tss_assigned_members, - tss_signing_contents, ) from .util import convert_proto_str_to_object @@ -840,12 +839,7 @@ def handle_set_restake_vault(self, msg): # TSS_HANDLER ################################## - def handle_set_tss_signing(self, msg): - self.conn.execute( - insert(tss_signings).values(**msg).on_conflict_do_update(constraint="tss_signings_pkey", set_=msg) - ) - - def handle_set_tss_signing_content(self, msg): + def handle_new_tss_signing(self, msg): content_obj = {} originator_obj = {} @@ -857,20 +851,17 @@ def handle_set_tss_signing_content(self, msg): originator_info_text = b64.b64decode(msg["originator_info"]).decode() originator_obj = convert_proto_str_to_object(originator_info_text) originator_obj["originator_type"] = b64.b64decode(msg["originator_type"]).decode() + + msg["content_info"] = b64.b64encode(json.dumps(content_obj).encode()).decode() + msg["originator_info"] = b64.b64encode(json.dumps(originator_obj).encode()).decode() + except Exception as e: print("An error occurred:", e) - new_msg = { - "id": msg["id"], - "content_info": b64.b64encode(json.dumps(content_obj).encode()).decode(), - "originator_info": b64.b64encode(json.dumps(originator_obj).encode()).decode(), - } + del msg["content_type"] + del msg["originator_type"] - self.conn.execute( - insert(tss_signing_contents) - .values(**new_msg) - .on_conflict_do_update(constraint="tss_signing_contents_pkey", set_=new_msg) - ) + self.conn.execute(tss_signings.insert(), msg) def handle_update_tss_signing(self, msg): condition = True diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index bb7b23db9..cc9292219 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -39,13 +39,16 @@ class CustomGroupStatus(sa.types.TypeDecorator): def process_bind_param(self, value, dialect): return GroupStatus(value) - + + tss_signings = sa.Table( "tss_signings", metadata, Column("id", sa.Integer, primary_key=True), Column("tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), Column("current_attempt", sa.Integer), + Column("content_info", CustomBase64), + Column("originator_info", CustomBase64), Column("originator", CustomBase64), Column("message", CustomBase64), Column("group_pub_key", CustomBase64), @@ -60,17 +63,7 @@ def process_bind_param(self, value, dialect): nullable=True, index=True, ), - sa.Index( - "ix_group_id_group_pub_key_status", "tss_group_id", "group_pub_key", "status" - ), -) - -tss_signing_contents = sa.Table( - "tss_signing_contents", - metadata, - Column("id", sa.Integer, primary_key=True), - Column("content_info", CustomBase64), - Column("originator_info", CustomBase64), + sa.Index("ix_group_id_group_pub_key_status", "tss_group_id", "group_pub_key", "status"), ) tss_groups = sa.Table( @@ -90,9 +83,7 @@ def process_bind_param(self, value, dialect): "tss_members", metadata, Column("id", sa.Integer, primary_key=True), - Column( - "tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id"), primary_key=True - ), + Column("tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id"), primary_key=True), Column("account_id", sa.Integer, sa.ForeignKey("accounts.id")), Column("pub_key", CustomBase64, nullable=True), Column("is_malicious", sa.Boolean), @@ -102,9 +93,7 @@ def process_bind_param(self, value, dialect): tss_assigned_members = sa.Table( "tss_assigned_members", metadata, - Column( - "tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id"), primary_key=True - ), + Column("tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id"), primary_key=True), Column("tss_signing_attempt", sa.Integer, primary_key=True), Column("tss_member_id", sa.Integer, primary_key=True), Column("tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), @@ -113,9 +102,7 @@ def process_bind_param(self, value, dialect): Column("binding_factor", CustomBase64), Column("pub_nonce", CustomBase64), Column("signature", CustomBase64, nullable=True), - Column( - "submitted_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True - ), + Column("submitted_height", sa.Integer, sa.ForeignKey("blocks.height"), nullable=True), sa.ForeignKeyConstraint( ["tss_group_id", "tss_member_id"], ["tss_members.tss_group_id", "tss_members.id"], diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index 27537aeef..76d47ac08 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -135,8 +135,8 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, events []a case *bandtsstypes.MsgActivate: h.handleBandtssMsgActivate(ctx, msg) case *bandtsstypes.MsgRequestSignature: - h.handleTssEventRequestSignature(ctx, evMap) h.handleTssEventCreateSigning(ctx, evMap) + h.handleTssEventRequestSignature(ctx, evMap) h.handleBandtssEventSigningRequestCreated(ctx, evMap) case *feedstypes.MsgVote: h.handleFeedsMsgVote(ctx, msg, evMap) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 2b676526b..5f2b0bffe 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -10,15 +10,23 @@ import ( "github.com/bandprotocol/chain/v3/x/tss/types" ) -func (h *Hook) emitSetTssSigningContent( - signingID tss.SigningID, +func (h *Hook) emitNewTssSigning( + signing types.Signing, contentType []byte, content []byte, originatorType []byte, originator []byte, ) { - h.Write("SET_TSS_SIGNING_CONTENT", common.JsDict{ - "id": signingID, + h.Write("NEW_TSS_SIGNING", common.JsDict{ + "id": signing.ID, + "current_attempt": signing.CurrentAttempt, + "tss_group_id": signing.GroupID, + "originator": parseBytes(signing.Originator), + "message": parseBytes(signing.Message), + "group_pub_key": parseBytes(signing.GroupPubKey), + "group_pub_nonce": parseBytes(signing.GroupPubNonce), + "status": signing.Status, + "created_height": signing.CreatedHeight, "content_type": parseBytes(contentType), "content_info": parseBytes(content), "originator_type": parseBytes(originatorType), @@ -26,14 +34,10 @@ func (h *Hook) emitSetTssSigningContent( }) } -func (h *Hook) emitSetTssSigning(signing types.Signing) { - h.Write("SET_TSS_SIGNING", common.JsDict{ +func (h *Hook) emitUpdateTssSigningAttempt(signing types.Signing) { + h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, "current_attempt": signing.CurrentAttempt, - "tss_group_id": signing.GroupID, - "originator": parseBytes(signing.Originator), - "message": parseBytes(signing.Message), - "group_pub_key": parseBytes(signing.GroupPubKey), "group_pub_nonce": parseBytes(signing.GroupPubNonce), "status": signing.Status, "created_height": signing.CreatedHeight, @@ -123,7 +127,7 @@ func (h *Hook) handleInitTssModule(ctx sdk.Context) { } // handleTssEventCreateGroup implements emitter handler for CreateGroup event. -func (h *Hook) handleTssEventCreateSigning(_ sdk.Context, evMap common.EvMap) { +func (h *Hook) handleTssEventCreateSigning(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeySigningID] contentTypes := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyContentType] contentInfos := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyContentInfo] @@ -131,9 +135,11 @@ func (h *Hook) handleTssEventCreateSigning(_ sdk.Context, evMap common.EvMap) { originatorInfos := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyOriginatorInfo] for i, sid := range sids { - signingID := tss.SigningID(common.Atoui(sid)) - h.emitSetTssSigningContent( - signingID, + id := tss.SigningID(common.Atoi(sid)) + signing := h.tssKeeper.MustGetSigning(ctx, id) + + h.emitNewTssSigning( + signing, []byte(contentTypes[i]), []byte(contentInfos[i]), []byte(originatorTypes[i]), @@ -153,7 +159,7 @@ func (h *Hook) handleTssEventRequestSignature(ctx sdk.Context, evMap common.EvMa attempt := signing.CurrentAttempt attemptInfo := h.tssKeeper.MustGetSigningAttempt(ctx, id, attempt) - h.emitSetTssSigning(signing) + h.emitUpdateTssSigningAttempt(signing) for _, am := range attemptInfo.AssignedMembers { h.emitNewTssAssignedMember(signing.ID, attempt, signing.GroupID, am) diff --git a/scripts/bandtss/proposal_transition_group.json b/scripts/bandtss/proposal_transition_group.json index 59b32a0e8..9116f10ac 100755 --- a/scripts/bandtss/proposal_transition_group.json +++ b/scripts/bandtss/proposal_transition_group.json @@ -8,7 +8,7 @@ "band1nx0xkpnytk35wvflsg7gszf9smw3vaeauk248q" ], "threshold": "2", - "exec_time": "2024-11-27T19:50:00+00:00", + "exec_time": "2024-11-28T19:50:00+00:00", "authority": "band10d07y265gmmuvt4z0w9aw880jnsr700jrdn8wm" } ], diff --git a/x/tss/keeper/keeper_signing.go b/x/tss/keeper/keeper_signing.go index 494037f31..58f7b36d7 100644 --- a/x/tss/keeper/keeper_signing.go +++ b/x/tss/keeper/keeper_signing.go @@ -51,11 +51,6 @@ func (k Keeper) RequestSigning( return 0, err } - // initiate new signing round - if err = k.InitiateNewSigningRound(ctx, signingID); err != nil { - return 0, err - } - contentType := fmt.Sprintf("%s/%s", content.OrderRoute(), content.OrderType()) ctx.EventManager().EmitEvent(sdk.NewEvent( types.EventTypeCreateSigning, @@ -67,6 +62,11 @@ func (k Keeper) RequestSigning( sdk.NewAttribute(types.AttributeKeyOriginatorInfo, originator.String()), )) + // initiate new signing round + if err = k.InitiateNewSigningRound(ctx, signingID); err != nil { + return 0, err + } + return signingID, nil } From 0d96cb9dc28032814cccdd4bd315a14ee47080b4 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 28 Nov 2024 00:03:20 +0700 Subject: [PATCH 126/132] fix event attribute --- hooks/emitter/tss.go | 4 +-- x/tss/keeper/keeper_signing.go | 11 ++++--- x/tss/types/codec.go | 11 +++++++ x/tss/types/events.go | 59 +++++++++++++++++----------------- x/tss/types/originator.go | 10 ------ 5 files changed, 49 insertions(+), 46 deletions(-) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 5f2b0bffe..207ba8acd 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -130,9 +130,9 @@ func (h *Hook) handleInitTssModule(ctx sdk.Context) { func (h *Hook) handleTssEventCreateSigning(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeySigningID] contentTypes := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyContentType] - contentInfos := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyContentInfo] + contentInfos := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyContent] originatorTypes := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyOriginatorType] - originatorInfos := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyOriginatorInfo] + originatorInfos := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyOriginator] for i, sid := range sids { id := tss.SigningID(common.Atoi(sid)) diff --git a/x/tss/keeper/keeper_signing.go b/x/tss/keeper/keeper_signing.go index 58f7b36d7..4dbd72558 100644 --- a/x/tss/keeper/keeper_signing.go +++ b/x/tss/keeper/keeper_signing.go @@ -51,15 +51,16 @@ func (k Keeper) RequestSigning( return 0, err } - contentType := fmt.Sprintf("%s/%s", content.OrderRoute(), content.OrderType()) ctx.EventManager().EmitEvent(sdk.NewEvent( types.EventTypeCreateSigning, sdk.NewAttribute(types.AttributeKeySigningID, fmt.Sprintf("%d", signingID)), sdk.NewAttribute(types.AttributeKeyGroupID, fmt.Sprintf("%d", groupID)), - sdk.NewAttribute(types.AttributeKeyContentType, contentType), - sdk.NewAttribute(types.AttributeKeyContentInfo, content.String()), - sdk.NewAttribute(types.AttributeKeyOriginatorType, originator.Type()), - sdk.NewAttribute(types.AttributeKeyOriginatorInfo, originator.String()), + sdk.NewAttribute(types.AttributeKeyContentType, sdk.MsgTypeURL(content)), + sdk.NewAttribute(types.AttributeKeyContent, content.String()), + sdk.NewAttribute(types.AttributeKeyOriginatorType, sdk.MsgTypeURL(originator)), + sdk.NewAttribute(types.AttributeKeyOriginator, originator.String()), + sdk.NewAttribute(types.AttributeKeyEncodedOriginator, hex.EncodeToString(originatorBz)), + sdk.NewAttribute(types.AttributeKeyMessage, hex.EncodeToString(contentMsg)), )) // initiate new signing round diff --git a/x/tss/types/codec.go b/x/tss/types/codec.go index 59d0fdfae..f1de88026 100644 --- a/x/tss/types/codec.go +++ b/x/tss/types/codec.go @@ -19,6 +19,11 @@ func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { legacy.RegisterAminoMsg(cdc, &MsgSubmitSignature{}, "tss/MsgSubmitSignature") legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "tss/MsgUpdateParams") + cdc.RegisterInterface((*Originator)(nil), nil) + cdc.RegisterInterface((*Content)(nil), nil) + + cdc.RegisterConcrete(&DirectOriginator{}, "tss/DirectOriginator", nil) + cdc.RegisterConcrete(&TunnelOriginator{}, "tss/TunnelOriginator", nil) cdc.RegisterConcrete(&TextSignatureOrder{}, "tss/TextSignatureOrder", nil) cdc.RegisterConcrete(Params{}, "tss/Params", nil) } @@ -36,6 +41,12 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { &MsgUpdateParams{}, ) + registry.RegisterInterface( + "tss.v1beta1.Originator", + (*Originator)(nil), + &DirectOriginator{}, &TunnelOriginator{}, + ) + registry.RegisterInterface( "tss.v1beta1.Content", (*Content)(nil), diff --git a/x/tss/types/events.go b/x/tss/types/events.go index 5127e18ea..a91757d9b 100644 --- a/x/tss/types/events.go +++ b/x/tss/types/events.go @@ -18,33 +18,34 @@ const ( EventTypeSigningFailed = "signing_failed" EventTypeSubmitSignature = "submit_signature" - AttributeKeyGroupID = "group_id" - AttributeKeyMemberID = "member_id" - AttributeKeyAddress = "address" - AttributeKeySize = "size" - AttributeKeyThreshold = "threshold" - AttributeKeyPubKey = "pub_key" - AttributeKeyStatus = "status" - AttributeKeyDKGContext = "dkg_context" - AttributeKeyModuleOwner = "module_owner" - AttributeKeyRound1Info = "round1_info" - AttributeKeyRound2Info = "round2_info" - AttributeKeyComplainantID = "complainant_id" - AttributeKeyRespondentID = "respondent_id" - AttributeKeyKeySym = "key_sym" - AttributeKeySignature = "signature" - AttributeKeyOwnPubKeySig = "own_pub_key_sig" - AttributeKeySigningID = "signing_id" - AttributeKeyReason = "reason" - AttributeKeyMessage = "message" - AttributeKeyGroupPubNonce = "group_pub_nonce" - AttributeKeyAttempt = "attempt" - AttributeKeyPubNonce = "pub_nonce" - AttributeKeyBindingFactor = "binding_factor" - AttributeKeyPubD = "pub_d" - AttributeKeyPubE = "pub_e" - AttributeKeyContentInfo = "content_info" - AttributeKeyContentType = "content_type" - AttributeKeyOriginatorInfo = "originator_info" - AttributeKeyOriginatorType = "originator_type" + AttributeKeyGroupID = "group_id" + AttributeKeyMemberID = "member_id" + AttributeKeyAddress = "address" + AttributeKeySize = "size" + AttributeKeyThreshold = "threshold" + AttributeKeyPubKey = "pub_key" + AttributeKeyStatus = "status" + AttributeKeyDKGContext = "dkg_context" + AttributeKeyModuleOwner = "module_owner" + AttributeKeyRound1Info = "round1_info" + AttributeKeyRound2Info = "round2_info" + AttributeKeyComplainantID = "complainant_id" + AttributeKeyRespondentID = "respondent_id" + AttributeKeyKeySym = "key_sym" + AttributeKeySignature = "signature" + AttributeKeyOwnPubKeySig = "own_pub_key_sig" + AttributeKeySigningID = "signing_id" + AttributeKeyReason = "reason" + AttributeKeyMessage = "message" + AttributeKeyGroupPubNonce = "group_pub_nonce" + AttributeKeyAttempt = "attempt" + AttributeKeyPubNonce = "pub_nonce" + AttributeKeyBindingFactor = "binding_factor" + AttributeKeyPubD = "pub_d" + AttributeKeyPubE = "pub_e" + AttributeKeyContent = "content" + AttributeKeyContentType = "content_type" + AttributeKeyOriginator = "originator" + AttributeKeyOriginatorType = "originator_type" + AttributeKeyEncodedOriginator = "encoded_originator" ) diff --git a/x/tss/types/originator.go b/x/tss/types/originator.go index 94195fae6..afd879920 100644 --- a/x/tss/types/originator.go +++ b/x/tss/types/originator.go @@ -27,7 +27,6 @@ type Originator interface { Encode() ([]byte, error) Validate(p Params) error - Type() string } // ==================================== @@ -72,11 +71,6 @@ func (o DirectOriginator) Encode() ([]byte, error) { return bz, nil } -// Type returns the type of the originator. -func (o DirectOriginator) Type() string { - return "DirectOriginator" -} - // ==================================== // TunnelOriginator // ==================================== @@ -129,7 +123,3 @@ func (o TunnelOriginator) Encode() ([]byte, error) { return bz, nil } - -func (o TunnelOriginator) Type() string { - return "TunnelOriginator" -} From c83777b4616b4b36b904a57c992f57d770d08206 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 28 Nov 2024 14:46:09 +0700 Subject: [PATCH 127/132] fix fields --- flusher/flusher/handler.py | 17 ++++++----------- flusher/flusher/tss_db.py | 8 +++++--- hooks/emitter/tss.go | 26 +++++++++++++------------- 3 files changed, 24 insertions(+), 27 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index feea5a89c..6277cb37b 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -844,23 +844,18 @@ def handle_new_tss_signing(self, msg): originator_obj = {} try: - content_info_text = b64.b64decode(msg["content_info"]).decode() - content_obj = convert_proto_str_to_object(content_info_text) - content_obj["content_type"] = b64.b64decode(msg["content_type"]).decode() + content_text = b64.b64decode(msg["content"]).decode() + content_obj = convert_proto_str_to_object(content_text) - originator_info_text = b64.b64decode(msg["originator_info"]).decode() - originator_obj = convert_proto_str_to_object(originator_info_text) - originator_obj["originator_type"] = b64.b64decode(msg["originator_type"]).decode() + originator_text = b64.b64decode(msg["originator"]).decode() + originator_obj = convert_proto_str_to_object(originator_text) - msg["content_info"] = b64.b64encode(json.dumps(content_obj).encode()).decode() - msg["originator_info"] = b64.b64encode(json.dumps(originator_obj).encode()).decode() + msg["content"] = content_obj + msg["originator"] = originator_obj except Exception as e: print("An error occurred:", e) - del msg["content_type"] - del msg["originator_type"] - self.conn.execute(tss_signings.insert(), msg) def handle_update_tss_signing(self, msg): diff --git a/flusher/flusher/tss_db.py b/flusher/flusher/tss_db.py index cc9292219..5a16c75a4 100644 --- a/flusher/flusher/tss_db.py +++ b/flusher/flusher/tss_db.py @@ -47,9 +47,11 @@ def process_bind_param(self, value, dialect): Column("id", sa.Integer, primary_key=True), Column("tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id")), Column("current_attempt", sa.Integer), - Column("content_info", CustomBase64), - Column("originator_info", CustomBase64), - Column("originator", CustomBase64), + Column("content_type", sa.String), + Column("content", sa.JSON), + Column("originator_type", sa.String), + Column("originator", sa.JSON), + Column("encoded_originator", CustomBase64), Column("message", CustomBase64), Column("group_pub_key", CustomBase64), Column("group_pub_nonce", CustomBase64), diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 207ba8acd..dbc1da8b7 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -18,19 +18,19 @@ func (h *Hook) emitNewTssSigning( originator []byte, ) { h.Write("NEW_TSS_SIGNING", common.JsDict{ - "id": signing.ID, - "current_attempt": signing.CurrentAttempt, - "tss_group_id": signing.GroupID, - "originator": parseBytes(signing.Originator), - "message": parseBytes(signing.Message), - "group_pub_key": parseBytes(signing.GroupPubKey), - "group_pub_nonce": parseBytes(signing.GroupPubNonce), - "status": signing.Status, - "created_height": signing.CreatedHeight, - "content_type": parseBytes(contentType), - "content_info": parseBytes(content), - "originator_type": parseBytes(originatorType), - "originator_info": parseBytes(originator), + "id": signing.ID, + "current_attempt": signing.CurrentAttempt, + "tss_group_id": signing.GroupID, + "encoded_originator": parseBytes(signing.Originator), + "message": parseBytes(signing.Message), + "group_pub_key": parseBytes(signing.GroupPubKey), + "group_pub_nonce": parseBytes(signing.GroupPubNonce), + "status": signing.Status, + "created_height": signing.CreatedHeight, + "content_type": parseBytes(contentType), + "content": parseBytes(content), + "originator_type": parseBytes(originatorType), + "originator": parseBytes(originator), }) } From ab430bb6d9f11fb7ee4936a5a4a1f128b6ed320f Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 28 Nov 2024 16:16:12 +0700 Subject: [PATCH 128/132] fix emitting event from bytes to text --- flusher/flusher/handler.py | 13 ++----------- hooks/emitter/tss.go | 24 ++++++++++++------------ 2 files changed, 14 insertions(+), 23 deletions(-) diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 6277cb37b..75c63dca1 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -840,18 +840,9 @@ def handle_set_restake_vault(self, msg): ################################## def handle_new_tss_signing(self, msg): - content_obj = {} - originator_obj = {} - try: - content_text = b64.b64decode(msg["content"]).decode() - content_obj = convert_proto_str_to_object(content_text) - - originator_text = b64.b64decode(msg["originator"]).decode() - originator_obj = convert_proto_str_to_object(originator_text) - - msg["content"] = content_obj - msg["originator"] = originator_obj + msg["content"] = convert_proto_str_to_object(msg["content"]) + msg["originator"] = convert_proto_str_to_object(msg["originator"]) except Exception as e: print("An error occurred:", e) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index dbc1da8b7..410ab2dc8 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -12,10 +12,10 @@ import ( func (h *Hook) emitNewTssSigning( signing types.Signing, - contentType []byte, - content []byte, - originatorType []byte, - originator []byte, + contentType string, + content string, + originatorType string, + originator string, ) { h.Write("NEW_TSS_SIGNING", common.JsDict{ "id": signing.ID, @@ -27,10 +27,10 @@ func (h *Hook) emitNewTssSigning( "group_pub_nonce": parseBytes(signing.GroupPubNonce), "status": signing.Status, "created_height": signing.CreatedHeight, - "content_type": parseBytes(contentType), - "content": parseBytes(content), - "originator_type": parseBytes(originatorType), - "originator": parseBytes(originator), + "content_type": contentType, + "content": content, + "originator_type": originatorType, + "originator": originator, }) } @@ -140,10 +140,10 @@ func (h *Hook) handleTssEventCreateSigning(ctx sdk.Context, evMap common.EvMap) h.emitNewTssSigning( signing, - []byte(contentTypes[i]), - []byte(contentInfos[i]), - []byte(originatorTypes[i]), - []byte(originatorInfos[i]), + contentTypes[i], + contentInfos[i], + originatorTypes[i], + originatorInfos[i], ) } } From e9ea17829016df995a2545a63471b21ee16a95b0 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 28 Nov 2024 16:19:16 +0700 Subject: [PATCH 129/132] remove register interface --- x/tss/types/codec.go | 6 ------ 1 file changed, 6 deletions(-) diff --git a/x/tss/types/codec.go b/x/tss/types/codec.go index ae9ff5d25..5348b906a 100644 --- a/x/tss/types/codec.go +++ b/x/tss/types/codec.go @@ -41,12 +41,6 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { &MsgUpdateParams{}, ) - registry.RegisterInterface( - "tss.v1beta1.Originator", - (*Originator)(nil), - &DirectOriginator{}, &TunnelOriginator{}, - ) - registry.RegisterInterface( "tss.v1beta1.Content", (*Content)(nil), From 121d7ca61cea00594940be88852c5891b92f4110 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 28 Nov 2024 16:37:13 +0700 Subject: [PATCH 130/132] Fix oracle --- hooks/emitter/oracle.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/hooks/emitter/oracle.go b/hooks/emitter/oracle.go index be25eb07f..9ffcc3383 100644 --- a/hooks/emitter/oracle.go +++ b/hooks/emitter/oracle.go @@ -127,7 +127,7 @@ func (h *Hook) emitUpdateResult( }) } -func (h *Hook) emitUpdateResultTSS( +func (h *Hook) emitUpdateResultBandtss( ctx sdk.Context, id types.RequestID, executeGasUsed uint64, @@ -267,7 +267,7 @@ func (h *Hook) handleEventRequestExecute(ctx sdk.Context, evMap common.EvMap) { reasons[0], ) } else if bandtssErrCodespace, ok := evMap[types.EventTypeResolve+"."+types.AttributeKeySigningErrCodespace]; ok { - h.emitUpdateResultTSS( + h.emitUpdateResultBandtss( ctx, rid, executeGasUsed, @@ -276,13 +276,13 @@ func (h *Hook) handleEventRequestExecute(ctx sdk.Context, evMap common.EvMap) { bandtssErrCodespace[0], uint64(common.Atoi(evMap[types.EventTypeResolve+"."+types.AttributeKeySigningErrCode][0])), ) - } else if tssSid, ok := evMap[types.EventTypeResolve+"."+types.AttributeKeySigningID]; ok { - h.emitUpdateResultTSS( + } else if bandtssSigningIDs, ok := evMap[types.EventTypeResolve+"."+types.AttributeKeySigningID]; ok { + h.emitUpdateResultBandtss( ctx, rid, executeGasUsed, "", - uint64(common.Atoi(tssSid[0])), + uint64(common.Atoi(bandtssSigningIDs[0])), "", 0, ) From aed4c2503197ea338234b7069b86f7aea9576d99 Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 28 Nov 2024 16:44:18 +0700 Subject: [PATCH 131/132] change name to TSS --- hooks/emitter/decoder.go | 28 ++++++++-------- hooks/emitter/decoder_test.go | 14 ++++---- hooks/emitter/emitter.go | 2 +- hooks/emitter/handler.go | 16 +++++----- hooks/emitter/tss.go | 60 +++++++++++++++++------------------ 5 files changed, 60 insertions(+), 60 deletions(-) diff --git a/hooks/emitter/decoder.go b/hooks/emitter/decoder.go index 1c020e88a..5306fc7a6 100644 --- a/hooks/emitter/decoder.go +++ b/hooks/emitter/decoder.go @@ -148,19 +148,19 @@ func DecodeMsg(msg sdk.Msg, detail common.JsDict) { case *bandtsstypes.MsgUpdateParams: DecodeBandtssMsgUpdateParams(msg, detail) case *tsstypes.MsgSubmitDKGRound1: - DecodeTssMsgSubmitDKGRound1(msg, detail) + DecodeTSSMsgSubmitDKGRound1(msg, detail) case *tsstypes.MsgSubmitDKGRound2: - DecodeTssMsgSubmitDKGRound2(msg, detail) + DecodeTSSMsgSubmitDKGRound2(msg, detail) case *tsstypes.MsgComplain: - DecodeTssMsgComplain(msg, detail) + DecodeTSSMsgComplain(msg, detail) case *tsstypes.MsgConfirm: - DecodeTssMsgConfirm(msg, detail) + DecodeTSSMsgConfirm(msg, detail) case *tsstypes.MsgSubmitDEs: - DecodeTssMsgSubmitDEs(msg, detail) + DecodeTSSMsgSubmitDEs(msg, detail) case *tsstypes.MsgSubmitSignature: - DecodeTssMsgSubmitSignature(msg, detail) + DecodeTSSMsgSubmitSignature(msg, detail) case *tsstypes.MsgUpdateParams: - DecodeTssMsgUpdateParams(msg, detail) + DecodeTSSMsgUpdateParams(msg, detail) case *group.MsgCreateGroup: DecodeGroupMsgCreateGroup(msg, detail) case *group.MsgCreateGroupPolicy: @@ -749,44 +749,44 @@ func DecodeBandtssMsgUpdateParams(msg *bandtsstypes.MsgUpdateParams, detail comm detail["authority"] = msg.GetAuthority() } -func DecodeTssMsgSubmitDKGRound1(msg *tsstypes.MsgSubmitDKGRound1, detail common.JsDict) { +func DecodeTSSMsgSubmitDKGRound1(msg *tsstypes.MsgSubmitDKGRound1, detail common.JsDict) { detail["group_id"] = msg.GroupID detail["round1_info"] = msg.Round1Info detail["sender"] = msg.Sender } -func DecodeTssMsgSubmitDKGRound2(msg *tsstypes.MsgSubmitDKGRound2, detail common.JsDict) { +func DecodeTSSMsgSubmitDKGRound2(msg *tsstypes.MsgSubmitDKGRound2, detail common.JsDict) { detail["group_id"] = msg.GroupID detail["round2_info"] = msg.Round2Info detail["sender"] = msg.Sender } -func DecodeTssMsgComplain(msg *tsstypes.MsgComplain, detail common.JsDict) { +func DecodeTSSMsgComplain(msg *tsstypes.MsgComplain, detail common.JsDict) { detail["group_id"] = msg.GroupID detail["complaints"] = msg.Complaints detail["sender"] = msg.Sender } -func DecodeTssMsgConfirm(msg *tsstypes.MsgConfirm, detail common.JsDict) { +func DecodeTSSMsgConfirm(msg *tsstypes.MsgConfirm, detail common.JsDict) { detail["group_id"] = msg.GroupID detail["member_id"] = msg.MemberID detail["own_pub_key_sig"] = msg.OwnPubKeySig detail["sender"] = msg.Sender } -func DecodeTssMsgSubmitDEs(msg *tsstypes.MsgSubmitDEs, detail common.JsDict) { +func DecodeTSSMsgSubmitDEs(msg *tsstypes.MsgSubmitDEs, detail common.JsDict) { detail["des"] = msg.DEs detail["sender"] = msg.Sender } -func DecodeTssMsgSubmitSignature(msg *tsstypes.MsgSubmitSignature, detail common.JsDict) { +func DecodeTSSMsgSubmitSignature(msg *tsstypes.MsgSubmitSignature, detail common.JsDict) { detail["signing_id"] = msg.SigningID detail["member_id"] = msg.MemberID detail["signature"] = msg.Signature detail["signer"] = msg.Signer } -func DecodeTssMsgUpdateParams(msg *tsstypes.MsgUpdateParams, detail common.JsDict) { +func DecodeTSSMsgUpdateParams(msg *tsstypes.MsgUpdateParams, detail common.JsDict) { detail["params"] = msg.GetParams() detail["authority"] = msg.GetAuthority() } diff --git a/hooks/emitter/decoder_test.go b/hooks/emitter/decoder_test.go index e448a310d..b0937760a 100644 --- a/hooks/emitter/decoder_test.go +++ b/hooks/emitter/decoder_test.go @@ -1081,7 +1081,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgSubmitDKGRound1() { Sender: SenderAddress.String(), } - emitter.DecodeTssMsgSubmitDKGRound1(&msg, detail) + emitter.DecodeTSSMsgSubmitDKGRound1(&msg, detail) expectedJSON := `{"group_id":1,"round1_info":{"member_id":1,"coefficient_commits":["706F696E74","706F696E74"],"one_time_pub_key":"706F696E74","a0_signature":"7369676E6174757265","one_time_signature":"7369676E6174757265"},"sender":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0"}` suite.testCompareJson(detail, expectedJSON) } @@ -1098,7 +1098,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgSubmitDKGRound2() { Sender: SenderAddress.String(), } - emitter.DecodeTssMsgSubmitDKGRound2(&msg, detail) + emitter.DecodeTSSMsgSubmitDKGRound2(&msg, detail) expectedJSON := "{\"group_id\":1,\"round2_info\":{\"member_id\":1,\"encrypted_secret_shares\":[\"656E635365637265745368617265\"]},\"sender\":\"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0\"}" suite.testCompareJson(detail, expectedJSON) } @@ -1119,7 +1119,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgComplain() { Sender: SenderAddress.String(), } - emitter.DecodeTssMsgComplain(&msg, detail) + emitter.DecodeTSSMsgComplain(&msg, detail) expectedJSON := `{"complaints":[{"complainant":1,"respondent":2,"key_sym":"6B65795F73796D","signature":"7369676E6174757265"}],"group_id":1,"sender":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0"}` suite.testCompareJson(detail, expectedJSON) } @@ -1134,7 +1134,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgConfirm() { Sender: SenderAddress.String(), } - emitter.DecodeTssMsgConfirm(&msg, detail) + emitter.DecodeTSSMsgConfirm(&msg, detail) expectedJSON := `{"group_id":1,"member_id":1,"own_pub_key_sig":"7369676E6174757265","sender":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0"}` suite.testCompareJson(detail, expectedJSON) } @@ -1147,7 +1147,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgSubmitDE() { Sender: SenderAddress.String(), } - emitter.DecodeTssMsgSubmitDEs(&msg, detail) + emitter.DecodeTSSMsgSubmitDEs(&msg, detail) expectedJSON := `{"des":[{"pub_d":"7075625F64","pub_e":"7075625F65"}],"sender":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0"}` suite.testCompareJson(detail, expectedJSON) } @@ -1162,7 +1162,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgSubmitSignature() { Signer: SenderAddress.String(), } - emitter.DecodeTssMsgSubmitSignature(&msg, detail) + emitter.DecodeTSSMsgSubmitSignature(&msg, detail) expectedJSON := `{"member_id":1,"signature":"7369676E6174757265","signer":"band12djkuer9wgqqqqqqqqqqqqqqqqqqqqqqck96t0","signing_id":1}` suite.testCompareJson(detail, expectedJSON) } @@ -1175,7 +1175,7 @@ func (suite *DecoderTestSuite) TestDecodeMsgUpdateParams() { Params: tsstypes.DefaultParams(), } - emitter.DecodeTssMsgUpdateParams(&msg, detail) + emitter.DecodeTSSMsgUpdateParams(&msg, detail) expectedJSON := `{"authority":"band1g96hg6r0wf5hg7gqqqqqqqqqqqqqqqqq4rjgsx","params":{"max_group_size":20,"max_de_size":300,"creation_period":30000,"signing_period":100,"max_signing_attempt":5,"max_memo_length":100,"max_message_length":1000}}` suite.testCompareJson(detail, expectedJSON) } diff --git a/hooks/emitter/emitter.go b/hooks/emitter/emitter.go index 0f84ef689..6a272ccb9 100644 --- a/hooks/emitter/emitter.go +++ b/hooks/emitter/emitter.go @@ -302,7 +302,7 @@ func (h *Hook) AfterInitChain(ctx sdk.Context, req *abci.RequestInitChain, res * } // TSS module - h.handleInitTssModule(ctx) + h.handleInitTSSModule(ctx) // Bandtss module h.handleInitBandtssModule(ctx) diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index 76d47ac08..507f6578b 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -135,8 +135,8 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, events []a case *bandtsstypes.MsgActivate: h.handleBandtssMsgActivate(ctx, msg) case *bandtsstypes.MsgRequestSignature: - h.handleTssEventCreateSigning(ctx, evMap) - h.handleTssEventRequestSignature(ctx, evMap) + h.handleTSSEventCreateSigning(ctx, evMap) + h.handleTSSEventRequestSignature(ctx, evMap) h.handleBandtssEventSigningRequestCreated(ctx, evMap) case *feedstypes.MsgVote: h.handleFeedsMsgVote(ctx, msg, evMap) @@ -174,7 +174,7 @@ func (h *Hook) handleMsg(ctx sdk.Context, txHash []byte, msg sdk.Msg, events []a case *group.MsgWithdrawProposal: h.handleGroupMsgWithdrawProposal(ctx, evMap) case *tsstypes.MsgSubmitSignature: - h.handleTssEventSubmitSignature(ctx, evMap) + h.handleTSSEventSubmitSignature(ctx, evMap) default: break } @@ -237,13 +237,13 @@ func (h *Hook) handleBeginBlockEndBlockEvent( case channeltypes.EventTypeSendPacket: h.handleEventSendPacket(ctx, evMap) case tsstypes.EventTypeCreateSigning: - h.handleTssEventCreateSigning(ctx, evMap) + h.handleTSSEventCreateSigning(ctx, evMap) case tsstypes.EventTypeRequestSignature: - h.handleTssEventRequestSignature(ctx, evMap) + h.handleTSSEventRequestSignature(ctx, evMap) case tsstypes.EventTypeSigningSuccess: - h.handleTssEventSigningSuccess(ctx, evMap) + h.handleTSSEventSigningSuccess(ctx, evMap) case tsstypes.EventTypeSigningFailed: - h.handleTssEventSigningFailed(ctx, evMap) + h.handleTSSEventSigningFailed(ctx, evMap) case tsstypes.EventTypeCreateGroup, tsstypes.EventTypeRound2Success, tsstypes.EventTypeRound3Success, @@ -252,7 +252,7 @@ func (h *Hook) handleBeginBlockEndBlockEvent( tsstypes.EventTypeRound3Failed: groupIDs := evMap[event.Type+"."+tsstypes.AttributeKeyGroupID] for _, gid := range groupIDs { - h.handleTssSetGroup(ctx, tss.GroupID(common.Atoi(gid))) + h.handleTSSSetGroup(ctx, tss.GroupID(common.Atoi(gid))) } case proto.MessageName(&group.EventProposalPruned{}): h.handleGroupEventProposalPruned(evMap) diff --git a/hooks/emitter/tss.go b/hooks/emitter/tss.go index 410ab2dc8..aa65030ec 100644 --- a/hooks/emitter/tss.go +++ b/hooks/emitter/tss.go @@ -10,7 +10,7 @@ import ( "github.com/bandprotocol/chain/v3/x/tss/types" ) -func (h *Hook) emitNewTssSigning( +func (h *Hook) emitNewTSSSigning( signing types.Signing, contentType string, content string, @@ -34,7 +34,7 @@ func (h *Hook) emitNewTssSigning( }) } -func (h *Hook) emitUpdateTssSigningAttempt(signing types.Signing) { +func (h *Hook) emitUpdateTSSSigningAttempt(signing types.Signing) { h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, "current_attempt": signing.CurrentAttempt, @@ -44,7 +44,7 @@ func (h *Hook) emitUpdateTssSigningAttempt(signing types.Signing) { }) } -func (h *Hook) emitUpdateTssSigningSuccess(signing types.Signing) { +func (h *Hook) emitUpdateTSSSigningSuccess(signing types.Signing) { h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, "status": signing.Status, @@ -52,7 +52,7 @@ func (h *Hook) emitUpdateTssSigningSuccess(signing types.Signing) { }) } -func (h *Hook) emitUpdateTssSigningFailed(reason string, signing types.Signing) { +func (h *Hook) emitUpdateTSSSigningFailed(reason string, signing types.Signing) { h.Write("UPDATE_TSS_SIGNING", common.JsDict{ "id": signing.ID, "status": signing.Status, @@ -60,7 +60,7 @@ func (h *Hook) emitUpdateTssSigningFailed(reason string, signing types.Signing) }) } -func (h *Hook) emitSetTssGroup(group types.Group, dkgContext []byte) { +func (h *Hook) emitSetTSSGroup(group types.Group, dkgContext []byte) { h.Write("SET_TSS_GROUP", common.JsDict{ "id": group.ID, "size": group.Size_, @@ -73,7 +73,7 @@ func (h *Hook) emitSetTssGroup(group types.Group, dkgContext []byte) { }) } -func (h *Hook) emitSetTssMember(member types.Member) { +func (h *Hook) emitSetTSSMember(member types.Member) { h.Write("SET_TSS_MEMBER", common.JsDict{ "id": member.ID, "tss_group_id": member.GroupID, @@ -84,7 +84,7 @@ func (h *Hook) emitSetTssMember(member types.Member) { }) } -func (h *Hook) emitNewTssAssignedMember( +func (h *Hook) emitNewTSSAssignedMember( sid tss.SigningID, attempt uint64, gid tss.GroupID, @@ -102,7 +102,7 @@ func (h *Hook) emitNewTssAssignedMember( }) } -func (h *Hook) emitUpdateTssAssignedMember( +func (h *Hook) emitUpdateTSSAssignedMember( signingID tss.SigningID, attempt uint64, memberID tss.MemberID, @@ -119,15 +119,15 @@ func (h *Hook) emitUpdateTssAssignedMember( } // handleInitTSSModule implements emitter handler for initializing tss module. -func (h *Hook) handleInitTssModule(ctx sdk.Context) { +func (h *Hook) handleInitTSSModule(ctx sdk.Context) { groups := h.tssKeeper.GetGroups(ctx) for _, group := range groups { - h.emitSetTssGroup(group, nil) // DKG data is already removed. + h.emitSetTSSGroup(group, nil) // DKG data is already removed. } } -// handleTssEventCreateGroup implements emitter handler for CreateGroup event. -func (h *Hook) handleTssEventCreateSigning(ctx sdk.Context, evMap common.EvMap) { +// handleTSSEventCreateGroup implements emitter handler for CreateGroup event. +func (h *Hook) handleTSSEventCreateSigning(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeySigningID] contentTypes := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyContentType] contentInfos := evMap[types.EventTypeCreateSigning+"."+types.AttributeKeyContent] @@ -138,7 +138,7 @@ func (h *Hook) handleTssEventCreateSigning(ctx sdk.Context, evMap common.EvMap) id := tss.SigningID(common.Atoi(sid)) signing := h.tssKeeper.MustGetSigning(ctx, id) - h.emitNewTssSigning( + h.emitNewTSSSigning( signing, contentTypes[i], contentInfos[i], @@ -148,8 +148,8 @@ func (h *Hook) handleTssEventCreateSigning(ctx sdk.Context, evMap common.EvMap) } } -// handleTssEventRequestSignature implements emitter handler for RequestSignature event. -func (h *Hook) handleTssEventRequestSignature(ctx sdk.Context, evMap common.EvMap) { +// handleTSSEventRequestSignature implements emitter handler for RequestSignature event. +func (h *Hook) handleTSSEventRequestSignature(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeRequestSignature+"."+types.AttributeKeySigningID] for _, sid := range sids { @@ -159,27 +159,27 @@ func (h *Hook) handleTssEventRequestSignature(ctx sdk.Context, evMap common.EvMa attempt := signing.CurrentAttempt attemptInfo := h.tssKeeper.MustGetSigningAttempt(ctx, id, attempt) - h.emitUpdateTssSigningAttempt(signing) + h.emitUpdateTSSSigningAttempt(signing) for _, am := range attemptInfo.AssignedMembers { - h.emitNewTssAssignedMember(signing.ID, attempt, signing.GroupID, am) + h.emitNewTSSAssignedMember(signing.ID, attempt, signing.GroupID, am) } } } -// handleTssEventSigningSuccess implements emitter handler for SigningSuccess event. -func (h *Hook) handleTssEventSigningSuccess(ctx sdk.Context, evMap common.EvMap) { +// handleTSSEventSigningSuccess implements emitter handler for SigningSuccess event. +func (h *Hook) handleTSSEventSigningSuccess(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeSigningSuccess+"."+types.AttributeKeySigningID] for _, sid := range sids { id := tss.SigningID(common.Atoi(sid)) signing := h.tssKeeper.MustGetSigning(ctx, id) - h.emitUpdateTssSigningSuccess(signing) + h.emitUpdateTSSSigningSuccess(signing) } } -// handleTssEventSigningFailed implements emitter handler for SigningSuccess event. -func (h *Hook) handleTssEventSigningFailed(ctx sdk.Context, evMap common.EvMap) { +// handleTSSEventSigningFailed implements emitter handler for SigningSuccess event. +func (h *Hook) handleTSSEventSigningFailed(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeSigningFailed+"."+types.AttributeKeySigningID] errReasons := evMap[types.EventTypeSigningFailed+"."+types.AttributeKeyReason] for i, sid := range sids { @@ -191,28 +191,28 @@ func (h *Hook) handleTssEventSigningFailed(ctx sdk.Context, evMap common.EvMap) errReason = errReasons[i] } - h.emitUpdateTssSigningFailed(errReason, signing) + h.emitUpdateTSSSigningFailed(errReason, signing) } } -// handleTssSetGroup implements emitter handler events related to group. -func (h *Hook) handleTssSetGroup(ctx sdk.Context, gid tss.GroupID) { +// handleTSSSetGroup implements emitter handler events related to group. +func (h *Hook) handleTSSSetGroup(ctx sdk.Context, gid tss.GroupID) { group := h.tssKeeper.MustGetGroup(ctx, gid) dkgContext, err := h.tssKeeper.GetDKGContext(ctx, gid) if err != nil { dkgContext = []byte{} } - h.emitSetTssGroup(group, dkgContext) + h.emitSetTSSGroup(group, dkgContext) members := h.tssKeeper.MustGetMembers(ctx, gid) for _, m := range members { - h.emitSetTssMember(m) + h.emitSetTSSMember(m) } } -// handleTssEventSubmitSignature implements emitter handler for SubmitSignature event. -func (h *Hook) handleTssEventSubmitSignature(ctx sdk.Context, evMap common.EvMap) { +// handleTSSEventSubmitSignature implements emitter handler for SubmitSignature event. +func (h *Hook) handleTSSEventSubmitSignature(ctx sdk.Context, evMap common.EvMap) { sids := evMap[types.EventTypeSubmitSignature+"."+types.AttributeKeySigningID] attempts := evMap[types.EventTypeSubmitSignature+"."+types.AttributeKeyAttempt] memberIDs := evMap[types.EventTypeSubmitSignature+"."+types.AttributeKeyMemberID] @@ -233,6 +233,6 @@ func (h *Hook) handleTssEventSubmitSignature(ctx sdk.Context, evMap common.EvMap } signature := tss.Signature(bz) - h.emitUpdateTssAssignedMember(signingID, attempt, memberID, signature, ctx.BlockHeight()) + h.emitUpdateTSSAssignedMember(signingID, attempt, memberID, signature, ctx.BlockHeight()) } } From 4da918e89b099d97d8c7d51eeb7c6ceee6e96cca Mon Sep 17 00:00:00 2001 From: nkitlabs Date: Thu, 28 Nov 2024 17:21:01 +0700 Subject: [PATCH 132/132] fix from comments --- flusher/flusher/bandtss_db.py | 12 ++++-------- flusher/flusher/handler.py | 4 ++-- hooks/emitter/bandtss.go | 4 ++-- hooks/emitter/handler.go | 2 +- 4 files changed, 9 insertions(+), 13 deletions(-) diff --git a/flusher/flusher/bandtss_db.py b/flusher/flusher/bandtss_db.py index e9e9e5c2d..5407f0f05 100644 --- a/flusher/flusher/bandtss_db.py +++ b/flusher/flusher/bandtss_db.py @@ -25,9 +25,7 @@ def process_bind_param(self, value, dialect): "bandtss_group_transitions", metadata, Column("proposal_id", sa.Integer, sa.ForeignKey("proposals.id"), primary_key=True), - Column( - "tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id"), nullable=True - ), + Column("tss_signing_id", sa.Integer, sa.ForeignKey("tss_signings.id"), nullable=True), Column( "current_tss_group_id", sa.Integer, @@ -60,8 +58,8 @@ def process_bind_param(self, value, dialect): ), ) -bandtss_current_groups = sa.Table( - "bandtss_current_groups", +bandtss_historical_current_groups = sa.Table( + "bandtss_historical_current_groups", metadata, Column( "proposal_id", @@ -88,9 +86,7 @@ def process_bind_param(self, value, dialect): bandtss_members = sa.Table( "bandtss_members", metadata, - Column( - "tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id"), primary_key=True - ), + Column("tss_group_id", sa.Integer, sa.ForeignKey("tss_groups.id"), primary_key=True), Column("account_id", sa.Integer, sa.ForeignKey("accounts.id"), primary_key=True), Column("is_active", sa.Boolean), Column("since", CustomDateTime, nullable=True), diff --git a/flusher/flusher/handler.py b/flusher/flusher/handler.py index 75c63dca1..223279814 100644 --- a/flusher/flusher/handler.py +++ b/flusher/flusher/handler.py @@ -59,7 +59,7 @@ ) from .restake_db import restake_vaults, restake_locks, restake_historical_stakes from .bandtss_db import ( - bandtss_current_groups, + bandtss_historical_current_groups, bandtss_members, bandtss_signings, bandtss_group_transitions, @@ -923,7 +923,7 @@ def handle_new_bandtss_current_group(self, msg): if proposal_id is not None: msg["proposal_id"] = proposal_id - self.conn.execute(bandtss_current_groups.insert(), msg) + self.conn.execute(bandtss_historical_current_groups.insert(), msg) def handle_set_bandtss_member(self, msg): msg["account_id"] = self.get_account_id(msg["address"]) diff --git a/hooks/emitter/bandtss.go b/hooks/emitter/bandtss.go index d6e935686..e4dc8f765 100644 --- a/hooks/emitter/bandtss.go +++ b/hooks/emitter/bandtss.go @@ -113,8 +113,8 @@ func (h *Hook) handleBandtssMsgActivate(ctx sdk.Context, msg *types.MsgActivate) h.handleBandtssUpdateMember(ctx, acc, msg.GroupID) } -// handleBandtssEventInactiveStatuses implements emitter handler for inactive status event. -func (h *Hook) handleBandtssEventInactiveStatuses(ctx sdk.Context, evMap common.EvMap) { +// handleBandtssEventInactiveStatus implements emitter handler for inactive status event. +func (h *Hook) handleBandtssEventInactiveStatus(ctx sdk.Context, evMap common.EvMap) { addresses := evMap[types.EventTypeInactiveStatus+"."+types.AttributeKeyAddress] groupIDs := evMap[types.EventTypeInactiveStatus+"."+types.AttributeKeyGroupID] if len(addresses) != len(groupIDs) { diff --git a/hooks/emitter/handler.go b/hooks/emitter/handler.go index 507f6578b..dd8f45884 100644 --- a/hooks/emitter/handler.go +++ b/hooks/emitter/handler.go @@ -209,7 +209,7 @@ func (h *Hook) handleBeginBlockEndBlockEvent( evMap := parseEvents([]abci.Event{event}) switch event.Type { case bandtsstypes.EventTypeInactiveStatus: - h.handleBandtssEventInactiveStatuses(ctx, evMap) + h.handleBandtssEventInactiveStatus(ctx, evMap) case bandtsstypes.EventTypeGroupTransition: h.handleBandtssEventGroupTransition(ctx, eventIdx, eventQuerier) case bandtsstypes.EventTypeGroupTransitionSuccess: