refactor(connect): validation in API methods

refactor(connect): validation in ethereumSignTypedData
refactor(connect): validation in `bitcoin/refTx`
refactor(connect): simple API methods
refactor(connect): additional device API methods
fix(connect): missing validation in `requestLogin` async
refactor(connect): additional ethereum API methods
refactor(connect): validation in `signMessage/verifyMessage` API
refactor(connect): validation in methods with bundled params
refactor(connect): validation in altcoin `GetAddress` APIs

refactor(connect): validation in `GetPublicKey` APIs

refactor(connect): validation in `authenticateDevice`, `eos`, `binance`, `ethereum` APIs

refactor(connect): validation in altcoin `signTransaction` APIs
refactor(connect): validation in `cardano` APIs
refactor(connect): validate with schema in authorizeCoinjoin API
fix(connect): fix types, re-enable assert in `typedCall`
fix(connect): minor lint and type issues
This commit is contained in:
Tomáš Martykán
2024-01-05 11:24:42 +01:00
committed by martin
parent 4fd7808ac2
commit 0c035c26a6
105 changed files with 2061 additions and 2043 deletions

View File

@@ -1,9 +1,9 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/ApplyFlags.js
import { AbstractMethod } from '../core/AbstractMethod';
import { validateParams } from './common/paramsValidator';
import { UI, createUiMessage } from '../events';
import type { PROTO } from '../constants';
import { PROTO } from '../constants';
import { Assert } from '@trezor/schema-utils';
export default class ApplyFlags extends AbstractMethod<'applyFlags', PROTO.ApplyFlags> {
init() {
@@ -12,7 +12,7 @@ export default class ApplyFlags extends AbstractMethod<'applyFlags', PROTO.Apply
const { payload } = this;
validateParams(payload, [{ name: 'flags', type: 'number', required: true }]);
Assert(PROTO.ApplyFlags, payload);
this.params = {
flags: payload.flags,

View File

@@ -2,8 +2,9 @@
import { AbstractMethod } from '../core/AbstractMethod';
import { UI, createUiMessage } from '../events';
import { validateParams } from './common/paramsValidator';
import type { PROTO } from '../constants';
import { PROTO } from '../constants';
import { Assert } from '@trezor/schema-utils';
import { ApplySettings as ApplySettingsSchema } from '../types/api/applySettings';
export default class ApplySettings extends AbstractMethod<'applySettings', PROTO.ApplySettings> {
init() {
@@ -11,18 +12,7 @@ export default class ApplySettings extends AbstractMethod<'applySettings', PROTO
this.useDeviceState = false;
const { payload } = this;
validateParams(payload, [
{ name: 'language', type: 'string' },
{ name: 'label', type: 'string' },
{ name: 'use_passphrase', type: 'boolean' },
{ name: 'homescreen', type: 'string' },
{ name: 'passphrase_source', type: 'number' },
{ name: 'passphrase_always_on_device', type: 'boolean' },
{ name: 'auto_lock_delay_ms', type: 'number' },
{ name: 'display_rotation', type: 'number' },
{ name: 'safety_checks', type: 'string' },
{ name: 'experimental_features', type: 'boolean' },
]);
Assert(ApplySettingsSchema, payload);
this.params = {
language: payload.language,
@@ -34,7 +24,6 @@ export default class ApplySettings extends AbstractMethod<'applySettings', PROTO
display_rotation: payload.display_rotation,
safety_checks: payload.safety_checks,
experimental_features: payload.experimental_features,
// @ts-expect-error passphrase_source is a legacy param
_passphrase_source: payload.passphrase_source,
};
}

View File

@@ -1,9 +1,10 @@
import { AbstractMethod } from '../core/AbstractMethod';
import { UI } from '../events';
import { validateParams, getFirmwareRange } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import { deviceAuthenticityConfig } from '../data/deviceAuthenticityConfig';
import { AuthenticateDeviceParams } from '../types/api/authenticateDevice';
import { getRandomChallenge, verifyAuthenticityProof } from './firmware/verifyAuthenticityProof';
import { Assert } from '@trezor/schema-utils';
export default class AuthenticateDevice extends AbstractMethod<
'authenticateDevice',
@@ -18,17 +19,7 @@ export default class AuthenticateDevice extends AbstractMethod<
const { payload } = this;
validateParams(payload, [
{ name: 'config', type: 'object' },
{ name: 'allowDebugKeys', type: 'boolean' },
]);
if (payload.config) {
validateParams(payload.config, [{ name: 'timestamp', type: 'string', required: true }]);
validateParams(payload.config.T2B1, [
{ name: 'rootPubKeys', type: 'array', required: true },
{ name: 'caPubKeys', type: 'array', required: true },
]);
}
Assert(AuthenticateDeviceParams, payload);
this.params = {
config: payload.config,

View File

@@ -1,5 +1,5 @@
import { AbstractMethod } from '../core/AbstractMethod';
import { validateParams, getFirmwareRange } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import { validatePath, getScriptType } from '../utils/pathUtils';
import { getBitcoinNetwork } from '../data/coinInfo';
import { PROTO } from '../constants';

View File

@@ -1,11 +1,14 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/BinanceGetAddress.js
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath, fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import { PROTO, ERRORS } from '../../../constants';
import { UI, createUiMessage } from '../../../events';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../../../types';
import { GetAddress as GetAddressSchema } from '../../../types/api/getAddress';
type Params = PROTO.BinanceGetAddress & {
address?: string;
@@ -27,20 +30,9 @@ export default class BinanceGetAddress extends AbstractMethod<'binanceGetAddress
: this.payload;
// validate bundle type
validateParams(payload, [
{ name: 'bundle', type: 'array' },
{ name: 'useEventListener', type: 'boolean' },
]);
Assert(Bundle(GetAddressSchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'address', type: 'string' },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'chunkify', type: 'boolean' },
]);
const path = validatePath(batch.path, 3);
return {
address_n: path,

View File

@@ -1,11 +1,13 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/BinanceGetPublicKey.js
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath, fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import { UI, createUiMessage } from '../../../events';
import type { PROTO } from '../../../constants';
import { Assert } from '@trezor/schema-utils';
import { Bundle, GetPublicKey as GetPublicKeySchema } from '../../../types';
export default class BinanceGetPublicKey extends AbstractMethod<
'binanceGetPublicKey',
@@ -25,15 +27,9 @@ export default class BinanceGetPublicKey extends AbstractMethod<
: this.payload;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
Assert(Bundle(GetPublicKeySchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'showOnTrezor', type: 'boolean' },
]);
const path = validatePath(batch.path, 3);
return {
address_n: path,

View File

@@ -1,10 +1,12 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/BinanceSignTransaction.js
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath } from '../../../utils/pathUtils';
import * as helper from '../binanceSignTx';
import { BinanceSignTransaction as BinanceSignTransactionSchema } from '../../../types/api/binance';
import { Assert } from '@trezor/schema-utils';
import type { BinancePreparedTransaction } from '../../../types/api/binance';
@@ -24,11 +26,7 @@ export default class BinanceSignTransaction extends AbstractMethod<
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'path', type: 'string', required: true },
{ name: 'transaction', required: true },
{ name: 'chunkify', type: 'boolean' },
]);
Assert(BinanceSignTransactionSchema, payload);
const path = validatePath(payload.path, 3);
const transaction = helper.validate(payload.transaction);
@@ -36,7 +34,7 @@ export default class BinanceSignTransaction extends AbstractMethod<
this.params = {
path,
transaction,
chunkify: typeof payload.chunkify === 'boolean' ? payload.chunkify : false,
chunkify: payload.chunkify ?? false,
};
}

View File

