Skip to content

chore(hardware-trezor): refactor TrezorKeyAgent to use Transform interface #1096

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

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
9 changes: 4 additions & 5 deletions packages/hardware-trezor/src/TrezorKeyAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,14 +203,13 @@ export class TrezorKeyAgent extends KeyAgentBase {
}

async signTransaction(
tx: Cardano.TxBodyWithHash,
{ body, hash }: Cardano.TxBodyWithHash,
{ knownAddresses, txInKeyPathMap }: SignTransactionContext
): Promise<Cardano.Signatures> {
try {
await this.isTrezorInitialized;
const trezorTxData = txToTrezor({
const trezorTxData = await txToTrezor(body, {
accountIndex: this.accountIndex,
cardanoTxBody: tx.body,
chainId: this.chainId,
knownAddresses,
txInKeyPathMap
Expand All @@ -226,7 +225,7 @@ export class TrezorKeyAgent extends KeyAgentBase {

const expectedPublicKeys = await Promise.all(
util
.ownSignatureKeyPaths(tx.body, knownAddresses, txInKeyPathMap)
.ownSignatureKeyPaths(body, knownAddresses, txInKeyPathMap)
.map((derivationPath) => this.derivePublicKey(derivationPath))
);

Expand All @@ -236,7 +235,7 @@ export class TrezorKeyAgent extends KeyAgentBase {

const signedData = result.payload;

if (signedData.hash !== tx.hash) {
if (signedData.hash !== hash) {
throw new errors.HwMappingError('Trezor computed a different transaction id');
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
import * as Trezor from '@trezor/connect';
import { BIP32Path } from '@cardano-sdk/crypto';
import { Cardano } from '@cardano-sdk/core';
import { Transform, isNotNil } from '@cardano-sdk/util';
import { TrezorTxTransformerContext } from '../types';
import { isNotNil } from '@cardano-sdk/util';
import { resolvePaymentKeyPathForTxIn } from './keyPaths';
import { util } from '@cardano-sdk/key-management';
import isArray from 'lodash/isArray';
import uniq from 'lodash/uniq';

export const mapAdditionalWitnessRequests = (inputs: Trezor.CardanoInput[], context: TrezorTxTransformerContext) => {
const paymentKeyPaths = uniq<BIP32Path>(
export const mapAdditionalWitnessRequests: Transform<
Cardano.TxIn[],
Trezor.DerivationPath[],
TrezorTxTransformerContext
> = (inputs, context) => {
const paymentKeyPaths = uniq<Trezor.DerivationPath>(
inputs
.map((i) => i.path)
.map((input) => resolvePaymentKeyPathForTxIn(input, context))
.filter(isNotNil)
.filter(isArray)
);
const additionalWitnessPaths: BIP32Path[] = [...paymentKeyPaths];
if (context.knownAddresses.length > 0) {

const additionalWitnessPaths: Trezor.DerivationPath[] = [...paymentKeyPaths];

if (context?.knownAddresses?.length) {
const stakeKeyPath = util.stakeKeyPathFromGroupedAddress(context.knownAddresses[0]);
if (stakeKeyPath) additionalWitnessPaths.push(stakeKeyPath);
}
Expand Down
3 changes: 2 additions & 1 deletion packages/hardware-trezor/src/transformers/assets.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as Trezor from '@trezor/connect';
import { Cardano } from '@cardano-sdk/core';
import { Transform } from '@cardano-sdk/util';

const compareAssetNameCanonically = (a: Trezor.CardanoToken, b: Trezor.CardanoToken) => {
if (a.assetNameBytes.length === b.assetNameBytes.length) {
Expand All @@ -12,7 +13,7 @@ const comparePolicyIdCanonically = (a: Trezor.CardanoAssetGroup, b: Trezor.Carda
// PolicyId is always of the same length
a.policyId > b.policyId ? 1 : -1;

const tokenMapToAssetGroup = (tokenMap: Cardano.TokenMap, isMint: boolean): Trezor.CardanoAssetGroup[] => {
const tokenMapToAssetGroup: Transform<Cardano.TokenMap, Trezor.CardanoAssetGroup[]> = (tokenMap, isMint) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting, so this just needed the generic type applied

const map = new Map<string, Array<Trezor.CardanoToken>>();

for (const [key, value] of tokenMap.entries()) {
Expand Down
6 changes: 5 additions & 1 deletion packages/hardware-trezor/src/transformers/auxiliaryData.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import * as Crypto from '@cardano-sdk/crypto';
import * as Trezor from '@trezor/connect';
import { Transform } from '@cardano-sdk/util';

export const mapAuxiliaryData = (auxiliaryDataHash: Crypto.Hash32ByteBase16): Trezor.CardanoAuxiliaryData => ({
export const mapAuxiliaryData: Transform<Crypto.Hash32ByteBase16, Trezor.CardanoAuxiliaryData> = (
auxiliaryDataHash
) => ({
cVoteRegistrationParameters: undefined, // Voting is not handled for now
hash: auxiliaryDataHash
});
118 changes: 52 additions & 66 deletions packages/hardware-trezor/src/transformers/certificates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,46 +3,15 @@ import * as Trezor from '@trezor/connect';
import { BIP32Path } from '@cardano-sdk/crypto';
import { Cardano } from '@cardano-sdk/core';
import { GroupedAddress, util } from '@cardano-sdk/key-management';
import { InvalidArgumentError /* , Transform*/ } from '@cardano-sdk/util';
import { InvalidArgumentError, Transform } from '@cardano-sdk/util';
import { TrezorTxTransformerContext } from '../types';

type StakeKeyCertificateType =
| Trezor.PROTO.CardanoCertificateType.STAKE_REGISTRATION
| Trezor.PROTO.CardanoCertificateType.STAKE_DEREGISTRATION;

type TrezorStakeKeyCertificate = {
type: StakeKeyCertificateType;
path?: BIP32Path;
type CertCredentialsType = {
scriptHash?: Crypto.Ed25519KeyHashHex;
keyHash?: Crypto.Ed25519KeyHashHex;
};

type TrezorDelegationCertificate = {
type: Trezor.PROTO.CardanoCertificateType.STAKE_DELEGATION;
path?: BIP32Path;
scriptHash?: Crypto.Ed25519KeyHashHex;
pool: string;
};

type TrezorPoolRegistrationCertificate = {
poolParameters: Trezor.CardanoPoolParameters;
type: Trezor.PROTO.CardanoCertificateType.STAKE_POOL_REGISTRATION;
};

type ScriptHashCertCredentials = {
scriptHash: Crypto.Ed25519KeyHashHex;
};

type KeyHashCertCredentials = {
keyHash: Crypto.Ed25519KeyHashHex;
};

type PathCertCredentials = {
path: BIP32Path;
};

type CertCredentialsType = ScriptHashCertCredentials | KeyHashCertCredentials | PathCertCredentials;

const getCertCredentials = (
stakeKeyHash: Crypto.Ed25519KeyHashHex,
knownAddresses: GroupedAddress[] | undefined
Expand All @@ -61,57 +30,73 @@ const getCertCredentials = (
};
};

const getStakeAddressCertificate = (
certificate: Cardano.StakeAddressCertificate,
context: TrezorTxTransformerContext,
type: StakeKeyCertificateType
): TrezorStakeKeyCertificate => {
const toPoolMetadata = (metadataJson: Cardano.PoolMetadataJson): Trezor.CardanoPoolMetadata => ({
hash: metadataJson.hash,
url: metadataJson.url
});

const getPoolOperatorKeyPath = (
operator: Cardano.RewardAccount,
context: TrezorTxTransformerContext
): BIP32Path | null => {
const knownAddress = context?.knownAddresses.find((address) => address.rewardAccount === operator);
return util.stakeKeyPathFromGroupedAddress(knownAddress);
};

export const getStakeAddressCertificate: Transform<
Cardano.StakeAddressCertificate,
Trezor.CardanoCertificate,
TrezorTxTransformerContext
> = (certificate, context) => {
const credentials = getCertCredentials(
certificate.stakeCredential.hash as unknown as Crypto.Ed25519KeyHashHex,
context.knownAddresses
context?.knownAddresses
);
const certificateType =
certificate.__typename === Cardano.CertificateType.StakeRegistration
? Trezor.PROTO.CardanoCertificateType.STAKE_REGISTRATION
: Trezor.PROTO.CardanoCertificateType.STAKE_DEREGISTRATION;
return {
...credentials,
type
keyHash: credentials.keyHash,
path: credentials.path,
pool: undefined,
poolParameters: undefined,
scriptHash: credentials.scriptHash,
type: certificateType
};
};

const getStakeDelegationCertificate = (
certificate: Cardano.StakeDelegationCertificate,
context: TrezorTxTransformerContext
): TrezorDelegationCertificate => {
export const getStakeDelegationCertificate: Transform<
Cardano.StakeDelegationCertificate,
Trezor.CardanoCertificate,
TrezorTxTransformerContext
> = (certificate, context) => {
const poolIdKeyHash = Cardano.PoolId.toKeyHash(certificate.poolId);
const credentials = getCertCredentials(
certificate.stakeCredential.hash as unknown as Crypto.Ed25519KeyHashHex,
context.knownAddresses
context?.knownAddresses
);
return {
...credentials,
keyHash: credentials.keyHash,
path: credentials.path,
pool: poolIdKeyHash,
poolParameters: undefined,
scriptHash: credentials.scriptHash,
type: Trezor.PROTO.CardanoCertificateType.STAKE_DELEGATION
};
};

const toPoolMetadata = (metadataJson: Cardano.PoolMetadataJson): Trezor.CardanoPoolMetadata => ({
hash: metadataJson.hash,
url: metadataJson.url
});

const getPoolOperatorKeyPath = (
operator: Cardano.RewardAccount,
context: TrezorTxTransformerContext
): BIP32Path | null => {
const knownAddress = context?.knownAddresses.find((address) => address.rewardAccount === operator);
return util.stakeKeyPathFromGroupedAddress(knownAddress);
};

export const getPoolRegistrationCertificate = (
certificate: Cardano.PoolRegistrationCertificate,
context: TrezorTxTransformerContext
): TrezorPoolRegistrationCertificate => {
export const getPoolRegistrationCertificate: Transform<
Cardano.PoolRegistrationCertificate,
Trezor.CardanoCertificate,
TrezorTxTransformerContext
> = (certificate, context) => {
if (!certificate.poolParameters.metadataJson)
throw new InvalidArgumentError('certificate', 'Missing pool registration pool metadata.');
return {
keyHash: undefined,
path: undefined,
pool: undefined,
poolParameters: {
cost: certificate.poolParameters.cost.toString(),
margin: {
Expand Down Expand Up @@ -153,16 +138,17 @@ export const getPoolRegistrationCertificate = (
rewardAccount: certificate.poolParameters.rewardAccount,
vrfKeyHash: certificate.poolParameters.vrf
},
scriptHash: undefined,
type: Trezor.PROTO.CardanoCertificateType.STAKE_POOL_REGISTRATION
};
};

const toCert = (cert: Cardano.Certificate, context: TrezorTxTransformerContext) => {
switch (cert.__typename) {
case Cardano.CertificateType.StakeRegistration:
return getStakeAddressCertificate(cert, context, Trezor.PROTO.CardanoCertificateType.STAKE_REGISTRATION);
return getStakeAddressCertificate(cert, context);
case Cardano.CertificateType.StakeDeregistration:
return getStakeAddressCertificate(cert, context, Trezor.PROTO.CardanoCertificateType.STAKE_DEREGISTRATION);
return getStakeAddressCertificate(cert, context);
case Cardano.CertificateType.StakeDelegation:
return getStakeDelegationCertificate(cert, context);
case Cardano.CertificateType.PoolRegistration:
Expand Down
10 changes: 4 additions & 6 deletions packages/hardware-trezor/src/transformers/keyPaths.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BIP32Path } from '@cardano-sdk/crypto';
import { Cardano } from '@cardano-sdk/core';
import { GroupedAddress, TxInId, util } from '@cardano-sdk/key-management';
import { TrezorTxTransformerContext } from '../types';
import { TxInId, util } from '@cardano-sdk/key-management';

/** Uses the given Trezor input resolver to resolve the payment key path for known addresses for given input transaction. */
export const resolvePaymentKeyPathForTxIn = (
Expand All @@ -15,13 +15,11 @@ export const resolvePaymentKeyPathForTxIn = (
}
};

// Resolves the stake key path for known addresses for the given reward address.
export const resolveStakeKeyPath = (
rewardAddress: Cardano.RewardAddress | undefined,
context: TrezorTxTransformerContext
rewardAddress: Cardano.RewardAddress,
knownAddresses: GroupedAddress[]
): BIP32Path | null => {
if (!rewardAddress) return null;
const knownAddress = context.knownAddresses.find(
const knownAddress = knownAddresses.find(
({ rewardAccount }) => rewardAccount === rewardAddress.toAddress().toBech32()
);
return util.stakeKeyPathFromGroupedAddress(knownAddress);
Expand Down
33 changes: 26 additions & 7 deletions packages/hardware-trezor/src/transformers/requiredSigners.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,48 @@
import * as Crypto from '@cardano-sdk/crypto';
import * as Trezor from '@trezor/connect';
import { Cardano } from '@cardano-sdk/core';
import { Transform } from '@cardano-sdk/util';
import { TrezorTxTransformerContext } from '../types';
import { util } from '@cardano-sdk/key-management';

export const toRequiredSigner = (
signer: Crypto.Ed25519KeyHashHex,
context: TrezorTxTransformerContext
): Trezor.CardanoRequiredSigner => {
export const toRequiredSigner: Transform<
Crypto.Ed25519KeyHashHex,
Trezor.CardanoRequiredSigner,
TrezorTxTransformerContext
> = (keyHash, context) => {
const paymentCredKnownAddress = context?.knownAddresses.find((address) => {
const paymentCredential = Cardano.Address.fromBech32(address.address)?.asBase()?.getPaymentCredential().hash;
return paymentCredential && paymentCredential.toString() === signer;
return paymentCredential && paymentCredential.toString() === keyHash;
});

const stakeCredKnownAddress = context?.knownAddresses.find((address) => {
const stakeCredential = Cardano.RewardAccount.toHash(address.rewardAccount);
return stakeCredential && stakeCredential.toString() === signer;
return stakeCredential && stakeCredential.toString() === keyHash;
});

const paymentKeyPath = paymentCredKnownAddress
? util.paymentKeyPathFromGroupedAddress(paymentCredKnownAddress)
: null;
const stakeKeyPath = stakeCredKnownAddress ? util.stakeKeyPathFromGroupedAddress(stakeCredKnownAddress) : null;

return paymentKeyPath ? { keyPath: paymentKeyPath } : stakeKeyPath ? { keyPath: stakeKeyPath } : { keyHash: signer };
if (paymentKeyPath) {
return {
keyHash: undefined,
keyPath: paymentKeyPath
};
}

if (stakeKeyPath) {
return {
keyHash: undefined,
keyPath: stakeKeyPath
};
}

return {
keyHash,
keyPath: undefined
};
};

export const mapRequiredSigners = (
Expand Down
Loading