Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: skyway nonces #1251

Merged
merged 1 commit into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions proto/palomachain/paloma/skyway/msgs.proto
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ message MsgSendToPalomaClaim {
palomachain.paloma.valset.MsgMetadata metadata = 9
[ (gogoproto.nullable) = false ];
uint64 skyway_nonce = 10;
string compass_id = 11;
}

message MsgSendToPalomaClaimResponse {
Expand All @@ -116,6 +117,7 @@ message MsgBatchSendToRemoteClaim {
palomachain.paloma.valset.MsgMetadata metadata = 7
[ (gogoproto.nullable) = false ];
uint64 skyway_nonce = 8;
string compass_id = 9;
}

message MsgBatchSendToRemoteClaimResponse {}
Expand Down Expand Up @@ -240,6 +242,7 @@ message MsgLightNodeSaleClaim {
(gogoproto.nullable) = false
];
string smart_contract_address = 9;
string compass_id = 10;
}

// MsgEstimateBatchGas is a message to estimate the gas for a batch
Expand Down
14 changes: 13 additions & 1 deletion util/eventbus/bus.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import (
"github.com/palomachain/paloma/util/liblog"
)

var skywayBatchBuilt = newEvent[SkywayBatchBuiltEvent]()
var (
skywayBatchBuilt = newEvent[SkywayBatchBuiltEvent]()
evmActivatedChain = newEvent[EVMActivatedChainEvent]()
)