@@ -1,13 +1,13 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/helpers/binanceSignTx.js
import { PROTO, ERRORS } from '../../constants';
import { validateParams } from '../common/paramsValidator';
import type {
import {
BinanceSDKTransaction,
BinancePreparedMessage,
BinancePreparedTransaction,
} from '../../types/api/binance';
import type { TypedCall } from '../../device/DeviceCommands';
import { Assert } from '@trezor/schema-utils';
const processTxRequest = async (
typedCall: TypedCall,
@@ -29,14 +29,7 @@ const processTxRequest = async (
// validate and translate params to protobuf
export const validate = (tx: BinanceSDKTransaction) => {
validateParams(tx, [
{ name: 'chain_id', type: 'string', required: true },
{ name: 'account_number', type: 'number' },
{ name: 'memo', type: 'string' },
{ name: 'sequence', type: 'number' },
{ name: 'source', type: 'number' },
{ name: 'message', type: 'object' },
]);
Assert(BinanceSDKTransaction, tx);
const preparedTx: BinancePreparedTransaction = {
chain_id: tx.chain_id,
@@ -50,10 +43,6 @@ export const validate = (tx: BinanceSDKTransaction) => {
const { transfer, placeOrder, cancelOrder } = tx;
if (transfer) {
validateParams(transfer, [
{ name: 'inputs', type: 'array', required: true },
{ name: 'outputs', type: 'array', required: true },
]);
preparedTx.messages.push({
...transfer,
type: 'BinanceTransferMsg',
@@ -61,14 +50,6 @@ export const validate = (tx: BinanceSDKTransaction) => {
}
if (placeOrder) {
validateParams(placeOrder, [
{ name: 'id', type: 'string' },
{ name: 'ordertype', type: 'number' },
{ name: 'price', type: 'number' },
{ name: 'quantity', type: 'number' },
{ name: 'sender', type: 'string' },
{ name: 'side', type: 'number' },
]);
preparedTx.messages.push({
...placeOrder,
type: 'BinanceOrderMsg',
@@ -76,11 +57,6 @@ export const validate = (tx: BinanceSDKTransaction) => {
}
if (cancelOrder) {
validateParams(cancelOrder, [
{ name: 'refid', type: 'string', required: true },
{ name: 'sender', type: 'string', required: true },
{ name: 'symbol', type: 'string', required: true },
]);
preparedTx.messages.push({
...cancelOrder,
type: 'BinanceCancelMsg',

View File

@@ -8,7 +8,6 @@ import {
} from '@trezor/utxo-lib';
import { bufferUtils } from '@trezor/utils';
import { getHDPath, getScriptType, getOutputScriptType } from '../../utils/pathUtils';
import { validateParams } from '../common/paramsValidator';
import { TypedError } from '../../constants/errors';
import type {
TxInput as BitcoinJsInput,
@@ -21,7 +20,8 @@ import type {
BitcoinNetworkInfo,
} from '../../types';
import type { RefTransaction, TransactionOptions } from '../../types/api/bitcoin';
import type { PROTO } from '../../constants';
import { PROTO } from '../../constants';
import { Assert, Type } from '@trezor/schema-utils';
// Referenced transactions are not required if:
// - all internal inputs script_type === SPENDTAPROOT
@@ -281,38 +281,38 @@ export const validateReferencedTransactions = ({
return transformReferencedTransaction(srcTx);
}
// validate common fields
// TODO: detailed params validation will be addressed in https://github.com/trezor/connect/pull/782
// currently it's 1:1 with previous validation in SignTransaction.js method
validateParams(tx, [
{ name: 'hash', type: 'string', required: true },
{ name: 'inputs', type: 'array', required: true },
{ name: 'version', type: 'number', required: true },
{ name: 'lock_time', type: 'number', required: true },
{ name: 'extra_data', type: 'string' },
{ name: 'timestamp', type: 'number' },
{ name: 'version_group_id', type: 'number' },
]);
Assert(
Type.Object({
hash: Type.String(),
version: Type.Number(),
lock_time: Type.Number(),
extra_data: Type.Optional(Type.String()),
timestamp: Type.Optional(Type.Number()),
version_group_id: Type.Optional(Type.Number()),
}),
tx,
);
// check if referenced transaction is in expected format (RBF)
if (origTxs.includes(tx.hash)) {
// validate specific fields of origTx
// protobuf.TxInput
validateParams(tx, [{ name: 'outputs', type: 'array', required: true }]);
// TODO: detailed validation will be addressed in #782
Assert(
Type.Object({
inputs: Type.Array(PROTO.TxInput),
}),
tx,
);
return tx;
}
// validate specific fields of refTx
validateParams(tx, [{ name: 'bin_outputs', type: 'array', required: true }]);
tx.inputs.forEach(input => {
validateParams(input, [
{ name: 'prev_hash', type: 'string', required: true },
{ name: 'prev_index', type: 'number', required: true },
{ name: 'script_sig', type: 'string', required: true },
{ name: 'sequence', type: 'number', required: true },
{ name: 'decred_tree', type: 'number' },
]);
});
Assert(
Type.Object({
inputs: Type.Array(PROTO.PrevInput),
bin_outputs: Type.Array(PROTO.TxOutputBinType),
}),
tx,
);
return {
hash: tx.hash,
@@ -322,19 +322,14 @@ export const validateReferencedTransactions = ({
timestamp: tx.timestamp,
version_group_id: tx.version_group_id,
expiry: tx.expiry,
// make exact protobuf.PrevInput
inputs: tx.inputs.map(input => ({
prev_hash: input.prev_hash,
prev_index: input.prev_index,
// TODO: https://github.com/trezor/trezor-suite/issues/5297
script_sig: input.script_sig!,
// TODO: https://github.com/trezor/trezor-suite/issues/5297
sequence: input.sequence!,
script_sig: input.script_sig,
sequence: input.sequence,
decred_tree: input.decred_tree,
})),
// make exact protobuf.TxOutputBinType
// TODO: https://github.com/trezor/trezor-suite/issues/5297
bin_outputs: tx.bin_outputs!.map(output => ({
bin_outputs: tx.bin_outputs.map(output => ({
amount: output.amount,
script_pubkey: output.script_pubkey,
decred_script_version: output.decred_script_version,

View File

@@ -1,11 +1,11 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/blockchain/BlockchainDisconnect.js
import { AbstractMethod } from '../core/AbstractMethod';
import { validateParams } from './common/paramsValidator';
import { ERRORS } from '../constants';
import { isBackendSupported, findBackend } from '../backend/BlockchainLink';
import { getCoinInfo } from '../data/coinInfo';
import type { CoinInfo } from '../types';
import { CoinObj, CoinInfo } from '../types';
import { Assert } from '@trezor/schema-utils';
type Params = {
coinInfo: CoinInfo;
@@ -20,7 +20,7 @@ export default class BlockchainDisconnect extends AbstractMethod<'blockchainDisc
const { payload } = this;
// validate incoming parameters
validateParams(payload, [{ name: 'coin', type: 'string', required: true }]);
Assert(CoinObj, payload);
const coinInfo = getCoinInfo(payload.coin);
if (!coinInfo) {

View File

@@ -1,6 +1,8 @@
import { AbstractMethod } from '../core/AbstractMethod';
import { getFirmwareRange } from './common/paramsValidator';
import { PROTO } from '../constants';
import { Assert } from '@trezor/schema-utils';
import { CancelCoinjoinAuthorization as CancelCoinjoinAuthorizationSchema } from '../types/api/cancelCoinjoinAuthorization';
export default class CancelCoinjoinAuthorization extends AbstractMethod<
'cancelCoinjoinAuthorization',
@@ -9,6 +11,8 @@ export default class CancelCoinjoinAuthorization extends AbstractMethod<
init() {
const { payload } = this;
Assert(CancelCoinjoinAuthorizationSchema, payload);
this.firmwareRange = getFirmwareRange(this.name, null, this.firmwareRange);
this.preauthorized =
typeof payload.preauthorized === 'boolean' ? payload.preauthorized : true;

View File

@@ -1,7 +1,7 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/CardanoGetAddress.js
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import {
@@ -12,6 +12,9 @@ import {
} from '../cardanoAddressParameters';
import { PROTO, ERRORS } from '../../../constants';
import { UI, createUiMessage } from '../../../events';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../../../types';
import { CardanoGetAddress as CardanoGetAddressSchema } from '../../../types/api/cardano';
type Params = PROTO.CardanoGetAddress & {
address?: string;
@@ -37,23 +40,9 @@ export default class CardanoGetAddress extends AbstractMethod<'cardanoGetAddress
: this.payload;
// validate bundle type
validateParams(payload, [
{ name: 'bundle', type: 'array' },
{ name: 'useEventListener', type: 'boolean' },
]);
Assert(Bundle(CardanoGetAddressSchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'addressParameters', type: 'object', required: true },
{ name: 'networkId', type: 'number', required: true },
{ name: 'protocolMagic', type: 'number', required: true },
{ name: 'derivationType', type: 'number' },
{ name: 'address', type: 'string' },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'chunkify', type: 'boolean' },
]);
validateAddressParameters(batch.addressParameters);
return {

View File

@@ -2,10 +2,14 @@
import { PROTO } from '../../../constants';
import { AbstractMethod } from '../../../core/AbstractMethod';
import { getFirmwareRange, validateParams } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath } from '../../../utils/pathUtils';
import type { CardanoNativeScript } from '../../../types/api/cardano';
import {
CardanoGetNativeScriptHash as CardanoGetNativeScriptHashSchema,
CardanoNativeScript,
} from '../../../types/api/cardano';
import { Assert } from '@trezor/schema-utils';
export default class CardanoGetNativeScriptHash extends AbstractMethod<
'cardanoGetNativeScriptHash',
@@ -21,11 +25,7 @@ export default class CardanoGetNativeScriptHash extends AbstractMethod<
const { payload } = this;
validateParams(payload, [
{ name: 'script', type: 'object', required: true },
{ name: 'displayFormat', type: 'number', required: true },
{ name: 'derivationType', type: 'number' },
]);
Assert(CardanoGetNativeScriptHashSchema, payload);
this.validateScript(payload.script);
@@ -44,15 +44,6 @@ export default class CardanoGetNativeScriptHash extends AbstractMethod<
}
validateScript(script: CardanoNativeScript) {
validateParams(script, [
{ name: 'type', type: 'number', required: true },
{ name: 'scripts', type: 'array', allowEmpty: true },
{ name: 'keyHash', type: 'string' },
{ name: 'requiredSignaturesCount', type: 'number' },
{ name: 'invalidBefore', type: 'uint' },
{ name: 'invalidHereafter', type: 'uint' },
]);
if (script.keyPath) {
validatePath(script.keyPath, 3);
}

View File

@@ -2,10 +2,13 @@
import { PROTO } from '../../../constants';
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath, fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import { UI, createUiMessage } from '../../../events';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../../../types';
import { CardanoGetPublicKey as CardanoGetPublicKeySchema } from '../../../types/api/cardano';
interface Params extends PROTO.CardanoGetPublicKey {
suppressBackupWarning?: boolean;
@@ -30,17 +33,9 @@ export default class CardanoGetPublicKey extends AbstractMethod<'cardanoGetPubli
: this.payload;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
Assert(Bundle(CardanoGetPublicKeySchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'derivationType', type: 'number' },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'suppressBackupWarning', type: 'boolean' },
]);
const path = validatePath(batch.path, 3);
return {
address_n: path,

View File

@@ -6,7 +6,7 @@
import { trezorUtils } from '@fivebinaries/coin-selection';
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath } from '../../../utils/pathUtils';
import {
@@ -26,14 +26,17 @@ import {
import { sendOutput, transformOutput } from '../cardanoOutputs';
import type { OutputWithData } from '../cardanoOutputs';
import { PROTO, ERRORS } from '../../../constants';
import type {
CardanoAuxiliaryDataSupplement,
CardanoSignedTxData,
CardanoSignedTxWitness,
import {
CardanoSignTransaction as CardanoSignTransactionSchema,
CardanoSignTransactionExtended,
type CardanoAuxiliaryDataSupplement,
type CardanoSignedTxData,
type CardanoSignedTxWitness,
} from '../../../types/api/cardano';
import { gatherWitnessPaths } from '../cardanoWitnesses';
import type { AssetGroupWithTokens } from '../cardanoTokenBundle';
import { tokenBundleToProto } from '../cardanoTokenBundle';
import { Assert, Type } from '@trezor/schema-utils';
// todo: remove when listed firmwares become mandatory for cardanoSignTransaction
const CardanoSignTransactionFeatures = Object.freeze({
@@ -131,30 +134,7 @@ export default class CardanoSignTransaction extends AbstractMethod<
}
// validate incoming parameters
validateParams(payload, [
{ name: 'signingMode', type: 'number', required: true },
{ name: 'inputs', type: 'array', required: true },
{ name: 'outputs', type: 'array', required: true, allowEmpty: true },
{ name: 'fee', type: 'uint', required: true },
{ name: 'ttl', type: 'uint' },
{ name: 'certificates', type: 'array', allowEmpty: true },
{ name: 'withdrawals', type: 'array', allowEmpty: true },
{ name: 'mint', type: 'array', allowEmpty: true },
{ name: 'validityIntervalStart', type: 'uint' },
{ name: 'scriptDataHash', type: 'string' },
{ name: 'collateralInputs', type: 'array', allowEmpty: true },
{ name: 'requiredSigners', type: 'array', allowEmpty: true },
{ name: 'totalCollateral', type: 'uint' },
{ name: 'referenceInputs', type: 'array', allowEmpty: true },
{ name: 'protocolMagic', type: 'number', required: true },
{ name: 'networkId', type: 'number', required: true },
{ name: 'additionalWitnessRequests', type: 'array', allowEmpty: true },
{ name: 'derivationType', type: 'number' },
{ name: 'includeNetworkId', type: 'boolean' },
{ name: 'unsignedTx', type: 'object' },
{ name: 'testnet', type: 'boolean' },
{ name: 'chunkify', type: 'boolean' },
]);
Assert(Type.Union([CardanoSignTransactionSchema, CardanoSignTransactionExtended]), payload);
const inputsWithPath = payload.inputs.map(transformInput);
@@ -167,19 +147,12 @@ export default class CardanoSignTransaction extends AbstractMethod<
let withdrawals: PROTO.CardanoTxWithdrawal[] = [];
if (payload.withdrawals) {
withdrawals = payload.withdrawals.map(withdrawal => {
validateParams(withdrawal, [
{ name: 'amount', type: 'uint', required: true },
{ name: 'scriptHash', type: 'string' },
{ name: 'keyHash', type: 'string' },
]);
return {
path: withdrawal.path ? validatePath(withdrawal.path, 5) : undefined,
amount: withdrawal.amount,
script_hash: withdrawal.scriptHash,
key_hash: withdrawal.keyHash,
};
});
withdrawals = payload.withdrawals.map(withdrawal => ({
path: withdrawal.path ? validatePath(withdrawal.path, 5) : undefined,
amount: withdrawal.amount,
script_hash: withdrawal.scriptHash,
key_hash: withdrawal.keyHash,
}));
}
let mint: AssetGroupWithTokens[] = [];
@@ -206,15 +179,15 @@ export default class CardanoSignTransaction extends AbstractMethod<
let requiredSigners: PROTO.CardanoTxRequiredSigner[] = [];
if (payload.requiredSigners) {
requiredSigners = payload.requiredSigners.map(requiredSigner => {
validateParams(requiredSigner, [{ name: 'keyHash', type: 'string' }]);
return {
key_path: requiredSigner.keyPath
? validatePath(requiredSigner.keyPath, 3)
: undefined,
key_hash: requiredSigner.keyHash,
} as PROTO.CardanoTxRequiredSigner;
});
requiredSigners = payload.requiredSigners.map(
requiredSigner =>
({
key_path: requiredSigner.keyPath
? validatePath(requiredSigner.keyPath, 3)
: undefined,
key_hash: requiredSigner.keyHash,
}) as PROTO.CardanoTxRequiredSigner,
);
}
const collateralReturnWithData = payload.collateralReturn

View File

@@ -1,18 +1,13 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/helpers/cardanoAddressParameters.js
import { validateParams } from '../common/paramsValidator';
import { validatePath } from '../../utils/pathUtils';
import { PROTO, ERRORS } from '../../constants';
import type { Device } from '../../device/Device';
import type { CardanoAddressParameters } from '../../types/api/cardano';
import { CardanoAddressParameters } from '../../types/api/cardano';
import { Assert } from '@trezor/schema-utils';
export const validateAddressParameters = (addressParameters: CardanoAddressParameters) => {
validateParams(addressParameters, [
{ name: 'addressType', type: 'number', required: true },
{ name: 'stakingKeyHash', type: 'string' },
{ name: 'paymentScriptHash', type: 'string' },
{ name: 'stakingScriptHash', type: 'string' },
]);
Assert(CardanoAddressParameters, addressParameters);
if (addressParameters.path) {
validatePath(addressParameters.path);
@@ -20,14 +15,6 @@ export const validateAddressParameters = (addressParameters: CardanoAddressParam
if (addressParameters.stakingPath) {
validatePath(addressParameters.stakingPath);
}
if (addressParameters.certificatePointer) {
validateParams(addressParameters.certificatePointer, [
{ name: 'blockIndex', type: 'number', required: true },
{ name: 'txIndex', type: 'number', required: true },
{ name: 'certificateIndex', type: 'number', required: true },
]);
}
};
export const modifyAddressParametersForBackwardsCompatibility = (

View File

@@ -5,15 +5,15 @@ import {
modifyAddressParametersForBackwardsCompatibility,
validateAddressParameters,
} from './cardanoAddressParameters';
import { validateParams } from '../common/paramsValidator';
import { validatePath } from '../../utils/pathUtils';
import type { Device } from '../../device/Device';
import { ERRORS, PROTO } from '../../constants';
import type {
import {
CardanoAuxiliaryData,
CardanoCVoteRegistrationDelegation,
CardanoCVoteRegistrationParameters,
} from '../../types/api/cardano';
import { Assert } from '@trezor/schema-utils';
const MAX_DELEGATION_COUNT = 32;
@@ -27,10 +27,7 @@ const transformDelegation = (
delegation.votePublicKey = delegation.votingPublicKey;
}
validateParams(delegation, [
{ name: 'votePublicKey', type: 'string', required: true },
{ name: 'weight', type: 'uint', required: true },
]);
Assert(CardanoCVoteRegistrationDelegation, delegation);
return {
vote_public_key: delegation.votePublicKey,
@@ -57,15 +54,7 @@ const transformCvoteRegistrationParameters = (
cVoteRegistrationParameters.rewardAddressParameters;
}
validateParams(cVoteRegistrationParameters, [
{ name: 'votePublicKey', type: 'string' },
{ name: 'stakingPath', required: true },
{ name: 'nonce', type: 'uint', required: true },
{ name: 'format', type: 'number' },
{ name: 'delegations', type: 'array', allowEmpty: true },
{ name: 'votingPurpose', type: 'uint' },
{ name: 'address', type: 'string' },
]);
Assert(CardanoCVoteRegistrationParameters, cVoteRegistrationParameters);
const { paymentAddressParameters } = cVoteRegistrationParameters;
if (paymentAddressParameters) {
validateAddressParameters(paymentAddressParameters);
@@ -96,12 +85,7 @@ const transformCvoteRegistrationParameters = (
export const transformAuxiliaryData = (
auxiliaryData: CardanoAuxiliaryData,
): PROTO.CardanoTxAuxiliaryData => {
validateParams(auxiliaryData, [
{
name: 'hash',
type: 'string',
},
]);
Assert(CardanoAuxiliaryData, auxiliaryData);
let cVoteRegistrationParameters;
if (auxiliaryData.cVoteRegistrationParameters) {

View File

@@ -1,52 +1,24 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/helpers/cardanoCertificate.js
import { validateParams } from '../common/paramsValidator';
import { validatePath } from '../../utils/pathUtils';
import { PROTO, ERRORS } from '../../constants';
import type {
import {
CardanoCertificate,
CardanoPoolParameters,
CardanoPoolMargin,
CardanoPoolOwner,
CardanoPoolRelay,
CardanoPoolMetadata,
} from '../../types/api/cardano';
import { Assert } from '@trezor/schema-utils';
const ipv4AddressToHex = (ipv4Address: string) =>
Buffer.from(ipv4Address.split('.').map(ipPart => parseInt(ipPart, 10))).toString('hex');
const ipv6AddressToHex = (ipv6Address: string) => ipv6Address.split(':').join('');
const validatePoolMargin = (margin: CardanoPoolMargin) => {
validateParams(margin, [
{ name: 'numerator', type: 'string', required: true },
{ name: 'denominator', type: 'string', required: true },
]);
};
const validatePoolMetadata = (metadata: CardanoPoolMetadata) => {
validateParams(metadata, [
{ name: 'url', type: 'string', required: true },
{ name: 'hash', type: 'string', required: true },
]);
};
const validatePoolRelay = (relay: CardanoPoolRelay) => {
validateParams(relay, [{ name: 'type', type: 'number', required: true }]);
Assert(CardanoPoolRelay, relay);
if (relay.type === PROTO.CardanoPoolRelayType.SINGLE_HOST_IP) {
const paramsToValidate: Parameters<typeof validateParams>[1] = [
{ name: 'port', type: 'number', required: true },
];
if (relay.ipv4Address) {
paramsToValidate.push({ name: 'ipv4Address', type: 'string', required: false });
}
if (relay.ipv6Address) {
paramsToValidate.push({ name: 'ipv6Address', type: 'string', required: false });
}
validateParams(relay, paramsToValidate);
if (!relay.ipv4Address && !relay.ipv6Address) {
throw ERRORS.TypedError(
'Method_InvalidParameter',
@@ -54,23 +26,21 @@ const validatePoolRelay = (relay: CardanoPoolRelay) => {
);
}
} else if (relay.type === PROTO.CardanoPoolRelayType.SINGLE_HOST_NAME) {
validateParams(relay, [
{ name: 'hostName', type: 'string', required: true },
{ name: 'port', type: 'number', required: true },
]);
if (!relay.hostName) {
throw ERRORS.TypedError('Method_InvalidParameter', 'hostName must be supplied');
}
if (!relay.port) {
throw ERRORS.TypedError('Method_InvalidParameter', 'port must be supplied');
}
} else if (relay.type === PROTO.CardanoPoolRelayType.MULTIPLE_HOST_NAME) {
validateParams(relay, [{ name: 'hostName', type: 'string', required: true }]);
if (!relay.hostName) {
throw ERRORS.TypedError('Method_InvalidParameter', 'hostName must be supplied');
}
}
};
const validatePoolOwners = (owners: CardanoPoolOwner[]) => {
owners.forEach(owner => {
if (owner.stakingKeyHash) {
validateParams(owner, [
{ name: 'stakingKeyHash', type: 'string', required: !owner.stakingKeyPath },
]);
}
if (owner.stakingKeyPath) {
validatePath(owner.stakingKeyPath, 5);
}
@@ -93,25 +63,9 @@ const validatePoolOwners = (owners: CardanoPoolOwner[]) => {
};
const validatePoolParameters = (poolParameters: CardanoPoolParameters) => {
validateParams(poolParameters, [
{ name: 'poolId', type: 'string', required: true },
{ name: 'vrfKeyHash', type: 'string', required: true },
{ name: 'pledge', type: 'string', required: true },
{ name: 'cost', type: 'string', required: true },
{ name: 'margin', type: 'object', required: true },
{ name: 'rewardAccount', type: 'string', required: true },
{ name: 'owners', type: 'array', required: true },
{ name: 'relays', type: 'array', required: true, allowEmpty: true },
{ name: 'metadata', type: 'object' },
]);
validatePoolMargin(poolParameters.margin);
Assert(CardanoPoolParameters, poolParameters);
validatePoolOwners(poolParameters.owners);
poolParameters.relays.forEach(validatePoolRelay);
if (poolParameters.metadata) {
validatePoolMetadata(poolParameters.metadata);
}
};
export type CertificateWithPoolOwnersAndRelays = {
@@ -168,25 +122,26 @@ const transformPoolParameters = (
export const transformCertificate = (
certificate: CardanoCertificate,
): CertificateWithPoolOwnersAndRelays => {
const paramsToValidate: Parameters<typeof validateParams>[1] = [
{ name: 'type', type: 'number', required: true },
];
if (certificate.type !== PROTO.CardanoCertificateType.STAKE_POOL_REGISTRATION) {
paramsToValidate.push({ name: 'scriptHash', type: 'string' });
paramsToValidate.push({ name: 'keyHash', type: 'string' });
}
Assert(CardanoCertificate, certificate);
if (certificate.type === PROTO.CardanoCertificateType.STAKE_DELEGATION) {
paramsToValidate.push({ name: 'pool', type: 'string', required: true });
if (!certificate.pool) {
throw ERRORS.TypedError(
'Method_InvalidParameter',
'pool must be supplied for STAKE_DELEGATION',
);
}
}
if (certificate.type === PROTO.CardanoCertificateType.STAKE_POOL_REGISTRATION) {
paramsToValidate.push({ name: 'poolParameters', type: 'object', required: true });
if (!certificate.poolParameters) {
throw ERRORS.TypedError(
'Method_InvalidParameter',
'poolParameters must be supplied for STAKE_POOL_REGISTRATION',
);
}
}
validateParams(certificate, paramsToValidate);
const { poolParameters, poolOwners, poolRelays } = transformPoolParameters(
certificate.poolParameters,
);

View File

@@ -1,26 +1,34 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/helpers/cardanoInputs.js
import { validateParams } from '../common/paramsValidator';
import { validatePath } from '../../utils/pathUtils';
import type { PROTO } from '../../constants';
import { PROTO } from '../../constants';
import { Assert, Type, Static } from '@trezor/schema-utils';
import { DerivationPath } from '../../exports';
export type Path = number[];
export type InputWithPath = {
input: PROTO.CardanoTxInput;
path?: Path;
};
export const Path = Type.Array(Type.Number());
export type CollateralInputWithPath = {
collateralInput: PROTO.CardanoTxCollateralInput;
path?: Path;
};
export const transformInput = (input: any): InputWithPath => {
validateParams(input, [
{ name: 'prev_hash', type: 'string', required: true },
{ name: 'prev_index', type: 'number', required: true },
]);
export type InputWithPath = Static<typeof InputWithPath>;
export const InputWithPath = Type.Object({
input: PROTO.CardanoTxInput,
path: Type.Optional(Path),
});
export type InputWithPathParam = Static<typeof InputWithPath>;
export const InputWithPathParam = Type.Composite([
PROTO.CardanoTxInput,
Type.Object({
path: Type.Optional(DerivationPath),
}),
]);
export const transformInput = (input: unknown): InputWithPath => {
Assert(InputWithPathParam, input);
return {
input: {
prev_hash: input.prev_hash,
@@ -30,11 +38,8 @@ export const transformInput = (input: any): InputWithPath => {
};
};
export const transformCollateralInput = (collateralInput: any): CollateralInputWithPath => {
validateParams(collateralInput, [
{ name: 'prev_hash', type: 'string', required: true },
{ name: 'prev_index', type: 'number', required: true },
]);
export const transformCollateralInput = (collateralInput: unknown): CollateralInputWithPath => {
Assert(InputWithPathParam, collateralInput);
return {
collateralInput: {
prev_hash: collateralInput.prev_hash,
@@ -44,11 +49,8 @@ export const transformCollateralInput = (collateralInput: any): CollateralInputW
};
};
export const transformReferenceInput = (referenceInput: any): PROTO.CardanoTxReferenceInput => {
validateParams(referenceInput, [
{ name: 'prev_hash', type: 'string', required: true },
{ name: 'prev_index', type: 'number', required: true },
]);
export const transformReferenceInput = (referenceInput: unknown): PROTO.CardanoTxReferenceInput => {
Assert(PROTO.CardanoTxInput, referenceInput);
return {
prev_hash: referenceInput.prev_hash,
prev_index: referenceInput.prev_index,

View File

@@ -3,12 +3,12 @@
// allow for...of statements
/* eslint-disable no-restricted-syntax */
import { validateParams } from '../common/paramsValidator';
import { addressParametersToProto, validateAddressParameters } from './cardanoAddressParameters';
import { tokenBundleToProto } from './cardanoTokenBundle';
import type { AssetGroupWithTokens } from './cardanoTokenBundle';
import { tokenBundleToProto, AssetGroupWithTokens } from './cardanoTokenBundle';
import { PROTO } from '../../constants';
import { hexStringByteLength, sendChunkedHexString } from './cardanoUtils';
import { CardanoAssetGroup, CardanoAddressParameters } from '../../types/api/cardano';
import { Assert, Type } from '@trezor/schema-utils';
export type OutputWithData = {
output: PROTO.CardanoTxOutput;
@@ -17,16 +17,19 @@ export type OutputWithData = {
referenceScript?: string;
};
export const transformOutput = (output: any): OutputWithData => {
validateParams(output, [
{ name: 'address', type: 'string' },
{ name: 'amount', type: 'uint', required: true },
{ name: 'tokenBundle', type: 'array', allowEmpty: true },
{ name: 'datumHash', type: 'string' },
{ name: 'format', type: 'number' },
{ name: 'inlineDatum', type: 'string' },
{ name: 'referenceScript', type: 'string' },
]);
export const OutputValidation = Type.Object({
address: Type.Optional(Type.String()),
amount: Type.Uint(),
tokenBundle: Type.Optional(Type.Array(CardanoAssetGroup)),
datumHash: Type.Optional(Type.String()),
format: Type.Optional(Type.Number()),
inlineDatum: Type.Optional(Type.String()),
referenceScript: Type.Optional(Type.String()),
addressParameters: Type.Optional(CardanoAddressParameters),
});
export const transformOutput = (output: unknown): OutputWithData => {
Assert(OutputValidation, output);
const result: OutputWithData = {
output: {

View File

@@ -1,34 +1,14 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/helpers/cardanoTokenBundle.js
import { validateParams } from '../common/paramsValidator';
import type { PROTO } from '../../constants';
import type { CardanoAssetGroup, CardanoToken } from '../../types/api/cardano';
import { PROTO } from '../../constants';
import { CardanoAssetGroup, CardanoToken } from '../../types/api/cardano';
import { Assert, Type, Static } from '@trezor/schema-utils';
export type AssetGroupWithTokens = {
policyId: string;
tokens: PROTO.CardanoToken[];
};
const validateTokens = (tokenAmounts: CardanoToken[]) => {
tokenAmounts.forEach(tokenAmount => {
validateParams(tokenAmount, [
{ name: 'assetNameBytes', type: 'string', required: true },
{ name: 'amount', type: 'uint' },
{ name: 'mintAmount', type: 'uint', allowNegative: true },
]);
});
};
const validateTokenBundle = (tokenBundle: CardanoAssetGroup[]) => {
tokenBundle.forEach(tokenGroup => {
validateParams(tokenGroup, [
{ name: 'policyId', type: 'string', required: true },
{ name: 'tokenAmounts', type: 'array', required: true },
]);
validateTokens(tokenGroup.tokenAmounts);
});
};
export type AssetGroupWithTokens = Static<typeof AssetGroupWithTokens>;
export const AssetGroupWithTokens = Type.Object({
policyId: Type.String(),
tokens: Type.Array(PROTO.CardanoToken),
});
const tokenAmountsToProto = (tokenAmounts: CardanoToken[]): PROTO.CardanoToken[] =>
tokenAmounts.map(tokenAmount => ({
@@ -38,7 +18,7 @@ const tokenAmountsToProto = (tokenAmounts: CardanoToken[]): PROTO.CardanoToken[]
}));
export const tokenBundleToProto = (tokenBundle: CardanoAssetGroup[]): AssetGroupWithTokens[] => {
validateTokenBundle(tokenBundle);
Assert(Type.Array(CardanoAssetGroup), tokenBundle);
return tokenBundle.map(tokenGroup => ({
policyId: tokenGroup.policyId,
tokens: tokenAmountsToProto(tokenGroup.tokenAmounts),

View File

@@ -1,8 +1,8 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/ChangePin.js
import { AbstractMethod } from '../core/AbstractMethod';
import { validateParams } from './common/paramsValidator';
import type { PROTO } from '../constants';
import { Assert } from '@trezor/schema-utils';
import { PROTO } from '../constants';
export default class ChangePin extends AbstractMethod<'changePin', PROTO.ChangePin> {
init() {
@@ -10,7 +10,7 @@ export default class ChangePin extends AbstractMethod<'changePin', PROTO.ChangeP
this.useDeviceState = false;
const { payload } = this;
validateParams(payload, [{ name: 'remove', type: 'boolean' }]);
Assert(PROTO.ChangePin, payload);
this.params = {
remove: payload.remove,

View File

@@ -2,9 +2,12 @@
import { UI, createUiMessage } from '../events';
import { AbstractMethod } from '../core/AbstractMethod';
import { validateParams, getFirmwareRange } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import { validatePath } from '../utils/pathUtils';
import type { PROTO } from '../constants';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../types/params';
import { CipherKeyValue as CipherKeyValueSchema } from '../types/api/cipherKeyValue';
export default class CipherKeyValue extends AbstractMethod<
'cipherKeyValue',
@@ -26,30 +29,16 @@ export default class CipherKeyValue extends AbstractMethod<
typeof payload.useEmptyPassphrase === 'boolean' ? payload.useEmptyPassphrase : true;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'key', type: 'string' },
{ name: 'value', type: 'string' },
{ name: 'encrypt', type: 'boolean' },
{ name: 'askOnEncrypt', type: 'boolean' },
{ name: 'askOnDecrypt', type: 'boolean' },
{ name: 'iv', type: 'string' },
]);
return {
address_n: validatePath(batch.path),
key: batch.key,
value: batch.value instanceof Buffer ? batch.value.toString('hex') : batch.value,
encrypt: batch.encrypt,
ask_on_encrypt: batch.askOnEncrypt,
ask_on_decrypt: batch.askOnDecrypt,
iv: batch.iv instanceof Buffer ? batch.iv.toString('hex') : batch.iv,
};
});
Assert(Bundle(CipherKeyValueSchema), payload);
this.params = payload.bundle.map(batch => ({
address_n: validatePath(batch.path),
key: batch.key,
value: batch.value instanceof Buffer ? batch.value.toString('hex') : batch.value,
encrypt: batch.encrypt,
ask_on_encrypt: batch.askOnEncrypt,
ask_on_decrypt: batch.askOnDecrypt,
iv: batch.iv instanceof Buffer ? batch.iv.toString('hex') : batch.iv,
}));
}
get info() {

View File

@@ -1,11 +1,13 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/EosGetPublicKey.js
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath, fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import { UI, createUiMessage } from '../../../events';
import type { PROTO } from '../../../constants';
import { Assert } from '@trezor/schema-utils';
import { Bundle, GetPublicKey as GetPublicKeySchema } from '../../../types';
export default class EosGetPublicKey extends AbstractMethod<
'eosGetPublicKey',
@@ -25,16 +27,9 @@ export default class EosGetPublicKey extends AbstractMethod<
: this.payload;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
Assert(Bundle(GetPublicKeySchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'chunkify', type: 'boolean' },
]);
const path = validatePath(batch.path, 3);
return {
address_n: path,

View File

@@ -1,11 +1,13 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/EosSignTransaction.js
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath } from '../../../utils/pathUtils';
import * as helper from '../eosSignTx';
import type { PROTO } from '../../../constants';
import { Assert } from '@trezor/schema-utils';
import { EosSignTransaction as EosSignTransactionSchema } from '../../../types/api/eos';
type Params = {
path: number[];
@@ -22,11 +24,7 @@ export default class EosSignTransaction extends AbstractMethod<'eosSignTransacti
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'path', required: true },
{ name: 'transaction', required: true },
{ name: 'chunkify', type: 'boolean' },
]);
Assert(EosSignTransactionSchema, payload);
const path = validatePath(payload.path, 3);
const { chain_id, header, ack } = helper.validate(payload.transaction);

View File

@@ -1,7 +1,7 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/EthereumGetAddress.js
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { validatePath, getSerializedPath, getSlip44ByPath } from '../../../utils/pathUtils';
import { getNetworkLabel } from '../../../utils/ethereumUtils';
import { getEthereumNetwork, getUniqueNetworks } from '../../../data/coinInfo';
@@ -14,6 +14,9 @@ import {
decodeEthereumDefinition,
ethereumNetworkInfoFromDefinition,
} from '../ethereumDefinitions';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../../../types';
import { GetAddress as GetAddressSchema } from '../../../types/api/getAddress';
type Params = PROTO.EthereumGetAddress & {
address?: string;
@@ -36,20 +39,9 @@ export default class EthereumGetAddress extends AbstractMethod<'ethereumGetAddre
: this.payload;
// validate bundle type
validateParams(payload, [
{ name: 'bundle', type: 'array' },
{ name: 'useEventListener', type: 'boolean' },
]);
Assert(Bundle(GetAddressSchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'address', type: 'string' },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'chunkify', type: 'boolean' },
]);
const path = validatePath(batch.path, 3);
const network = getEthereumNetwork(path);
this.firmwareRange = getFirmwareRange(this.name, network, this.firmwareRange);

View File

@@ -1,13 +1,15 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/EthereumGetPublicKey.js
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { validatePath } from '../../../utils/pathUtils';
import { getNetworkLabel } from '../../../utils/ethereumUtils';
import { getEthereumNetwork, getUniqueNetworks } from '../../../data/coinInfo';
import { UI, createUiMessage } from '../../../events';
import type { PROTO } from '../../../constants';
import type { EthereumNetworkInfo } from '../../../types';
import { Assert } from '@trezor/schema-utils';
import { Bundle, GetPublicKey as GetPublicKeySchema } from '../../../types';
type Params = PROTO.EthereumGetPublicKey & {
network?: EthereumNetworkInfo;
@@ -27,15 +29,9 @@ export default class EthereumGetPublicKey extends AbstractMethod<'ethereumGetPub
: this.payload;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
Assert(Bundle(GetPublicKeySchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'showOnTrezor', type: 'boolean' },
]);
const path = validatePath(batch.path, 3);
const network = getEthereumNetwork(path);
this.firmwareRange = getFirmwareRange(this.name, network, this.firmwareRange);

View File

@@ -1,15 +1,19 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/EthereumSignMessage.js
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getSlip44ByPath, validatePath } from '../../../utils/pathUtils';
import { getEthereumNetwork } from '../../../data/coinInfo';
import { getNetworkLabel } from '../../../utils/ethereumUtils';
import { messageToHex } from '../../../utils/formatUtils';
import type { PROTO } from '../../../constants';
import { getEthereumDefinitions } from '../ethereumDefinitions';
import type { EthereumNetworkInfo } from '../../../types';
import {
EthereumNetworkInfo,
EthereumSignMessage as EthereumSignMessageSchema,
} from '../../../types';
import type { EthereumDefinitions } from '@trezor/protobuf/lib/messages';
import { Assert } from '@trezor/schema-utils';
type Params = PROTO.EthereumSignMessage & {
network?: EthereumNetworkInfo;
@@ -23,11 +27,7 @@ export default class EthereumSignMessage extends AbstractMethod<'ethereumSignMes
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'path', required: true },
{ name: 'message', type: 'string', required: true },
{ name: 'hex', type: 'boolean' },
]);
Assert(EthereumSignMessageSchema, payload);
const path = validatePath(payload.path, 3);
const network = getEthereumNetwork(path);

View File

@@ -1,7 +1,7 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/EthereumSignTransaction.js
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getSlip44ByPath, validatePath } from '../../../utils/pathUtils';
import { getEthereumNetwork } from '../../../data/coinInfo';
import { getNetworkLabel } from '../../../utils/ethereumUtils';
@@ -13,8 +13,12 @@ import {
ethereumNetworkInfoFromDefinition,
} from '../ethereumDefinitions';
import type { EthereumTransaction, EthereumTransactionEIP1559 } from '../../../types/api/ethereum';
import type { EthereumNetworkInfo } from '../../../types';
import {
EthereumNetworkInfo,
EthereumSignTransaction as EthereumSignTransactionSchema,
} from '../../../types';
import type { EthereumDefinitions } from '@trezor/protobuf/lib/messages';
import { Assert } from '@trezor/schema-utils';
type Params = {
path: number[];
@@ -50,11 +54,7 @@ export default class EthereumSignTransaction extends AbstractMethod<
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'path', required: true },
{ name: 'transaction', required: true },
{ name: 'chunkify', type: 'boolean' },
]);
Assert(EthereumSignTransactionSchema, payload);
const path = validatePath(payload.path, 3);
const network = getEthereumNetwork(path);
@@ -75,30 +75,8 @@ export default class EthereumSignTransaction extends AbstractMethod<
);
if (isEIP1559) {
validateParams(tx, [
{ name: 'to', type: 'string', required: true },
{ name: 'value', type: 'string', required: true },
{ name: 'gasLimit', type: 'string', required: true },
{ name: 'maxFeePerGas', type: 'string', required: true },
{ name: 'maxPriorityFeePerGas', type: 'string', required: true },
{ name: 'nonce', type: 'string', required: true },
{ name: 'data', type: 'string' },
{ name: 'chainId', type: 'number', required: true },
]);
this.params = { path, network, type: 'eip1559', tx: strip(tx), chunkify };
} else {
validateParams(tx, [
{ name: 'to', type: 'string', required: true },
{ name: 'value', type: 'string', required: true },
{ name: 'gasLimit', type: 'string', required: true },
{ name: 'gasPrice', type: 'string', required: true },
{ name: 'nonce', type: 'string', required: true },
{ name: 'data', type: 'string' },
{ name: 'chainId', type: 'number' },
{ name: 'txType', type: 'number' },
]);
this.params = { path, network, type: 'legacy', tx: strip(tx), chunkify };
}

View File

@@ -3,12 +3,12 @@
/* eslint-disable no-restricted-syntax */
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getSlip44ByPath, validatePath } from '../../../utils/pathUtils';
import { getEthereumNetwork } from '../../../data/coinInfo';
import { getNetworkLabel } from '../../../utils/ethereumUtils';
import { PROTO, ERRORS } from '../../../constants';
import type {
import {
EthereumSignTypedDataTypes,
EthereumSignTypedData as EthereumSignTypedDataParams,
EthereumSignTypedHash as EthereumSignTypedHashParams,
@@ -16,9 +16,9 @@ import type {
import { getFieldType, parseArrayType, encodeData } from '../ethereumSignTypedData';
import { messageToHex } from '../../../utils/formatUtils';
import { getEthereumDefinitions } from '../ethereumDefinitions';
import type { EthereumNetworkInfo } from '../../../types';
import type { EthereumDefinitions } from '@trezor/protobuf/lib/messages';
import { DeviceModelInternal } from '../../../types';
import { EthereumNetworkInfo, DeviceModelInternal } from '../../../types';
import { EthereumDefinitions } from '@trezor/protobuf/lib/messages-schema';
import { Assert, Type } from '@trezor/schema-utils';
type Params = (
| Omit<EthereumSignTypedDataParams<EthereumSignTypedDataTypes>, 'path'>
@@ -28,6 +28,18 @@ type Params = (
network?: EthereumNetworkInfo;
definitions?: EthereumDefinitions;
};
const Params = Type.Intersect([
Type.Union([
Type.Omit(EthereumSignTypedDataParams, Type.Literal('path')),
Type.Omit(EthereumSignTypedHashParams, Type.Literal('path')),
]),
Type.Object({
address_n: Type.Array(Type.Number()),
network: Type.Optional(EthereumNetworkInfo),
definitions: Type.Optional(EthereumDefinitions),
}),
]);
export default class EthereumSignTypedData extends AbstractMethod<'ethereumSignTypedData', Params> {
init() {
this.requiredPermissions = ['read', 'write'];
@@ -35,15 +47,7 @@ export default class EthereumSignTypedData extends AbstractMethod<'ethereumSignT
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'path', required: true },
// T2T1
{ name: 'metamask_v4_compat', type: 'boolean', required: true },
{ name: 'data', type: 'object', required: true },
// T1B1 (optional params)
{ name: 'domain_separator_hash', type: 'string' },
{ name: 'message_hash', type: 'string' },
]);
Assert(Type.Union([EthereumSignTypedDataParams, EthereumSignTypedHashParams]), payload);
const path = validatePath(payload.path, 3);
const network = getEthereumNetwork(path);
@@ -116,10 +120,13 @@ export default class EthereumSignTypedData extends AbstractMethod<'ethereumSignT
const cmd = this.device.getCommands();
const { address_n, definitions } = this.params;
if (this.device.features.internal_model === DeviceModelInternal.T1B1) {
validateParams(this.params, [
{ name: 'domain_separator_hash', type: 'string', required: true },
{ name: 'message_hash', type: 'string' },
]);
Assert(
Type.Object({
domain_separator_hash: Type.String(),
message_hash: Type.Optional(Type.String()),
}),
this.params,
);
const { domain_separator_hash, message_hash } = this.params;
@@ -129,7 +136,7 @@ export default class EthereumSignTypedData extends AbstractMethod<'ethereumSignT
'EthereumTypedDataSignature',
{
address_n,
domain_separator_hash: domain_separator_hash as string, // TODO: https://github.com/trezor/trezor-suite/issues/5297
domain_separator_hash,
message_hash,
encoded_network: definitions?.encoded_network,
},

View File

@@ -1,9 +1,11 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/EthereumVerifyMessage.js
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { stripHexPrefix, messageToHex } from '../../../utils/formatUtils';
import type { PROTO } from '../../../constants';
import { Assert } from '@trezor/schema-utils';
import { EthereumVerifyMessage as EthereumVerifyMessageSchema } from '../../../types';
export default class EthereumVerifyMessage extends AbstractMethod<
'ethereumVerifyMessage',
@@ -16,12 +18,7 @@ export default class EthereumVerifyMessage extends AbstractMethod<
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'address', type: 'string', required: true },
{ name: 'signature', type: 'string', required: true },
{ name: 'message', type: 'string', required: true },
{ name: 'hex', type: 'boolean' },
]);
Assert(EthereumVerifyMessageSchema, payload);
const messageHex = payload.hex
? messageToHex(payload.message)

View File

@@ -4,9 +4,9 @@ import { EthereumDefinitions } from '@trezor/protobuf/lib/messages';
import { trzd } from '@trezor/protocol';
import { parseConfigure, decode as decodeProtobuf } from '@trezor/protobuf';
import { DataManager } from '../../data/DataManager';
import { validateParams } from '../common/paramsValidator';
import { EthereumNetworkInfo } from '../../types';
import { ethereumNetworkInfoBase } from '../../data/coinInfo';
import { Type, Static, Assert } from '@trezor/schema-utils';
interface GetEthereumDefinitions {
chainId?: number;
@@ -70,28 +70,31 @@ export const getEthereumDefinitions = async ({
/**
* decoded content of data retrieved from https://data.trezor.io/firmware/eth-definitions/...
*/
export interface EthereumNetworkDefinitionDecoded {
chain_id: number;
name: string;
slip44: number;
symbol: string;
}
export type EthereumNetworkDefinitionDecoded = Static<typeof EthereumNetworkDefinitionDecoded>;
export const EthereumNetworkDefinitionDecoded = Type.Object({
chain_id: Type.Number(),
name: Type.String(),
slip44: Type.Number(),
symbol: Type.String(),
});
/**
* decoded content of data retreived from https://data.trezor.io/firmware/eth-definitions/...
*/
export interface EthereumTokenDefinitionDecoded {
address: string; // dac17f958d2ee523a2206206994597c13d831ec7
chain_id: number; // 1
decimals: number; // 6
name: string; // Tether
symbol: string; // USDT
}
export type EthereumTokenDefinitionDecoded = Static<typeof EthereumTokenDefinitionDecoded>;
export const EthereumTokenDefinitionDecoded = Type.Object({
address: Type.String(), // dac17f958d2ee523a2206206994597c13d831ec7
chain_id: Type.Number(), // 1
decimals: Type.Number(), // 6
name: Type.String(), // Tether
symbol: Type.String(), // USDT
});
export interface EthereumDefinitionDecoded {
network?: EthereumNetworkDefinitionDecoded;
token?: EthereumTokenDefinitionDecoded;
}
export type EthereumDefinitionDecoded = Static<typeof EthereumDefinitionDecoded>;
export const EthereumDefinitionDecoded = Type.Object({
network: Type.Optional(EthereumNetworkDefinitionDecoded),
token: Type.Optional(EthereumTokenDefinitionDecoded),
});
export const decodeEthereumDefinition = (
encodedDefinition: EthereumDefinitions,
@@ -122,23 +125,11 @@ export const decodeEthereumDefinition = (
const decodedDefinition = decodeProtobuf(Message, protobufPayload);
if (key === 'encoded_network') {
validateParams(decodedDefinition, [
{ name: 'chain_id', type: 'number', required: true },
{ name: 'name', type: 'string', required: true },
{ name: 'slip44', type: 'number', required: true },
{ name: 'symbol', type: 'string', required: true },
]);
decoded.network = decodedDefinition as EthereumNetworkDefinitionDecoded;
Assert(EthereumNetworkDefinitionDecoded, decodedDefinition);
decoded.network = decodedDefinition;
} else if (key === 'encoded_token') {
validateParams(decodedDefinition, [
{ name: 'address', type: 'string', required: true },
{ name: 'chain_id', type: 'number', required: true },
{ name: 'name', type: 'string', required: true },
{ name: 'decimals', type: 'number', required: true },
{ name: 'symbol', type: 'string', required: true },
]);
decoded.token = decodedDefinition as EthereumTokenDefinitionDecoded;
Assert(EthereumTokenDefinitionDecoded, decodedDefinition);
decoded.token = decodedDefinition;
}
});

View File

@@ -11,9 +11,10 @@ import {
uploadFirmware,
calculateFirmwareHash,
} from './firmware';
import { validateParams } from './common/paramsValidator';
import { getReleases } from '../data/firmwareInfo';
import { IntermediaryVersion } from '../types';
import { Assert } from '@trezor/schema-utils';
import { FirmwareUpdate as FirmwareUpdateSchema } from '../types/api/firmwareUpdate';
type Params = {
binary?: ArrayBuffer;
@@ -34,15 +35,14 @@ export default class FirmwareUpdate extends AbstractMethod<'firmwareUpdate', Par
const { payload } = this;
validateParams(payload, [
{ name: 'version', type: 'array' },
{ name: 'btcOnly', type: 'boolean' },
{ name: 'baseUrl', type: 'string' },
{ name: 'binary', type: 'array-buffer' },
{ name: 'intermediaryVersion', type: 'number' },
]);
Assert(FirmwareUpdateSchema, payload);
if ('version' in payload) {
if (payload.binary) {
this.params = {
...this.params,
binary: payload.binary,
};
} else {
this.params = {
// either receive version and btcOnly
version: payload.version,
@@ -51,14 +51,6 @@ export default class FirmwareUpdate extends AbstractMethod<'firmwareUpdate', Par
intermediaryVersion: payload.intermediaryVersion,
};
}
if ('binary' in payload) {
// or binary
this.params = {
...this.params,
binary: payload.binary,
};
}
}
async confirmation() {

View File

@@ -1,15 +1,16 @@
import { AbstractMethod, MethodReturnType, DEFAULT_FIRMWARE_RANGE } from '../core/AbstractMethod';
import { validateParams, getFirmwareRange } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import { validatePath, getSerializedPath } from '../utils/pathUtils';
import { getAccountLabel } from '../utils/accountUtils';
import { getCoinInfo } from '../data/coinInfo';
import { PROTO, ERRORS } from '../constants';
import { UI, createUiMessage } from '../events';
import type { CoinInfo, DerivationPath } from '../types';
import type {
import { Bundle, type CoinInfo, type DerivationPath } from '../types';
import {
GetAccountDescriptorParams,
GetAccountDescriptorResponse,
} from '../types/api/getAccountDescriptor';
import { Assert } from '@trezor/schema-utils';
type Request = GetAccountDescriptorParams & { address_n: number[]; coinInfo: CoinInfo };
@@ -32,17 +33,9 @@ export default class GetAccountDescriptor extends AbstractMethod<
: this.payload;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
Assert(Bundle(GetAccountDescriptorParams), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters
validateParams(batch, [
{ name: 'coin', type: 'string', required: true },
{ name: 'path', type: 'string', required: true },
{ name: 'derivationType', type: 'number' },
{ name: 'suppressBackupWarning', type: 'boolean' },
]);
// validate coin info
const coinInfo = getCoinInfo(batch.coin);
if (!coinInfo) {

View File

@@ -1,12 +1,14 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/GetAddress.js
import { AbstractMethod, MethodReturnType } from '../core/AbstractMethod';
import { validateParams, validateCoinPath, getFirmwareRange } from './common/paramsValidator';
import { validateCoinPath, getFirmwareRange } from './common/paramsValidator';
import { validatePath, getLabel, getSerializedPath } from '../utils/pathUtils';
import { getBitcoinNetwork, fixCoinInfoNetwork, getUniqueNetworks } from '../data/coinInfo';
import { PROTO, ERRORS } from '../constants';
import { UI, createUiMessage } from '../events';
import type { BitcoinNetworkInfo } from '../types';
import { Bundle, type BitcoinNetworkInfo } from '../types';
import { Assert } from '@trezor/schema-utils';
import { GetAddress as GetAddressSchema } from '../types/api/getAddress';
type Params = PROTO.GetAddress & {
address?: string;
@@ -29,31 +31,9 @@ export default class GetAddress extends AbstractMethod<'getAddress', Params[]> {
: this.payload;
// validate bundle type
validateParams(payload, [
{ name: 'bundle', type: 'array' },
{ name: 'useEventListener', type: 'boolean' },
]);
Assert(Bundle(GetAddressSchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'coin', type: 'string' },
{ name: 'address', type: 'string' },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'multisig', type: 'object' },
{ name: 'scriptType', type: 'string' },
{ name: 'unlockPath', type: 'object' },
{ name: 'chunkify', type: 'boolean' },
]);
if (batch.unlockPath) {
validateParams(batch.unlockPath, [
{ name: 'address_n', required: true, type: 'array' },
{ name: 'mac', required: true, type: 'string' },
]);
}
const path = validatePath(batch.path, 1);
let coinInfo: BitcoinNetworkInfo | undefined;
if (batch.coin) {

View File

@@ -1,10 +1,10 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/GetCoinInfo.js
import { AbstractMethod } from '../core/AbstractMethod';
import { validateParams } from './common/paramsValidator';
import { ERRORS } from '../constants';
import { getCoinInfo } from '../data/coinInfo';
import type { CoinInfo } from '../types';
import { CoinObj, CoinInfo } from '../types';
import { Assert } from '@trezor/schema-utils';
type Params = {
coinInfo: CoinInfo;
@@ -18,7 +18,7 @@ export default class GetCoinInfo extends AbstractMethod<'getCoinInfo', Params> {
const { payload } = this;
validateParams(payload, [{ name: 'coin', type: 'string', required: true }]);
Assert(CoinObj, payload);
const coinInfo = getCoinInfo(payload.coin);
if (!coinInfo) {

View File

@@ -1,7 +1,8 @@
import { AbstractMethod } from '../core/AbstractMethod';
import { PROTO } from '../constants';
import { UI } from '../events';
import { getFirmwareRange, validateParams } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import { Assert } from '@trezor/schema-utils';
export default class GetFirmwareHash extends AbstractMethod<
'getFirmwareHash',
@@ -15,7 +16,7 @@ export default class GetFirmwareHash extends AbstractMethod<
const { payload } = this;
validateParams(payload, [{ name: 'challenge', type: 'string' }]);
Assert(PROTO.GetFirmwareHash, payload);
this.firmwareRange = getFirmwareRange(this.name, null, this.firmwareRange);

View File

@@ -1,9 +1,12 @@
import { AbstractMethod, MethodReturnType } from '../core/AbstractMethod';
import { validateParams, getFirmwareRange } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import { validatePath, getScriptType, getSerializedPath } from '../utils/pathUtils';
import { getBitcoinNetwork } from '../data/coinInfo';
import { PROTO } from '../constants';
import { UI, createUiMessage } from '../events';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../exports';
import { GetOwnershipId as GetOwnershipIdSchema } from '../types/api/getOwnershipId';
export default class GetOwnershipId extends AbstractMethod<
'getOwnershipId',
@@ -22,17 +25,9 @@ export default class GetOwnershipId extends AbstractMethod<
: this.payload;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
Assert(Bundle(GetOwnershipIdSchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'coin', type: 'string' },
{ name: 'multisig', type: 'object' },
{ name: 'scriptType', type: 'string' },
]);
const address_n = validatePath(batch.path, 1);
const coinInfo = getBitcoinNetwork(batch.coin || address_n);
const script_type = batch.scriptType || getScriptType(address_n);

View File

@@ -1,9 +1,12 @@
import { AbstractMethod, MethodReturnType } from '../core/AbstractMethod';
import { validateParams, getFirmwareRange } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import { validatePath, getScriptType, getSerializedPath } from '../utils/pathUtils';
import { getBitcoinNetwork } from '../data/coinInfo';
import { PROTO } from '../constants';
import { UI, createUiMessage } from '../events';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../exports';
import { GetOwnershipProof as GetOwnershipProofSchema } from '../types/api/getOwnershipProof';
export default class GetOwnershipProof extends AbstractMethod<
'getOwnershipProof',
@@ -22,21 +25,9 @@ export default class GetOwnershipProof extends AbstractMethod<
: this.payload;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
Assert(Bundle(GetOwnershipProofSchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'coin', type: 'string' },
{ name: 'multisig', type: 'object' },
{ name: 'scriptType', type: 'string' },
{ name: 'userConfirmation', type: 'boolean' },
{ name: 'ownershipIds', type: 'array' },
{ name: 'commitmentData', type: 'string' },
{ name: 'preauthorized', type: 'boolean' },
]);
const address_n = validatePath(batch.path, 1);
const coinInfo = getBitcoinNetwork(batch.coin || address_n);
const script_type = batch.scriptType || getScriptType(address_n);

View File

@@ -1,13 +1,16 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/GetPublicKey.js
import { AbstractMethod, MethodReturnType } from '../core/AbstractMethod';
import { validateParams, validateCoinPath, getFirmwareRange } from './common/paramsValidator';
import { validateCoinPath, getFirmwareRange } from './common/paramsValidator';
import { validatePath } from '../utils/pathUtils';
import { UI, createUiMessage } from '../events';
import { getBitcoinNetwork } from '../data/coinInfo';
import { getPublicKeyLabel } from '../utils/accountUtils';
import type { BitcoinNetworkInfo } from '../types';
import type { PROTO } from '../constants';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../types';
import { GetPublicKey as GetPublicKeySchema } from '../types/api/getPublicKey';
type Params = PROTO.GetPublicKey & {
coinInfo?: BitcoinNetworkInfo;
@@ -29,29 +32,9 @@ export default class GetPublicKey extends AbstractMethod<'getPublicKey', Params[
: this.payload;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
Assert(Bundle(GetPublicKeySchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'coin', type: 'string' },
{ name: 'crossChain', type: 'boolean' },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'scriptType', type: ['string', 'number'] },
{ name: 'ignoreXpubMagic', type: 'boolean' },
{ name: 'ecdsaCurveName', type: 'boolean' },
{ name: 'unlockPath', type: 'object' },
{ name: 'suppressBackupWarning', type: 'boolean' },
]);
if (batch.unlockPath) {
validateParams(batch.unlockPath, [
{ name: 'address_n', required: true, type: 'array' },
{ name: 'mac', required: true, type: 'string' },
]);
}
let coinInfo: BitcoinNetworkInfo | undefined;
if (batch.coin) {
coinInfo = getBitcoinNetwork(batch.coin);

View File

@@ -1,11 +1,14 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/NEMGetAddress.js
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath, fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import { PROTO, ERRORS } from '../../../constants';
import { UI, createUiMessage } from '../../../events';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../../../types';
import { GetAddress as GetAddressSchema } from '../../../types/api/getAddress';
type Params = PROTO.NEMGetAddress & {
address?: string;
@@ -31,21 +34,9 @@ export default class NEMGetAddress extends AbstractMethod<'nemGetAddress', Param
: this.payload;
// validate bundle type
validateParams(payload, [
{ name: 'bundle', type: 'array' },
{ name: 'useEventListener', type: 'boolean' },
]);
Assert(Bundle(GetAddressSchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'address', type: 'string' },
{ name: 'network', type: 'number' },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'chunkify', type: 'boolean' },
]);
const path = validatePath(batch.path, 3);
return {
address_n: path,

View File

@@ -1,11 +1,13 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/NEMSignTransaction.js
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath } from '../../../utils/pathUtils';
import * as helper from '../nemSignTx';
import type { PROTO } from '../../../constants';
import { Assert } from '@trezor/schema-utils';
import { NEMSignTransaction as NEMSignTransactionSchema } from '../../../types/api/nem';
export default class NEMSignTransaction extends AbstractMethod<
'nemSignTransaction',
@@ -17,11 +19,7 @@ export default class NEMSignTransaction extends AbstractMethod<
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'path', required: true },
{ name: 'transaction', required: true },
{ name: 'chunkify', type: 'boolean' },
]);
Assert(NEMSignTransactionSchema, payload);
const path = validatePath(payload.path, 3);
// incoming data should be in nem-sdk format

View File

@@ -1,11 +1,12 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/PushTransaction.js
import { AbstractMethod } from '../core/AbstractMethod';
import { validateParams } from './common/paramsValidator';
import { getCoinInfo } from '../data/coinInfo';
import { ERRORS } from '../constants';
import { isBackendSupported, initBlockchain } from '../backend/BlockchainLink';
import type { CoinInfo } from '../types';
import { Assert } from '@trezor/schema-utils';
import { PushTransaction as PushTransactionSchema } from '../types/api/pushTransaction';
type Params = {
tx: string;
@@ -21,10 +22,7 @@ export default class PushTransaction extends AbstractMethod<'pushTransaction', P
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'tx', type: 'string', required: true },
{ name: 'coin', type: 'string', required: true },
]);
Assert(PushTransactionSchema, payload);
const coinInfo = getCoinInfo(payload.coin);
if (!coinInfo) {

View File

@@ -2,8 +2,9 @@
import { AbstractMethod } from '../core/AbstractMethod';
import { UI, createUiMessage } from '../events';
import { validateParams } from './common/paramsValidator';
import { Assert } from '@trezor/schema-utils';
import type { PROTO } from '../constants';
import { RecoveryDevice as RecoveryDeviceSchema } from '../types/api/recoveryDevice';
export default class RecoveryDevice extends AbstractMethod<'recoveryDevice', PROTO.RecoveryDevice> {
init() {
@@ -12,17 +13,7 @@ export default class RecoveryDevice extends AbstractMethod<'recoveryDevice', PRO
const { payload } = this;
validateParams(payload, [
{ name: 'word_count', type: 'number' },
{ name: 'passphrase_protection', type: 'boolean' },
{ name: 'pin_protection', type: 'boolean' },
{ name: 'language', type: 'string' },
{ name: 'label', type: 'string' },
{ name: 'enforce_wordlist', type: 'boolean' },
{ name: 'type', type: 'number' },
{ name: 'u2f_counter', type: 'number' },
{ name: 'dry_run', type: 'boolean' },
]);
Assert(RecoveryDeviceSchema, payload);
this.params = {
word_count: payload.word_count,
passphrase_protection: payload.passphrase_protection,

View File

@@ -1,12 +1,14 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/RequestLogin.js
import { AbstractMethod } from '../core/AbstractMethod';
import { validateParams, getFirmwareRange } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import { ERRORS } from '../constants';
import { UI, createUiMessage } from '../events';
import { DataManager } from '../data/DataManager';
import type { ConnectSettings } from '../types';
import type { PROTO } from '../constants';
import { Assert, Type } from '@trezor/schema-utils';
import { RequestLoginSchema } from '../types/api/requestLogin';
export default class RequestLogin extends AbstractMethod<'requestLogin', PROTO.SignIdentity> {
asyncChallenge?: boolean;
@@ -31,11 +33,7 @@ export default class RequestLogin extends AbstractMethod<'requestLogin', PROTO.S
}
// validate incoming parameters
validateParams(payload, [
{ name: 'challengeHidden', type: 'string' },
{ name: 'challengeVisual', type: 'string' },
{ name: 'asyncChallenge', type: 'boolean' },
]);
Assert(RequestLoginSchema, payload);
this.params = {
identity,
@@ -67,10 +65,13 @@ export default class RequestLogin extends AbstractMethod<'requestLogin', PROTO.S
}
// validate incoming parameters
validateParams(payload, [
{ name: 'challengeHidden', type: 'string', required: true },
{ name: 'challengeVisual', type: 'string', required: true },
]);
Assert(
Type.Object({
challengeHidden: Type.String(),
challengeVisual: Type.String(),
}),
payload,
);
this.params.challenge_hidden = payload.challengeHidden;
this.params.challenge_visual = payload.challengeVisual;

View File

@@ -2,8 +2,10 @@
import { AbstractMethod } from '../core/AbstractMethod';
import { UI, createUiMessage } from '../events';
import { validateParams, getFirmwareRange } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import type { PROTO } from '../constants';
import { Assert } from '@trezor/schema-utils';
import { ResetDevice as ResetDeviceSchema } from '../types/api/resetDevice';
export default class ResetDevice extends AbstractMethod<'resetDevice', PROTO.ResetDevice> {
confirmed?: boolean;
@@ -16,18 +18,7 @@ export default class ResetDevice extends AbstractMethod<'resetDevice', PROTO.Res
const { payload } = this;
// validate bundle type
validateParams(payload, [
{ name: 'display_random', type: 'boolean' },
{ name: 'strength', type: 'number' },
{ name: 'passphrase_protection', type: 'boolean' },
{ name: 'pin_protection', type: 'boolean' },
{ name: 'language', type: 'string' },
{ name: 'label', type: 'string' },
{ name: 'u2f_counter', type: 'number' },
{ name: 'skip_backup', type: 'boolean' },
{ name: 'no_backup', type: 'boolean' },
{ name: 'backup_type', type: 'number' },
]);
Assert(ResetDeviceSchema, payload);
this.params = {
display_random: payload.display_random,

View File

@@ -1,11 +1,14 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/RippleGetAddress.js
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath, fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import { PROTO, ERRORS } from '../../../constants';
import { UI, createUiMessage } from '../../../events';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../../../types';
import { GetAddress as GetAddressSchema } from '../../../types/api/getAddress';
type Params = PROTO.RippleGetAddress & {
address?: string;
@@ -31,20 +34,9 @@ export default class RippleGetAddress extends AbstractMethod<'rippleGetAddress',
: this.payload;
// validate bundle type
validateParams(payload, [
{ name: 'bundle', type: 'array' },
{ name: 'useEventListener', type: 'boolean' },
]);
Assert(Bundle(GetAddressSchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'address', type: 'string' },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'chunkify', type: 'boolean' },
]);
const path = validatePath(batch.path, 3);
return {
address_n: path,

View File

@@ -1,10 +1,12 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/RippleSignTransaction.js
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath } from '../../../utils/pathUtils';
import type { PROTO } from '../../../constants';
import { Assert } from '@trezor/schema-utils';
import { RippleSignTransaction as RippleSignTransactionSchema } from '../../../types/api/ripple';
export default class RippleSignTransaction extends AbstractMethod<
'rippleSignTransaction',
@@ -20,30 +22,11 @@ export default class RippleSignTransaction extends AbstractMethod<
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'path', required: true },
{ name: 'transaction', required: true },
{ name: 'chunkify', type: 'boolean' },
]);
Assert(RippleSignTransactionSchema, payload);
const path = validatePath(payload.path, 5);
// incoming data should be in ripple-sdk format
const { transaction, chunkify } = payload;
validateParams(transaction, [
{ name: 'fee', type: 'uint' },
{ name: 'flags', type: 'number' },
{ name: 'sequence', type: 'number' },
{ name: 'maxLedgerVersion', type: 'number' },
{ name: 'payment', type: 'object' },
]);
validateParams(transaction.payment, [
{ name: 'amount', type: 'uint', required: true },
{ name: 'destination', type: 'string', required: true },
{ name: 'destinationTag', type: 'number' },
]);
this.params = {
address_n: path,
fee: transaction.fee,

View File

@@ -1,7 +1,8 @@
import { AbstractMethod } from '../core/AbstractMethod';
import { DEVICE, createDeviceMessage } from '../events';
import { PROTO } from '../constants';
import { getFirmwareRange, validateParams } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import { Assert } from '@trezor/schema-utils';
export default class SetBusy extends AbstractMethod<'setBusy', PROTO.SetBusy> {
init() {
@@ -10,7 +11,7 @@ export default class SetBusy extends AbstractMethod<'setBusy', PROTO.SetBusy> {
const { payload } = this;
validateParams(payload, [{ name: 'expiry_ms', type: 'number' }]);
Assert(PROTO.SetBusy, payload);
this.firmwareRange = getFirmwareRange(this.name, undefined, this.firmwareRange);

View File

@@ -1,12 +1,14 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/SignMessage.js
import { AbstractMethod } from '../core/AbstractMethod';
import { validateParams, validateCoinPath, getFirmwareRange } from './common/paramsValidator';
import { validateCoinPath, getFirmwareRange } from './common/paramsValidator';
import { validatePath, getLabel, getScriptType } from '../utils/pathUtils';
import { getBitcoinNetwork } from '../data/coinInfo';
import { messageToHex } from '../utils/formatUtils';
import type { BitcoinNetworkInfo } from '../types';
import type { PROTO } from '../constants';
import { SignMessage as SignMessageSchema } from '../types';
import { Assert } from '@trezor/schema-utils';
export default class SignMessage extends AbstractMethod<'signMessage', PROTO.SignMessage> {
init() {
@@ -15,13 +17,7 @@ export default class SignMessage extends AbstractMethod<'signMessage', PROTO.Sig
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'path', required: true },
{ name: 'coin', type: 'string' },
{ name: 'message', type: 'string', required: true },
{ name: 'hex', type: 'boolean' },
{ name: 'no_script_type', type: 'boolean' },
]);
Assert(SignMessageSchema, payload);
const path = validatePath(payload.path);
let coinInfo: BitcoinNetworkInfo | undefined;

View File

@@ -1,25 +1,12 @@
import { Assert } from '@trezor/schema-utils';
import { SolanaTxAdditionalInfo } from '../../types/api/solana';
import { validateParams } from '../common/paramsValidator';
const validateAdditionalInfo = (additionalInfo: SolanaTxAdditionalInfo) => {
validateParams(additionalInfo, [{ name: 'tokenAccountsInfos', type: 'array' }]);
additionalInfo.tokenAccountsInfos?.forEach(tokenAccountInfo => {
validateParams(tokenAccountInfo, [
{ name: 'baseAddress', type: 'string', required: true },
{ name: 'tokenProgram', type: 'string', required: true },
{ name: 'tokenMint', type: 'string', required: true },
{ name: 'tokenAccount', type: 'string', required: true },
]);
});
};
export const transformAdditionalInfo = (additionalInfo?: SolanaTxAdditionalInfo) => {
if (!additionalInfo) {
return undefined;
}
validateAdditionalInfo(additionalInfo);
Assert(SolanaTxAdditionalInfo, additionalInfo);
return {
token_accounts_infos:

View File

@@ -1,9 +1,12 @@
import { ERRORS, PROTO } from '../../../constants';
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath, fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import { UI, createUiMessage } from '../../../events';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../../../types';
import { GetAddress as GetAddressSchema } from '../../../types/api/getAddress';
type Params = PROTO.SolanaGetAddress & {
address?: string;
@@ -29,17 +32,9 @@ export default class SolanaGetAddress extends AbstractMethod<'solanaGetAddress',
: this.payload;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
Assert(Bundle(GetAddressSchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'address', type: 'string' },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'chunkify', type: 'boolean' },
]);
const path = validatePath(batch.path, 2);
return {
address_n: path,

View File

@@ -1,9 +1,11 @@
import { PROTO } from '../../../constants';
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath, fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import { UI, createUiMessage } from '../../../events';
import { Assert } from '@trezor/schema-utils';
import { Bundle, GetPublicKey as GetPublicKeySchema } from '../../../types';
export default class SolanaGetPublicKey extends AbstractMethod<
'solanaGetPublicKey',
@@ -27,15 +29,9 @@ export default class SolanaGetPublicKey extends AbstractMethod<
: this.payload;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
Assert(Bundle(GetPublicKeySchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'showOnTrezor', type: 'boolean' },
]);
const path = validatePath(batch.path, 2);
return {
address_n: path,

View File

@@ -1,9 +1,11 @@
import { PROTO } from '../../../constants';
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath } from '../../../utils/pathUtils';
import { transformAdditionalInfo } from '../additionalInfo';
import { Assert } from '@trezor/schema-utils';
import { SolanaSignTransaction as SolanaSignTransactionSchema } from '../../../types/api/solana';
export default class SolanaSignTransaction extends AbstractMethod<
'solanaSignTransaction',
@@ -20,10 +22,7 @@ export default class SolanaSignTransaction extends AbstractMethod<
const { payload } = this;
// validate bundle type
validateParams(payload, [
{ name: 'path', required: true },
{ name: 'serializedTx', type: 'string', required: true },
]);
Assert(SolanaSignTransactionSchema, payload);
const path = validatePath(payload.path, 2);

View File

@@ -1,11 +1,14 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/StellarGetAddress.js
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath, fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import { PROTO, ERRORS } from '../../../constants';
import { UI, createUiMessage } from '../../../events';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../../../types';
import { GetAddress as GetAddressSchema } from '../../../types/api/getAddress';
type Params = PROTO.StellarGetAddress & {
address?: string;
@@ -31,20 +34,9 @@ export default class StellarGetAddress extends AbstractMethod<'stellarGetAddress
: this.payload;
// validate bundle type
validateParams(payload, [
{ name: 'bundle', type: 'array' },
{ name: 'useEventListener', type: 'boolean' },
]);
Assert(Bundle(GetAddressSchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'address', type: 'string' },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'chunkify', type: 'boolean' },
]);
const path = validatePath(batch.path, 3);
return {
address_n: path,

View File

@@ -1,12 +1,16 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/StellarSignTransaction.js
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath } from '../../../utils/pathUtils';
import * as helper from '../stellarSignTx';
import { ERRORS } from '../../../constants';
import { StellarTransaction } from '../../../types/api/stellar';
import {
StellarTransaction,
StellarSignTransaction as StellarSignTransactionSchema,
} from '../../../types/api/stellar';
import { Assert } from '@trezor/schema-utils';
type Params = {
path: number[];
@@ -33,11 +37,7 @@ export default class StellarSignTransaction extends AbstractMethod<
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'path', required: true },
{ name: 'networkPassphrase', type: 'string', required: true },
{ name: 'transaction', required: true },
]);
Assert(StellarSignTransactionSchema, payload);
const path = validatePath(payload.path, 3);
// incoming data should be in stellar-sdk format

View File

@@ -1,13 +1,13 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/helpers/stellarSignTx.js
import { PROTO, ERRORS } from '../../constants';
import { validateParams } from '../common/paramsValidator';
import type { TypedCall } from '../../device/DeviceCommands';
import type {
import {
StellarTransaction,
StellarOperation,
StellarOperationMessage,
} from '../../types/api/stellar';
import { Assert } from '@trezor/schema-utils';
const processTxRequest = async (
typedCall: TypedCall,
@@ -59,12 +59,10 @@ const transformSignMessage = (tx: StellarTransaction) => {
// transform incoming parameters to protobuf messages format
const transformOperation = (op: StellarOperation): StellarOperationMessage | undefined => {
Assert(StellarOperation, op);
switch (op.type) {
case 'createAccount':
validateParams(op, [
{ name: 'destination', type: 'string', required: true },
{ name: 'startingBalance', type: 'uint', required: true },
]);
return {
type: 'StellarCreateAccountOp',
source_account: op.source,
@@ -73,10 +71,6 @@ const transformOperation = (op: StellarOperation): StellarOperationMessage | und
};
case 'payment':
validateParams(op, [
{ name: 'destination', type: 'string', required: true },
{ name: 'amount', type: 'uint', required: true },
]);
return {
type: 'StellarPaymentOp',
source_account: op.source,
@@ -86,7 +80,6 @@ const transformOperation = (op: StellarOperation): StellarOperationMessage | und
};
case 'pathPaymentStrictReceive':
validateParams(op, [{ name: 'destAmount', type: 'uint', required: true }]);
return {
type: 'StellarPathPaymentStrictReceiveOp',
source_account: op.source,
@@ -99,7 +92,6 @@ const transformOperation = (op: StellarOperation): StellarOperationMessage | und
};
case 'pathPaymentStrictSend':
validateParams(op, [{ name: 'destMin', type: 'uint', required: true }]);
return {
type: 'StellarPathPaymentStrictSendOp',
source_account: op.source,
@@ -112,7 +104,6 @@ const transformOperation = (op: StellarOperation): StellarOperationMessage | und
};
case 'createPassiveSellOffer':
validateParams(op, [{ name: 'amount', type: 'uint', required: true }]);
return {
type: 'StellarCreatePassiveSellOfferOp',
source_account: op.source,
@@ -124,7 +115,6 @@ const transformOperation = (op: StellarOperation): StellarOperationMessage | und
};
case 'manageSellOffer':
validateParams(op, [{ name: 'amount', type: 'uint', required: true }]);
return {
type: 'StellarManageSellOfferOp',
source_account: op.source,
@@ -137,7 +127,6 @@ const transformOperation = (op: StellarOperation): StellarOperationMessage | und
};
case 'manageBuyOffer':
validateParams(op, [{ name: 'amount', type: 'uint', required: true }]);
return {
type: 'StellarManageBuyOfferOp',
source_account: op.source,
@@ -173,7 +162,6 @@ const transformOperation = (op: StellarOperation): StellarOperationMessage | und
}
case 'changeTrust':
validateParams(op, [{ name: 'limit', type: 'uint' }]);
return {
type: 'StellarChangeTrustOp',
source_account: op.source,

View File

@@ -1,11 +1,14 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/TezosGetAddress.js
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath, fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import { PROTO, ERRORS } from '../../../constants';
import { UI, createUiMessage } from '../../../events';
import { Assert } from '@trezor/schema-utils';
import { Bundle } from '../../../types';
import { GetAddress as GetAddressSchema } from '../../../types/api/getAddress';
type Params = PROTO.TezosGetAddress & {
address?: string;
@@ -31,20 +34,9 @@ export default class TezosGetAddress extends AbstractMethod<'tezosGetAddress', P
: this.payload;
// validate bundle type
validateParams(payload, [
{ name: 'bundle', type: 'array' },
{ name: 'useEventListener', type: 'boolean' },
]);
Assert(Bundle(GetAddressSchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'address', type: 'string' },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'chunkify', type: 'boolean' },
]);
const path = validatePath(batch.path, 3);
return {
address_n: path,

View File

@@ -1,11 +1,13 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/TezosGetPublicKey.js
import { AbstractMethod, MethodReturnType } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath, fromHardened, getSerializedPath } from '../../../utils/pathUtils';
import { UI, createUiMessage } from '../../../events';
import type { PROTO } from '../../../constants';
import { Assert } from '@trezor/schema-utils';
import { Bundle, GetPublicKey as GetPublicKeySchema } from '../../../types';
export default class TezosGetPublicKey extends AbstractMethod<
'tezosGetPublicKey',
@@ -29,16 +31,9 @@ export default class TezosGetPublicKey extends AbstractMethod<
: this.payload;
// validate bundle type
validateParams(payload, [{ name: 'bundle', type: 'array' }]);
Assert(Bundle(GetPublicKeySchema), payload);
this.params = payload.bundle.map(batch => {
// validate incoming parameters for each batch
validateParams(batch, [
{ name: 'path', required: true },
{ name: 'showOnTrezor', type: 'boolean' },
{ name: 'chunkify', type: 'boolean' },
]);
const path = validatePath(batch.path, 3);
return {
address_n: path,

View File

@@ -1,11 +1,13 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/TezosSignTransaction.js
import { AbstractMethod } from '../../../core/AbstractMethod';
import { validateParams, getFirmwareRange } from '../../common/paramsValidator';
import { getFirmwareRange } from '../../common/paramsValidator';
import { getMiscNetwork } from '../../../data/coinInfo';
import { validatePath } from '../../../utils/pathUtils';
import * as helper from '../tezosSignTx';
import type { PROTO } from '../../../constants';
import { Assert } from '@trezor/schema-utils';
import { TezosSignTransaction as TezosSignTransactionSchema } from '../../../types/api/tezos';
export default class TezosSignTransaction extends AbstractMethod<
'tezosSignTransaction',
@@ -22,11 +24,7 @@ export default class TezosSignTransaction extends AbstractMethod<
const { payload } = this;
// validate incoming parameters
validateParams(payload, [
{ name: 'path', required: true },
{ name: 'branch', type: 'string', required: true },
{ name: 'operation', required: true },
]);
Assert(TezosSignTransactionSchema, payload);
const path = validatePath(payload.path, 3);
this.params = helper.createTx(path, payload.branch, payload.operation);

View File

@@ -2,8 +2,8 @@
import * as bs58check from 'bs58check';
import { PROTO, ERRORS } from '../../constants';
import type { TezosOperation } from '../../types/api/tezos';
import { validateParams } from '../common/paramsValidator';
import { TezosOperation } from '../../types/api/tezos';
import { Assert } from '@trezor/schema-utils';
const PREFIX = {
B: new Uint8Array([1, 52]),
@@ -80,20 +80,11 @@ export const createTx = (
chunkify: typeof chunkify === 'boolean' ? chunkify : false,
};
Assert(TezosOperation, operation);
// reveal public key
if (operation.reveal) {
const { reveal } = operation;
// validate reveal parameters
validateParams(reveal, [
{ name: 'source', type: 'string', required: true },
{ name: 'public_key', type: 'string', required: true },
{ name: 'fee', type: 'uint', required: true },
{ name: 'counter', type: 'number', required: true },
{ name: 'gas_limit', type: 'number', required: true },
{ name: 'storage_limit', type: 'number', required: true },
]);
message = {
...message,
reveal: {
@@ -110,18 +101,6 @@ export const createTx = (
// transaction
if (operation.transaction) {
const { transaction } = operation;
// validate transaction parameters
validateParams(transaction, [
{ name: 'source', type: 'string', required: true },
{ name: 'destination', type: 'string', required: true },
{ name: 'amount', type: 'uint', required: true },
{ name: 'counter', type: 'number', required: true },
{ name: 'fee', type: 'uint', required: true },
{ name: 'gas_limit', type: 'number', required: true },
{ name: 'storage_limit', type: 'number', required: true },
]);
message = {
...message,
transaction: {
@@ -151,13 +130,6 @@ export const createTx = (
if (transaction.parameters_manager) {
const { parameters_manager } = transaction;
validateParams(parameters_manager, [
{ name: 'set_delegate', type: 'string', required: false },
{ name: 'cancel_delegate', type: 'boolean', required: false },
{ name: 'transfer', type: 'object', required: false },
]);
if (parameters_manager.set_delegate) {
message = {
...message,
@@ -185,12 +157,6 @@ export const createTx = (
if (parameters_manager.transfer) {
const { transfer } = parameters_manager;
validateParams(transfer, [
{ name: 'amount', type: 'uint', required: true },
{ name: 'destination', type: 'string', required: true },
]);
message = {
...message,
transaction: {
@@ -213,18 +179,6 @@ export const createTx = (
// origination
if (operation.origination) {
const { origination } = operation;
// validate origination parameters
validateParams(origination, [
{ name: 'source', type: 'string', required: true },
{ name: 'balance', type: 'number', required: true },
{ name: 'fee', type: 'uint', required: true },
{ name: 'counter', type: 'number', required: true },
{ name: 'gas_limit', type: 'number', required: true },
{ name: 'storage_limit', type: 'number', required: true },
{ name: 'script', type: 'string', required: true },
]);
message = {
...message,
origination: {
@@ -252,17 +206,6 @@ export const createTx = (
// delegation
if (operation.delegation) {
const { delegation } = operation;
// validate delegation parameters
validateParams(delegation, [
{ name: 'source', type: 'string', required: true },
{ name: 'delegate', type: 'string', required: true },
{ name: 'fee', type: 'uint', required: true },
{ name: 'counter', type: 'number', required: true },
{ name: 'gas_limit', type: 'number', required: true },
{ name: 'storage_limit', type: 'number', required: true },
]);
message = {
...message,
delegation: {

View File

@@ -1,7 +1,9 @@
import { AbstractMethod } from '../core/AbstractMethod';
import { PROTO } from '../constants';
import { validatePath } from '../utils/pathUtils';
import { getFirmwareRange, validateParams } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import { Assert } from '@trezor/schema-utils';
import { UnlockPathParams } from '../types/api/unlockPath';
export default class UnlockPath extends AbstractMethod<'unlockPath', PROTO.UnlockPath> {
init() {
@@ -11,10 +13,7 @@ export default class UnlockPath extends AbstractMethod<'unlockPath', PROTO.Unloc
const { payload } = this;
validateParams(payload, [
{ name: 'path', required: true },
{ name: 'mac', type: 'string' },
]);
Assert(UnlockPathParams, payload);
const path = validatePath(payload.path, 1);
this.params = {

View File

@@ -1,11 +1,13 @@
// origin: https://github.com/trezor/connect/blob/develop/src/js/core/methods/VerifyMessage.js
import { AbstractMethod } from '../core/AbstractMethod';
import { validateParams, getFirmwareRange } from './common/paramsValidator';
import { getFirmwareRange } from './common/paramsValidator';
import { getBitcoinNetwork } from '../data/coinInfo';
import { getLabel } from '../utils/pathUtils';
import { messageToHex } from '../utils/formatUtils';
import { PROTO, ERRORS } from '../constants';
import { VerifyMessage as VerifyMessageSchema } from '../types';
import { Assert } from '@trezor/schema-utils';
export default class VerifyMessage extends AbstractMethod<'verifyMessage', PROTO.VerifyMessage> {
init() {
@@ -14,13 +16,7 @@ export default class VerifyMessage extends AbstractMethod<'verifyMessage', PROTO
const { payload } = this;
// validate incoming parameters for each batch
validateParams(payload, [
{ name: 'address', type: 'string', required: true },
{ name: 'signature', type: 'string', required: true },
{ name: 'message', type: 'string', required: true },
{ name: 'coin', type: 'string', required: true },
{ name: 'hex', type: 'boolean' },
]);
Assert(VerifyMessageSchema, payload);
const coinInfo = getBitcoinNetwork(payload.coin);
if (!coinInfo) {

View File

@@ -1,3 +1,4 @@
import { Type, Static } from '@trezor/schema-utils';
// constants from https://nemproject.github.io/
export enum Networks {
@@ -6,6 +7,9 @@ export enum Networks {
mijin = 0x60,
}
export type EnumNetworks = Static<typeof EnumNetworks>;
export const EnumNetworks = Type.Enum(Networks);
export enum TxType {
TRANSFER = 0x0101,
COSIGNING = 0x0102,
@@ -18,8 +22,14 @@ export enum TxType {
SUPPLY_CHANGE = 0x4002,
}
export type EnumTxType = Static<typeof EnumTxType>;
export const EnumTxType = Type.Enum(TxType);
export enum TxVersion {
mainnet = Networks.mainnet << 24,
testnet = Networks.testnet << 24,
mijin = Networks.mijin << 24,
}
export type EnumTxVersion = Static<typeof EnumTxVersion>;
export const EnumTxVersion = Type.Enum(TxVersion);

View File

@@ -1,18 +1,40 @@
import { Static, Type } from '@trezor/schema-utils';
import { PROTO } from '../constants';
type CertPubKeys = {
rootPubKeys: string[];
caPubKeys: string[];
};
type CertPubKeys = Static<typeof CertPubKeys>;
const CertPubKeys = Type.Object({
rootPubKeys: Type.Array(Type.String()),
caPubKeys: Type.Array(Type.String()),
});
// NOTE: only T2B1 model is required in config, other models should be optional and undefined
type ModelPubKeys = Record<PROTO.DeviceModelInternal.T2B1, CertPubKeys & { debug?: CertPubKeys }> &
Partial<Record<Exclude<PROTO.DeviceModelInternal, 'T2B1'>, undefined>>;
type ModelPubKeys = Static<typeof ModelPubKeys>;
const ModelPubKeys = Type.Intersect([
Type.Record(
Type.Literal(PROTO.DeviceModelInternal.T2B1),
Type.Intersect([
CertPubKeys,
Type.Object({
debug: Type.Optional(CertPubKeys),
}),
]),
),
Type.Partial(
Type.Record(
Type.Exclude(Type.KeyOfEnum(PROTO.DeviceModelInternal), Type.Literal('T2B1')),
Type.Undefined(),
),
),
]);
export interface DeviceAuthenticityConfig extends ModelPubKeys {
version: number;
timestamp: string;
}
export type DeviceAuthenticityConfig = Static<typeof DeviceAuthenticityConfig>;
export const DeviceAuthenticityConfig = Type.Intersect([
ModelPubKeys,
Type.Object({
version: Type.Number(),
timestamp: Type.String(),
}),
]);
/**
* How to update this config or check Sentry "Device authenticity invalid!" error? Please read this internal description:

View File

@@ -22,7 +22,7 @@ import { initLog } from '../utils/debug';
import type { Device } from './Device';
import type { CoinInfo, BitcoinNetworkInfo, Network } from '../types';
import type { HDNodeResponse } from '../types/api/getPublicKey';
// import { Assert } from '@trezor/schema-utils';
import { Assert } from '@trezor/schema-utils';
type MessageType = Messages.MessageType;
type MessageKey = keyof MessageType;
@@ -422,7 +422,7 @@ export class DeviceCommands {
}
// Assert message type
// msg is allowed to be undefined for some calls, in that case the schema is an empty object
// Assert(Messages.MessageType.properties[type], msg ?? {});
Assert(Messages.MessageType.properties[type], msg ?? {});
const response = await this._commonCall(type, msg);
try {
assertType(response, resType);

View File

@@ -55,9 +55,9 @@ export const management = async (api: TrezorConnect) => {
fwAuto.payload.hash.toLowerCase();
}
// @ts-expect-error: cannot use both
api.firmwareUpdate({
binary: new ArrayBuffer(0),
// @ts-expect-error: cannot use both
version: [2, 2, 0],
});

View File

@@ -1,4 +1,13 @@
import type { PROTO } from '../../constants';
import { Type, Static } from '@trezor/schema-utils';
import { PROTO } from '../../constants';
import type { Params, Response } from '../params';
export declare function applySettings(params: Params<PROTO.ApplySettings>): Response<PROTO.Success>;
export type ApplySettings = Static<typeof ApplySettings>;
export const ApplySettings = Type.Composite([
PROTO.ApplySettings,
Type.Object({
passphrase_source: Type.Optional(Type.Number()),
}),
]);
export declare function applySettings(params: Params<ApplySettings>): Response<PROTO.Success>;

View File

@@ -1,10 +1,12 @@
import type { DeviceAuthenticityConfig } from '../../data/deviceAuthenticityConfig';
import { Static, Type } from '@trezor/schema-utils';
import { DeviceAuthenticityConfig } from '../../data/deviceAuthenticityConfig';
import type { Params, Response } from '../params';
export interface AuthenticateDeviceParams {
config?: DeviceAuthenticityConfig;
allowDebugKeys?: boolean;
}
export type AuthenticateDeviceParams = Static<typeof AuthenticateDeviceParams>;
export const AuthenticateDeviceParams = Type.Object({
config: Type.Optional(DeviceAuthenticityConfig),
allowDebugKeys: Type.Optional(Type.Boolean()),
});
export type AuthenticateDeviceResult =
| {

View File

@@ -1,17 +1,21 @@
import type { PROTO } from '../../constants';
import type { Params, Response, DerivationPath } from '../params';
import type { Params, Response } from '../params';
export interface AuthorizeCoinjoin {
path: DerivationPath;
coordinator: string;
maxRounds: number;
maxCoordinatorFeeRate: number;
maxFeePerKvbyte: number;
coin?: string;
scriptType?: PROTO.InternalInputScriptType;
amountUnit?: PROTO.AmountUnit;
preauthorized?: boolean;
}
import { Static, Type } from '@trezor/schema-utils';
import { DerivationPath } from '../params';
import { PROTO } from '../../constants';
export type AuthorizeCoinjoin = Static<typeof AuthorizeCoinjoin>;
export const AuthorizeCoinjoin = Type.Object({
path: DerivationPath,
coordinator: Type.String(),
maxRounds: Type.Number(),
maxCoordinatorFeeRate: Type.Number(),
maxFeePerKvbyte: Type.Number(),
coin: Type.Optional(Type.String()),
scriptType: Type.Optional(PROTO.InternalInputScriptType),
amountUnit: Type.Optional(PROTO.EnumAmountUnit),
preauthorized: Type.Optional(Type.Boolean()),
});
export declare function authorizeCoinjoin(
params: Params<AuthorizeCoinjoin>,

View File

@@ -1,40 +1,57 @@
import type { PROTO } from '../../../constants';
import type { DerivationPath } from '../../params';
import { PROTO } from '../../../constants';
import { DerivationPath } from '../../params';
import { Type, Static } from '@trezor/schema-utils';
// BinanceSDKTransaction from https://github.com/binance-chain/javascript-sdk/blob/master/src/tx/index.js
export interface BinanceSDKTransaction {
chain_id: string;
account_number?: number; // default 0
memo?: string;
sequence?: number; // default 0
source?: number; // default 0
export type BinanceSDKTransaction = Static<typeof BinanceSDKTransaction>;
export const BinanceSDKTransaction = Type.Object({
chain_id: Type.String(),
account_number: Type.Optional(Type.Number()),
memo: Type.Optional(Type.String()),
sequence: Type.Optional(Type.Number()),
source: Type.Optional(Type.Number()),
transfer: Type.Optional(PROTO.BinanceTransferMsg),
placeOrder: Type.Optional(PROTO.BinanceOrderMsg),
cancelOrder: Type.Optional(PROTO.BinanceCancelMsg),
});
transfer?: PROTO.BinanceTransferMsg;
placeOrder?: PROTO.BinanceOrderMsg;
cancelOrder?: PROTO.BinanceCancelMsg;
}
export type BinancePreparedMessage = Static<typeof BinancePreparedMessage>;
export const BinancePreparedMessage = Type.Union([
Type.Intersect([
PROTO.BinanceTransferMsg,
Type.Object({
type: Type.Literal('BinanceTransferMsg'),
}),
]),
Type.Intersect([
PROTO.BinanceOrderMsg,
Type.Object({
type: Type.Literal('BinanceOrderMsg'),
}),
]),
Type.Intersect([
PROTO.BinanceCancelMsg,
Type.Object({
type: Type.Literal('BinanceCancelMsg'),
}),
]),
]);
export type BinancePreparedMessage =
| (PROTO.BinanceTransferMsg & {
type: 'BinanceTransferMsg';
})
| (PROTO.BinanceOrderMsg & {
type: 'BinanceOrderMsg';
})
| (PROTO.BinanceCancelMsg & {
type: 'BinanceCancelMsg';
});
export type BinancePreparedTransaction = Static<typeof BinancePreparedTransaction>;
export const BinancePreparedTransaction = Type.Intersect([
BinanceSDKTransaction,
Type.Object({
messages: Type.Array(BinancePreparedMessage),
account_number: Type.Number(),
sequence: Type.Number(),
source: Type.Number(),
}),
]);
export interface BinancePreparedTransaction extends BinanceSDKTransaction {
messages: BinancePreparedMessage[];
account_number: number;
sequence: number;
source: number;
}
export interface BinanceSignTransaction {
path: DerivationPath;
transaction: BinanceSDKTransaction;
chunkify?: boolean;
}
export type BinanceSignTransaction = Static<typeof BinanceSignTransaction>;
export const BinanceSignTransaction = Type.Object({
path: DerivationPath,
transaction: BinanceSDKTransaction,
chunkify: Type.Optional(Type.Boolean()),
});

View File

@@ -2,17 +2,19 @@ import type { AccountAddresses } from '@trezor/blockchain-link';
import type { Transaction as BlockbookTransaction } from '@trezor/blockchain-link-types/lib/blockbook';
import type { PROTO } from '../../../constants';
import type { AccountTransaction } from '../../account';
import type { DerivationPath, ProtoWithDerivationPath } from '../../params';
import { DerivationPath, ProtoWithDerivationPath } from '../../params';
import { Static, Type } from '@trezor/schema-utils';
// signMessage
export interface SignMessage {
path: DerivationPath;
coin: string;
message: string;
hex?: boolean;
no_script_type?: boolean;
}
export type SignMessage = Static<typeof SignMessage>;
export const SignMessage = Type.Object({
path: DerivationPath,
coin: Type.Optional(Type.String()),
message: Type.String(),
hex: Type.Optional(Type.Boolean()),
no_script_type: Type.Optional(Type.Boolean()),
});
// signTransaction
@@ -100,10 +102,11 @@ export type SignedTransaction = {
// verifyMessage
export interface VerifyMessage {
address: string;
signature: string;
message: string;
coin: string;
hex?: boolean;
}
export type VerifyMessage = Static<typeof VerifyMessage>;
export const VerifyMessage = Type.Object({
address: Type.String(),
signature: Type.String(),
message: Type.String(),
coin: Type.String(),
hex: Type.Optional(Type.Boolean()),
});

View File

@@ -1,9 +1,11 @@
import { Static, Type } from '@trezor/schema-utils';
import type { PROTO } from '../../constants';
import type { Params, Response } from '../params';
interface CancelCoinjoinAuthorization {
preauthorized?: boolean;
}
export type CancelCoinjoinAuthorization = Static<typeof CancelCoinjoinAuthorization>;
export const CancelCoinjoinAuthorization = Type.Object({
preauthorized: Type.Optional(Type.Boolean()),
});
export declare function cancelCoinjoinAuthorization(
params: Params<CancelCoinjoinAuthorization>,

View File

@@ -1,33 +1,37 @@
import type { PROTO } from '../../../constants';
import type { GetPublicKey, PublicKey, DerivationPath } from '../../params';
import { Type, Static } from '@trezor/schema-utils';
import { PROTO } from '../../../constants';
import { GetPublicKey, PublicKey, DerivationPath } from '../../params';
// cardanoGetAddress
export interface CardanoCertificatePointer {
blockIndex: number;
txIndex: number;
certificateIndex: number;
}
export type CardanoCertificatePointer = Static<typeof CardanoCertificatePointer>;
export const CardanoCertificatePointer = Type.Object({
blockIndex: Type.Number(),
txIndex: Type.Number(),
certificateIndex: Type.Number(),
});
export interface CardanoAddressParameters {
addressType: PROTO.CardanoAddressType;
path?: DerivationPath;
stakingPath?: DerivationPath;
stakingKeyHash?: string;
certificatePointer?: CardanoCertificatePointer;
paymentScriptHash?: string;
stakingScriptHash?: string;
}
export type CardanoAddressParameters = Static<typeof CardanoAddressParameters>;
export const CardanoAddressParameters = Type.Object({
addressType: PROTO.EnumCardanoAddressType,
path: Type.Optional(DerivationPath),
stakingPath: Type.Optional(DerivationPath),
stakingKeyHash: Type.Optional(Type.String()),
certificatePointer: Type.Optional(CardanoCertificatePointer),
paymentScriptHash: Type.Optional(Type.String()),
stakingScriptHash: Type.Optional(Type.String()),
});
export interface CardanoGetAddress {
addressParameters: CardanoAddressParameters;
protocolMagic: number;
networkId: number;
address?: string;
showOnTrezor?: boolean;
derivationType?: PROTO.CardanoDerivationType;
chunkify?: boolean;
}
export type CardanoGetAddress = Static<typeof CardanoGetAddress>;
export const CardanoGetAddress = Type.Object({
addressParameters: CardanoAddressParameters,
protocolMagic: Type.Number(),
networkId: Type.Number(),
address: Type.Optional(Type.String()),
showOnTrezor: Type.Optional(Type.Boolean()),
derivationType: Type.Optional(PROTO.EnumCardanoDerivationType),
chunkify: Type.Optional(Type.Boolean()),
});
export interface CardanoAddress {
addressParameters: CardanoAddressParameters;
@@ -40,31 +44,40 @@ export interface CardanoAddress {
// cardanoGetNativeScriptHash
export interface CardanoNativeScript {
type: PROTO.CardanoNativeScriptType;
scripts?: CardanoNativeScript[];
keyHash?: string;
keyPath?: DerivationPath;
requiredSignaturesCount?: number;
invalidBefore?: string;
invalidHereafter?: string;
}
export type CardanoNativeScript = Static<typeof CardanoNativeScript>;
export const CardanoNativeScript = Type.Recursive(This =>
Type.Object({
type: PROTO.EnumCardanoNativeScriptType,
scripts: Type.Optional(Type.Array(This)),
keyHash: Type.Optional(Type.String()),
keyPath: Type.Optional(DerivationPath),
requiredSignaturesCount: Type.Optional(Type.Number()),
invalidBefore: Type.Optional(Type.String()),
invalidHereafter: Type.Optional(Type.String()),
}),
);
export interface CardanoGetNativeScriptHash {
script: CardanoNativeScript;
displayFormat: PROTO.CardanoNativeScriptHashDisplayFormat;
derivationType?: PROTO.CardanoDerivationType;
}
export type CardanoGetNativeScriptHash = Static<typeof CardanoGetNativeScriptHash>;
export const CardanoGetNativeScriptHash = Type.Object({
script: CardanoNativeScript,
displayFormat: PROTO.EnumCardanoNativeScriptHashDisplayFormat,
derivationType: Type.Optional(PROTO.EnumCardanoDerivationType),
});
export interface CardanoNativeScriptHash {
scriptHash: string;
}
export type CardanoNativeScriptHash = Static<typeof CardanoNativeScriptHash>;
export const CardanoNativeScriptHash = Type.Object({
scriptHash: Type.String(),
});
// cardanoGetPublicKey
export interface CardanoGetPublicKey extends GetPublicKey {
derivationType?: PROTO.CardanoDerivationType;
}
export type CardanoGetPublicKey = Static<typeof CardanoGetPublicKey>;
export const CardanoGetPublicKey = Type.Intersect([
GetPublicKey,
Type.Object({
derivationType: Type.Optional(PROTO.EnumCardanoDerivationType),
}),
]);
export interface CardanoPublicKey extends PublicKey {
node: PROTO.HDNodeType;
@@ -72,169 +85,206 @@ export interface CardanoPublicKey extends PublicKey {
// cardanoSignTransaction
export interface CardanoInput {
path?: DerivationPath;
prev_hash: string;
prev_index: number;
}
export type CardanoInput = Static<typeof CardanoInput>;
export const CardanoInput = Type.Object({
path: Type.Optional(DerivationPath),
prev_hash: Type.String(),
prev_index: Type.Number(),
});
export interface CardanoToken {
assetNameBytes: string;
amount?: string;
mintAmount?: string;
}
export type CardanoToken = Static<typeof CardanoToken>;
export const CardanoToken = Type.Object({
assetNameBytes: Type.String(),
amount: Type.Optional(Type.String()),
mintAmount: Type.Optional(Type.String()),
});
export interface CardanoAssetGroup {
policyId: string;
tokenAmounts: CardanoToken[];
}
export type CardanoAssetGroup = Static<typeof CardanoAssetGroup>;
export const CardanoAssetGroup = Type.Object({
policyId: Type.String(),
tokenAmounts: Type.Array(CardanoToken),
});
export type CardanoOutput = (
| {
addressParameters: CardanoAddressParameters;
}
| {
address: string;
}
) & {
amount: string;
tokenBundle?: CardanoAssetGroup[];
datumHash?: string;
format?: PROTO.CardanoTxOutputSerializationFormat;
inlineDatum?: string;
referenceScript?: string;
};
export type CardanoOutput = Static<typeof CardanoOutput>;
export const CardanoOutput = Type.Intersect([
Type.Union([
Type.Object({
addressParameters: CardanoAddressParameters,
}),
Type.Object({
address: Type.String(),
}),
]),
Type.Object({
amount: Type.String(),
tokenBundle: Type.Optional(Type.Array(CardanoAssetGroup)),
datumHash: Type.Optional(Type.String()),
format: Type.Optional(PROTO.EnumCardanoTxOutputSerializationFormat),
inlineDatum: Type.Optional(Type.String()),
referenceScript: Type.Optional(Type.String()),
}),
]);
export interface CardanoPoolOwner {
stakingKeyPath?: DerivationPath;
stakingKeyHash?: string;
}
export type CardanoPoolOwner = Static<typeof CardanoPoolOwner>;
export const CardanoPoolOwner = Type.Object({
stakingKeyPath: Type.Optional(DerivationPath),
stakingKeyHash: Type.Optional(Type.String()),
});
export interface CardanoPoolRelay {
type: PROTO.CardanoPoolRelayType;
ipv4Address?: string;
ipv6Address?: string;
port?: number;
hostName?: string;
}
export type CardanoPoolRelay = Static<typeof CardanoPoolRelay>;
export const CardanoPoolRelay = Type.Object({
type: PROTO.EnumCardanoPoolRelayType,
ipv4Address: Type.Optional(Type.String()),
ipv6Address: Type.Optional(Type.String()),
port: Type.Optional(Type.Number()),
hostName: Type.Optional(Type.String()),
});
export interface CardanoPoolMetadata {
url: string;
hash: string;
}
export type CardanoPoolMetadata = Static<typeof CardanoPoolMetadata>;
export const CardanoPoolMetadata = Type.Object({
url: Type.String(),
hash: Type.String(),
});
export interface CardanoPoolMargin {
numerator: string;
denominator: string;
}
export type CardanoPoolMargin = Static<typeof CardanoPoolMargin>;
export const CardanoPoolMargin = Type.Object({
numerator: Type.String(),
denominator: Type.String(),
});
export interface CardanoPoolParameters {
poolId: string;
vrfKeyHash: string;
pledge: string;
cost: string;
margin: CardanoPoolMargin;
rewardAccount: string;
owners: CardanoPoolOwner[];
relays: CardanoPoolRelay[];
metadata: CardanoPoolMetadata;
}
export type CardanoPoolParameters = Static<typeof CardanoPoolParameters>;
export const CardanoPoolParameters = Type.Object({
poolId: Type.String(),
vrfKeyHash: Type.String(),
pledge: Type.String(),
cost: Type.String(),
margin: CardanoPoolMargin,
rewardAccount: Type.String(),
owners: Type.Array(CardanoPoolOwner),
relays: Type.Array(CardanoPoolRelay),
metadata: Type.Optional(CardanoPoolMetadata),
});
export interface CardanoCertificate {
type: PROTO.CardanoCertificateType;
path?: DerivationPath;
pool?: string;
poolParameters?: CardanoPoolParameters;
scriptHash?: string;
keyHash?: string;
}
export type CardanoCertificate = Static<typeof CardanoCertificate>;
export const CardanoCertificate = Type.Object({
type: PROTO.EnumCardanoCertificateType,
path: Type.Optional(DerivationPath),
pool: Type.Optional(Type.String()),
poolParameters: Type.Optional(CardanoPoolParameters),
scriptHash: Type.Optional(Type.String()),
keyHash: Type.Optional(Type.String()),
});
export interface CardanoWithdrawal {
path?: DerivationPath;
amount: string;
scriptHash?: string;
keyHash?: string;
}
export type CardanoWithdrawal = Static<typeof CardanoWithdrawal>;
export const CardanoWithdrawal = Type.Object({
path: Type.Optional(DerivationPath),
amount: Type.String(),
scriptHash: Type.Optional(Type.String()),
keyHash: Type.Optional(Type.String()),
});
export type CardanoMint = CardanoAssetGroup[];
export type CardanoMint = Static<typeof CardanoMint>;
export const CardanoMint = Type.Array(CardanoAssetGroup);
export interface CardanoCollateralInput {
path?: DerivationPath;
prev_hash: string;
prev_index: number;
}
export type CardanoCollateralInput = Static<typeof CardanoCollateralInput>;
export const CardanoCollateralInput = Type.Object({
path: Type.Optional(DerivationPath),
prev_hash: Type.String(),
prev_index: Type.Number(),
});
export interface CardanoRequiredSigner {
keyPath?: DerivationPath;
keyHash?: string;
}
export type CardanoRequiredSigner = Static<typeof CardanoRequiredSigner>;
export const CardanoRequiredSigner = Type.Object({
keyPath: Type.Optional(DerivationPath),
keyHash: Type.Optional(Type.String()),
});
export interface CardanoReferenceInput {
prev_hash: string;
prev_index: number;
}
export type CardanoReferenceInput = Static<typeof CardanoReferenceInput>;
export const CardanoReferenceInput = Type.Object({
prev_hash: Type.String(),
prev_index: Type.Number(),
});
export interface CardanoCVoteRegistrationDelegation {
votePublicKey: string;
weight: number;
}
export type CardanoCVoteRegistrationDelegation = Static<typeof CardanoCVoteRegistrationDelegation>;
export const CardanoCVoteRegistrationDelegation = Type.Object({
votePublicKey: Type.String(),
weight: Type.Number(),
});
export interface CardanoCVoteRegistrationParameters {
votePublicKey?: string;
stakingPath: DerivationPath;
paymentAddressParameters?: CardanoAddressParameters;
nonce: string;
format?: PROTO.CardanoCVoteRegistrationFormat;
delegations?: CardanoCVoteRegistrationDelegation[];
votingPurpose?: number;
paymentAddress?: string;
}
export type CardanoCVoteRegistrationParameters = Static<typeof CardanoCVoteRegistrationParameters>;
export const CardanoCVoteRegistrationParameters = Type.Object({
votePublicKey: Type.Optional(Type.String()),
stakingPath: DerivationPath,
paymentAddressParameters: Type.Optional(CardanoAddressParameters),
nonce: Type.String(),
format: Type.Optional(PROTO.EnumCardanoCVoteRegistrationFormat),
delegations: Type.Optional(Type.Array(CardanoCVoteRegistrationDelegation)),
votingPurpose: Type.Optional(Type.Number()),
paymentAddress: Type.Optional(Type.String()),
});
export interface CardanoAuxiliaryData {
hash?: string;
cVoteRegistrationParameters?: CardanoCVoteRegistrationParameters;
}
export type CardanoAuxiliaryData = Static<typeof CardanoAuxiliaryData>;
export const CardanoAuxiliaryData = Type.Object({
hash: Type.Optional(Type.String()),
cVoteRegistrationParameters: Type.Optional(CardanoCVoteRegistrationParameters),
});
export interface CardanoSignTransaction {
inputs: CardanoInput[];
outputs: CardanoOutput[];
fee: string;
ttl?: string;
certificates?: CardanoCertificate[];
withdrawals?: CardanoWithdrawal[];
validityIntervalStart?: string;
auxiliaryData?: CardanoAuxiliaryData;
mint?: CardanoMint;
scriptDataHash?: string;
collateralInputs?: CardanoCollateralInput[];
requiredSigners?: CardanoRequiredSigner[];
collateralReturn?: CardanoOutput;
totalCollateral?: string;
referenceInputs?: CardanoReferenceInput[];
additionalWitnessRequests?: DerivationPath[];
protocolMagic: number;
networkId: number;
signingMode: PROTO.CardanoTxSigningMode;
derivationType?: PROTO.CardanoDerivationType;
includeNetworkId?: boolean;
chunkify?: boolean;
}
export type CardanoSignTransaction = Static<typeof CardanoSignTransaction>;
export const CardanoSignTransaction = Type.Object({
inputs: Type.Array(CardanoInput),
outputs: Type.Array(CardanoOutput),
fee: Type.Uint(),
ttl: Type.Optional(Type.Uint()),
certificates: Type.Optional(Type.Array(CardanoCertificate)),
withdrawals: Type.Optional(Type.Array(CardanoWithdrawal)),
validityIntervalStart: Type.Optional(Type.String()),
auxiliaryData: Type.Optional(CardanoAuxiliaryData),
mint: Type.Optional(CardanoMint),
scriptDataHash: Type.Optional(Type.String()),
collateralInputs: Type.Optional(Type.Array(CardanoCollateralInput)),
requiredSigners: Type.Optional(Type.Array(CardanoRequiredSigner)),
collateralReturn: Type.Optional(CardanoOutput),
totalCollateral: Type.Optional(Type.String()),
referenceInputs: Type.Optional(Type.Array(CardanoReferenceInput)),
additionalWitnessRequests: Type.Optional(Type.Array(DerivationPath)),
protocolMagic: Type.Number(),
networkId: Type.Number(),
signingMode: PROTO.EnumCardanoTxSigningMode,
derivationType: Type.Optional(PROTO.EnumCardanoDerivationType),
includeNetworkId: Type.Optional(Type.Boolean()),
chunkify: Type.Optional(Type.Boolean()),
});
export interface CardanoSignedTxWitness {
type: PROTO.CardanoTxWitnessType;
pubKey: string;
signature: string;
chainCode?: string;
}
export type CardanoSignTransactionExtended = Static<typeof CardanoSignTransactionExtended>;
export const CardanoSignTransactionExtended = Type.Intersect([
CardanoSignTransaction,
Type.Object({
unsignedTx: Type.Object({
body: Type.String(),
hash: Type.String(),
}),
testnet: Type.Boolean(),
}),
]);
export interface CardanoAuxiliaryDataSupplement {
type: PROTO.CardanoTxAuxiliaryDataSupplementType;
auxiliaryDataHash: string;
cVoteRegistrationSignature?: string;
}
export type CardanoSignedTxWitness = Static<typeof CardanoSignedTxWitness>;
export const CardanoSignedTxWitness = Type.Object({
type: PROTO.EnumCardanoTxWitnessType,
pubKey: Type.String(),
signature: Type.String(),
chainCode: Type.Optional(Type.String()),
});
export interface CardanoSignedTxData {
hash: string;
witnesses: CardanoSignedTxWitness[];
auxiliaryDataSupplement?: CardanoAuxiliaryDataSupplement;
}
export type CardanoAuxiliaryDataSupplement = Static<typeof CardanoAuxiliaryDataSupplement>;
export const CardanoAuxiliaryDataSupplement = Type.Object({
type: PROTO.EnumCardanoTxAuxiliaryDataSupplementType,
auxiliaryDataHash: Type.String(),
cVoteRegistrationSignature: Type.Optional(Type.String()),
});
export type CardanoSignedTxData = Static<typeof CardanoSignedTxData>;
export const CardanoSignedTxData = Type.Object({
hash: Type.String(),
witnesses: Type.Array(CardanoSignedTxWitness),
auxiliaryDataSupplement: Type.Optional(CardanoAuxiliaryDataSupplement),
});

View File

@@ -1,15 +1,14 @@
import type { Params, Response } from '../params';
import type { CardanoSignTransaction, CardanoSignedTxData } from './cardano';
import type {
CardanoSignTransaction,
CardanoSignTransactionExtended,
CardanoSignedTxData,
} from './cardano';
export declare function cardanoSignTransaction(
params: Params<CardanoSignTransaction>,
params: Params<CardanoSignTransaction & { unsignedTx?: undefined; testnet?: undefined }>, // Explicitly distinguish type
): Response<CardanoSignedTxData>;
export declare function cardanoSignTransaction(
params: Params<
CardanoSignTransaction & {
unsignedTx: { body: string; hash: string };
testnet: boolean;
}
>,
params: Params<CardanoSignTransactionExtended>,
): Response<CardanoSignedTxData & { serializedTx: string }>;

View File

@@ -1,14 +1,16 @@
import type { Params, BundledParams, Response, DerivationPath } from '../params';
import { Params, BundledParams, Response, DerivationPath } from '../params';
import { Static, Type } from '@trezor/schema-utils';
export interface CipherKeyValue {
path: DerivationPath;
key: string;
value: string | Buffer;
encrypt?: boolean;
askOnEncrypt?: boolean;
askOnDecrypt?: boolean;
iv?: string | Buffer;
}
export type CipherKeyValue = Static<typeof CipherKeyValue>;
export const CipherKeyValue = Type.Object({
path: DerivationPath,
key: Type.String(),
value: Type.Union([Type.String(), Type.Buffer()]),
encrypt: Type.Optional(Type.Boolean()),
askOnEncrypt: Type.Optional(Type.Boolean()),
askOnDecrypt: Type.Optional(Type.Boolean()),
iv: Type.Optional(Type.Union([Type.String(), Type.Buffer()])),
});
export interface CipheredValue {
value: string;

View File

@@ -1,143 +1,201 @@
import type { PROTO } from '../../../constants';
import type { DerivationPath } from '../../params';
import { PROTO } from '../../../constants';
import { DerivationPath } from '../../params';
import { Type, Static } from '@trezor/schema-utils';
// eosGetPublicKey
export interface EosPublicKey {
wifPublicKey: string;
rawPublicKey: string;
path: number[];
serializedPath: string;
}
export type EosPublicKey = Static<typeof EosPublicKey>;
export const EosPublicKey = Type.Object({
wifPublicKey: Type.String(),
rawPublicKey: Type.String(),
path: Type.Array(Type.Number()),
serializedPath: Type.String(),
});
// eosSignTransaction
export interface EosTxHeader {
expiration: PROTO.UintType;
refBlockNum: number;
refBlockPrefix: number;
maxNetUsageWords: number;
maxCpuUsageMs: number;
delaySec: number;
}
export type EosTxHeader = Static<typeof EosTxHeader>;
export const EosTxHeader = Type.Object({
expiration: Type.Union([Type.Uint(), Type.String()]), // In tests expiration is a ISO date string
refBlockNum: Type.Number(),
refBlockPrefix: Type.Number(),
maxNetUsageWords: Type.Number(),
maxCpuUsageMs: Type.Number(),
delaySec: Type.Number(),
});
export interface EosAuthorization {
threshold: number;
keys: PROTO.EosAuthorizationKey[];
accounts: {
permission: PROTO.EosPermissionLevel;
weight: number;
}[];
waits: PROTO.EosAuthorizationWait[];
}
export type EosAuthorization = Static<typeof EosAuthorization>;
export const EosAuthorization = Type.Object({
threshold: Type.Number(),
keys: Type.Array(PROTO.EosAuthorizationKey),
accounts: Type.Array(
Type.Object({
permission: PROTO.EosPermissionLevel,
weight: Type.Number(),
}),
),
waits: Type.Array(PROTO.EosAuthorizationWait),
});
export interface EosTxActionCommon {
account: string;
authorization: PROTO.EosPermissionLevel[];
}
export type EosTxAction =
| (EosTxActionCommon & {
name: 'transfer';
data: {
from: string;
to: string;
quantity: string;
memo: string;
};
})
| (EosTxActionCommon & {
name: 'delegatebw';
data: {
from: string;
receiver: string;
stake_net_quantity: string;
stake_cpu_quantity: string;
transfer: boolean;
};
})
| (EosTxActionCommon & {
name: 'undelegatebw';
data: {
from: string;
receiver: string;
unstake_net_quantity: string;
unstake_cpu_quantity: string;
};
})
| (EosTxActionCommon & {
name: 'buyram';
data: {
payer: string;
receiver: string;
quant: string;
};
})
| (EosTxActionCommon & {
name: 'buyrambytes';
data: PROTO.EosActionBuyRamBytes;
})
| (EosTxActionCommon & {
name: 'sellram';
data: PROTO.EosActionSellRam;
})
| (EosTxActionCommon & {
name: 'voteproducer';
data: {
voter: string;
proxy: string;
producers: string[];
};
})
| (EosTxActionCommon & {
name: 'refund';
data: PROTO.EosActionRefund;
})
| (EosTxActionCommon & {
name: 'updateauth';
data: {
account: string;
permission: string;
parent: string;
auth: EosAuthorization;
};
})
| (EosTxActionCommon & {
name: 'deleteauth';
data: PROTO.EosActionDeleteAuth;
})
| (EosTxActionCommon & {
name: 'linkauth';
data: PROTO.EosActionLinkAuth;
})
| (EosTxActionCommon & {
name: 'unlinkauth';
data: PROTO.EosActionUnlinkAuth;
})
| (EosTxActionCommon & {
name: 'newaccount';
data: {
creator: string;
name: string;
owner: EosAuthorization;
active: EosAuthorization;
};
});
export type EosTxActionCommon = Static<typeof EosTxActionCommon>;
export const EosTxActionCommon = Type.Object({
account: Type.String(),
authorization: Type.Array(PROTO.EosPermissionLevel),
});
export type EosTxAction = Static<typeof EosTxAction>;
export const EosTxAction = Type.Union([
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('transfer'),
data: Type.Object({
from: Type.String(),
to: Type.String(),
quantity: Type.String(),
memo: Type.String(),
}),
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('delegatebw'),
data: Type.Object({
from: Type.String(),
receiver: Type.String(),
stake_net_quantity: Type.String(),
stake_cpu_quantity: Type.String(),
transfer: Type.Boolean(),
}),
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('undelegatebw'),
data: Type.Object({
from: Type.String(),
receiver: Type.String(),
unstake_net_quantity: Type.String(),
unstake_cpu_quantity: Type.String(),
}),
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('buyram'),
data: Type.Object({
payer: Type.String(),
receiver: Type.String(),
quant: Type.String(),
}),
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('buyrambytes'),
data: PROTO.EosActionBuyRamBytes,
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('sellram'),
data: PROTO.EosActionSellRam,
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('voteproducer'),
data: Type.Object({
voter: Type.String(),
proxy: Type.String(),
producers: Type.Array(Type.String()),
}),
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('refund'),
data: PROTO.EosActionRefund,
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('updateauth'),
data: Type.Object({
account: Type.String(),
permission: Type.String(),
parent: Type.String(),
auth: EosAuthorization,
}),
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('deleteauth'),
data: PROTO.EosActionDeleteAuth,
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('linkauth'),
data: PROTO.EosActionLinkAuth,
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('unlinkauth'),
data: PROTO.EosActionUnlinkAuth,
}),
]),
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.Literal('newaccount'),
data: Type.Object({
creator: Type.String(),
name: Type.String(),
owner: EosAuthorization,
active: EosAuthorization,
}),
}),
]),
]);
// | EosTxActionCommon & {
// name: string;
// data: string;
// };
export interface EosSDKTransaction {
chainId: string;
header: EosTxHeader;
actions: Array<EosTxAction | (EosTxActionCommon & { name: string; data: string })>;
// actions: EosTxAction[];
}
export type EosSDKTransaction = Static<typeof EosSDKTransaction>;
export const EosSDKTransaction = Type.Object({
chainId: Type.String(),
header: EosTxHeader,
actions: Type.Array(
Type.Union([
EosTxAction,
Type.Intersect([
EosTxActionCommon,
Type.Object({
name: Type.String(),
data: Type.String(),
}),
]),
]),
),
});
export interface EosSignTransaction {
path: DerivationPath;
transaction: EosSDKTransaction;
chunkify?: boolean;
}
export type EosSignTransaction = Static<typeof EosSignTransaction>;
export const EosSignTransaction = Type.Object({
path: DerivationPath,
transaction: EosSDKTransaction,
chunkify: Type.Optional(Type.Boolean()),
});

View File

@@ -1,70 +1,86 @@
import type { DerivationPath } from '../../params';
import { Type, Static } from '@trezor/schema-utils';
import { DerivationPath } from '../../params';
// ethereumSignMessage
export interface EthereumSignMessage {
path: DerivationPath;
message: string;
hex?: boolean;
}
export type EthereumSignMessage = Static<typeof EthereumSignMessage>;
export const EthereumSignMessage = Type.Object({
path: DerivationPath,
message: Type.String(),
hex: Type.Optional(Type.Boolean()),
});
// ethereumSignTransaction
export interface EthereumTransaction {
to: string;
value: string;
gasPrice: string;
gasLimit: string;
maxFeePerGas?: typeof undefined;
maxPriorityFeePerGas?: typeof undefined;
nonce: string;
data?: string;
chainId: number;
txType?: number;
}
export type EthereumTransaction = Static<typeof EthereumTransaction>;
export const EthereumTransaction = Type.Object({
to: Type.String(),
value: Type.String(),
gasPrice: Type.String(),
gasLimit: Type.String(),
maxFeePerGas: Type.Optional(Type.Undefined()),
maxPriorityFeePerGas: Type.Optional(Type.Undefined()),
nonce: Type.String(),
data: Type.Optional(Type.String()),
chainId: Type.Number(),
txType: Type.Optional(Type.Number()),
});
export interface EthereumAccessList {
address: string;
storageKeys: string[];
}
export type EthereumAccessList = Static<typeof EthereumAccessList>;
export const EthereumAccessList = Type.Object({
address: Type.String(),
storageKeys: Type.Array(Type.String()),
});
export interface EthereumTransactionEIP1559 {
to: string;
value: string;
gasLimit: string;
gasPrice?: typeof undefined;
nonce: string;
data?: string;
chainId: number;
maxFeePerGas: string;
maxPriorityFeePerGas: string;
accessList?: EthereumAccessList[];
}
export type EthereumTransactionEIP1559 = Static<typeof EthereumTransactionEIP1559>;
export const EthereumTransactionEIP1559 = Type.Object({
to: Type.String(),
value: Type.String(),
gasLimit: Type.String(),
gasPrice: Type.Optional(Type.Undefined()),
nonce: Type.String(),
data: Type.Optional(Type.String()),
chainId: Type.Number(),
maxFeePerGas: Type.String(),
maxPriorityFeePerGas: Type.String(),
accessList: Type.Optional(Type.Array(EthereumAccessList)),
});
export interface EthereumSignTransaction {
path: DerivationPath;
transaction: EthereumTransaction | EthereumTransactionEIP1559;
chunkify?: boolean;
}
export type EthereumSignTransaction = Static<typeof EthereumSignTransaction>;
export const EthereumSignTransaction = Type.Object({
path: DerivationPath,
transaction: Type.Union([EthereumTransaction, EthereumTransactionEIP1559]),
chunkify: Type.Optional(Type.Boolean()),
});
export interface EthereumSignedTx {
v: string;
r: string;
s: string;
serializedTx: string;
}
export type EthereumSignedTx = Static<typeof EthereumSignedTx>;
export const EthereumSignedTx = Type.Object({
v: Type.String(),
r: Type.String(),
s: Type.String(),
serializedTx: Type.String(),
});
// ethereumSignTypedData
interface EthereumSignTypedDataTypeProperty {
name: string;
type: string;
}
type EthereumSignTypedDataTypeProperty = Static<typeof EthereumSignTypedDataTypeProperty>;
const EthereumSignTypedDataTypeProperty = Type.Object({
name: Type.String(),
type: Type.String(),
});
export interface EthereumSignTypedDataTypes {
EIP712Domain: EthereumSignTypedDataTypeProperty[];
[additionalProperties: string]: EthereumSignTypedDataTypeProperty[];
}
export const EthereumSignTypedDataTypes = Type.Object(
{
EIP712Domain: Type.Array(EthereumSignTypedDataTypeProperty),
},
{
additionalProperties: Type.Array(EthereumSignTypedDataTypeProperty),
},
);
export interface EthereumSignTypedDataMessage<T extends EthereumSignTypedDataTypes> {
types: T;
@@ -74,10 +90,27 @@ export interface EthereumSignTypedDataMessage<T extends EthereumSignTypedDataTyp
version?: string;
chainId?: number | bigint;
verifyingContract?: string;
salt?: ArrayBuffer;
salt?: ArrayBuffer | string;
};
message: { [fieldName: string]: any };
}
export const EthereumSignTypedDataMessage = Type.Object({
types: EthereumSignTypedDataTypes,
primaryType: Type.String(),
domain: Type.Object({
name: Type.Optional(Type.String()),
version: Type.Optional(Type.String()),
chainId: Type.Optional(Type.Union([Type.Number(), Type.BigInt()])),
verifyingContract: Type.Optional(Type.String()),
salt: Type.Optional(Type.Union([Type.ArrayBuffer(), Type.String()])),
}),
message: Type.Object(
{},
{
additionalProperties: Type.Any(),
},
),
});
export interface EthereumSignTypedData<T extends EthereumSignTypedDataTypes> {
path: DerivationPath;
@@ -86,6 +119,13 @@ export interface EthereumSignTypedData<T extends EthereumSignTypedDataTypes> {
domain_separator_hash?: undefined;
message_hash?: undefined;
}
export const EthereumSignTypedData = Type.Object({
path: DerivationPath,
data: EthereumSignTypedDataMessage,
metamask_v4_compat: Type.Boolean(),
domain_separator_hash: Type.Optional(Type.Undefined()),
message_hash: Type.Optional(Type.Undefined()),
});
/**
* T1B1 cannot currently calculate EIP-712 hashes by itself,
@@ -101,12 +141,20 @@ export interface EthereumSignTypedHash<T extends EthereumSignTypedDataTypes> {
/** Not required for domain-only signing, when EIP712Domain is the `primaryType` */
message_hash?: string;
}
export const EthereumSignTypedHash = Type.Object({
path: DerivationPath,
data: EthereumSignTypedDataMessage,
metamask_v4_compat: Type.Boolean(),
domain_separator_hash: Type.String(),
message_hash: Type.Optional(Type.String()),
});
// ethereumVerifyMessage
export interface EthereumVerifyMessage {
address: string;
message: string;
hex?: boolean;
signature: string;
}
export type EthereumVerifyMessage = Static<typeof EthereumVerifyMessage>;
export const EthereumVerifyMessage = Type.Object({
address: Type.String(),
message: Type.String(),
hex: Type.Optional(Type.Boolean()),
signature: Type.String(),
});

View File

@@ -1,16 +1,20 @@
import type { IntermediaryVersion } from '../firmware';
import { Static, Type } from '@trezor/schema-utils';
import { IntermediaryVersion } from '../firmware';
import type { Params, Response } from '../params';
export interface FirmwareUpdateBinary {
binary: ArrayBuffer;
}
export interface FirmwareUpdate {
version: number[];
btcOnly?: boolean;
baseUrl?: string;
intermediaryVersion?: IntermediaryVersion;
}
export type FirmwareUpdate = Static<typeof FirmwareUpdate>;
export const FirmwareUpdate = Type.Union([
Type.Object({
binary: Type.Optional(Type.Undefined()),
version: Type.Array(Type.Number()),
btcOnly: Type.Optional(Type.Boolean()),
baseUrl: Type.Optional(Type.String()),
intermediaryVersion: Type.Optional(IntermediaryVersion),
}),
Type.Object({
binary: Type.ArrayBuffer(),
}),
]);
export interface FirmwareUpdateResponse {
hash: string;
@@ -20,6 +24,3 @@ export interface FirmwareUpdateResponse {
export declare function firmwareUpdate(
params: Params<FirmwareUpdate>,
): Response<FirmwareUpdateResponse>;
export declare function firmwareUpdate(
params: Params<FirmwareUpdateBinary>,
): Response<FirmwareUpdateResponse>;

View File

@@ -1,12 +1,14 @@
import type { PROTO } from '../../constants';
import type { Params, BundledParams, Response, DerivationPath } from '../params';
import { Static, Type } from '@trezor/schema-utils';
import { PROTO } from '../../constants';
import { Params, BundledParams, Response, DerivationPath } from '../params';
export interface GetAccountDescriptorParams {
path: DerivationPath;
coin: string;
derivationType?: PROTO.CardanoDerivationType;
suppressBackupWarning?: boolean;
}
export type GetAccountDescriptorParams = Static<typeof GetAccountDescriptorParams>;
export const GetAccountDescriptorParams = Type.Object({
path: DerivationPath,
coin: Type.String(),
derivationType: Type.Optional(PROTO.EnumCardanoDerivationType),
suppressBackupWarning: Type.Optional(Type.Boolean()),
});
export interface GetAccountDescriptorResponse {
descriptor: string;

View File

@@ -1,5 +1,6 @@
import type { PROTO } from '../../constants';
import type {
import { Static, Type } from '@trezor/schema-utils';
import { PROTO } from '../../constants';
import {
GetAddress as GetAddressShared,
Address as AddressShared,
Params,
@@ -7,13 +8,17 @@ import type {
Response,
} from '../params';
interface GetAddress extends GetAddressShared {
coin?: string;
crossChain?: boolean;
multisig?: PROTO.MultisigRedeemScriptType;
scriptType?: PROTO.InternalInputScriptType;
unlockPath?: PROTO.UnlockPath;
}
export type GetAddress = Static<typeof GetAddress>;
export const GetAddress = Type.Composite([
GetAddressShared,
Type.Object({
coin: Type.Optional(Type.String()),
crossChain: Type.Optional(Type.Boolean()),
multisig: Type.Optional(PROTO.MultisigRedeemScriptType),
scriptType: Type.Optional(PROTO.InternalInputScriptType),
unlockPath: Type.Optional(Type.Object({ address_n: Type.Array(Type.Number()) })),
}),
]);
type Address = AddressShared & PROTO.Address;

View File

@@ -1,12 +1,14 @@
import type { PROTO } from '../../constants';
import type { Params, BundledParams, Response, DerivationPath } from '../params';
import { Static, Type } from '@trezor/schema-utils';
import { PROTO } from '../../constants';
import { Params, BundledParams, Response, DerivationPath } from '../params';
export interface GetOwnershipId {
path: DerivationPath;
coin?: string;
multisig?: PROTO.MultisigRedeemScriptType;
scriptType?: PROTO.InternalInputScriptType;
}
export type GetOwnershipId = Static<typeof GetOwnershipId>;
export const GetOwnershipId = Type.Object({
path: DerivationPath,
coin: Type.Optional(Type.String()),
multisig: Type.Optional(PROTO.MultisigRedeemScriptType),
scriptType: Type.Optional(PROTO.InternalInputScriptType),
});
export interface OwnershipId extends PROTO.OwnershipId {
path: number[];

View File

@@ -1,16 +1,18 @@
import type { PROTO } from '../../constants';
import type { Params, BundledParams, Response, DerivationPath } from '../params';
import { Static, Type } from '@trezor/schema-utils';
import { PROTO } from '../../constants';
import { Params, BundledParams, Response, DerivationPath } from '../params';
export interface GetOwnershipProof {
path: DerivationPath;
coin?: string;
multisig?: PROTO.MultisigRedeemScriptType;
scriptType?: PROTO.InternalInputScriptType;
userConfirmation?: boolean;
ownershipIds?: string[];
commitmentData?: string;
preauthorized?: boolean;
}
export type GetOwnershipProof = Static<typeof GetOwnershipProof>;
export const GetOwnershipProof = Type.Object({
path: DerivationPath,
coin: Type.Optional(Type.String()),
multisig: Type.Optional(PROTO.MultisigRedeemScriptType),
scriptType: Type.Optional(PROTO.InternalInputScriptType),
userConfirmation: Type.Optional(Type.Boolean()),
ownershipIds: Type.Optional(Type.Array(Type.String())),
commitmentData: Type.Optional(Type.String()),
preauthorized: Type.Optional(Type.Boolean()),
});
export interface OwnershipProof extends PROTO.OwnershipProof {
path: number[];

View File

@@ -1,32 +1,33 @@
import type { PROTO } from '../../constants';
import type {
GetPublicKey as GetPublicKeyShared,
Params,
BundledParams,
Response,
} from '../params';
import { PROTO } from '../../constants';
import { GetPublicKey as GetPublicKeyShared, Params, BundledParams, Response } from '../params';
import { Type, Static } from '@trezor/schema-utils';
export interface GetPublicKey extends GetPublicKeyShared {
coin?: string;
crossChain?: boolean;
scriptType?: PROTO.InternalInputScriptType;
ignoreXpubMagic?: boolean;
ecdsaCurveName?: string;
unlockPath?: PROTO.UnlockPath;
}
export type GetPublicKey = Static<typeof GetPublicKey>;
export const GetPublicKey = Type.Intersect([
GetPublicKeyShared,
Type.Object({
coin: Type.Optional(Type.String()),
crossChain: Type.Optional(Type.Boolean()),
scriptType: Type.Optional(PROTO.InternalInputScriptType),
ignoreXpubMagic: Type.Optional(Type.Boolean()),
ecdsaCurveName: Type.Optional(Type.String()),
unlockPath: Type.Optional(PROTO.UnlockPath),
}),
]);
// PROTO.HDNodeType with camelcase fields + path
export interface HDNodeResponse {
path: number[];
serializedPath: string;
childNum: number;
xpub: string;
xpubSegwit?: string;
chainCode: string;
publicKey: string;
fingerprint: number;
depth: number;
}
export type HDNodeResponse = Static<typeof HDNodeResponse>;
export const HDNodeResponse = Type.Object({
path: Type.Array(Type.Number()),
serializedPath: Type.String(),
childNum: Type.Number(),
xpub: Type.String(),
xpubSegwit: Type.Optional(Type.String()),
chainCode: Type.String(),
publicKey: Type.String(),
fingerprint: Type.Number(),
depth: Type.Number(),
});
export declare function getPublicKey(params: Params<GetPublicKey>): Response<HDNodeResponse>;
export declare function getPublicKey(

View File

@@ -1,116 +1,172 @@
import type { PROTO, NEM } from '../../../constants';
import type { DerivationPath } from '../../params';
import { PROTO, NEM } from '../../../constants';
import { DerivationPath } from '../../params';
import { Type, Static } from '@trezor/schema-utils';
// NEM types from nem-sdk
// https://nemproject.github.io/#transferTransaction
export interface MosaicID {
namespaceId: string;
name: string;
}
export type MosaicID = Static<typeof MosaicID>;
export const MosaicID = Type.Object({
namespaceId: Type.String(),
name: Type.String(),
});
export interface MosaicDefinition {
levy?: {
type?: PROTO.NEMMosaicLevy;
fee?: number;
recipient?: string;
mosaicId?: MosaicID;
};
id: MosaicID;
description: string;
properties?: {
name: 'divisibility' | 'initialSupply' | 'supplyMutable' | 'transferable';
value: string;
}[];
}
export type MosaicDefinition = Static<typeof MosaicDefinition>;
export const MosaicDefinition = Type.Object({
levy: Type.Optional(
Type.Object({
type: Type.Optional(PROTO.EnumNEMMosaicLevy),
fee: Type.Optional(Type.Number()),
recipient: Type.Optional(Type.String()),
mosaicId: Type.Optional(MosaicID),
}),
),
id: MosaicID,
description: Type.String(),
properties: Type.Optional(
Type.Array(
Type.Object({
name: Type.Union([
Type.Literal('divisibility'),
Type.Literal('initialSupply'),
Type.Literal('supplyMutable'),
Type.Literal('transferable'),
]),
value: Type.String(),
}),
),
),
});
export interface NEMMosaic {
mosaicId: MosaicID;
quantity: number;
}
export type NEMMosaic = Static<typeof NEMMosaic>;
export const NEMMosaic = Type.Object({
mosaicId: MosaicID,
quantity: Type.Number(),
});
export interface Modification {
modificationType: PROTO.NEMModificationType;
cosignatoryAccount: string;
}
export type Modification = Static<typeof Modification>;
export const Modification = Type.Object({
modificationType: PROTO.EnumNEMModificationType,
cosignatoryAccount: Type.String(),
});
export interface Message {
payload?: string;
type?: number;
publicKey?: string; // not present in sdk
}
export type Message = Static<typeof Message>;
export const Message = Type.Object({
payload: Type.Optional(Type.String()),
type: Type.Optional(Type.Number()),
publicKey: Type.Optional(Type.String()), // not present in sdk
});
export interface TransactionCommon {
version: NEM.TxVersion;
timeStamp: number;
fee: number;
deadline: number;
signer?: string;
}
export type TransactionCommon = Static<typeof TransactionCommon>;
export const TransactionCommon = Type.Object({
version: NEM.EnumTxVersion,
timeStamp: Type.Number(),
fee: Type.Number(),
deadline: Type.Number(),
signer: Type.Optional(Type.String()),
});
export type NEMTransferTransaction = TransactionCommon & {
type: NEM.TxType.TRANSFER;
recipient: string;
amount: PROTO.UintType;
mosaics?: NEMMosaic[];
message?: Message;
};
export type NEMTransferTransaction = Static<typeof NEMTransferTransaction>;
export const NEMTransferTransaction = Type.Intersect([
TransactionCommon,
Type.Object({
type: Type.Literal(NEM.TxType.TRANSFER),
recipient: Type.String(),
amount: Type.Uint(),
mosaics: Type.Optional(Type.Array(NEMMosaic)),
message: Type.Optional(Message),
}),
]);
export type NEMImportanceTransaction = TransactionCommon & {
type: NEM.TxType.IMPORTANCE_TRANSFER;
importanceTransfer: {
mode: PROTO.NEMImportanceTransferMode;
publicKey: string;
};
};
export type NEMImportanceTransaction = Static<typeof NEMImportanceTransaction>;
export const NEMImportanceTransaction = Type.Intersect([
TransactionCommon,
Type.Object({
type: Type.Literal(NEM.TxType.IMPORTANCE_TRANSFER),
importanceTransfer: Type.Object({
mode: PROTO.EnumNEMImportanceTransferMode,
publicKey: Type.String(),
}),
}),
]);
export type NEMAggregateModificationTransaction = TransactionCommon & {
type: NEM.TxType.AGGREGATE_MODIFICATION;
modifications?: Modification[];
minCosignatories: {
relativeChange: number;
};
};
export type NEMAggregateModificationTransaction = Static<
typeof NEMAggregateModificationTransaction
>;
export const NEMAggregateModificationTransaction = Type.Intersect([
TransactionCommon,
Type.Object({
type: Type.Literal(NEM.TxType.AGGREGATE_MODIFICATION),
modifications: Type.Optional(Type.Array(Modification)),
minCosignatories: Type.Object({
relativeChange: Type.Number(),
}),
}),
]);
export type NEMProvisionNamespaceTransaction = TransactionCommon & {
type: NEM.TxType.PROVISION_NAMESPACE;
newPart: string;
parent?: string;
rentalFeeSink: string;
rentalFee: number;
};
export type NEMProvisionNamespaceTransaction = Static<typeof NEMProvisionNamespaceTransaction>;
export const NEMProvisionNamespaceTransaction = Type.Intersect([
TransactionCommon,
Type.Object({
type: Type.Literal(NEM.TxType.PROVISION_NAMESPACE),
newPart: Type.String(),
parent: Type.Optional(Type.String()),
rentalFeeSink: Type.String(),
rentalFee: Type.Number(),
}),
]);
export type NEMMosaicCreationTransaction = TransactionCommon & {
type: NEM.TxType.MOSAIC_CREATION;
mosaicDefinition: MosaicDefinition;
creationFeeSink: string;
creationFee: number;
};
export type NEMMosaicCreationTransaction = Static<typeof NEMMosaicCreationTransaction>;
export const NEMMosaicCreationTransaction = Type.Intersect([
TransactionCommon,
Type.Object({
type: Type.Literal(NEM.TxType.MOSAIC_CREATION),
mosaicDefinition: MosaicDefinition,
creationFeeSink: Type.String(),
creationFee: Type.Number(),
}),
]);
export type NEMSupplyChangeTransaction = TransactionCommon & {
type: NEM.TxType.SUPPLY_CHANGE;
mosaicId: MosaicID;
supplyType: PROTO.NEMSupplyChangeType;
delta: number;
};
export type NEMSupplyChangeTransaction = Static<typeof NEMSupplyChangeTransaction>;
export const NEMSupplyChangeTransaction = Type.Intersect([
TransactionCommon,
Type.Object({
type: Type.Literal(NEM.TxType.SUPPLY_CHANGE),
mosaicId: MosaicID,
supplyType: PROTO.EnumNEMSupplyChangeType,
delta: Type.Number(),
}),
]);
export type NEMRegularTransaction =
| NEMTransferTransaction
| NEMImportanceTransaction
| NEMAggregateModificationTransaction
| NEMProvisionNamespaceTransaction
| NEMMosaicCreationTransaction
| NEMSupplyChangeTransaction;
export type NEMRegularTransaction = Static<typeof NEMRegularTransaction>;
export const NEMRegularTransaction = Type.Union([
NEMTransferTransaction,
NEMImportanceTransaction,
NEMAggregateModificationTransaction,
NEMProvisionNamespaceTransaction,
NEMMosaicCreationTransaction,
NEMSupplyChangeTransaction,
]);
export type NEMMultisigTransaction = TransactionCommon & {
type: NEM.TxType.COSIGNING | NEM.TxType.MULTISIG | NEM.TxType.MULTISIG_SIGNATURE;
otherTrans: NEMRegularTransaction;
};
export type NEMMultisigTransaction = Static<typeof NEMMultisigTransaction>;
export const NEMMultisigTransaction = Type.Intersect([
TransactionCommon,
Type.Object({
type: Type.Union([
Type.Literal(NEM.TxType.COSIGNING),
Type.Literal(NEM.TxType.MULTISIG),
Type.Literal(NEM.TxType.MULTISIG_SIGNATURE),
]),
otherTrans: NEMRegularTransaction,
}),
]);
export type NEMTransaction = NEMRegularTransaction | NEMMultisigTransaction;
export type NEMTransaction = Static<typeof NEMTransaction>;
export const NEMTransaction = Type.Union([NEMRegularTransaction, NEMMultisigTransaction]);
export interface NEMSignTransaction {
path: DerivationPath;
transaction: NEMTransaction;
chunkify?: boolean;
}
export type NEMSignTransaction = Static<typeof NEMSignTransaction>;
export const NEMSignTransaction = Type.Object({
path: DerivationPath,
transaction: NEMTransaction,
chunkify: Type.Optional(Type.Boolean()),
});

View File

@@ -2,12 +2,14 @@
* Bitcoin, Bitcoin-like, Ethereum-like, Ripple
* Broadcasts the transaction to the selected network.
*/
import { Static, Type } from '@trezor/schema-utils';
import type { Params, Response } from '../params';
export type PushTransaction = {
tx: string;
coin: string;
};
export type PushTransaction = Static<typeof PushTransaction>;
export const PushTransaction = Type.Object({
tx: Type.String(),
coin: Type.String(),
});
// push transaction response
export interface PushedTransaction {

View File

@@ -2,11 +2,18 @@
* Ask device to initiate recovery procedure
*/
import type { PROTO } from '../../constants';
import { Static, Type } from '@trezor/schema-utils';
import { PROTO } from '../../constants';
import type { Params, Response } from '../params';
export interface RecoveryDevice extends Omit<PROTO.RecoveryDevice, 'word_count'> {
word_count?: 12 | 18 | 24;
}
export type RecoveryDevice = Static<typeof RecoveryDevice>;
export const RecoveryDevice = Type.Composite([
PROTO.RecoveryDevice,
Type.Object({
word_count: Type.Optional(
Type.Union([Type.Literal(12), Type.Literal(18), Type.Literal(24)]),
),
}),
]);
export declare function recoveryDevice(params: Params<RecoveryDevice>): Response<PROTO.Success>;

View File

@@ -5,21 +5,27 @@
* visual challenge that will be shown on the device.
*/
import { Static, Type } from '@trezor/schema-utils';
import type { Params, Response } from '../params';
export interface LoginChallenge {
challengeHidden: string;
challengeVisual: string;
callback?: undefined;
asyncChallenge?: undefined;
}
export type LoginChallenge = Static<typeof LoginChallenge>;
export const LoginChallenge = Type.Object({
challengeHidden: Type.String(),
challengeVisual: Type.String(),
asyncChallenge: Type.Optional(Type.Undefined()),
callback: Type.Optional(Type.Undefined()),
});
export interface RequestLoginAsync {
callback: () => LoginChallenge;
asyncChallenge?: boolean;
challengeHidden?: undefined;
challengeVisual?: undefined;
}
export type RequestLoginAsync = Static<typeof RequestLoginAsync>;
export const RequestLoginAsync = Type.Object({
challengeHidden: Type.Optional(Type.Undefined()),
challengeVisual: Type.Optional(Type.Undefined()),
asyncChallenge: Type.Optional(Type.Boolean()),
callback: Type.Function([], LoginChallenge),
});
export type RequestLoginSchema = Static<typeof RequestLoginSchema>;
export const RequestLoginSchema = Type.Union([RequestLoginAsync, LoginChallenge]);
export interface Login {
address: string;
@@ -27,6 +33,4 @@ export interface Login {
signature: string;
}
export declare function requestLogin(
params: Params<RequestLoginAsync | LoginChallenge>,
): Response<Login>;
export declare function requestLogin(params: Params<RequestLoginSchema>): Response<Login>;

View File

@@ -2,21 +2,16 @@
* Performs device setup and generates a new seed.
*/
import type { PROTO } from '../../constants';
import { Static, Type } from '@trezor/schema-utils';
import { PROTO } from '../../constants';
import type { Params, Response } from '../params';
export interface ResetDevice {
// TODO: unify
display_random?: boolean;
strength?: number;
passphrase_protection?: boolean;
pin_protection?: boolean;
language?: string;
label?: string;
u2f_counter?: number;
skip_backup?: boolean;
no_backup?: boolean;
backup_type?: 0 | 1;
}
export type ResetDevice = Static<typeof ResetDevice>;
export const ResetDevice = Type.Composite([
PROTO.ResetDevice,
Type.Object({
backup_type: Type.Optional(Type.Union([Type.Literal(0), Type.Literal(1)])),
}),
]);
export declare function resetDevice(params: Params<ResetDevice>): Response<PROTO.Success>;

View File

@@ -1,26 +1,31 @@
import type { DerivationPath } from '../../params';
import { DerivationPath } from '../../params';
import { Type, Static } from '@trezor/schema-utils';
export interface RipplePayment {
amount: string;
destination: string;
destinationTag?: number;
}
export type RipplePayment = Static<typeof RipplePayment>;
export const RipplePayment = Type.Object({
amount: Type.String(),
destination: Type.String(),
destinationTag: Type.Optional(Type.Number()),
});
export interface RippleTransaction {
fee: string;
flags?: number;
sequence: number;
maxLedgerVersion?: number; // Proto: "last_ledger_sequence"
payment: RipplePayment;
}
export type RippleTransaction = Static<typeof RippleTransaction>;
export const RippleTransaction = Type.Object({
fee: Type.String(),
flags: Type.Optional(Type.Number()),
sequence: Type.Number(),
maxLedgerVersion: Type.Optional(Type.Number()), // Proto: "last_ledger_sequence"
payment: RipplePayment,
});
export interface RippleSignTransaction {
path: DerivationPath;
transaction: RippleTransaction;
chunkify?: boolean;
}
export type RippleSignTransaction = Static<typeof RippleSignTransaction>;
export const RippleSignTransaction = Type.Object({
path: DerivationPath,
transaction: RippleTransaction,
chunkify: Type.Optional(Type.Boolean()),
});
export interface RippleSignedTx {
serializedTx: string;
signature: string;
}
export type RippleSignedTx = Static<typeof RippleSignedTx>;
export const RippleSignedTx = Type.Object({
serializedTx: Type.String(),
signature: Type.String(),
});

View File

@@ -1,30 +1,39 @@
import type { PublicKey } from '../../params';
import { PublicKey } from '../../params';
import { Type, Static } from '@trezor/schema-utils';
// solanaGetPublicKey
export interface SolanaPublicKey extends PublicKey {
publicKey: string;
}
export type SolanaPublicKey = Static<typeof SolanaPublicKey>;
export const SolanaPublicKey = Type.Intersect([
PublicKey,
Type.Object({
publicKey: Type.String(),
}),
]);
// solanaSignTransaction
export interface SolanaTxTokenAccountInfo {
baseAddress: string;
tokenProgram: string;
tokenMint: string;
tokenAccount: string;
}
export type SolanaTxTokenAccountInfo = Static<typeof SolanaTxTokenAccountInfo>;
export const SolanaTxTokenAccountInfo = Type.Object({
baseAddress: Type.String(),
tokenProgram: Type.String(),
tokenMint: Type.String(),
tokenAccount: Type.String(),
});
export interface SolanaTxAdditionalInfo {
tokenAccountsInfos?: SolanaTxTokenAccountInfo[];
}
export type SolanaTxAdditionalInfo = Static<typeof SolanaTxAdditionalInfo>;
export const SolanaTxAdditionalInfo = Type.Object({
tokenAccountsInfos: Type.Optional(Type.Array(SolanaTxTokenAccountInfo)),
});
export interface SolanaSignTransaction {
path: string | number[];
serializedTx: string;
additionalInfo?: SolanaTxAdditionalInfo;
}
export type SolanaSignTransaction = Static<typeof SolanaSignTransaction>;
export const SolanaSignTransaction = Type.Object({
path: Type.Union([Type.String(), Type.Array(Type.Number())]),
serializedTx: Type.String(),
additionalInfo: Type.Optional(SolanaTxAdditionalInfo),
});
export interface SolanaSignedTransaction {
signature: string;
}
export type SolanaSignedTransaction = Static<typeof SolanaSignedTransaction>;
export const SolanaSignedTransaction = Type.Object({
signature: Type.String(),
});

View File

@@ -1,223 +1,307 @@
// Stellar types from stellar-sdk
// https://github.com/stellar/js-stellar-base
import type { PROTO } from '../../../constants';
import type { DerivationPath } from '../../params';
import { PROTO } from '../../../constants';
import { DerivationPath } from '../../params';
import { Type, Static } from '@trezor/schema-utils';
export interface StellarAsset {
type: PROTO.StellarAssetType;
code?: string;
issuer?: string;
}
export type StellarAsset = Static<typeof StellarAsset>;
export const StellarAsset = Type.Object({
type: Type.Union([PROTO.EnumStellarAssetType, Type.KeyOfEnum(PROTO.StellarAssetType)]),
code: Type.Optional(Type.String()),
issuer: Type.Optional(Type.String()),
});
export interface StellarCreateAccountOperation {
type: 'createAccount'; // Proto: "StellarCreateAccountOp"
source?: string; // Proto: "source_account"
destination: string; // Proto: "new_account",
startingBalance: string; // Proto: "starting_balance"
}
export type StellarCreateAccountOperation = Static<typeof StellarCreateAccountOperation>;
export const StellarCreateAccountOperation = Type.Object({
type: Type.Literal('createAccount'), // Proto: "StellarCreateAccountOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
destination: Type.String(), // Proto: "new_account",
startingBalance: Type.String(), // Proto: "starting_balance"
});
export interface StellarPaymentOperation {
type: 'payment'; // Proto: "StellarPaymentOp"
source?: string; // Proto: "source_account"
destination: string; // Proto: "destination_account"
asset: StellarAsset; // Proto: ok
amount: string; // Proto: ok
}
export type StellarPaymentOperation = Static<typeof StellarPaymentOperation>;
export const StellarPaymentOperation = Type.Object({
type: Type.Literal('payment'), // Proto: "StellarPaymentOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
destination: Type.String(), // Proto: "destination_account"
asset: StellarAsset, // Proto: ok
amount: Type.String(), // Proto: ok
});
export interface StellarPathPaymentStrictReceiveOperation {
type: 'pathPaymentStrictReceive'; // Proto: "StellarPathPaymentStrictReceiveOp"
source?: string; // Proto: "source_account"
sendAsset: StellarAsset; // Proto: "send_asset"
sendMax: string; // Proto: "send_max"
destination: string; // Proto: "destination_account"
destAsset: StellarAsset; // Proto: "destination_asset"
destAmount: string; // Proto "destination_amount"
path?: StellarAsset[]; // Proto: "paths"
}
export type StellarPathPaymentStrictReceiveOperation = Static<
typeof StellarPathPaymentStrictReceiveOperation
>;
export const StellarPathPaymentStrictReceiveOperation = Type.Object({
type: Type.Literal('pathPaymentStrictReceive'), // Proto: "StellarPathPaymentStrictReceiveOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
sendAsset: StellarAsset, // Proto: "send_asset"
sendMax: Type.Uint(), // Proto: "send_max"
destination: Type.String(), // Proto: "destination_account"
destAsset: StellarAsset, // Proto: "destination_asset"
destAmount: Type.Uint(), // Proto "destination_amount"
path: Type.Optional(Type.Array(StellarAsset)), // Proto: "paths"
});
export interface StellarPathPaymentStrictSendOperation {
type: 'pathPaymentStrictSend'; // Proto: "StellarPathPaymentStrictSendOp"
source?: string; // Proto: "source_account"
sendAsset: StellarAsset; // Proto: "send_asset"
sendAmount: string; // Proto: "send_amount"
destination: string; // Proto: "destination_account"
destAsset: StellarAsset; // Proto: "destination_asset"
destMin: string; // Proto "destination_min"
path?: StellarAsset[]; // Proto: "paths"
}
export type StellarPathPaymentStrictSendOperation = Static<
typeof StellarPathPaymentStrictSendOperation
>;
export const StellarPathPaymentStrictSendOperation = Type.Object({
type: Type.Literal('pathPaymentStrictSend'), // Proto: "StellarPathPaymentStrictSendOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
sendAsset: StellarAsset, // Proto: "send_asset"
sendAmount: Type.Uint(), // Proto: "send_amount"
destination: Type.String(), // Proto: "destination_account"
destAsset: StellarAsset, // Proto: "destination_asset"
destMin: Type.Uint(), // Proto "destination_min"
path: Type.Optional(Type.Array(StellarAsset)), // Proto: "paths"
});
export interface StellarPassiveSellOfferOperation {
type: 'createPassiveSellOffer'; // Proto: "StellarCreatePassiveSellOfferOp"
source?: string; // Proto: "source_account"
buying: StellarAsset; // Proto: "buying_asset"
selling: StellarAsset; // Proto: "selling_asset"
amount: string; // Proto: ok
price: { n: number; d: number }; // Proto: "price_n" and "price_d"
}
export type StellarPassiveSellOfferOperation = Static<typeof StellarPassiveSellOfferOperation>;
export const StellarPassiveSellOfferOperation = Type.Object({
type: Type.Literal('createPassiveSellOffer'), // Proto: "StellarCreatePassiveSellOfferOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
buying: StellarAsset, // Proto: "buying_asset"
selling: StellarAsset, // Proto: "selling_asset"
amount: Type.Uint(), // Proto: ok
price: Type.Object({
// Proto: "price_n" and "price_d"
n: Type.Number(),
d: Type.Number(),
}),
});
export interface StellarManageSellOfferOperation {
type: 'manageSellOffer'; // Proto: "StellarManageSellOfferOp"
source?: string; // Proto: "source_account"
buying: StellarAsset; // Proto: "buying_asset"
selling: StellarAsset; // Proto: "selling_asset"
amount: string; // Proto: ok
offerId?: string; // Proto: "offer_id" // not found in stellar-sdk
price: { n: number; d: number }; // Proto: "price_n" and "price_d"
}
export type StellarManageSellOfferOperation = Static<typeof StellarManageSellOfferOperation>;
export const StellarManageSellOfferOperation = Type.Object({
type: Type.Literal('manageSellOffer'), // Proto: "StellarManageSellOfferOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
buying: StellarAsset, // Proto: "buying_asset"
selling: StellarAsset, // Proto: "selling_asset"
amount: Type.Uint(), // Proto: ok
offerId: Type.Optional(Type.Uint()), // Proto: "offer_id" // not found in stellar-sdk
price: Type.Object({
// Proto: "price_n" and "price_d"
n: Type.Number(),
d: Type.Number(),
}),
});
export interface StellarManageBuyOfferOperation {
type: 'manageBuyOffer'; // Proto: "StellarManageBuyOfferOp"
source?: string; // Proto: "source_account"
buying: StellarAsset; // Proto: "buying_asset"
selling: StellarAsset; // Proto: "selling_asset"
amount: string; // Proto: ok
offerId?: string; // Proto: "offer_id" // not found in stellar-sdk
price: { n: number; d: number }; // Proto: "price_n" and "price_d"
}
export type StellarManageBuyOfferOperation = Static<typeof StellarManageBuyOfferOperation>;
export const StellarManageBuyOfferOperation = Type.Object({
type: Type.Literal('manageBuyOffer'), // Proto: "StellarManageBuyOfferOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
buying: StellarAsset, // Proto: "buying_asset"
selling: StellarAsset, // Proto: "selling_asset"
amount: Type.Uint(), // Proto: ok
offerId: Type.Optional(Type.Uint()), // Proto: "offer_id" // not found in stellar-sdk
price: Type.Object({
// Proto: "price_n" and "price_d"
n: Type.Number(),
d: Type.Number(),
}),
});
export interface StellarSetOptionsOperation {
type: 'setOptions'; // Proto: "StellarSetOptionsOp"
source?: string; // Proto: "source_account"
signer?: {
type: PROTO.StellarSignerType;
key: string | Buffer;
weight?: number;
};
inflationDest?: string; // Proto: "inflation_destination_account"
clearFlags?: number; // Proto: "clear_flags"
setFlags?: number; // Proto: "set_flags"
masterWeight?: PROTO.UintType; // Proto: "master_weight"
lowThreshold?: PROTO.UintType; // Proto: "low_threshold"
medThreshold?: PROTO.UintType; // Proto: "medium_threshold"
highThreshold?: PROTO.UintType; // Proto: "high_threshold"
homeDomain?: string; // Proto: "home_domain"
}
export type StellarSetOptionsOperation = Static<typeof StellarSetOptionsOperation>;
export const StellarSetOptionsOperation = Type.Object({
type: Type.Literal('setOptions'), // Proto: "StellarSetOptionsOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
signer: Type.Optional(
Type.Object({
type: PROTO.EnumStellarSignerType,
key: Type.Union([Type.String(), Type.Buffer()]),
weight: Type.Optional(Type.Number()),
}),
),
inflationDest: Type.Optional(Type.String()), // Proto: "inflation_destination_account"
clearFlags: Type.Optional(Type.Number()), // Proto: "clear_flags"
setFlags: Type.Optional(Type.Number()), // Proto: "set_flags"
masterWeight: Type.Optional(Type.Uint()), // Proto: "master_weight"
lowThreshold: Type.Optional(Type.Uint()), // Proto: "low_threshold"
medThreshold: Type.Optional(Type.Uint()), // Proto: "medium_threshold"
highThreshold: Type.Optional(Type.Uint()), // Proto: "high_threshold"
homeDomain: Type.Optional(Type.String()), // Proto: "home_domain"
});
export interface StellarChangeTrustOperation {
type: 'changeTrust'; // Proto: "StellarChangeTrustOp"
source?: string; // Proto: "source_account"
line: StellarAsset; // Proto: ok
limit: string; // Proto: ok
}
export type StellarChangeTrustOperation = Static<typeof StellarChangeTrustOperation>;
export const StellarChangeTrustOperation = Type.Object({
type: Type.Literal('changeTrust'), // Proto: "StellarChangeTrustOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
line: StellarAsset, // Proto: ok
limit: Type.String(), // Proto: ok
});
export interface StellarAllowTrustOperation {
type: 'allowTrust'; // Proto: "StellarAllowTrustOp"
source?: string; // Proto: "source_account"
trustor: string; // Proto: "trusted_account"
assetCode: string; // Proto: "asset_code"
assetType: PROTO.StellarAssetType; // Proto: "asset_type"
authorize?: boolean | typeof undefined; // Proto: "is_authorized" > parse to number
}
export type StellarAllowTrustOperation = Static<typeof StellarAllowTrustOperation>;
export const StellarAllowTrustOperation = Type.Object({
type: Type.Literal('allowTrust'), // Proto: "StellarAllowTrustOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
trustor: Type.String(), // Proto: "trusted_account"
assetCode: Type.String(), // Proto: "asset_code"
assetType: PROTO.EnumStellarAssetType, // Proto: "asset_type"
authorize: Type.Optional(Type.Union([Type.Boolean(), Type.Undefined()])), // Proto: "is_authorized" > parse to number
});
export interface StellarAccountMergeOperation {
type: 'accountMerge'; // Proto: "StellarAccountMergeOp"
source?: string; // Proto: "source_account"
destination: string; // Proto: "destination_account"
}
export type StellarAccountMergeOperation = Static<typeof StellarAccountMergeOperation>;
export const StellarAccountMergeOperation = Type.Object({
type: Type.Literal('accountMerge'), // Proto: "StellarAccountMergeOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
destination: Type.String(), // Proto: "destination_account"
});
export interface StellarManageDataOperation {
type: 'manageData'; // Proto: "StellarManageDataOp"
source?: string; // Proto: "source_account"
name: string; // Proto: "key"
value?: string | Buffer; // Proto: "value"
}
export type StellarManageDataOperation = Static<typeof StellarManageDataOperation>;
export const StellarManageDataOperation = Type.Object({
type: Type.Literal('manageData'), // Proto: "StellarManageDataOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
name: Type.String(), // Proto: "key"
value: Type.Optional(Type.Union([Type.String(), Type.Buffer()])), // Proto: "value"
});
// (?) Missing in stellar API but present in Proto messages
export interface StellarBumpSequenceOperation {
type: 'bumpSequence'; // Proto: "StellarBumpSequenceOp"
source?: string; // Proto: "source_account"
bumpTo: string; // Proto: "bump_to"
}
export type StellarBumpSequenceOperation = Static<typeof StellarBumpSequenceOperation>;
export const StellarBumpSequenceOperation = Type.Object({
type: Type.Literal('bumpSequence'), // Proto: "StellarBumpSequenceOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
bumpTo: Type.Uint(), // Proto: "bump_to"
});
// (?) Missing in Proto messages, but present in Stellar API
export interface StellarInflationOperation {
type: 'inflation';
source?: string; // Proto: "source_account"
}
export type StellarInflationOperation = Static<typeof StellarInflationOperation>;
export const StellarInflationOperation = Type.Object({
type: Type.Literal('inflation'), // Proto: "StellarInflationOp"
source: Type.Optional(Type.String()), // Proto: "source_account"
});
export type StellarOperation =
| StellarCreateAccountOperation
| StellarPaymentOperation
| StellarPathPaymentStrictReceiveOperation
| StellarPathPaymentStrictSendOperation
| StellarPassiveSellOfferOperation
| StellarManageSellOfferOperation
| StellarManageBuyOfferOperation
| StellarSetOptionsOperation
| StellarChangeTrustOperation
| StellarAllowTrustOperation
| StellarAccountMergeOperation
| StellarInflationOperation
| StellarManageDataOperation
| StellarBumpSequenceOperation;
export type StellarOperation = Static<typeof StellarOperation>;
export const StellarOperation = Type.Union([
StellarCreateAccountOperation,
StellarPaymentOperation,
StellarPathPaymentStrictReceiveOperation,
StellarPathPaymentStrictSendOperation,
StellarPassiveSellOfferOperation,
StellarManageSellOfferOperation,
StellarManageBuyOfferOperation,
StellarSetOptionsOperation,
StellarChangeTrustOperation,
StellarAllowTrustOperation,
StellarAccountMergeOperation,
StellarInflationOperation,
StellarManageDataOperation,
StellarBumpSequenceOperation,
]);
export interface StellarTransaction {
source: string; // Proto: "source_account"
fee: number; // Proto: ok
sequence: PROTO.UintType; // Proto: "sequence_number"
timebounds?: {
minTime: number; // Proto: "timebounds_start"
maxTime: number; // Proto: "timebounds_end"
};
memo?: {
type: PROTO.StellarMemoType; // Proto: "memo_type"
id?: string; // Proto: "memo_id"
text?: string; // Proto: "memo_text"
hash?: string | Buffer; // Proto: "memo_hash"
};
operations: StellarOperation[]; // Proto: calculated array length > "num_operations"
}
export type StellarTransaction = Static<typeof StellarTransaction>;
export const StellarTransaction = Type.Object({
source: Type.String(), // Proto: "source_account"
fee: Type.Number(), // Proto: ok
sequence: Type.Uint(), // Proto: "sequence_number"
timebounds: Type.Optional(
Type.Object({
minTime: Type.Number(), // Proto: "timebounds_start"
maxTime: Type.Number(), // Proto: "timebounds_end"
}),
),
memo: Type.Optional(
Type.Object({
type: PROTO.EnumStellarMemoType, // Proto: "memo_type"
id: Type.Optional(Type.Uint()), // Proto: "memo_id"
text: Type.Optional(Type.String()), // Proto: "memo_text"
hash: Type.Optional(Type.Union([Type.String(), Type.Buffer()])), // Proto: "memo_hash"
}),
),
operations: Type.Array(StellarOperation), // Proto: calculated array length > "num_operations"
});
export interface StellarSignTransaction {
path: DerivationPath;
networkPassphrase: string;
transaction: StellarTransaction;
}
export type StellarSignTransaction = Static<typeof StellarSignTransaction>;
export const StellarSignTransaction = Type.Object({
path: DerivationPath,
networkPassphrase: Type.String(),
transaction: StellarTransaction,
});
export interface StellarSignedTx {
publicKey: string;
signature: string;
}
export type StellarSignedTx = Static<typeof StellarSignedTx>;
export const StellarSignedTx = Type.Object({
publicKey: Type.String(),
signature: Type.String(),
});
// NOTE: StellarOperation (stellar-sdk) transformed to type & payload from PROTO
export type StellarOperationMessage =
| ({
type: 'StellarCreateAccountOp';
} & PROTO.StellarCreateAccountOp)
| ({
type: 'StellarPaymentOp';
} & PROTO.StellarPaymentOp)
| ({
type: 'StellarPathPaymentStrictReceiveOp';
} & PROTO.StellarPathPaymentStrictReceiveOp)
| ({
type: 'StellarPathPaymentStrictSendOp';
} & PROTO.StellarPathPaymentStrictSendOp)
| ({
type: 'StellarManageSellOfferOp';
} & PROTO.StellarManageSellOfferOp)
| ({
type: 'StellarManageBuyOfferOp';
} & PROTO.StellarManageBuyOfferOp)
| ({
type: 'StellarCreatePassiveSellOfferOp';
} & PROTO.StellarCreatePassiveSellOfferOp)
| ({
type: 'StellarSetOptionsOp';
} & PROTO.StellarSetOptionsOp)
| ({
type: 'StellarChangeTrustOp';
} & PROTO.StellarChangeTrustOp)
| ({
type: 'StellarAllowTrustOp';
} & PROTO.StellarAllowTrustOp)
| ({
type: 'StellarAccountMergeOp';
} & PROTO.StellarAccountMergeOp)
| ({
type: 'StellarManageDataOp';
} & PROTO.StellarManageDataOp)
| ({
type: 'StellarBumpSequenceOp';
} & PROTO.StellarBumpSequenceOp);
export type StellarOperationMessage = Static<typeof StellarOperationMessage>;
export const StellarOperationMessage = Type.Union([
Type.Intersect([
Type.Object({
type: Type.Literal('StellarCreateAccountOp'),
}),
PROTO.StellarCreateAccountOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarPaymentOp'),
}),
PROTO.StellarPaymentOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarPathPaymentStrictReceiveOp'),
}),
PROTO.StellarPathPaymentStrictReceiveOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarPathPaymentStrictSendOp'),
}),
PROTO.StellarPathPaymentStrictSendOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarManageSellOfferOp'),
}),
PROTO.StellarManageSellOfferOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarManageBuyOfferOp'),
}),
PROTO.StellarManageBuyOfferOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarCreatePassiveSellOfferOp'),
}),
PROTO.StellarCreatePassiveSellOfferOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarSetOptionsOp'),
}),
PROTO.StellarSetOptionsOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarChangeTrustOp'),
}),
PROTO.StellarChangeTrustOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarAllowTrustOp'),
}),
PROTO.StellarAllowTrustOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarAccountMergeOp'),
}),
PROTO.StellarAccountMergeOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarManageDataOp'),
}),
PROTO.StellarManageDataOp,
]),
Type.Intersect([
Type.Object({
type: Type.Literal('StellarBumpSequenceOp'),
}),
PROTO.StellarBumpSequenceOp,
]),
]);

View File

@@ -1,67 +1,76 @@
import type { DerivationPath } from '../../params';
import { DerivationPath } from '../../params';
import { Type, Static } from '@trezor/schema-utils';
export interface TezosRevealOperation {
source: string;
fee: number;
counter: number;
gas_limit: number;
storage_limit: number;
public_key: string;
}
export type TezosRevealOperation = Static<typeof TezosRevealOperation>;
export const TezosRevealOperation = Type.Object({
source: Type.String(),
fee: Type.Number(),
counter: Type.Number(),
gas_limit: Type.Number(),
storage_limit: Type.Number(),
public_key: Type.String(),
});
export interface TezosManagerTransfer {
destination: string;
amount: number;
}
export type TezosManagerTransfer = Static<typeof TezosManagerTransfer>;
export const TezosManagerTransfer = Type.Object({
destination: Type.String(),
amount: Type.Number(),
});
export interface TezosParametersManager {
set_delegate?: string;
cancel_delegate?: boolean;
transfer?: TezosManagerTransfer;
}
export type TezosParametersManager = Static<typeof TezosParametersManager>;
export const TezosParametersManager = Type.Object({
set_delegate: Type.Optional(Type.String()),
cancel_delegate: Type.Optional(Type.Boolean()),
transfer: Type.Optional(TezosManagerTransfer),
});
export interface TezosTransactionOperation {
source: string;
destination: string;
amount: number;
counter: number;
fee: number;
gas_limit: number;
storage_limit: number;
parameters?: number[];
parameters_manager?: TezosParametersManager;
}
export type TezosTransactionOperation = Static<typeof TezosTransactionOperation>;
export const TezosTransactionOperation = Type.Object({
source: Type.String(),
destination: Type.String(),
amount: Type.Number(),
counter: Type.Number(),
fee: Type.Number(),
gas_limit: Type.Number(),
storage_limit: Type.Number(),
parameters: Type.Optional(Type.Array(Type.Number())),
parameters_manager: Type.Optional(TezosParametersManager),
});
export interface TezosOriginationOperation {
source: string;
balance: number;
delegate?: string;
script: DerivationPath;
fee: number;
counter: number;
gas_limit: number;
storage_limit: number;
}
export type TezosOriginationOperation = Static<typeof TezosOriginationOperation>;
export const TezosOriginationOperation = Type.Object({
source: Type.String(),
balance: Type.Number(),
delegate: Type.Optional(Type.String()),
script: DerivationPath,
fee: Type.Number(),
counter: Type.Number(),
gas_limit: Type.Number(),
storage_limit: Type.Number(),
});
export interface TezosDelegationOperation {
source: string;
delegate: string;
fee: number;
counter: number;
gas_limit: number;
storage_limit: number;
}
export type TezosDelegationOperation = Static<typeof TezosDelegationOperation>;
export const TezosDelegationOperation = Type.Object({
source: Type.String(),
delegate: Type.String(),
fee: Type.Number(),
counter: Type.Number(),
gas_limit: Type.Number(),
storage_limit: Type.Number(),
});
export interface TezosOperation {
reveal?: TezosRevealOperation;
transaction?: TezosTransactionOperation;
origination?: TezosOriginationOperation;
delegation?: TezosDelegationOperation;
}
export type TezosOperation = Static<typeof TezosOperation>;
export const TezosOperation = Type.Object({
reveal: Type.Optional(TezosRevealOperation),
transaction: Type.Optional(TezosTransactionOperation),
origination: Type.Optional(TezosOriginationOperation),
delegation: Type.Optional(TezosDelegationOperation),
});
export interface TezosSignTransaction {
path: DerivationPath;
branch: string;
operation: TezosOperation;
chunkify?: boolean;
}
export type TezosSignTransaction = Static<typeof TezosSignTransaction>;
export const TezosSignTransaction = Type.Object({
path: DerivationPath,
branch: Type.String(),
operation: TezosOperation,
chunkify: Type.Optional(Type.Boolean()),
});

View File

@@ -1,9 +1,11 @@
import { Static, Type } from '@trezor/schema-utils';
import { Params, Response, DerivationPath } from '../params';
import type { PROTO } from '../../constants';
import type { Params, Response, DerivationPath } from '../params';
export interface UnlockPathParams {
path: DerivationPath;
mac?: string;
}
export type UnlockPathParams = Static<typeof UnlockPathParams>;
export const UnlockPathParams = Type.Object({
path: DerivationPath,
mac: Type.Optional(Type.String()),
});
export declare function unlockPath(params: Params<UnlockPathParams>): Response<PROTO.UnlockPath>;

View File

@@ -1,67 +1,102 @@
import { Network } from '@trezor/utxo-lib';
import { Type, Static } from '@trezor/schema-utils';
import { FeeLevel } from './fees';
export type { Network } from '@trezor/utxo-lib';
// TODO: refactor in utxo-lib
// import { Network } from '@trezor/utxo-lib';
export type Bip32 = Static<typeof Bip32>;
export const Bip32 = Type.Object({
public: Type.Number(),
private: Type.Number(),
});
export interface CoinSupport {
connect: boolean;
T1B1: string | false;
T2T1: string | false;
T2B1: string | false;
}
export type Network = Static<typeof Network>;
export const Network = Type.Object({
messagePrefix: Type.String(),
bech32: Type.String(),
bip32: Bip32,
pubKeyHash: Type.Number(),
scriptHash: Type.Number(),
wif: Type.Number(),
forkId: Type.Optional(Type.Number()),
});
export interface BlockchainLink {
type: string;
url: string[];
}
export type CoinObj = Static<typeof CoinObj>;
export const CoinObj = Type.Object({
coin: Type.String(),
});
interface Common {
label: string; // Human readable format, label != name
name: string; // Trezor readable format
shortcut: string;
slip44: number;
support: CoinSupport;
decimals: number;
blockchainLink?: BlockchainLink;
blockTime: number;
minFee: number;
maxFee: number;
defaultFees: FeeLevel[];
}
export type CoinSupport = Static<typeof CoinSupport>;
export const CoinSupport = Type.Object({
connect: Type.Boolean(),
T1B1: Type.Union([Type.String(), Type.Literal(false)]),
T2T1: Type.Union([Type.String(), Type.Literal(false)]),
T2B1: Type.Union([Type.String(), Type.Literal(false)]),
});
export interface BitcoinNetworkInfo extends Common {
type: 'bitcoin';
cashAddrPrefix?: string;
curveName: string;
dustLimit: number;
forceBip143: boolean;
hashGenesisBlock: string;
maxAddressLength: number;
maxFeeSatoshiKb: number;
minAddressLength: number;
minFeeSatoshiKb: number;
segwit: boolean;
export type BlockchainLink = Static<typeof BlockchainLink>;
export const BlockchainLink = Type.Object({
type: Type.String(),
url: Type.Array(Type.String()),
});
xPubMagic: number;
xPubMagicSegwitNative?: number;
xPubMagicSegwit?: number;
taproot?: boolean;
type Common = Static<typeof Common>;
const Common = Type.Object({
label: Type.String(),
name: Type.String(),
shortcut: Type.String(),
slip44: Type.Number(),
support: CoinSupport,
decimals: Type.Number(),
blockchainLink: Type.Optional(BlockchainLink),
blockTime: Type.Number(),
minFee: Type.Number(),
maxFee: Type.Number(),
defaultFees: Type.Array(FeeLevel),
});
// custom
network: Network;
isBitcoin: boolean;
}
export type BitcoinNetworkInfo = Static<typeof BitcoinNetworkInfo>;
export const BitcoinNetworkInfo = Type.Intersect([
Common,
Type.Object({
type: Type.Literal('bitcoin'),
cashAddrPrefix: Type.Optional(Type.String()),
curveName: Type.String(),
dustLimit: Type.Number(),
forceBip143: Type.Boolean(),
hashGenesisBlock: Type.String(),
maxAddressLength: Type.Number(),
maxFeeSatoshiKb: Type.Number(),
minAddressLength: Type.Number(),
minFeeSatoshiKb: Type.Number(),
segwit: Type.Boolean(),
xPubMagic: Type.Number(),
xPubMagicSegwitNative: Type.Optional(Type.Number()),
xPubMagicSegwit: Type.Optional(Type.Number()),
taproot: Type.Optional(Type.Boolean()),
network: Network,
isBitcoin: Type.Boolean(),
}),
]);
export interface EthereumNetworkInfo extends Common {
type: 'ethereum';
chainId: number;
network?: typeof undefined;
}
export type EthereumNetworkInfo = Static<typeof EthereumNetworkInfo>;
export const EthereumNetworkInfo = Type.Intersect([
Common,
Type.Object({
type: Type.Literal('ethereum'),
chainId: Type.Number(),
network: Type.Optional(Type.Undefined()),
}),
]);
export interface MiscNetworkInfo extends Common {
type: 'misc' | 'nem';
curve: string;
network?: typeof undefined; // compatibility
}
export type MiscNetworkInfo = Static<typeof MiscNetworkInfo>;
export const MiscNetworkInfo = Type.Intersect([
Common,
Type.Object({
type: Type.Union([Type.Literal('misc'), Type.Literal('nem')]),
curve: Type.String(),
network: Type.Optional(Type.Undefined()),
}),
]);
export type CoinInfo = BitcoinNetworkInfo | EthereumNetworkInfo | MiscNetworkInfo;
export type CoinInfo = Static<typeof CoinInfo>;
export const CoinInfo = Type.Union([BitcoinNetworkInfo, EthereumNetworkInfo, MiscNetworkInfo]);

View File

@@ -1,29 +1,41 @@
export interface FeeInfo {
blockTime: number;
minFee: number;
maxFee: number;
dustLimit: number;
}
import { Type, Static } from '@trezor/schema-utils';
export interface FeeLevel {
label: 'high' | 'normal' | 'economy' | 'low' | 'custom';
feePerUnit: string;
blocks: number;
feeLimit?: string; // eth gas limit
feePerTx?: string; // fee for BlockchainEstimateFeeParams.request.specific
}
export type FeeInfo = Static<typeof FeeInfo>;
export const FeeInfo = Type.Object({
blockTime: Type.Number(),
minFee: Type.Number(),
maxFee: Type.Number(),
dustLimit: Type.Number(),
});
export type SelectFeeLevel =
| {
name: string;
fee: '0';
feePerByte?: undefined;
disabled: true;
}
| {
name: string;
fee: string;
feePerByte: string;
minutes: number;
total: string;
};
export type FeeLevel = Static<typeof FeeLevel>;
export const FeeLevel = Type.Object({
label: Type.Union([
Type.Literal('high'),
Type.Literal('normal'),
Type.Literal('economy'),
Type.Literal('low'),
Type.Literal('custom'),
]),
feePerUnit: Type.String(),
blocks: Type.Number(),
feeLimit: Type.Optional(Type.String()),
feePerTx: Type.Optional(Type.String()),
});
export type SelectFeeLevel = Static<typeof SelectFeeLevel>;
export const SelectFeeLevel = Type.Union([
Type.Object({
name: Type.String(),
fee: Type.Literal('0'),
feePerByte: Type.Optional(Type.Undefined()),
disabled: Type.Literal(true),
}),
Type.Object({
name: Type.String(),
fee: Type.String(),
feePerByte: Type.String(),
minutes: Type.Number(),
total: Type.String(),
}),
]);

View File

@@ -1,3 +1,5 @@
import { Type } from '@trezor/schema-utils';
export interface FirmwareRange {
T1B1: {
min: string;
@@ -32,6 +34,7 @@ export type FirmwareRelease = {
};
export type IntermediaryVersion = 1 | 2 | 3;
export const IntermediaryVersion = Type.Union([Type.Literal(1), Type.Literal(2), Type.Literal(3)]);
export type ReleaseInfo = {
changelog: FirmwareRelease[] | null;

View File

@@ -1,6 +1,6 @@
// API params
import { Type } from '@trezor/schema-utils';
import { Type, TSchema, Static } from '@trezor/schema-utils';
export interface CommonParams {
device?: {
@@ -23,6 +23,7 @@ export type Params<T> = CommonParams & T & { bundle?: undefined };
interface Bundle<T> {
bundle: T[];
}
export const Bundle = <T extends TSchema>(type: T) => Type.Object({ bundle: Type.Array(type) });
export type BundledParams<T> = CommonParams & Bundle<T>;
@@ -61,12 +62,14 @@ export type ProtoWithAddressN<P extends ProtoWithDerivationPath<any>> =
P extends ProtoWithDerivationPath<infer T> ? T : unknown;
// Common fields for all *.getAddress methods
export interface GetAddress {
path: DerivationPath;
address?: string;
showOnTrezor?: boolean;
chunkify?: boolean;
}
export type GetAddress = Static<typeof GetAddress>;
export const GetAddress = Type.Object({
path: DerivationPath,
address: Type.Optional(Type.String()),
showOnTrezor: Type.Optional(Type.Boolean()),
chunkify: Type.Optional(Type.Boolean()),
useEventListener: Type.Optional(Type.Boolean()),
});
export interface Address {
address: string;
@@ -75,15 +78,17 @@ export interface Address {
}
// Common fields for all *.getPublicKey methods
export interface GetPublicKey {
path: DerivationPath;
showOnTrezor?: boolean;
suppressBackupWarning?: boolean;
chunkify?: boolean;
}
export type GetPublicKey = Static<typeof GetPublicKey>;
export const GetPublicKey = Type.Object({
path: DerivationPath,
showOnTrezor: Type.Optional(Type.Boolean()),
suppressBackupWarning: Type.Optional(Type.Boolean()),
chunkify: Type.Optional(Type.Boolean()),
});
export interface PublicKey {
publicKey: string;
path: number[];
serializedPath: string;
}
export type PublicKey = Static<typeof PublicKey>;
export const PublicKey = Type.Object({
publicKey: Type.String(),
path: Type.Array(Type.Number()),
serializedPath: Type.String(),
});

View File

@@ -170,8 +170,7 @@ const TYPE_PATCH = {
'EosActionNewAccount.creator': 'string',
'EosActionNewAccount.name': 'string',
'ResetDevice.backup_type': 'string | number', // BackupType is a enum. in Features displayed as string, in resetDevice method param accepted as number
//'StellarAssetType.type': '0 | 1 | 2', // TODO: test if this is correct
'StellarAssetType.type': '"NATIVE" | "ALPHANUM4" | "ALPHANUM12"',
'StellarAsset.type': '0 | 1 | 2 | "NATIVE" | "ALPHANUM4" | "ALPHANUM12"', // StellarAssetType is a enum, accepted as both number and string
'StellarSignTx.sequence_number': UINT_TYPE,
'StellarSignTx.memo_id': UINT_TYPE,
'StellarSignTx.memo_hash': 'Buffer | string',

View File

@@ -2240,7 +2240,14 @@ export const EnumStellarAssetType = Type.Enum(StellarAssetType);
export type StellarAsset = Static<typeof StellarAsset>;
export const StellarAsset = Type.Object({
type: EnumStellarAssetType,
type: Type.Union([
Type.Literal(0),
Type.Literal(1),
Type.Literal(2),
Type.Literal('NATIVE'),
Type.Literal('ALPHANUM4'),
Type.Literal('ALPHANUM12'),
]),
code: Type.Optional(Type.String()),
issuer: Type.Optional(Type.String()),
});

Some files were not shown because too many files have changed in this diff Show More