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/4.22.100] Ledger app 5 catalyst registration adaptation #3249

Merged
merged 4 commits into from
Jul 20, 2023
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
8 changes: 6 additions & 2 deletions packages/yoroi-extension/app/api/ada/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ export type CreateLedgerSignTxDataRequest = {|
signRequest: HaskellShelleyTxSignRequest,
network: $ReadOnly<NetworkRow>,
addressingMap: string => (void | $PropertyType<Addressing, 'addressing'>),
cip36: boolean,
|};
export type CreateLedgerSignTxDataResponse = {|
ledgerSignTxPayload: SignTransactionRequest,
Expand Down Expand Up @@ -961,6 +962,7 @@ export default class AdaApi {
byronNetworkMagic: config.ByronNetworkId,
networkId: Number.parseInt(config.ChainNetworkId, 10),
addressingMap: request.addressingMap,
cip36: request.cip36,
});

Logger.debug(`${nameof(AdaApi)}::${nameof(this.createLedgerSignTxData)} success: ` + stringifyData(ledgerSignTxPayload));
Expand Down Expand Up @@ -2382,6 +2384,8 @@ export default class AdaApi {
const usedUtxos = signRequest.senderUtxos.map(utxo => (
{ txHash: utxo.tx_hash, index: utxo.tx_index }
));
const metadata = signRequest.unsignedTx.get_auxiliary_data();

const transaction = CardanoShelleyTransaction.fromData({
txid: txId,
type: isIntraWallet ? 'self' : 'expend',
Expand All @@ -2397,8 +2401,8 @@ export default class AdaApi {
block: null,
certificates: [],
ttl: new BigNumber(String(signRequest.unsignedTx.build().ttl())),
metadata: signRequest.metadata
? Buffer.from(signRequest.metadata.to_bytes()).toString('hex')
metadata: metadata
? Buffer.from(metadata.to_bytes()).toString('hex')
: null,
withdrawals: signRequest.withdrawals().map(withdrawal => ({
address: withdrawal.address,
Expand Down
71 changes: 71 additions & 0 deletions packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/catalyst.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,74 @@ export function generateRegistration(request: {|
(hashedMetadata) => request.stakePrivateKey.sign(hashedMetadata).to_hex(),
);
}

export function generateCip15RegistrationMetadata(
votingPublicKey: string,
stakingPublicKey: string,
rewardAddress: string,
nonce: number,
signer: Uint8Array => string,
): RustModule.WalletV4.AuxiliaryData {

/**
* Catalyst follows a certain standard to prove the voting power
* A transaction is submitted with following metadata format for the registration process
* label: 61284
* {
* 1: "pubkey generated for catalyst app",
* 2: "stake key public key",
* 3: "address to receive rewards to"
* 4: "slot number"
* }
* label: 61285
* {
* 1: "signature of blake2b-256 hash of the metadata signed using stakekey"
* }
*/

const registrationData = RustModule.WalletV4.encode_json_str_to_metadatum(
JSON.stringify({
'1': prefix0x(votingPublicKey),
'2': prefix0x(stakingPublicKey),
'3': prefix0x(rewardAddress),
'4': nonce,
}),
RustModule.WalletV4.MetadataJsonSchema.BasicConversions
);
const generalMetadata = RustModule.WalletV4.GeneralTransactionMetadata.new();
generalMetadata.insert(
RustModule.WalletV4.BigNum.from_str(CatalystLabels.DATA.toString()),
registrationData
);

const hashedMetadata = blake2b(256 / 8).update(
generalMetadata.to_bytes()
).digest('binary');

generalMetadata.insert(
RustModule.WalletV4.BigNum.from_str(CatalystLabels.SIG.toString()),
RustModule.WalletV4.encode_json_str_to_metadatum(
JSON.stringify({
'1': prefix0x(signer(hashedMetadata)),
}),
RustModule.WalletV4.MetadataJsonSchema.BasicConversions
)
);

// This is how Ledger constructs the metadata. We must be consistent with it.
const metadataList = RustModule.WalletV4.MetadataList.new();
metadataList.add(
RustModule.WalletV4.TransactionMetadatum.from_bytes(
generalMetadata.to_bytes()
)
);
metadataList.add(
RustModule.WalletV4.TransactionMetadatum.new_list(
RustModule.WalletV4.MetadataList.new()
)
);

return RustModule.WalletV4.AuxiliaryData.from_bytes(
metadataList.to_bytes()
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export async function createLedgerSignTxPayload(request: {|
byronNetworkMagic: number,
networkId: number,
addressingMap: string => (void | $PropertyType<Addressing, 'addressing'>),
cip36: boolean,
|}): Promise<SignTransactionRequest> {
const txBody = request.signRequest.unsignedTx.build();

Expand Down Expand Up @@ -94,32 +95,54 @@ export async function createLedgerSignTxPayload(request: {|
const { votingPublicKey, stakingKeyPath, nonce, paymentKeyPath, } =
request.signRequest.ledgerNanoCatalystRegistrationTxSignData;

auxiliaryData = {
type: TxAuxiliaryDataType.CIP36_REGISTRATION,
params: {
format: CIP36VoteRegistrationFormat.CIP_36,
delegations: [
{
type: CIP36VoteDelegationType.KEY,
voteKeyHex: votingPublicKey.replace(/^0x/, ''),
weight: 1,
if (request.cip36) {
auxiliaryData = {
type: TxAuxiliaryDataType.CIP36_REGISTRATION,
params: {
format: CIP36VoteRegistrationFormat.CIP_36,
delegations: [
{
type: CIP36VoteDelegationType.KEY,
voteKeyHex: votingPublicKey.replace(/^0x/, ''),
weight: 1,
},
],
stakingPath: stakingKeyPath,
paymentDestination: {
type: TxOutputDestinationType.DEVICE_OWNED,
params: {
type: AddressType.BASE_PAYMENT_KEY_STAKE_KEY,
params: {
spendingPath: paymentKeyPath,
stakingPath: stakingKeyPath,
},
},
},
],
stakingPath: stakingKeyPath,
paymentDestination: {
type: TxOutputDestinationType.DEVICE_OWNED,
params: {
type: AddressType.BASE_PAYMENT_KEY_STAKE_KEY,
nonce,
votingPurpose: 0,
}
};
} else {
auxiliaryData = {
type: TxAuxiliaryDataType.CIP36_REGISTRATION,
params: {
format: CIP36VoteRegistrationFormat.CIP_15,
voteKeyHex: votingPublicKey.replace(/^0x/, ''),
stakingPath: stakingKeyPath,
paymentDestination: {
type: TxOutputDestinationType.DEVICE_OWNED,
params: {
spendingPath: paymentKeyPath,
stakingPath: stakingKeyPath,
type: AddressType.BASE_PAYMENT_KEY_STAKE_KEY,
params: {
spendingPath: paymentKeyPath,
stakingPath: stakingKeyPath,
},
},
},
},
nonce,
votingPurpose: 0,
}
};
nonce,
}
};
}
} else if (request.signRequest.metadata != null) {
auxiliaryData = {
type: TxAuxiliaryDataType.ARBITRARY_HASH,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,7 @@ test('Create Ledger transaction', async () => {
}
return undefined;
},
cip36: true,
});

expect(response).toStrictEqual(({
Expand Down
46 changes: 36 additions & 10 deletions packages/yoroi-extension/app/stores/ada/send/LedgerSendStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@ import type {
import { genAddressingLookup } from '../../stateless/addressStores';
import type { ActionsMap } from '../../../actions/index';
import type { StoresMap } from '../../index';
import { generateRegistrationMetadata } from '../../../api/ada/lib/cardanoCrypto/catalyst';
import {
generateRegistrationMetadata,
generateCip15RegistrationMetadata,
} from '../../../api/ada/lib/cardanoCrypto/catalyst';

/** Note: Handles Ledger Signing */
export default class LedgerSendStore extends Store<StoresMap, ActionsMap> {
Expand Down Expand Up @@ -207,18 +210,29 @@ export default class LedgerSendStore extends Store<StoresMap, ActionsMap> {
locale: this.stores.profile.currentLocale,
});

let cip36: boolean = false;
if (request.signRequest.ledgerNanoCatalystRegistrationTxSignData) {
const getVersionResponse = await ledgerConnect.getVersion({
serial: request.expectedSerial,
dontCloseTab: true,
});
cip36 = getVersionResponse.compatibility.supportsCIP36Vote === true;
}

const network = request.publicDeriver.getParent().getNetworkInfo();

const { ledgerSignTxPayload } = await this.api.ada.createLedgerSignTxData({
signRequest: request.signRequest,
network,
addressingMap: request.addressingMap,
cip36,
});

const ledgerSignTxResp: LedgerSignTxResponse =
await ledgerConnect.signTransaction({
serial: request.expectedSerial,
params: ledgerSignTxPayload,
useOpenTab: true,
});

// There is no need of ledgerConnect after this line.
Expand Down Expand Up @@ -247,15 +261,27 @@ export default class LedgerSendStore extends Store<StoresMap, ActionsMap> {
const { cip36VoteRegistrationSignatureHex } =
ledgerSignTxResp.auxiliaryDataSupplement;

metadata = generateRegistrationMetadata(
votingPublicKey,
stakingKey,
paymentAddress,
nonce,
(_hashedMetadata) => {
return cip36VoteRegistrationSignatureHex;
},
);
if (cip36) {
metadata = generateRegistrationMetadata(
votingPublicKey,
stakingKey,
paymentAddress,
nonce,
(_hashedMetadata) => {
return cip36VoteRegistrationSignatureHex;
},
);
} else {
metadata = generateCip15RegistrationMetadata(
votingPublicKey,
stakingKey,
paymentAddress,
nonce,
(_hashedMetadata) => {
return cip36VoteRegistrationSignatureHex;
},
);
}
// We can verify that
// Buffer.from(
// blake2b(256 / 8).update(metadata.to_bytes()).digest('binary')
Expand Down
28 changes: 27 additions & 1 deletion packages/yoroi-extension/app/utils/hwConnectHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type ShowAddressRequestWrapper = {|

export class LedgerConnect {
locale: string;
tabId: ?number;

constructor(params: {| locale: string |}) {
this.locale = params.locale;
Expand Down Expand Up @@ -59,11 +60,14 @@ export class LedgerConnect {
signTransaction: {|
serial: ?string,
params: SignTransactionRequest,
useOpenTab?: boolean,
|} => Promise<SignTransactionResponse> = (request) => {
return this._requestLedger(
OPERATION_NAME.SIGN_TX,
request.params,
request.serial,
false,
request.useOpenTab === true,
);
}

Expand All @@ -78,12 +82,34 @@ export class LedgerConnect {
);
}

getVersion: {|
serial: ?string,
dontCloseTab?: boolean,
|} => Promise<GetVersionResponse> = (request) => {
return this._requestLedger(
OPERATION_NAME.GET_LEDGER_VERSION,
undefined,
request.serial,
true,
);
}

async _requestLedger(
action: string,
params: any,
serial: ?string,
dontCloseTab?: boolean = false,
useOpenTab?: boolean = false,
): any {
const tabId = await this._createLedgerTab();
let tabId;
if (useOpenTab && this.tabId != null) {
tabId = this.tabId;
} else {
tabId = await this._createLedgerTab();
if (dontCloseTab) {
this.tabId = tabId;
}
}

return new Promise((resolve, reject) => {
chrome.tabs.sendMessage(
Expand Down
Loading