type (
EventHandler[E any] func(context.Context, E) error
Expand Down Expand Up @@ -58,3 +61,12 @@ type SkywayBatchBuiltEvent struct {
func SkywayBatchBuilt() *Event[SkywayBatchBuiltEvent] {
return &skywayBatchBuilt
}

type EVMActivatedChainEvent struct {
ChainReferenceID string
SmartContractUniqueID []byte
}

func EVMActivatedChain() *Event[EVMActivatedChainEvent] {
return &evmActivatedChain
}
5 changes: 5 additions & 0 deletions x/evm/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,11 @@ func (k Keeper) ActivateChainReferenceID(
k.Logger(sdkCtx).Error("error while activating chain with a new smart contract", args...)
} else {
k.Logger(sdkCtx).Info("activated chain with a new smart contract", args...)

eventbus.EVMActivatedChain().Publish(ctx, eventbus.EVMActivatedChainEvent{
ChainReferenceID: chainReferenceID,
SmartContractUniqueID: smartContractUniqueID,
})
}
}()
chainInfo, err := k.GetChainInfo(ctx, chainReferenceID)
Expand Down
2 changes: 0 additions & 2 deletions x/evm/keeper/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ func buildKeeper(t *testing.T) (*Keeper, sdk.Context, mockedServices) {
// test-chain mocks
mockServices.ValsetKeeper.On("GetCurrentSnapshot", mock.Anything).Return(unpublishedSnapshot, nil)
mockServices.ConsensusKeeper.On("PutMessageInQueue", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil)
mockServices.SkywayKeeper.On("GetLastObservedSkywayNonce", mock.Anything, mock.Anything).Return(uint64(100), nil)
mockServices.MetrixKeeper.On("Validators", mock.Anything, mock.Anything).Return(&metrixtypes.QueryValidatorsResponse{
ValMetrics: getMetrics(3),
}, nil)
Expand All @@ -98,7 +97,6 @@ func buildKeeper(t *testing.T) (*Keeper, sdk.Context, mockedServices) {
// invalid-test-chain mocks
mockServices.ValsetKeeper.On("GetCurrentSnapshot", mock.Anything).Return(unpublishedSnapshot, nil)
mockServices.ConsensusKeeper.On("PutMessageInQueue", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(uint64(0), nil)
mockServices.SkywayKeeper.On("GetLastObservedSkywayNonce", mock.Anything, mock.Anything).Return(uint64(100), nil)
mockServices.MetrixKeeper.On("Validators", mock.Anything, mock.Anything).Return(&metrixtypes.QueryValidatorsResponse{
ValMetrics: getMetrics(3),
}, nil)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ func addDeploymentToKeeper(t *testing.T, ctx sdk.Context, k *Keeper, mockService
// test-chain mocks
mockServices.ValsetKeeper.On("GetCurrentSnapshot", mock.Anything).Return(unpublishedSnapshot, nil)
mockServices.ConsensusKeeper.On("PutMessageInQueue", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(uint64(10), nil)
mockServices.SkywayKeeper.On("GetLastObservedSkywayNonce", mock.Anything, mock.Anything).Return(uint64(100), nil)
mockServices.MetrixKeeper.On("Validators", mock.Anything, mock.Anything).Return(&metrixtypes.QueryValidatorsResponse{
ValMetrics: getMetrics(3),
}, nil)
Expand Down
6 changes: 1 addition & 5 deletions x/evm/keeper/smart_contract_deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,10 +272,6 @@ func (k Keeper) deploySmartContractToChain(ctx context.Context, chainInfo *types
}
uniqueID := generateSmartContractID(ctx)
k.createSmartContractDeployment(ctx, smartContract, chainInfo, uniqueID[:])
lastSkywayNonce, err := k.Skyway.GetLastObservedSkywayNonce(ctx, chainInfo.GetChainReferenceID())
if err != nil {
return fmt.Errorf("failed to get last observed skyway nonce: %w", err)
}

// set the smart contract constructor arguments
logger.Info(
Expand All @@ -284,7 +280,7 @@ func (k Keeper) deploySmartContractToChain(ctx context.Context, chainInfo *types
"validators-size", len(valset.GetValidators()),
"power-size", len(valset.GetPowers()),
)
input, err := contractABI.Pack("", uniqueID, big.NewInt(0), (&big.Int{}).SetUint64(lastSkywayNonce), types.TransformValsetToCompassValset(&valset), feeMgrAddr)
input, err := contractABI.Pack("", uniqueID, big.NewInt(0), big.NewInt(0), types.TransformValsetToCompassValset(&valset), feeMgrAddr)
if err != nil {
return err
}
Expand Down
37 changes: 35 additions & 2 deletions x/skyway/keeper/attestation.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,9 @@ func (k Keeper) DeleteAttestation(ctx context.Context, chainReferenceID string,
func (k Keeper) GetAttestationMapping(ctx context.Context, chainReferenceID string) (attestationMapping map[uint64][]types.Attestation, orderedKeys []uint64, err error) {
attestationMapping = make(map[uint64][]types.Attestation)
var g whoops.Group

lastCompassID := k.GetLatestCompassID(ctx, chainReferenceID)

g.Add(
k.IterateAttestations(ctx, chainReferenceID, false, func(_ []byte, att types.Attestation) bool {
claim, err := k.UnpackAttestationClaim(&att)
Expand All @@ -275,6 +278,13 @@ func (k Keeper) GetAttestationMapping(ctx context.Context, chainReferenceID stri
return true
}

// Do not include claims originating from the other compass
// versions, since we won't be able to attest them anyway. They may
// also repeat the nonce, so we can't list them here.
if lastCompassID != "" && claim.GetCompassID() != lastCompassID {
return false
}

if val, ok := attestationMapping[claim.GetSkywayNonce()]; !ok {
attestationMapping[claim.GetSkywayNonce()] = []types.Attestation{att}
} else {
Expand Down Expand Up @@ -454,12 +464,13 @@ func (k Keeper) setLastObservedSkywayNonce(ctx context.Context, chainReferenceID
if err != nil {
return err
}

// event nonce must increase, unless it's zero at which point allow zero to be set
// as many times as needed (genesis test setup etc)
zeroCase := last == 0 && nonce == 0
if last >= nonce && !zeroCase {
if nonce != 0 && nonce < last {
return fmt.Errorf("event nonce going backwards or replay")
}

store.Set(types.LastObservedEventNonceKey, types.UInt64Bytes(nonce))
return nil
}
Expand Down Expand Up @@ -528,3 +539,25 @@ func (k Keeper) IterateValidatorLastEventNonces(ctx context.Context, chainRefere
}
return nil
}

// GetLatestCompassID returns the latest compass ID on record after
// message attestation
func (k Keeper) GetLatestCompassID(
ctx context.Context,
chainReferenceID string,
) string {
store := k.GetStore(ctx, chainReferenceID)
bytes := store.Get(types.LatestCompassIDKey)

return string(bytes)
}

// setLatestCompassID stores the latest compass ID received
func (k Keeper) setLatestCompassID(
ctx context.Context,
chainReferenceID string,
compassID string,
) {
store := k.GetStore(ctx, chainReferenceID)
store.Set(types.LatestCompassIDKey, []byte(compassID))
}
34 changes: 34 additions & 0 deletions x/skyway/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
ibctransferkeeper "github.com/cosmos/ibc-go/v8/modules/apps/transfer/keeper"
"github.com/palomachain/paloma/util/eventbus"
keeperutil "github.com/palomachain/paloma/util/keeper"
"github.com/palomachain/paloma/util/liblog"
"github.com/palomachain/paloma/x/skyway/types"
Expand Down Expand Up @@ -88,6 +89,39 @@ func NewKeeper(
attestationHandler.ValidateMembers()
k.AttestationHandler = attestationHandler
k.authority = authority

eventbus.EVMActivatedChain().Subscribe(
"skyway-keeper",
func(ctx context.Context, e eventbus.EVMActivatedChainEvent) error {
logger := liblog.FromKeeper(ctx, k).
WithComponent("skyway-activated-chain-callback").
WithFields(
"chain_reference_id", e.ChainReferenceID,
"smart_contract_unique_id", string(e.SmartContractUniqueID),
)

k.setLatestCompassID(ctx, e.ChainReferenceID, string(e.SmartContractUniqueID))

err := k.setLastObservedSkywayNonce(ctx, e.ChainReferenceID, 0)
if err != nil {
logger.WithError(err).Warn("Failed to reset skyway nonce")
return err
}

err = k.IterateValidatorLastEventNonces(ctx, e.ChainReferenceID, func(key []byte, _ uint64) bool {
store := k.GetStore(ctx, e.ChainReferenceID)
store.Delete(key)
return false
})
if err != nil {
logger.WithError(err).Warn("Failed to reset validator skyway nonces")
return err
}

logger.Info("Updated last observed nonce successfully")
return nil
})

return k
}

Expand Down
3 changes: 3 additions & 0 deletions x/skyway/types/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ var (
BridgeTransferLimitPrefix = "bridge-transfer-limit"
BridgeTransferUsagePrefix = "bridge-transfer-usage"
LightNodeSaleContractsPrefix = "light-node-sale-contracts"

// LatestCompassIDKey stores the latest compass ID received
LatestCompassIDKey = HashString("LatestCompassIDKey")
)

// GetOrchestratorAddressKey returns the following key format
Expand Down
2 changes: 2 additions & 0 deletions x/skyway/types/legacy_msgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ func (msg *MsgBatchSendToEthClaim) ClaimHash() ([]byte, error) {
return tmhash.Sum([]byte(path)), nil
}

func (msg *MsgBatchSendToEthClaim) GetCompassID() string { return "" }

func (msg MsgBatchSendToEthClaim) GetClaimer() sdk.AccAddress {
err := msg.ValidateBasic()
if err != nil {
Expand Down
22 changes: 18 additions & 4 deletions x/skyway/types/msgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ type EthereumClaim interface {
GetChainReferenceId() string
// Returns the reference ID of the remote chain on which this claim was observed.
GetSkywayNonce() uint64
// Returns the compass ID that sent the original message
GetCompassID() string
}

// nolint: exhaustruct
Expand Down Expand Up @@ -251,10 +253,14 @@ const (
// note that the Orchestrator is the only field excluded from this hash, this is because that value is used higher up in the store
// structure for who has made what claim and is verified by the msg ante-handler for signatures
func (msg *MsgSendToPalomaClaim) ClaimHash() ([]byte, error) {
path := fmt.Sprintf("%d/%d/%s/%s/%s/%s", msg.SkywayNonce, msg.EthBlockHeight, msg.TokenContract, msg.Amount.String(), msg.EthereumSender, msg.PalomaReceiver)
path := fmt.Sprintf("%d/%d/%s/%s/%s/%s/%s", msg.SkywayNonce, msg.EthBlockHeight, msg.TokenContract, msg.Amount.String(), msg.EthereumSender, msg.PalomaReceiver, msg.CompassId)
return tmhash.Sum([]byte(path)), nil
}

func (msg *MsgSendToPalomaClaim) GetCompassID() string {
return msg.CompassId
}

func (msg *MsgBatchSendToRemoteClaim) SetOrchestrator(orchestrator sdk.AccAddress) {
msg.Orchestrator = orchestrator.String()
}
Expand Down Expand Up @@ -286,10 +292,14 @@ func (e *MsgBatchSendToRemoteClaim) ValidateBasic() error {

// Hash implements WithdrawBatch.Hash
func (msg *MsgBatchSendToRemoteClaim) ClaimHash() ([]byte, error) {
path := fmt.Sprintf("%d/%d/%d/%s", msg.SkywayNonce, msg.EthBlockHeight, msg.BatchNonce, msg.TokenContract)
path := fmt.Sprintf("%d/%d/%d/%s/%s", msg.SkywayNonce, msg.EthBlockHeight, msg.BatchNonce, msg.TokenContract, msg.CompassId)
return tmhash.Sum([]byte(path)), nil
}

func (msg *MsgBatchSendToRemoteClaim) GetCompassID() string {
return msg.CompassId
}

func (msg MsgBatchSendToRemoteClaim) GetClaimer() sdk.AccAddress {
err := msg.ValidateBasic()
if err != nil {
Expand Down Expand Up @@ -405,11 +415,15 @@ func (msg *MsgLightNodeSaleClaim) ValidateBasic() error {
}

func (msg *MsgLightNodeSaleClaim) ClaimHash() ([]byte, error) {
path := fmt.Sprintf("%d/%d/%s/%s", msg.SkywayNonce, msg.EthBlockHeight,
msg.ClientAddress, msg.Amount.String())
path := fmt.Sprintf("%d/%d/%s/%s/%s", msg.SkywayNonce, msg.EthBlockHeight,
msg.ClientAddress, msg.Amount.String(), msg.CompassId)
return tmhash.Sum([]byte(path)), nil
}

func (msg *MsgLightNodeSaleClaim) GetCompassID() string {
return msg.CompassId
}

func (msg MsgLightNodeSaleClaim) GetClaimer() sdk.AccAddress {
err := msg.ValidateBasic()
if err != nil {
Expand Down
Loading
Loading