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

fix: signatures replayed across different networks #321

Closed
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ Contains bug fixes.
Contains all the PRs that improved the code without changing the behaviors.
-->

# v1.0.6-fix
### Added

### Changed

### Fixed
- Fixed signatures not to be replayed across different networks

# v1.0.5-Prerelease
### Added
- Arkeo testnet validator addresses to airdrop
Expand Down
28 changes: 27 additions & 1 deletion arkeocli/claim.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package arkeocli

import (
"context"
"strconv"

"cosmossdk.io/errors"
Expand Down Expand Up @@ -36,6 +37,18 @@ func runClaimCmd(cmd *cobra.Command, args []string) (err error) {
return err
}

node, err := clientCtx.GetNode()
if err != nil {
return errors.Wrapf(err, "failed to get node")
}
status, err := node.Status(context.Background())
if err != nil {
return errors.Wrapf(err, "failed to get node status")
}
currentBlock := status.SyncInfo.LatestBlockHeight

expiresAtBlock := currentBlock + types.DefaultSignatureExpiration

key, err := ensureKeys(cmd)
if err != nil {
return err
Expand Down Expand Up @@ -80,7 +93,18 @@ func runClaimCmd(cmd *cobra.Command, args []string) (err error) {
return err
}

signBytes := types.GetBytesToSign(contract.Id, nonce)
chainId, err := cmd.Flags().GetString("chain-id")
if err != nil {
return errors.Wrapf(err, "chain-id should be specified")
}
if chainId == "" {
chainId, err = promptForArg(cmd, "Specify Chain ID: ")
if err != nil {
return err
}
}

signBytes := types.GetBytesToSign(contract.Id, nonce, chainId, expiresAtBlock)
signature, _, err := clientCtx.Keyring.Sign(key.Name, signBytes, signing.SignMode_SIGN_MODE_DIRECT)
if err != nil {
return errors.Wrapf(err, "error signing")
Expand All @@ -91,6 +115,8 @@ func runClaimCmd(cmd *cobra.Command, args []string) (err error) {
contract.Id,
nonce,
signature,
chainId,
expiresAtBlock,
)
if err := msg.ValidateBasic(); err != nil {
return err
Expand Down
2 changes: 2 additions & 0 deletions proto/arkeo/arkeo/tx.proto
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ message MsgClaimContractIncome {
uint64 contract_id = 2;
bytes signature = 4;
int64 nonce = 5;
string chain_id = 6;
int64 signature_expires_at_block = 7;
}

message MsgClaimContractIncomeResponse {}
Expand Down
22 changes: 12 additions & 10 deletions sentinel/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,25 @@ type ContractAuth struct {
}

type ArkAuth struct {
ContractId uint64
Spender common.PubKey
Nonce int64
Signature []byte
ContractId uint64
Spender common.PubKey
Nonce int64
Signature []byte
ChainId string
ExpiresAtBlock int64
}

// String implement fmt.Stringer
func (aa ArkAuth) String() string {
return GenerateArkAuthString(aa.ContractId, aa.Nonce, aa.Signature)
return GenerateArkAuthString(aa.ContractId, aa.Nonce, aa.Signature, aa.ChainId, aa.ExpiresAtBlock)
}

func GenerateArkAuthString(contractId uint64, nonce int64, signature []byte) string {
return fmt.Sprintf("%s:%s", GenerateMessageToSign(contractId, nonce), hex.EncodeToString(signature))
func GenerateArkAuthString(contractId uint64, nonce int64, signature []byte, chainId string, expiresAtBlock int64) string {
return fmt.Sprintf("%s:%s", GenerateMessageToSign(contractId, nonce, chainId, expiresAtBlock), hex.EncodeToString(signature))
}

func GenerateMessageToSign(contractId uint64, nonce int64) string {
return fmt.Sprintf("%d:%d", contractId, nonce)
func GenerateMessageToSign(contractId uint64, nonce int64, chainId string, expiresAtBlock int64) string {
return fmt.Sprintf("%d:%d:%s:%d", contractId, nonce, chainId, expiresAtBlock)
}

func parseContractAuth(raw string) (ContractAuth, error) {
Expand Down Expand Up @@ -117,7 +119,7 @@ func (aa ArkAuth) Validate(provider common.PubKey) error {
if err != nil {
return fmt.Errorf("internal server error: %w", err)
}
msg := types.NewMsgClaimContractIncome(creator, aa.ContractId, aa.Nonce, aa.Signature)
msg := types.NewMsgClaimContractIncome(creator, aa.ContractId, aa.Nonce, aa.Signature, aa.ChainId, aa.ExpiresAtBlock)
err = msg.ValidateBasic()
return err
}
Expand Down
9 changes: 6 additions & 3 deletions sentinel/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ func TestArkAuth(t *testing.T) {
pk, err := common.NewPubKeyFromCrypto(pub)
require.NoError(t, err)

chaindId := "arkeo-1"
expiresAtBlock := int64(10)

var signature []byte
nonce := int64(3)
service := common.BTCService
Expand All @@ -50,13 +53,13 @@ func TestArkAuth(t *testing.T) {
require.NoError(t, err)

// happy path
raw := GenerateArkAuthString(contractId, nonce, signature)
raw := GenerateArkAuthString(contractId, nonce, signature, chaindId, expiresAtBlock)
_, err = parseArkAuth(raw)
require.NoError(t, err)

// bad signature
raw = GenerateArkAuthString(contractId, nonce, signature)
_, err = parseArkAuth(raw + "randome not hex!")
raw = GenerateArkAuthString(contractId, nonce, signature, chaindId, expiresAtBlock)
_, err = parseArkAuth(raw + "random not hex!")
require.Error(t, err)
}

Expand Down
27 changes: 25 additions & 2 deletions test/regression/cmd/operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,12 @@ func createContractAuth(input map[string]string) (string, bool, error) {
if len(input["timestamp"]) == 0 {
return "", true, fmt.Errorf("missing required field: timestamp")
}
if len(input["chain_id"]) == 0 {
return "", true, fmt.Errorf("missing required field: chain_id")
}
if len(input["expires_at_block"]) == 0 {
return "", true, fmt.Errorf("missing required field: expires_at_block")
}

id, err := strconv.ParseUint(input["id"], 10, 64)
if err != nil {
Expand All @@ -289,8 +295,13 @@ func createContractAuth(input map[string]string) (string, bool, error) {
return "", true, fmt.Errorf("failed to parse timestamp: %s", err)
}

expiresAtBlock, err := strconv.ParseInt(input["expires_at_block"], 10, 64)
if err != nil {
return "", true, fmt.Errorf("failed to parse timestamp: %s", err)
}

// sign our msg
msg := sentinel.GenerateMessageToSign(id, timestamp)
msg := sentinel.GenerateMessageToSign(id, timestamp, input["chain_id"], expiresAtBlock)
auth, err := signThis(msg, input["signer"])
return auth, true, err
}
Expand All @@ -315,6 +326,18 @@ func createAuth(input map[string]string) (string, bool, error) {
return "", true, fmt.Errorf("missing required field: nonce")
}

if len(input["chain_id"]) == 0 {
return "", true, fmt.Errorf("missing required field: chain_id")
}
if len(input["expires_at_block"]) == 0 {
return "", true, fmt.Errorf("missing required field: expires_at_block")
}

expiresAtBlock, err := strconv.ParseInt(input["expires_at_block"], 10, 64)
if err != nil {
return "", true, fmt.Errorf("failed to parse timestamp: %s", err)
}

id, err := strconv.ParseUint(input["id"], 10, 64)
if err != nil {
return "", true, fmt.Errorf("failed to parse id: %s", err)
Expand All @@ -323,7 +346,7 @@ func createAuth(input map[string]string) (string, bool, error) {
if err != nil {
return "", true, fmt.Errorf("failed to parse nonce: %s", err)
}
msg := sentinel.GenerateMessageToSign(id, nonce)
msg := sentinel.GenerateMessageToSign(id, nonce, input["chain_id"], expiresAtBlock)
auth, err := signThis(msg, input["signer"])
return auth, true, err
}
Expand Down
9 changes: 6 additions & 3 deletions tools/curleo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ func main() {
head := flag.String("H", "", "header")
flag.Parse()

chainId := flag.String("chain_id", "", "chain id")
expiresAtBlock := flag.Int64("expires_at_block", 0, "block expiration time")

c := cosmos.GetConfig()
c.SetBech32PrefixForAccount(app.AccountAddressPrefix, app.AccountAddressPrefix+"pub")

Expand All @@ -77,7 +80,7 @@ func main() {
println(fmt.Sprintf("no active contract found for provider:%s cbhain:%s - will attempt free tier", metadata.Configuration.ProviderPubKey.String(), service))
} else {
claim := curl.getClaim(contract.Id)
auth := curl.sign(*user, contract.Id, claim.Nonce+1)
auth := curl.sign(*user, contract.Id, claim.Nonce+1, *chainId, *expiresAtBlock)
values.Add(sentinel.QueryArkAuth, auth)
}
u.RawQuery = values.Encode()
Expand Down Expand Up @@ -189,7 +192,7 @@ func (c Curl) parseMetadata() sentinel.Metadata {
return meta
}

func (c Curl) sign(user string, contractId uint64, nonce int64) string {
func (c Curl) sign(user string, contractId uint64, nonce int64, chainId string, expiresAtBlock int64) string {
interfaceRegistry := codectypes.NewInterfaceRegistry()
std.RegisterInterfaces(interfaceRegistry)
ModuleBasics.RegisterInterfaces(interfaceRegistry)
Expand All @@ -203,7 +206,7 @@ func (c Curl) sign(user string, contractId uint64, nonce int64) string {
if err != nil {
log.Fatal(err)
}
msg := sentinel.GenerateMessageToSign(contractId, nonce)
msg := sentinel.GenerateMessageToSign(contractId, nonce, chainId, expiresAtBlock)

println("invoking Sign...")
signature, pk, err := kb.Sign(user, []byte(msg), signing.SignMode_SIGN_MODE_DIRECT)
Expand Down
30 changes: 29 additions & 1 deletion x/arkeo/client/cli/tx_claim_contract_income.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"context"
"encoding/hex"

"github.com/arkeonetwork/arkeo/x/arkeo/types"
Expand All @@ -14,7 +15,7 @@ import (

func CmdClaimContractIncome() *cobra.Command {
cmd := &cobra.Command{
Use: "claim-contract-income [contract-id] [nonce] [signature]",
Use: "claim-contract-income [contract-id] [nonce] [signature] [chain-id]",
Short: "Broadcast message claimContractIncome",
Args: cobra.ExactArgs(4),
RunE: func(cmd *cobra.Command, args []string) (err error) {
Expand All @@ -32,15 +33,41 @@ func CmdClaimContractIncome() *cobra.Command {
if err != nil {
return err
}

signature, err := hex.DecodeString(args[2])
if err != nil {
return err
}

chainID := args[3]

node, err := clientCtx.GetNode()
if err != nil {
return err
}

status, err := node.Status(context.Background())
if err != nil {
return err
}
currentBlock := status.SyncInfo.LatestBlockHeight

// Get expiration delta from flags (default to 50 blocks if not specified)
expirationDelta, err := cmd.Flags().GetInt64("expiration-delta")
if err != nil {
expirationDelta = 50
}

// Calculate expiration block
expiresAtBlock := currentBlock + expirationDelta

msg := types.NewMsgClaimContractIncome(
clientCtx.GetFromAddress(),
argContractId,
argNonce,
signature,
chainID,
expiresAtBlock,
)
if err := msg.ValidateBasic(); err != nil {
return err
Expand All @@ -50,6 +77,7 @@ func CmdClaimContractIncome() *cobra.Command {
}

flags.AddTxFlagsToCmd(cmd)
cmd.Flags().Int64("expiration-delta", 50, "number of blocks until expiration")

return cmd
}
2 changes: 1 addition & 1 deletion x/arkeo/keeper/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ func SetupKeeperWithStaking(t testing.TB) (cosmos.Context, Keeper, stakingkeeper
"ArkeoParams",
)

ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger())
ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()).WithChainID("arkeo-1")

govModuleAddr := "tarkeo1krj9ywwmqcellgunxg66kjw5dtt402kq0uf6pu"
_ = paramskeeper.NewKeeper(cdc, amino, keyParams, tkeyParams)
Expand Down
14 changes: 12 additions & 2 deletions x/arkeo/keeper/msg_server_claim_contract_income.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,22 @@
}

contract, err := k.GetContract(ctx, msg.ContractId)

if err != nil {
return err
}

if msg.ChainId != ctx.ChainID() {
return errors.Wrapf(types.ErrInvalidChainID, "expected %s, got %s", ctx.ChainID(), msg.ChainId)

}

Check failure on line 47 in x/arkeo/keeper/msg_server_claim_contract_income.go

View workflow job for this annotation

GitHub Actions / lint

unnecessary trailing newline (whitespace)

if msg.SignatureExpiresAtBlock <= ctx.BlockHeight() {
return errors.Wrapf(types.ErrSignatureExpired,
"current block height %d is greater than or equal to expiration block %d",
ctx.BlockHeight(),
msg.SignatureExpiresAtBlock)
}

if contract.Nonce >= msg.Nonce {
return errors.Wrapf(types.ErrClaimContractIncomeBadNonce, "contract nonce (%d) is greater than msg nonce (%d)", contract.Nonce, msg.Nonce)
}
Expand All @@ -62,7 +73,6 @@
}

// excute settlement

_, err = k.mgr.SettleContract(ctx, contract, msg.Nonce, false)
if err != nil {
return err
Expand Down
Loading
Loading