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

[stacked] support ledger cosmos signing in staking-cli #26

Merged
merged 2 commits into from
Feb 24, 2025
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
860 changes: 833 additions & 27 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions packages/cosmos/src/staker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,9 +309,10 @@ export class CosmosStaker {
const acc = await getAccount(cosmosClient, this.networkConfig.lcdUrl, signerAddress)
const signDoc = await genSignableTx(this.networkConfig, chainID, tx, acc.accountNumber, acc.sequence, memo ?? '')

const { sig, pk } = await genSignDocSignature(signer, acc, signDoc)
const isEVM = this.networkConfig.isEVM ?? false
const { sig, pk } = await genSignDocSignature(signer, acc, signDoc, isEVM)

const pkType = this.networkConfig.isEVM ? acc.pubkey?.type ?? undefined : undefined
const pkType = isEVM ? acc.pubkey?.type ?? undefined : undefined
const signedTx = genSignedTx(signDoc, sig, pk, pkType)

// IMPORTANT: verify that signer address matches derived address from signature
Expand Down
15 changes: 9 additions & 6 deletions packages/cosmos/src/tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,15 +216,18 @@ export async function genSignableTx (
export async function genSignDocSignature (
signer: Signer,
signerAccount: Account,
signDoc: StdSignDoc
signDoc: StdSignDoc,
isEVM: boolean
): Promise<{ sig: Signature; pk: Uint8Array }> {
if (signerAccount.pubkey === null) {
throw new Error('Signer account pubkey is not set')
// The LCD doesn't have to return a public key for an acocunt, therefore
// we do a best effort check to assert the pubkey type is ethsecp256k1
if (isEVM && signerAccount.pubkey !== undefined) {
if (!signerAccount.pubkey?.type.toLowerCase().includes('ethsecp256k1')) {
throw new Error('signer account pubkey type is not ethsecp256k1')
}
}

const msg = signerAccount.pubkey.type.toLowerCase().includes('ethsecp256k1')
? keccak256(serializeSignDoc(signDoc))
: new Sha256(serializeSignDoc(signDoc)).digest()
const msg = isEVM ? keccak256(serializeSignDoc(signDoc)) : new Sha256(serializeSignDoc(signDoc)).digest()
const message = Buffer.from(msg).toString('hex')
const note = SafeJSONStringify(signDoc, 2)

Expand Down
5 changes: 3 additions & 2 deletions packages/signer-ledger-cosmos/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
"dependencies": {
"@chorus-one/signer": "^1.0.0",
"@chorus-one/utils": "^1.0.0",
"@ledgerhq/hw-app-cosmos": "^6.7.0",
"@ledgerhq/hw-transport": "^6.31.0"
"@ledgerhq/hw-transport": "^6.31.0",
"@zondax/ledger-cosmos-js": "^4.0.0",
"@noble/curves": "^1.4.2"
}
}
33 changes: 21 additions & 12 deletions packages/signer-ledger-cosmos/src/signer.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { nopLogger } from '@chorus-one/utils'
import type { Logger } from '@chorus-one/utils'
import { sortObjectByKeys } from '@chorus-one/utils'
import type { LedgerCosmosSignerConfig } from './types'
import type { Signature, SignerData } from '@chorus-one/signer'
import Cosmos from '@ledgerhq/hw-app-cosmos'
import { secp256k1 } from '@noble/curves/secp256k1'
import CosmosApp from '@zondax/ledger-cosmos-js'
import Transport from '@ledgerhq/hw-transport'

/**
Expand All @@ -16,7 +18,7 @@ export class LedgerCosmosSigner {
private readonly config: LedgerCosmosSignerConfig
private readonly transport: Transport
private accounts: Map<string, { hdPath: string; publicKey: Uint8Array }>
private app?: Cosmos
private app?: CosmosApp
private logger: Logger

/**
Expand All @@ -43,15 +45,15 @@ export class LedgerCosmosSigner {
* @returns A promise that resolves once the initialization is complete.
*/
async init (): Promise<void> {
const app = new Cosmos(this.transport)
const app = new CosmosApp(this.transport)
this.app = app

this.config.accounts.forEach(async (account: { hdPath: string }) => {
const response = await app.getAddress(account.hdPath, this.config.bechPrefix)
const response = await app.getAddressAndPubKey(account.hdPath, this.config.bechPrefix)

this.accounts.set(response.address.toLowerCase(), {
this.accounts.set(response.bech32_address.toLowerCase(), {
hdPath: account.hdPath,
publicKey: Buffer.from(response.publicKey, 'hex')
publicKey: response.compressed_pk
})
})
}
Expand All @@ -75,16 +77,23 @@ export class LedgerCosmosSigner {
}

const account = this.getAccount(signerAddress)
const { signature, return_code } = await this.app.sign(account.hdPath, signerData.message)

if (signature === null) {
throw new Error(`failed to sign message: ${return_code}`)
const { signature } = await this.app.sign(
account.hdPath,
Buffer.from(JSON.stringify(sortObjectByKeys(signerData.data.signDoc)), 'utf-8'),
this.config.bechPrefix,
0 // 0 for JSON, 1 for TEXTUAL
)

if (signature.length === 0) {
throw new Error(`failed to sign message`)
}

const secpsig = secp256k1.Signature.fromDER(signature)
const sig = {
fullSig: Buffer.from(signature).toString('hex'),
r: Buffer.from(signature.subarray(0, 32)).toString('hex'),
s: Buffer.from(signature.subarray(32, 64)).toString('hex'),
fullSig: secpsig.toCompactHex(),
r: Buffer.from(secpsig.toCompactRawBytes().subarray(0, 32)).toString('hex'),
s: Buffer.from(secpsig.toCompactRawBytes().subarray(32, 64)).toString('hex'),
v: 0
}

Expand Down
1 change: 1 addition & 0 deletions packages/staking-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"@chorus-one/signer": "^1.0.0",
"@chorus-one/signer-fireblocks": "^1.0.0",
"@chorus-one/signer-ledger-ton": "^1.0.0",
"@chorus-one/signer-ledger-cosmos": "^1.0.0",
"@chorus-one/signer-local": "^1.0.0",
"@chorus-one/solana": "^1.0.0",
"@chorus-one/substrate": "^1.0.1",
Expand Down
25 changes: 15 additions & 10 deletions packages/staking-cli/src/signer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { FireblocksSigner } from '@chorus-one/signer-fireblocks'
import { LocalSigner } from '@chorus-one/signer-local'
import { Logger } from '@chorus-one/utils'
import { LedgerTonSigner } from '@chorus-one/signer-ledger-ton'
import { LedgerCosmosSigner } from '@chorus-one/signer-ledger-cosmos'
import TransportNodeHid from '@ledgerhq/hw-transport-node-hid'

export async function newSigner (
Expand Down Expand Up @@ -53,17 +54,21 @@ export async function newSigner (
})
}
case SignerType.LEDGER: {
if (config.networkType !== 'ton') {
throw new Error('Ledger signer is only supported for TON network')
switch (config.networkType) {
case 'ton':
return new LedgerTonSigner({
transport: await TransportNodeHid.create(),
logger: options.logger,
...config.ledger
})
case 'cosmos':
return new LedgerCosmosSigner({
transport: await TransportNodeHid.create(),
logger: options.logger,
...config.ledger
})
}

const transport = await TransportNodeHid.create()

return new LedgerTonSigner({
transport: transport,
logger: options.logger,
...config.ledger
})
throw new Error(`Ledger signer is not supported for ${config.networkType} network type`)
}
}
}
2 changes: 1 addition & 1 deletion packages/staking-cli/src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export interface Config {
localsigner: LocalSignerCliConfig

// use ledger hardware wallet as signer
ledger: LedgerTonSignerConfig // | LedgerCosmosSignerConfig | ...
ledger: LedgerTonSignerConfig | LedgerCosmosSignerConfig

// the network type to interact with
networkType: NetworkType
Expand Down
2 changes: 2 additions & 0 deletions packages/staking-cli/tsconfig.cjs.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
{ "path": "../near" },
{ "path": "../signer-fireblocks" },
{ "path": "../signer-local" },
{ "path": "../signer-ledger-ton" },
{ "path": "../signer-ledger-cosmos" },
{ "path": "../signer" },
{ "path": "../solana" },
{ "path": "../substrate" },
Expand Down
4 changes: 4 additions & 0 deletions packages/staking-cli/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
"@chorus-one/near": ["../near/src"],
"@chorus-one/signer-fireblocks": ["../signer-fireblocks/src"],
"@chorus-one/signer-local": ["../signer-local/src"],
"@chorus-one/signer-ledger-ton": ["../signer-ledger-ton/src"],
"@chorus-one/signer-ledger-cosmos": ["../signer-ledger-cosmos/src"],
"@chorus-one/signer": ["../signer/src"],
"@chorus-one/solana": ["../solana/src"],
"@chorus-one/substrate": ["../substrate/src"],
Expand All @@ -26,6 +28,8 @@
{ "path": "../near" },
{ "path": "../signer-fireblocks" },
{ "path": "../signer-local" },
{ "path": "../signer-ledger-ton" },
{ "path": "../signer-ledger-cosmos" },
{ "path": "../signer" },
{ "path": "../solana" },
{ "path": "../substrate" },
Expand Down
14 changes: 14 additions & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,17 @@ export function checkMaxDecimalPlaces (denomMultiplier: string) {
throw new Error(`denomMultiplier ${denomMultiplier} exceeds maximum decimal precision: ${MAX_DECIMAL_PLACES}`)
}
}

export function sortObjectByKeys<T> (obj: T): T {
if (Array.isArray(obj)) {
return obj.map(sortObjectByKeys) as T
} else if (obj !== null && typeof obj === 'object') {
return Object.keys(obj)
.sort()
.reduce((acc, key) => {
;(acc as any)[key] = sortObjectByKeys((obj as any)[key])
return acc
}, {} as T)
}
return obj
}