From 2fb1bd5157803e7eae3b0ba2491426a72fa993e1 Mon Sep 17 00:00:00 2001 From: "Justin R. Evans" <330911+jurevans@users.noreply.github.com> Date: Tue, 26 Sep 2023 11:36:12 -0400 Subject: [PATCH] Update Ledger signing for multisig changes (#388) * Update Ledger signing for multisig fixes * Enable IBC now that it can be parsed --- .../extension/src/background/ledger/ledger.ts | 4 +- .../src/background/ledger/service.ts | 36 +++---- apps/extension/src/utils/index.ts | 12 +-- packages/ledger-namada/dist/common.d.ts | 4 - packages/ledger-namada/dist/common.js.map | 2 +- packages/ledger-namada/dist/config.d.ts | 5 +- packages/ledger-namada/dist/config.js | 7 +- packages/ledger-namada/dist/config.js.map | 2 +- packages/ledger-namada/dist/namadaApp.d.ts | 6 +- packages/ledger-namada/dist/namadaApp.js | 30 ++---- packages/ledger-namada/dist/namadaApp.js.map | 2 +- .../ledger-namada/dist/processResponses.d.ts | 3 +- .../ledger-namada/dist/processResponses.js | 90 +++++++---------- .../dist/processResponses.js.map | 2 +- packages/ledger-namada/dist/types.d.ts | 31 +++--- packages/ledger-namada/dist/types.js | 26 ++--- packages/ledger-namada/dist/types.js.map | 2 +- packages/shared/lib/Cargo.lock | 10 +- packages/shared/lib/Cargo.toml | 2 +- packages/shared/lib/src/sdk/mod.rs | 50 +++++----- packages/shared/lib/src/sdk/signature.rs | 98 ++++++------------- packages/types/src/tx/schema/signature.ts | 19 ++-- packages/types/src/tx/types.ts | 11 +-- 23 files changed, 188 insertions(+), 266 deletions(-) diff --git a/apps/extension/src/background/ledger/ledger.ts b/apps/extension/src/background/ledger/ledger.ts index c398e040efc..3edba389ee9 100644 --- a/apps/extension/src/background/ledger/ledger.ts +++ b/apps/extension/src/background/ledger/ledger.ts @@ -30,7 +30,7 @@ export const DEFAULT_LEDGER_BIP44_PATH = makeBip44Path(coinType, { }); export class Ledger { - constructor(public readonly namadaApp: NamadaApp | undefined = undefined) {} + constructor(public readonly namadaApp: NamadaApp | undefined = undefined) { } /** * Returns an initialized Ledger class instance with initialized Transport @@ -85,7 +85,7 @@ export class Ledger { // Return address as bech32-encoded string address: address.toString(), // Return public key as hex-encoded string - publicKey: publicKey.toString("hex"), + publicKey: publicKey.toString("hex").substring(2), }; } diff --git a/apps/extension/src/background/ledger/service.ts b/apps/extension/src/background/ledger/service.ts index a56239f1daf..3e975aa9723 100644 --- a/apps/extension/src/background/ledger/service.ts +++ b/apps/extension/src/background/ledger/service.ts @@ -87,18 +87,20 @@ export class LedgerService { bytes: string, signatures: ResponseSign ): Promise { - const { wrapperSignature, rawSignature } = signatures; + const { signature } = signatures; + + if (!signature) { + throw new Error("Signature not provided") + } try { // Serialize signatures - const rawSig = encodeSignature(rawSignature); - const wrapperSig = encodeSignature(wrapperSignature); + const sig = encodeSignature(signature); await this.sdk.submit_signed_reveal_pk( fromBase64(txMsg), fromBase64(bytes), - rawSig, - wrapperSig + sig, ); } catch (e) { console.warn(e); @@ -118,25 +120,23 @@ export class LedgerService { } const encodedTx = getEncodedTxByType(txType, txMsg); - const { wrapperSignature, rawSignature } = signatures; + const { signature } = signatures; + + if (!signature) { + throw new Error("Signature not provided!") + } // Serialize signatures - const rawSig = encodeSignature(rawSignature); - const wrapperSig = encodeSignature(wrapperSignature); + const sig = encodeSignature(signature); await this.broadcaster.startTx(msgId, txType); try { - // TODO: Remove this check once IBC Transfer is supported on Ledger! - // Disable tx submission for Ledger devices - if (txType !== TxType.IBCTransfer) { - await this.sdk.submit_signed_tx( - encodedTx, - fromBase64(bytes), - rawSig, - wrapperSig - ); - } + await this.sdk.submit_signed_tx( + encodedTx, + fromBase64(bytes), + sig, + ); // Clear pending tx if successful await this.txStore.set(msgId, null); diff --git a/apps/extension/src/utils/index.ts b/apps/extension/src/utils/index.ts index d40ec763830..26662904cb3 100644 --- a/apps/extension/src/utils/index.ts +++ b/apps/extension/src/utils/index.ts @@ -68,15 +68,15 @@ export const generateId = ( * Convert ISignature into serialized and encoded signature */ export const encodeSignature = (sig: ISignature): Uint8Array => { - const { secIndices, singlesig, sigType, multisigIndices, multisig } = sig; + const { pubkey, raw_indices, raw_signature, wrapper_indices, wrapper_signature } = sig; /* eslint-disable */ const props = { - secIndices: new Uint8Array((secIndices as any).data), - singlesig: singlesig ? new Uint8Array((singlesig as any).data) : undefined, - sigType, - multisigIndices: new Uint8Array((multisigIndices as any).data), - multisig: multisig.map((sig) => new Uint8Array((sig as any).data)) + pubkey: new Uint8Array((pubkey as any).data), + rawIndices: new Uint8Array((raw_indices as any).data), + rawSignature: new Uint8Array((raw_signature as any).data), + wrapperIndices: new Uint8Array((wrapper_indices as any).data), + wrapperSignature: new Uint8Array((wrapper_signature as any).data), }; /* eslint-enable */ diff --git a/packages/ledger-namada/dist/common.d.ts b/packages/ledger-namada/dist/common.d.ts index 82838188716..e1722002ed7 100644 --- a/packages/ledger-namada/dist/common.d.ts +++ b/packages/ledger-namada/dist/common.d.ts @@ -33,10 +33,6 @@ export declare const SIGN_VALUES_P2: { export declare const ERROR_CODE: { NoError: number; }; -export declare const enum SignatureType { - RawSignature = 0, - WrapperSignature = 1 -} export declare enum LedgerError { U2FUnknown = 1, U2FBadRequest = 2, diff --git a/packages/ledger-namada/dist/common.js.map b/packages/ledger-namada/dist/common.js.map index 762a48f9c79..52bfc592128 100644 --- a/packages/ledger-namada/dist/common.js.map +++ b/packages/ledger-namada/dist/common.js.map @@ -1 +1 @@ -{"version":3,"file":"common.js","sourceRoot":"","sources":["../src/common.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;mFAcmF;AACtE,QAAA,UAAU,GAAG,GAAG,CAAA;AAEhB,QAAA,YAAY,GAAG;IAC1B,IAAI,EAAE,IAAI;IACV,GAAG,EAAE,IAAI;IACT,IAAI,EAAE,IAAI;CACX,CAAA;AAEY,QAAA,SAAS,GAAG;IACvB,aAAa,EAAE,IAAI;IACnB,sBAAsB,EAAE,IAAI;CAC7B,CAAA;AAEY,QAAA,SAAS,GAAG;IACvB,OAAO,EAAE,IAAI;CACd,CAAA;AAED,qCAAqC;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AAC,CAAC,CAAA;IAEvC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;QAC5C,IAAI,KAAK,GAAG,CAAC,CAAA;QACb,IAAI,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,CAAA;QACxB,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;YACvB,KAAK,IAAI,QAAQ,CAAA;YACjB,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;SAC3B;QAED,MAAM,WAAW,GAAG,MAAM,CAAC,KAAK,CAAC,CAAA;QAEjC,IAAI,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE;YAC7B,MAAM,IAAI,KAAK,CAAC,kBAAkB,KAAK,6CAA6C,CAAC,CAAA;SACtF;QAED,IAAI,WAAW,IAAI,QAAQ,EAAE;YAC3B,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAA;SACzE;QAED,KAAK,IAAI,WAAW,CAAA;QAEpB,GAAG,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAA;KAC1C;IAED,OAAO,GAAG,CAAA;AACZ,CAAC;AA1CD,sCA0CC","sourcesContent":["/** ******************************************************************************\n * (c) 2018 - 2023 Zondax AG\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ******************************************************************************* */\nexport const CHUNK_SIZE = 250\n\nexport const PAYLOAD_TYPE = {\n INIT: 0x00,\n ADD: 0x01,\n LAST: 0x02,\n}\n\nexport const P1_VALUES = {\n ONLY_RETRIEVE: 0x00,\n SHOW_ADDRESS_IN_DEVICE: 0x01,\n}\n\nexport const P2_VALUES = {\n DEFAULT: 0x00,\n}\n\n// noinspection JSUnusedGlobalSymbols\nexport const SIGN_VALUES_P2 = {\n DEFAULT: 0x00,\n}\n\nexport const ERROR_CODE = {\n NoError: 0x9000,\n}\n\nexport const enum SignatureType {\n RawSignature = 0,\n WrapperSignature = 1,\n}\n\nexport enum LedgerError {\n U2FUnknown = 1,\n U2FBadRequest = 2,\n U2FConfigurationUnsupported = 3,\n U2FDeviceIneligible = 4,\n U2FTimeout = 5,\n Timeout = 14,\n NoErrors = 0x9000,\n DeviceIsBusy = 0x9001,\n ErrorDerivingKeys = 0x6802,\n ExecutionError = 0x6400,\n WrongLength = 0x6700,\n EmptyBuffer = 0x6982,\n OutputBufferTooSmall = 0x6983,\n DataIsInvalid = 0x6984,\n ConditionsNotSatisfied = 0x6985,\n TransactionRejected = 0x6986,\n BadKeyHandle = 0x6a80,\n InvalidP1P2 = 0x6b00,\n InstructionNotSupported = 0x6d00,\n AppDoesNotSeemToBeOpen = 0x6e01,\n UnknownError = 0x6f00,\n SignVerifyError = 0x6f01,\n}\n\nexport const ERROR_DESCRIPTION = {\n [LedgerError.U2FUnknown]: 'U2F: Unknown',\n [LedgerError.U2FBadRequest]: 'U2F: Bad request',\n [LedgerError.U2FConfigurationUnsupported]: 'U2F: Configuration unsupported',\n [LedgerError.U2FDeviceIneligible]: 'U2F: Device Ineligible',\n [LedgerError.U2FTimeout]: 'U2F: Timeout',\n [LedgerError.Timeout]: 'Timeout',\n [LedgerError.NoErrors]: 'No errors',\n [LedgerError.DeviceIsBusy]: 'Device is busy',\n [LedgerError.ErrorDerivingKeys]: 'Error deriving keys',\n [LedgerError.ExecutionError]: 'Execution Error',\n [LedgerError.WrongLength]: 'Wrong Length',\n [LedgerError.EmptyBuffer]: 'Empty Buffer',\n [LedgerError.OutputBufferTooSmall]: 'Output buffer too small',\n [LedgerError.DataIsInvalid]: 'Data is invalid',\n [LedgerError.ConditionsNotSatisfied]: 'Conditions not satisfied',\n [LedgerError.TransactionRejected]: 'Transaction rejected',\n [LedgerError.BadKeyHandle]: 'Bad key handle',\n [LedgerError.InvalidP1P2]: 'Invalid P1/P2',\n [LedgerError.InstructionNotSupported]: 'Instruction not supported',\n [LedgerError.AppDoesNotSeemToBeOpen]: 'App does not seem to be open',\n [LedgerError.UnknownError]: 'Unknown error',\n [LedgerError.SignVerifyError]: 'Sign/verify error',\n}\n\nexport function errorCodeToString(statusCode: LedgerError) {\n if (statusCode in ERROR_DESCRIPTION) return ERROR_DESCRIPTION[statusCode]\n return `Unknown Status Code: ${statusCode}`\n}\n\nfunction isDict(v: any) {\n return typeof v === 'object' && v !== null && !(v instanceof Array) && !(v instanceof Date)\n}\n\nexport function processErrorResponse(response: any) {\n if (response) {\n if (isDict(response)) {\n if (Object.prototype.hasOwnProperty.call(response, 'statusCode')) {\n return {\n returnCode: response.statusCode,\n errorMessage: errorCodeToString(response.statusCode),\n }\n }\n\n if (Object.prototype.hasOwnProperty.call(response, 'returnCode') && Object.prototype.hasOwnProperty.call(response, 'errorMessage')) {\n return response\n }\n }\n return {\n returnCode: 0xffff,\n errorMessage: response.toString(),\n }\n }\n\n return {\n returnCode: 0xffff,\n errorMessage: response.toString(),\n }\n}\n\nconst HARDENED = 0x80000000\nconst DEFAULT_DER_PATH_LEN = 6\nconst IDENTITY_DER_PATH_LEN = 4 // m/888'/0'/\n\nexport function serializePath(path: string) {\n if (!path.startsWith('m')) {\n throw new Error(`Path should start with \"m\" (e.g \"m/44'/5757'/5'/0/3\")`)\n }\n\n const pathArray = path.split('/')\n\n let allocSize = 0\n\n if (pathArray.length === DEFAULT_DER_PATH_LEN || pathArray.length === IDENTITY_DER_PATH_LEN) {\n allocSize = (pathArray.length - 1) * 4 + 1\n } else {\n throw new Error(`Invalid path. (e.g \"m/44'/134'/0/0/0\"`)\n }\n\n const buf = Buffer.alloc(allocSize)\n buf.writeUInt8(pathArray.length - 1, 0)\n\n for (let i = 1; i < pathArray.length; i += 1) {\n let value = 0\n let child = pathArray[i]\n if (child.endsWith(\"'\")) {\n value += HARDENED\n child = child.slice(0, -1)\n }\n\n const childNumber = Number(child)\n\n if (Number.isNaN(childNumber)) {\n throw new Error(`Invalid path : ${child} is not a number. (e.g \"m/44'/461'/5'/0/3\")`)\n }\n\n if (childNumber >= HARDENED) {\n throw new Error('Incorrect child value (bigger or equal to 0x80000000)')\n }\n\n value += childNumber\n\n buf.writeUInt32LE(value, 4 * (i - 1) + 1)\n }\n\n return buf\n}\n"]} \ No newline at end of file +{"version":3,"file":"common.js","sourceRoot":"","sources":["../src/common.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;mFAcmF;AACtE,QAAA,UAAU,GAAG,GAAG,CAAA;AAEhB,QAAA,YAAY,GAAG;IAC1B,IAAI,EAAE,IAAI;IACV,GAAG,EAAE,IAAI;IACT,IAAI,EAAE,IAAI;CACX,CAAA;AAEY,QAAA,SAAS,GAAG;IACvB,aAAa,EAAE,IAAI;IACnB,sBAAsB,EAAE,IAAI;CAC7B,CAAA;AAEY,QAAA,SAAS,GAAG;IACvB,OAAO,EAAE,IAAI;CACd,CAAA;AAED,qCAAqC;AACxB,QAAA,cAAc,GAAG;IAC5B,OAAO,EAAE,IAAI;CACd,CAAA;AAEY,QAAA,UAAU,GAAG;IACxB,OAAO,EAAE,MAAM;CAChB,CAAA;AAED,IAAY,WAuBX;AAvBD,WAAY,WAAW;IACrB,yDAAc,CAAA;IACd,+DAAiB,CAAA;IACjB,2FAA+B,CAAA;IAC/B,2EAAuB,CAAA;IACvB,yDAAc,CAAA;IACd,oDAAY,CAAA;IACZ,yDAAiB,CAAA;IACjB,iEAAqB,CAAA;IACrB,2EAA0B,CAAA;IAC1B,qEAAuB,CAAA;IACvB,+DAAoB,CAAA;IACpB,+DAAoB,CAAA;IACpB,iFAA6B,CAA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AAK,CAAC,CAAA;QAEjC,IAAI,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE;YAC7B,MAAM,IAAI,KAAK,CAAC,kBAAkB,KAAK,6CAA6C,CAAC,CAAA;SACtF;QAED,IAAI,WAAW,IAAI,QAAQ,EAAE;YAC3B,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAA;SACzE;QAED,KAAK,IAAI,WAAW,CAAA;QAEpB,GAAG,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAA;KAC1C;IAED,OAAO,GAAG,CAAA;AACZ,CAAC;AA1CD,sCA0CC","sourcesContent":["/** ******************************************************************************\n * (c) 2018 - 2023 Zondax AG\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ******************************************************************************* */\nexport const CHUNK_SIZE = 250\n\nexport const PAYLOAD_TYPE = {\n INIT: 0x00,\n ADD: 0x01,\n LAST: 0x02,\n}\n\nexport const P1_VALUES = {\n ONLY_RETRIEVE: 0x00,\n SHOW_ADDRESS_IN_DEVICE: 0x01,\n}\n\nexport const P2_VALUES = {\n DEFAULT: 0x00,\n}\n\n// noinspection JSUnusedGlobalSymbols\nexport const SIGN_VALUES_P2 = {\n DEFAULT: 0x00,\n}\n\nexport const ERROR_CODE = {\n NoError: 0x9000,\n}\n\nexport enum LedgerError {\n U2FUnknown = 1,\n U2FBadRequest = 2,\n U2FConfigurationUnsupported = 3,\n U2FDeviceIneligible = 4,\n U2FTimeout = 5,\n Timeout = 14,\n NoErrors = 0x9000,\n DeviceIsBusy = 0x9001,\n ErrorDerivingKeys = 0x6802,\n ExecutionError = 0x6400,\n WrongLength = 0x6700,\n EmptyBuffer = 0x6982,\n OutputBufferTooSmall = 0x6983,\n DataIsInvalid = 0x6984,\n ConditionsNotSatisfied = 0x6985,\n TransactionRejected = 0x6986,\n BadKeyHandle = 0x6a80,\n InvalidP1P2 = 0x6b00,\n InstructionNotSupported = 0x6d00,\n AppDoesNotSeemToBeOpen = 0x6e01,\n UnknownError = 0x6f00,\n SignVerifyError = 0x6f01,\n}\n\nexport const ERROR_DESCRIPTION = {\n [LedgerError.U2FUnknown]: 'U2F: Unknown',\n [LedgerError.U2FBadRequest]: 'U2F: Bad request',\n [LedgerError.U2FConfigurationUnsupported]: 'U2F: Configuration unsupported',\n [LedgerError.U2FDeviceIneligible]: 'U2F: Device Ineligible',\n [LedgerError.U2FTimeout]: 'U2F: Timeout',\n [LedgerError.Timeout]: 'Timeout',\n [LedgerError.NoErrors]: 'No errors',\n [LedgerError.DeviceIsBusy]: 'Device is busy',\n [LedgerError.ErrorDerivingKeys]: 'Error deriving keys',\n [LedgerError.ExecutionError]: 'Execution Error',\n [LedgerError.WrongLength]: 'Wrong Length',\n [LedgerError.EmptyBuffer]: 'Empty Buffer',\n [LedgerError.OutputBufferTooSmall]: 'Output buffer too small',\n [LedgerError.DataIsInvalid]: 'Data is invalid',\n [LedgerError.ConditionsNotSatisfied]: 'Conditions not satisfied',\n [LedgerError.TransactionRejected]: 'Transaction rejected',\n [LedgerError.BadKeyHandle]: 'Bad key handle',\n [LedgerError.InvalidP1P2]: 'Invalid P1/P2',\n [LedgerError.InstructionNotSupported]: 'Instruction not supported',\n [LedgerError.AppDoesNotSeemToBeOpen]: 'App does not seem to be open',\n [LedgerError.UnknownError]: 'Unknown error',\n [LedgerError.SignVerifyError]: 'Sign/verify error',\n}\n\nexport function errorCodeToString(statusCode: LedgerError) {\n if (statusCode in ERROR_DESCRIPTION) return ERROR_DESCRIPTION[statusCode]\n return `Unknown Status Code: ${statusCode}`\n}\n\nfunction isDict(v: any) {\n return typeof v === 'object' && v !== null && !(v instanceof Array) && !(v instanceof Date)\n}\n\nexport function processErrorResponse(response: any) {\n if (response) {\n if (isDict(response)) {\n if (Object.prototype.hasOwnProperty.call(response, 'statusCode')) {\n return {\n returnCode: response.statusCode,\n errorMessage: errorCodeToString(response.statusCode),\n }\n }\n\n if (Object.prototype.hasOwnProperty.call(response, 'returnCode') && Object.prototype.hasOwnProperty.call(response, 'errorMessage')) {\n return response\n }\n }\n return {\n returnCode: 0xffff,\n errorMessage: response.toString(),\n }\n }\n\n return {\n returnCode: 0xffff,\n errorMessage: response.toString(),\n }\n}\n\nconst HARDENED = 0x80000000\nconst DEFAULT_DER_PATH_LEN = 6\nconst IDENTITY_DER_PATH_LEN = 4 // m/888'/0'/\n\nexport function serializePath(path: string) {\n if (!path.startsWith('m')) {\n throw new Error(`Path should start with \"m\" (e.g \"m/44'/5757'/5'/0/3\")`)\n }\n\n const pathArray = path.split('/')\n\n let allocSize = 0\n\n if (pathArray.length === DEFAULT_DER_PATH_LEN || pathArray.length === IDENTITY_DER_PATH_LEN) {\n allocSize = (pathArray.length - 1) * 4 + 1\n } else {\n throw new Error(`Invalid path. (e.g \"m/44'/134'/0/0/0\"`)\n }\n\n const buf = Buffer.alloc(allocSize)\n buf.writeUInt8(pathArray.length - 1, 0)\n\n for (let i = 1; i < pathArray.length; i += 1) {\n let value = 0\n let child = pathArray[i]\n if (child.endsWith(\"'\")) {\n value += HARDENED\n child = child.slice(0, -1)\n }\n\n const childNumber = Number(child)\n\n if (Number.isNaN(childNumber)) {\n throw new Error(`Invalid path : ${child} is not a number. (e.g \"m/44'/461'/5'/0/3\")`)\n }\n\n if (childNumber >= HARDENED) {\n throw new Error('Incorrect child value (bigger or equal to 0x80000000)')\n }\n\n value += childNumber\n\n buf.writeUInt32LE(value, 4 * (i - 1) + 1)\n }\n\n return buf\n}\n"]} \ No newline at end of file diff --git a/packages/ledger-namada/dist/config.d.ts b/packages/ledger-namada/dist/config.d.ts index 5f81c2aa7b3..1d4a0b0a4e3 100644 --- a/packages/ledger-namada/dist/config.d.ts +++ b/packages/ledger-namada/dist/config.d.ts @@ -22,9 +22,8 @@ export declare const INS: { GET_IVK: number; GET_OVK: number; GET_NF: number; - GET_SIGNATURE: number; }; export declare const SALT_LEN = 8; export declare const HASH_LEN = 32; -export declare const PK_LEN_25519 = 32; -export declare const ED25519_SIGNATURE_LEN = 64; +export declare const PK_LEN_PLUS_TAG = 33; +export declare const SIG_LEN_PLUS_TAG = 65; diff --git a/packages/ledger-namada/dist/config.js b/packages/ledger-namada/dist/config.js index 3f52e80b84e..5d2e199bd5e 100644 --- a/packages/ledger-namada/dist/config.js +++ b/packages/ledger-namada/dist/config.js @@ -1,6 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.ED25519_SIGNATURE_LEN = exports.PK_LEN_25519 = exports.HASH_LEN = exports.SALT_LEN = exports.INS = exports.CLA = void 0; +exports.SIG_LEN_PLUS_TAG = exports.PK_LEN_PLUS_TAG = exports.HASH_LEN = exports.SALT_LEN = exports.INS = exports.CLA = void 0; /** ****************************************************************************** * (c) 2018 - 2022 Zondax AG * @@ -25,10 +25,9 @@ exports.INS = { GET_IVK: 0x04, GET_OVK: 0x05, GET_NF: 0x06, - GET_SIGNATURE: 0x0a, }; exports.SALT_LEN = 8; exports.HASH_LEN = 32; -exports.PK_LEN_25519 = 32; -exports.ED25519_SIGNATURE_LEN = 64; +exports.PK_LEN_PLUS_TAG = 33; +exports.SIG_LEN_PLUS_TAG = 65; //# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/packages/ledger-namada/dist/config.js.map b/packages/ledger-namada/dist/config.js.map index f97b947a423..0138e67cd2c 100644 --- a/packages/ledger-namada/dist/config.js.map +++ b/packages/ledger-namada/dist/config.js.map @@ -1 +1 @@ -{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;mFAcmF;AACtE,QAAA,GAAG,GAAG,IAAI,CAAA;AACV,QAAA,GAAG,GAAG;IACjB,WAAW,EAAE,IAAI;IACjB,cAAc,EAAE,IAAI;IACpB,IAAI,EAAE,IAAI;IAEV,gBAAgB,EAAE,IAAI;IACtB,OAAO,EAAE,IAAI;IACb,OAAO,EAAE,IAAI;IACb,MAAM,EAAE,IAAI;IAEZ,aAAa,EAAE,IAAI;CACpB,CAAA;AACY,QAAA,QAAQ,GAAG,CAAC,CAAA;AACZ,QAAA,QAAQ,GAAG,EAAE,CAAA;AACb,QAAA,YAAY,GAAG,EAAE,CAAA;AACjB,QAAA,qBAAqB,GAAG,EAAE,CAAA","sourcesContent":["/** ******************************************************************************\n * (c) 2018 - 2022 Zondax AG\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ******************************************************************************* */\nexport const CLA = 0x57\nexport const INS = {\n GET_VERSION: 0x00,\n GET_PUBLIC_KEY: 0x01,\n SIGN: 0x02,\n\n GET_MASP_ADDRESS: 0x03,\n GET_IVK: 0x04,\n GET_OVK: 0x05,\n GET_NF: 0x06,\n\n GET_SIGNATURE: 0x0a,\n}\nexport const SALT_LEN = 8\nexport const HASH_LEN = 32\nexport const PK_LEN_25519 = 32\nexport const ED25519_SIGNATURE_LEN = 64\n"]} \ No newline at end of file +{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;mFAcmF;AACtE,QAAA,GAAG,GAAG,IAAI,CAAA;AACV,QAAA,GAAG,GAAG;IACjB,WAAW,EAAE,IAAI;IACjB,cAAc,EAAE,IAAI;IACpB,IAAI,EAAE,IAAI;IAEV,gBAAgB,EAAE,IAAI;IACtB,OAAO,EAAE,IAAI;IACb,OAAO,EAAE,IAAI;IACb,MAAM,EAAE,IAAI;CACb,CAAA;AACY,QAAA,QAAQ,GAAG,CAAC,CAAA;AACZ,QAAA,QAAQ,GAAG,EAAE,CAAA;AACb,QAAA,eAAe,GAAG,EAAE,CAAA;AACpB,QAAA,gBAAgB,GAAG,EAAE,CAAA","sourcesContent":["/** ******************************************************************************\n * (c) 2018 - 2022 Zondax AG\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ******************************************************************************* */\nexport const CLA = 0x57\nexport const INS = {\n GET_VERSION: 0x00,\n GET_PUBLIC_KEY: 0x01,\n SIGN: 0x02,\n\n GET_MASP_ADDRESS: 0x03,\n GET_IVK: 0x04,\n GET_OVK: 0x05,\n GET_NF: 0x06,\n}\nexport const SALT_LEN = 8\nexport const HASH_LEN = 32\nexport const PK_LEN_PLUS_TAG = 33\nexport const SIG_LEN_PLUS_TAG = 65\n"]} \ No newline at end of file diff --git a/packages/ledger-namada/dist/namadaApp.d.ts b/packages/ledger-namada/dist/namadaApp.d.ts index e4b118cb259..69371ee4b32 100644 --- a/packages/ledger-namada/dist/namadaApp.d.ts +++ b/packages/ledger-namada/dist/namadaApp.d.ts @@ -16,8 +16,8 @@ ******************************************************************************* */ import Transport from '@ledgerhq/hw-transport'; import { ResponseAddress, ResponseAppInfo, ResponseBase, ResponseSign, ResponseVersion } from './types'; -import { LedgerError, SignatureType } from './common'; -export { LedgerError, SignatureType }; +import { LedgerError } from './common'; +export { LedgerError }; export * from './types'; export declare class NamadaApp { transport: Transport; @@ -28,7 +28,5 @@ export declare class NamadaApp { getAddressAndPubKey(path: string): Promise; showAddressAndPubKey(path: string): Promise; signSendChunk(chunkIdx: number, chunkNum: number, chunk: Buffer, ins: number): Promise; - getSignature(signatureType: SignatureType): Promise; - _sign(path: string, message: Buffer): Promise; sign(path: string, message: Buffer): Promise; } diff --git a/packages/ledger-namada/dist/namadaApp.js b/packages/ledger-namada/dist/namadaApp.js index 140ce528172..aaefb4a7cb0 100644 --- a/packages/ledger-namada/dist/namadaApp.js +++ b/packages/ledger-namada/dist/namadaApp.js @@ -15,7 +15,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.NamadaApp = exports.LedgerError = void 0; -const types_1 = require("./types"); const common_1 = require("./common"); Object.defineProperty(exports, "LedgerError", { enumerable: true, get: function () { return common_1.LedgerError; } }); const config_1 = require("./config"); @@ -145,18 +144,20 @@ class NamadaApp { returnCode === common_1.LedgerError.SignVerifyError) { errorMessage = `${errorMessage} : ${response.subarray(0, response.length - 2).toString('ascii')}`; } + if (returnCode === common_1.LedgerError.NoErrors && response.length > 2) { + return { + signature: (0, processResponses_1.getSignatureResponse)(response), + returnCode, + errorMessage, + }; + } return { returnCode: returnCode, errorMessage: errorMessage, }; }, common_1.processErrorResponse); } - async getSignature(signatureType) { - return this.transport - .send(config_1.CLA, config_1.INS.GET_SIGNATURE, common_1.P1_VALUES.ONLY_RETRIEVE, signatureType, Buffer.from([]), [common_1.LedgerError.NoErrors]) - .then((response) => { return (0, processResponses_1.processGetSignatureResponse)(signatureType, response); }, common_1.processErrorResponse); - } - async _sign(path, message) { + async sign(path, message) { const serializedPath = (0, common_1.serializePath)(path); return this.prepareChunks(serializedPath, message).then(chunks => { return this.signSendChunk(1, chunks.length, chunks[0], config_1.INS.SIGN).then(async (response) => { @@ -174,21 +175,6 @@ class NamadaApp { }, common_1.processErrorResponse); }, common_1.processErrorResponse); } - async sign(path, message) { - const signCommand = await this._sign(path, message); - const result = { - returnCode: signCommand.returnCode, - errorMessage: signCommand.errorMessage, - wrapperSignature: new types_1.Signature(), - rawSignature: new types_1.Signature(), - }; - if (signCommand.returnCode !== common_1.LedgerError.NoErrors) { - return result; - } - result.wrapperSignature = new types_1.Signature(await this.getSignature(1 /* SignatureType.WrapperSignature */)); - result.rawSignature = new types_1.Signature(await this.getSignature(0 /* SignatureType.RawSignature */)); - return result; - } } exports.NamadaApp = NamadaApp; //# sourceMappingURL=namadaApp.js.map \ No newline at end of file diff --git a/packages/ledger-namada/dist/namadaApp.js.map b/packages/ledger-namada/dist/namadaApp.js.map index 842891e5389..39342793606 100644 --- a/packages/ledger-namada/dist/namadaApp.js.map +++ b/packages/ledger-namada/dist/namadaApp.js.map @@ -1 +1 @@ -{"version":3,"file":"namadaApp.js","sourceRoot":"","sources":["../src/namadaApp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAgBA,mCAAkH;AAElH,qCASiB;AAKR,4FAXP,oBAAW,OAWO;AAHpB,qCAAmC;AACnC,yDAAwF;AAGxF,0CAAuB;AAEvB,MAAa,SAAS;IAGpB,YAAY,SAAoB;QAC9B,IAAI,CAAC,SAAS,EAAE;YACd,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;SAClD;QAED,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;IAC5B,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,cAAsB,EAAE,OAAe;QACzD,MAAM,MAAM,GAAG,EAAE,CAAA;QAEjB,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAA;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,IAAI,mBAAU,EAAE;YACnD,IAAI,GAAG,GAAG,CAAC,GAAG,mBAAU,CAAA;YACxB,IAAI,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE;gBACtB,GAAG,GAAG,OAAO,CAAC,MAAM,CAAA;aACrB;YACD,MAAM,CAA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AAC,EAAE,YAAG,CAAC,IAAI,CAAC,CAAA;oBAC5E,IAAI,MAAM,CAAC,UAAU,KAAK,oBAAW,CAAC,QAAQ,EAAE;wBAC9C,MAAK;qBACN;iBACF;gBACD,OAAO,MAAM,CAAA;YACf,CAAC,EAAE,6BAAoB,CAAC,CAAA;QAC1B,CAAC,EAAE,6BAAoB,CAAC,CAAA;IAC1B,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,IAAY,EAAE,OAAe;QACtC,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;QAEnD,MAAM,MAAM,GAAiB;YAC3B,UAAU,EAAE,WAAW,CAAC,UAAU;YAClC,YAAY,EAAE,WAAW,CAAC,YAAY;YACtC,gBAAgB,EAAE,IAAI,iBAAS,EAAE;YACjC,YAAY,EAAE,IAAI,iBAAS,EAAE;SAC9B,CAAA;QAED,IAAI,WAAW,CAAC,UAAU,KAAK,oBAAW,CAAC,QAAQ,EAAE;YACnD,OAAO,MAAM,CAAA;SACd;QAED,MAAM,CAAC,gBAAgB,GAAG,IAAI,iBAAS,CAAC,MAAM,IAAI,CAAC,YAAY,wCAAgC,CAAC,CAAA;QAChG,MAAM,CAAC,YAAY,GAAG,IAAI,iBAAS,CAAC,MAAM,IAAI,CAAC,YAAY,oCAA4B,CAAC,CAAA;QAExF,OAAO,MAAM,CAAA;IACf,CAAC;CAyCF;AA9OD,8BA8OC","sourcesContent":["/** ******************************************************************************\n * (c) 2018 - 2022 Zondax AG\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ******************************************************************************* */\nimport Transport from '@ledgerhq/hw-transport'\nimport { ResponseAddress, ResponseAppInfo, ResponseBase, ResponseSign, ResponseVersion, Signature } from './types'\n\nimport {\n CHUNK_SIZE,\n errorCodeToString,\n LedgerError,\n P1_VALUES,\n PAYLOAD_TYPE,\n processErrorResponse,\n serializePath,\n SignatureType,\n} from './common'\n\nimport { CLA, INS } from './config'\nimport { processGetAddrResponse, processGetSignatureResponse } from './processResponses'\n\nexport { LedgerError, SignatureType }\nexport * from './types'\n\nexport class NamadaApp {\n transport: Transport\n\n constructor(transport: Transport) {\n if (!transport) {\n throw new Error('Transport has not been defined')\n }\n\n this.transport = transport\n }\n\n async prepareChunks(serializedPath: Buffer, message: Buffer) {\n const chunks = []\n\n chunks.push(serializedPath)\n for (let i = 0; i < message.length; i += CHUNK_SIZE) {\n let end = i + CHUNK_SIZE\n if (i > message.length) {\n end = message.length\n }\n chunks.push(message.subarray(i, end))\n }\n\n return chunks\n }\n\n async getVersion(): Promise {\n return this.transport.send(CLA, INS.GET_VERSION, 0, 0).then((response: any) => {\n const errorCodeData = response.slice(-2)\n const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n let targetId = 0\n if (response.length >= 9) {\n /* eslint-disable no-bitwise */\n targetId = (response[5] << 24) + (response[6] << 16) + (response[7] << 8) + (response[8] << 0)\n /* eslint-enable no-bitwise */\n }\n\n return {\n returnCode: returnCode,\n errorMessage: errorCodeToString(returnCode),\n // ///\n testMode: response[0] !== 0,\n major: response[1],\n minor: response[2],\n patch: response[3],\n deviceLocked: response[4] === 1,\n targetId: targetId.toString(16),\n }\n }, processErrorResponse)\n }\n\n async getAppInfo(): Promise {\n return this.transport.send(0xb0, 0x01, 0, 0).then(response => {\n const errorCodeData = response.slice(-2)\n const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n const result: { errorMessage?: string; returnCode?: LedgerError } = {}\n\n let appName = 'err'\n let appVersion = 'err'\n let flagLen = 0\n let flagsValue = 0\n\n if (response[0] !== 1) {\n // Ledger responds with format ID 1. There is no spec for any format != 1\n result.errorMessage = 'response format ID not recognized'\n result.returnCode = LedgerError.DeviceIsBusy\n } else {\n const appNameLen = response[1]\n appName = response.slice(2, 2 + appNameLen).toString('ascii')\n let idx = 2 + appNameLen\n const appVersionLen = response[idx]\n idx += 1\n appVersion = response.slice(idx, idx + appVersionLen).toString('ascii')\n idx += appVersionLen\n const appFlagsLen = response[idx]\n idx += 1\n flagLen = appFlagsLen\n flagsValue = response[idx]\n }\n\n return {\n returnCode,\n errorMessage: errorCodeToString(returnCode),\n //\n appName,\n appVersion,\n flagLen,\n flagsValue,\n flagRecovery: (flagsValue & 1) !== 0,\n // eslint-disable-next-line no-bitwise\n flagSignedMcuCode: (flagsValue & 2) !== 0,\n // eslint-disable-next-line no-bitwise\n flagOnboarded: (flagsValue & 4) !== 0,\n // eslint-disable-next-line no-bitwise\n flagPINValidated: (flagsValue & 128) !== 0,\n }\n }, processErrorResponse)\n }\n\n async getAddressAndPubKey(path: string): Promise {\n const serializedPath = serializePath(path)\n return this.transport\n .send(CLA, INS.GET_PUBLIC_KEY, P1_VALUES.ONLY_RETRIEVE, 0, serializedPath, [LedgerError.NoErrors])\n .then(processGetAddrResponse, processErrorResponse)\n }\n\n async showAddressAndPubKey(path: string): Promise {\n const serializedPath = serializePath(path)\n return this.transport\n .send(CLA, INS.GET_PUBLIC_KEY, P1_VALUES.SHOW_ADDRESS_IN_DEVICE, 0, serializedPath, [LedgerError.NoErrors])\n .then(processGetAddrResponse, processErrorResponse)\n }\n\n async signSendChunk(chunkIdx: number, chunkNum: number, chunk: Buffer, ins: number): Promise {\n let payloadType = PAYLOAD_TYPE.ADD\n const p2 = 0\n if (chunkIdx === 1) {\n payloadType = PAYLOAD_TYPE.INIT\n }\n if (chunkIdx === chunkNum) {\n payloadType = PAYLOAD_TYPE.LAST\n }\n\n return this.transport\n .send(CLA, ins, payloadType, p2, chunk, [\n LedgerError.NoErrors,\n LedgerError.DataIsInvalid,\n LedgerError.BadKeyHandle,\n LedgerError.SignVerifyError,\n ])\n .then((response: Buffer) => {\n const errorCodeData = response.subarray(-2)\n const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n let errorMessage = errorCodeToString(returnCode)\n\n if (\n returnCode === LedgerError.BadKeyHandle ||\n returnCode === LedgerError.DataIsInvalid ||\n returnCode === LedgerError.SignVerifyError\n ) {\n errorMessage = `${errorMessage} : ${response.subarray(0, response.length - 2).toString('ascii')}`\n }\n\n return {\n returnCode: returnCode,\n errorMessage: errorMessage,\n } as ResponseSign\n }, processErrorResponse)\n }\n\n async getSignature(signatureType: SignatureType) {\n return this.transport\n .send(CLA, INS.GET_SIGNATURE, P1_VALUES.ONLY_RETRIEVE, signatureType, Buffer.from([]), [LedgerError.NoErrors])\n .then((response: Buffer) => {return processGetSignatureResponse(signatureType, response);}, processErrorResponse)\n }\n\n async _sign(path: string, message: Buffer) {\n const serializedPath = serializePath(path)\n\n return this.prepareChunks(serializedPath, message).then(chunks => {\n return this.signSendChunk(1, chunks.length, chunks[0], INS.SIGN).then(async response => {\n let result = {\n returnCode: response.returnCode,\n errorMessage: response.errorMessage,\n }\n\n for (let i = 1; i < chunks.length; i++) {\n result = await this.signSendChunk(1 + i, chunks.length, chunks[i], INS.SIGN)\n if (result.returnCode !== LedgerError.NoErrors) {\n break\n }\n }\n return result\n }, processErrorResponse)\n }, processErrorResponse)\n }\n\n async sign(path: string, message: Buffer) {\n const signCommand = await this._sign(path, message)\n\n const result: ResponseSign = {\n returnCode: signCommand.returnCode,\n errorMessage: signCommand.errorMessage,\n wrapperSignature: new Signature(),\n rawSignature: new Signature(),\n }\n\n if (signCommand.returnCode !== LedgerError.NoErrors) {\n return result\n }\n\n result.wrapperSignature = new Signature(await this.getSignature(SignatureType.WrapperSignature))\n result.rawSignature = new Signature(await this.getSignature(SignatureType.RawSignature))\n\n return result\n }\n\n /* Not implemented yet\n async getShieldedAddressAndPubKey(path: number, div: Buffer): Promise {\n const buf = Buffer.alloc(4);\n buf.writeUInt32LE(path, 0);\n return this.transport\n .send(CLA, INS.GET_MASP_ADDRESS, P1_VALUES.ONLY_RETRIEVE, 0, Buffer.concat([buf, div]), [LedgerError.NoErrors])\n .then(processGetShieldedAddrResponse, processErrorResponse)\n }\n\n async showShieldedAddressAndPubKey(path: number, div: Buffer): Promise {\n const buf = Buffer.alloc(4);\n buf.writeUInt32LE(path, 0);\n return this.transport\n .send(CLA, INS.GET_MASP_ADDRESS, P1_VALUES.SHOW_ADDRESS_IN_DEVICE, 0, Buffer.concat([buf, div]), [LedgerError.NoErrors])\n .then(processGetShieldedAddrResponse, processErrorResponse)\n }\n\n async getIncomingViewingKey(path: number): Promise {\n const buf = Buffer.alloc(4);\n buf.writeUInt32LE(path, 0);\n return this.transport\n .send(CLA, INS.GET_IVK, P1_VALUES.SHOW_ADDRESS_IN_DEVICE, 0, buf, [LedgerError.NoErrors])\n .then(processIncomingViewingKeyResponse, processErrorResponse)\n }\n\n async getOutgoingViewingKey(path: number): Promise {\n const buf = Buffer.alloc(4);\n buf.writeUInt32LE(path, 0);\n return this.transport\n .send(CLA, INS.GET_OVK, P1_VALUES.SHOW_ADDRESS_IN_DEVICE, 0, buf, [LedgerError.NoErrors])\n .then(processOutgoingViewingKeyResponse, processErrorResponse)\n }\n\n async getNullifier(pos: Uint8Array, cm: Buffer): Promise {\n return this.transport\n .send(CLA, INS.GET_NF, P1_VALUES.ONLY_RETRIEVE, 0, Buffer.concat([pos, cm]), [LedgerError.NoErrors])\n .then(processNullifierResponse, processErrorResponse)\n }\n */\n}\n"]} \ No newline at end of file +{"version":3,"file":"namadaApp.js","sourceRoot":"","sources":["../src/namadaApp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAkBA,qCAQiB;AAKR,4FAVP,oBAAW,OAUO;AAHpB,qCAAmC;AACnC,yDAAiF;AAGjF,0CAAuB;AAEvB,MAAa,SAAS;IAGpB,YAAY,SAAoB;QAC9B,IAAI,CAAC,SAAS,EAAE;YACd,MAAM,IAAI,KAAK,CAAC,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,CAAC,UAAU;oBAC/B,YAAY,EAAE,QAAQ,CAAC,YAAY;iBACpC,CAAA;gBAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;oBACtC,MAAM,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,YAAG,CAAC,IAAI,CAAC,CAAA;oBAC5E,IAAI,MAAM,CAAC,UAAU,KAAK,oBAAW,CAAC,QAAQ,EAAE;wBAC9C,MAAK;qBACN;iBACF;gBACD,OAAO,MAAM,CAAA;YACf,CAAC,EAAE,6BAAoB,CAAC,CAAA;QAC1B,CAAC,EAAE,6BAAoB,CAAC,CAAA;IAC1B,CAAC;CAyCF;AA5ND,8BA4NC","sourcesContent":["/** ******************************************************************************\n * (c) 2018 - 2022 Zondax AG\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ******************************************************************************* */\nimport Transport from '@ledgerhq/hw-transport'\nimport { ResponseAddress, ResponseAppInfo, ResponseBase, ResponseSign, ResponseVersion } from './types'\n\nimport {\n CHUNK_SIZE,\n errorCodeToString,\n LedgerError,\n P1_VALUES,\n PAYLOAD_TYPE,\n processErrorResponse,\n serializePath,\n} from './common'\n\nimport { CLA, INS } from './config'\nimport { getSignatureResponse, processGetAddrResponse } from './processResponses'\n\nexport { LedgerError }\nexport * from './types'\n\nexport class NamadaApp {\n transport: Transport\n\n constructor(transport: Transport) {\n if (!transport) {\n throw new Error('Transport has not been defined')\n }\n\n this.transport = transport\n }\n\n async prepareChunks(serializedPath: Buffer, message: Buffer) {\n const chunks = []\n\n chunks.push(serializedPath)\n for (let i = 0; i < message.length; i += CHUNK_SIZE) {\n let end = i + CHUNK_SIZE\n if (i > message.length) {\n end = message.length\n }\n chunks.push(message.subarray(i, end))\n }\n\n return chunks\n }\n\n async getVersion(): Promise {\n return this.transport.send(CLA, INS.GET_VERSION, 0, 0).then((response: any) => {\n const errorCodeData = response.slice(-2)\n const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n let targetId = 0\n if (response.length >= 9) {\n /* eslint-disable no-bitwise */\n targetId = (response[5] << 24) + (response[6] << 16) + (response[7] << 8) + (response[8] << 0)\n /* eslint-enable no-bitwise */\n }\n\n return {\n returnCode: returnCode,\n errorMessage: errorCodeToString(returnCode),\n // ///\n testMode: response[0] !== 0,\n major: response[1],\n minor: response[2],\n patch: response[3],\n deviceLocked: response[4] === 1,\n targetId: targetId.toString(16),\n }\n }, processErrorResponse)\n }\n\n async getAppInfo(): Promise {\n return this.transport.send(0xb0, 0x01, 0, 0).then(response => {\n const errorCodeData = response.slice(-2)\n const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n const result: { errorMessage?: string; returnCode?: LedgerError } = {}\n\n let appName = 'err'\n let appVersion = 'err'\n let flagLen = 0\n let flagsValue = 0\n\n if (response[0] !== 1) {\n // Ledger responds with format ID 1. There is no spec for any format != 1\n result.errorMessage = 'response format ID not recognized'\n result.returnCode = LedgerError.DeviceIsBusy\n } else {\n const appNameLen = response[1]\n appName = response.slice(2, 2 + appNameLen).toString('ascii')\n let idx = 2 + appNameLen\n const appVersionLen = response[idx]\n idx += 1\n appVersion = response.slice(idx, idx + appVersionLen).toString('ascii')\n idx += appVersionLen\n const appFlagsLen = response[idx]\n idx += 1\n flagLen = appFlagsLen\n flagsValue = response[idx]\n }\n\n return {\n returnCode,\n errorMessage: errorCodeToString(returnCode),\n //\n appName,\n appVersion,\n flagLen,\n flagsValue,\n flagRecovery: (flagsValue & 1) !== 0,\n // eslint-disable-next-line no-bitwise\n flagSignedMcuCode: (flagsValue & 2) !== 0,\n // eslint-disable-next-line no-bitwise\n flagOnboarded: (flagsValue & 4) !== 0,\n // eslint-disable-next-line no-bitwise\n flagPINValidated: (flagsValue & 128) !== 0,\n }\n }, processErrorResponse)\n }\n\n async getAddressAndPubKey(path: string): Promise {\n const serializedPath = serializePath(path)\n return this.transport\n .send(CLA, INS.GET_PUBLIC_KEY, P1_VALUES.ONLY_RETRIEVE, 0, serializedPath, [LedgerError.NoErrors])\n .then(processGetAddrResponse, processErrorResponse)\n }\n\n async showAddressAndPubKey(path: string): Promise {\n const serializedPath = serializePath(path)\n return this.transport\n .send(CLA, INS.GET_PUBLIC_KEY, P1_VALUES.SHOW_ADDRESS_IN_DEVICE, 0, serializedPath, [LedgerError.NoErrors])\n .then(processGetAddrResponse, processErrorResponse)\n }\n\n async signSendChunk(chunkIdx: number, chunkNum: number, chunk: Buffer, ins: number): Promise {\n let payloadType = PAYLOAD_TYPE.ADD\n const p2 = 0\n if (chunkIdx === 1) {\n payloadType = PAYLOAD_TYPE.INIT\n }\n if (chunkIdx === chunkNum) {\n payloadType = PAYLOAD_TYPE.LAST\n }\n\n return this.transport\n .send(CLA, ins, payloadType, p2, chunk, [\n LedgerError.NoErrors,\n LedgerError.DataIsInvalid,\n LedgerError.BadKeyHandle,\n LedgerError.SignVerifyError,\n ])\n .then((response: Buffer) => {\n const errorCodeData = response.subarray(-2)\n const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n let errorMessage = errorCodeToString(returnCode)\n\n if (\n returnCode === LedgerError.BadKeyHandle ||\n returnCode === LedgerError.DataIsInvalid ||\n returnCode === LedgerError.SignVerifyError\n ) {\n errorMessage = `${errorMessage} : ${response.subarray(0, response.length - 2).toString('ascii')}`\n }\n\n if (returnCode === LedgerError.NoErrors && response.length > 2) {\n return {\n signature: getSignatureResponse(response),\n returnCode,\n errorMessage,\n };\n }\n\n return {\n returnCode: returnCode,\n errorMessage: errorMessage,\n } as ResponseSign\n }, processErrorResponse)\n }\n\n async sign(path: string, message: Buffer): Promise {\n const serializedPath = serializePath(path)\n\n return this.prepareChunks(serializedPath, message).then(chunks => {\n return this.signSendChunk(1, chunks.length, chunks[0], INS.SIGN).then(async response => {\n let result: ResponseSign = {\n returnCode: response.returnCode,\n errorMessage: response.errorMessage,\n }\n\n for (let i = 1; i < chunks.length; i++) {\n result = await this.signSendChunk(1 + i, chunks.length, chunks[i], INS.SIGN)\n if (result.returnCode !== LedgerError.NoErrors) {\n break\n }\n }\n return result\n }, processErrorResponse)\n }, processErrorResponse)\n }\n\n /* Not implemented yet\n async getShieldedAddressAndPubKey(path: number, div: Buffer): Promise {\n const buf = Buffer.alloc(4);\n buf.writeUInt32LE(path, 0);\n return this.transport\n .send(CLA, INS.GET_MASP_ADDRESS, P1_VALUES.ONLY_RETRIEVE, 0, Buffer.concat([buf, div]), [LedgerError.NoErrors])\n .then(processGetShieldedAddrResponse, processErrorResponse)\n }\n\n async showShieldedAddressAndPubKey(path: number, div: Buffer): Promise {\n const buf = Buffer.alloc(4);\n buf.writeUInt32LE(path, 0);\n return this.transport\n .send(CLA, INS.GET_MASP_ADDRESS, P1_VALUES.SHOW_ADDRESS_IN_DEVICE, 0, Buffer.concat([buf, div]), [LedgerError.NoErrors])\n .then(processGetShieldedAddrResponse, processErrorResponse)\n }\n\n async getIncomingViewingKey(path: number): Promise {\n const buf = Buffer.alloc(4);\n buf.writeUInt32LE(path, 0);\n return this.transport\n .send(CLA, INS.GET_IVK, P1_VALUES.SHOW_ADDRESS_IN_DEVICE, 0, buf, [LedgerError.NoErrors])\n .then(processIncomingViewingKeyResponse, processErrorResponse)\n }\n\n async getOutgoingViewingKey(path: number): Promise {\n const buf = Buffer.alloc(4);\n buf.writeUInt32LE(path, 0);\n return this.transport\n .send(CLA, INS.GET_OVK, P1_VALUES.SHOW_ADDRESS_IN_DEVICE, 0, buf, [LedgerError.NoErrors])\n .then(processOutgoingViewingKeyResponse, processErrorResponse)\n }\n\n async getNullifier(pos: Uint8Array, cm: Buffer): Promise {\n return this.transport\n .send(CLA, INS.GET_NF, P1_VALUES.ONLY_RETRIEVE, 0, Buffer.concat([pos, cm]), [LedgerError.NoErrors])\n .then(processNullifierResponse, processErrorResponse)\n }\n */\n}\n"]} \ No newline at end of file diff --git a/packages/ledger-namada/dist/processResponses.d.ts b/packages/ledger-namada/dist/processResponses.d.ts index a1ffa222bb3..9450fd9ba54 100644 --- a/packages/ledger-namada/dist/processResponses.d.ts +++ b/packages/ledger-namada/dist/processResponses.d.ts @@ -14,9 +14,8 @@ * limitations under the License. ******************************************************************************* */ /// -import { SignatureType } from './common'; import { ISignature } from './types'; -export declare function processGetSignatureResponse(signatureType: SignatureType, response: Buffer): ISignature; +export declare function getSignatureResponse(response: Buffer): ISignature; export declare function processGetAddrResponse(response: Buffer): { publicKey: Buffer; address: Buffer; diff --git a/packages/ledger-namada/dist/processResponses.js b/packages/ledger-namada/dist/processResponses.js index a5c0a584df7..63473cff818 100644 --- a/packages/ledger-namada/dist/processResponses.js +++ b/packages/ledger-namada/dist/processResponses.js @@ -15,71 +15,47 @@ * limitations under the License. ******************************************************************************* */ Object.defineProperty(exports, "__esModule", { value: true }); -exports.processGetAddrResponse = exports.processGetSignatureResponse = void 0; +exports.processGetAddrResponse = exports.getSignatureResponse = void 0; const common_1 = require("./common"); const config_1 = require("./config"); -function processGetSignatureResponse(signatureType, response) { +function getSignatureResponse(response) { console.log('Processing get signature response'); + // App sign response: [ pubkey(33) | raw_salt(8) | raw_signature(65) | wrapper_salt(8) | wrapper_signature(65) | + // raw_indices_len(1) | wrapper_indices_len(1) | indices(wrapper_indices_len) ] let offset = 0; - const hashesLen = response[offset] + response[offset + 1] * 0x100 + response[offset + 2] * 0x10000 + response[offset + 3] * 0x1000000; - offset += 4; - const secIndices = Buffer.from(response.subarray(offset, offset + hashesLen)); - offset += hashesLen; - switch (signatureType) { - case 1 /* SignatureType.WrapperSignature */: { - const hasSignature = response[offset]; - offset += 1; - let singlesig = null; - if (hasSignature) { - singlesig = Buffer.from(response.subarray(offset, offset + 65)); - offset += 65; - } - const raw = Buffer.from(response.subarray(0, offset)); - return { - sigType: signatureType, - secIndices, - singlesig, - multisig: [], - multisigIndices: Buffer.from([]), - raw, - }; - } - case 0 /* SignatureType.RawSignature */: { - const multisigLen = response[offset] + response[offset + 1] * 0x100 + response[offset + 2] * 0x10000 + response[offset + 3] * 0x1000000; - offset += 4; - var multisig = []; - var multisigIndices = Buffer.alloc(multisigLen); - for (let i = 0; i < multisigLen; i += 1) { - let signature = Buffer.from(response.subarray(offset, offset + 65)); - offset += 65; - multisig.push(signature); - multisigIndices.writeInt8(response[offset]); - offset += 1; - } - const raw = Buffer.from(response.subarray(0, offset)); - return { - sigType: signatureType, - secIndices, - multisig, - multisigIndices, - singlesig: null, - raw, - }; - } - } + const pubkey = Buffer.from(response.subarray(offset, offset + config_1.PK_LEN_PLUS_TAG)); + offset += config_1.PK_LEN_PLUS_TAG; + const raw_salt = Buffer.from(response.subarray(offset, offset + config_1.SALT_LEN)); + offset += config_1.SALT_LEN; + const raw_signature = Buffer.from(response.subarray(offset, offset + config_1.SIG_LEN_PLUS_TAG)); + offset += config_1.SIG_LEN_PLUS_TAG; + const wrapper_salt = Buffer.from(response.subarray(offset, offset + config_1.SALT_LEN)); + offset += config_1.SALT_LEN; + const wrapper_signature = Buffer.from(response.subarray(offset, offset + config_1.SIG_LEN_PLUS_TAG)); + offset += config_1.SIG_LEN_PLUS_TAG; + const raw_indices_len = response[offset]; + offset += 1; + const wrapper_indices_len = response[offset]; + offset += 1; + const raw_indices = Buffer.from(response.subarray(offset, offset + raw_indices_len)); + const wrapper_indices = Buffer.from(response.subarray(offset, offset + wrapper_indices_len)); + return { + pubkey, + raw_salt, + raw_signature, + wrapper_salt, + wrapper_signature, + raw_indices, + wrapper_indices, + }; } -exports.processGetSignatureResponse = processGetSignatureResponse; +exports.getSignatureResponse = getSignatureResponse; function processGetAddrResponse(response) { console.log('Processing get address response'); - let partialResponse = response; - const errorCodeData = partialResponse.subarray(-2); + const errorCodeData = response.subarray(-2); const returnCode = errorCodeData[0] * 256 + errorCodeData[1]; - //get public key len (variable) - const publicKey = Buffer.from(partialResponse.slice(0, config_1.PK_LEN_25519)); - //"advance" buffer - partialResponse = partialResponse.slice(config_1.PK_LEN_25519); - // get the implicit address corresponding to the public key - const address = Buffer.from(partialResponse.slice(0, -2)); + const publicKey = Buffer.from(response.subarray(0, config_1.PK_LEN_PLUS_TAG)); + const address = Buffer.from(response.subarray(config_1.PK_LEN_PLUS_TAG, -2)); return { publicKey, address, diff --git a/packages/ledger-namada/dist/processResponses.js.map b/packages/ledger-namada/dist/processResponses.js.map index 83183c90b89..070ceb7ee6b 100644 --- a/packages/ledger-namada/dist/processResponses.js.map +++ b/packages/ledger-namada/dist/processResponses.js.map @@ -1 +1 @@ -{"version":3,"file":"processResponses.js","sourceRoot":"","sources":["../src/processResponses.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;mFAcmF;;;AAEnF,qCAA2D;AAC3D,qCAA2D;AAG3D,SAAgB,2BAA2B,CAAC,aAA4B,EAAE,QAAgB;IACxF,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAA;IAEhD,IAAI,MAAM,GAAG,CAAC,CAAA;IACd,MAAM,SAAS,GAAG,QAAQ,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAC,CAAC,CAAC,GAAC,KAAK,GAAG,QAAQ,CAAC,MAAM,GAAC,CAAC,CAAC,GAAC,OAAO,GAAG,QAAQ,CAAC,MAAM,GAAC,CAAC,CAAC,GAAC,SAAS,CAAA;IACzH,MAAM,IAAI,CAAC,CAAA;IACX,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAC,SAAS,CAAC,CAAC,CAAA;IAC3E,MAAM,IAAI,SAAS,CAAA;IACnB,QAAO,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DAAmD;AAEnD,mCAAmC;AAEnC,oDAAoD;AACpD,iEAAiE;AAEjE,oCAAoC;AACpC,8DAA8D;AAE9D,uBAAuB;AACvB,gDAAgD;AAEhD,6CAA6C;AAC7C,2CAA2C;AAE3C,uBAAuB;AACvB,+CAA+C;AAE/C,wDAAwD;AACxD,4EAA4E;AAE5E,aAAa;AACb,eAAe;AACf,mBAAmB;AACnB,oBAAoB;AACpB,kBAAkB;AAClB,mDAAmD;AACnD,MAAM;AACN,IAAI;AAEJ,iEAAiE;AACjE,+CAA+C;AAE/C,qCAAqC;AAErC,oDAAoD;AACpD,iEAAiE;AAEjE,oCAAoC;AACpC,8DAA8D;AAE9D,aAAa;AACb,eAAe;AACf,kBAAkB;AAClB,mDAAmD;AACnD,MAAM;AACN,IAAI;AAEJ,wDAAwD;AACxD,qDAAqD;AAErD,qCAAqC;AAErC,oDAAoD;AACpD,iEAAiE;AAEjE,6DAA6D;AAE7D,aAAa;AACb,cAAc;AACd,kBAAkB;AAClB,mDAAmD;AACnD,MAAM;AACN,IAAI;AAEJ,iEAAiE;AACjE,+CAA+C;AAE/C,qCAAqC;AAErC,oDAAoD;AACpD,iEAAiE;AAEjE,oCAAoC;AACpC,8DAA8D;AAE9D,aAAa;AACb,eAAe;AACf,kBAAkB;AAClB,mDAAmD;AACnD,MAAM;AACN,IAAI","sourcesContent":["/** ******************************************************************************\n * (c) 2018 - 2022 Zondax AG\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ******************************************************************************* */\n\nimport { errorCodeToString, SignatureType } from './common'\nimport { HASH_LEN, PK_LEN_25519, SALT_LEN } from './config'\nimport { ISignature } from './types'\n\nexport function processGetSignatureResponse(signatureType: SignatureType, response: Buffer): ISignature {\n console.log('Processing get signature response')\n\n let offset = 0\n const hashesLen = response[offset] + response[offset+1]*0x100 + response[offset+2]*0x10000 + response[offset+3]*0x1000000\n offset += 4\n const secIndices = Buffer.from(response.subarray(offset, offset+hashesLen))\n offset += hashesLen\n switch(signatureType) {\n case SignatureType.WrapperSignature: {\n const hasSignature = response[offset]\n offset += 1\n let singlesig = null\n if(hasSignature) {\n singlesig = Buffer.from(response.subarray(offset, offset + 65))\n offset += 65\n }\n const raw = Buffer.from(response.subarray(0, offset))\n\n return {\n sigType: signatureType,\n secIndices,\n singlesig,\n multisig: [],\n multisigIndices: Buffer.from([]),\n raw,\n }\n }\n case SignatureType.RawSignature: {\n const multisigLen = response[offset] + response[offset+1]*0x100 + response[offset+2]*0x10000 + response[offset+3]*0x1000000\n offset += 4\n var multisig = []\n var multisigIndices = Buffer.alloc(multisigLen)\n for (let i = 0; i < multisigLen; i += 1) {\n let signature = Buffer.from(response.subarray(offset, offset + 65))\n offset += 65\n multisig.push(signature)\n multisigIndices.writeInt8(response[offset])\n offset += 1\n }\n const raw = Buffer.from(response.subarray(0, offset))\n \n return {\n sigType: signatureType,\n secIndices,\n multisig,\n multisigIndices,\n singlesig: null,\n raw,\n }\n }\n }\n}\n\nexport function processGetAddrResponse(response: Buffer) {\n console.log('Processing get address response')\n\n let partialResponse = response\n\n const errorCodeData = partialResponse.subarray(-2)\n const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n //get public key len (variable)\n const publicKey = Buffer.from(partialResponse.slice(0, PK_LEN_25519))\n\n //\"advance\" buffer\n partialResponse = partialResponse.slice(PK_LEN_25519)\n\n // get the implicit address corresponding to the public key\n const address = Buffer.from(partialResponse.slice(0, -2))\n\n return {\n publicKey,\n address,\n returnCode,\n errorMessage: errorCodeToString(returnCode),\n }\n}\n\n// Not used yet\n// function processGetShieldedAddrResponse(response: Buffer) {\n// console.log(\"Processing get address response\")\n\n// let partialResponse = response\n\n// const errorCodeData = partialResponse.slice(-2)\n// const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n// //get public key len (variable)\n// const raw_pkd = Buffer.from(partialResponse.slice(0, 32))\n\n// //\"advance\" buffer\n// partialResponse = partialResponse.slice(32)\n\n// // get the length of the bech32m address\n// const bech32m_len = partialResponse[0]\n\n// //\"advance\" buffer\n// partialResponse = partialResponse.slice(1)\n\n// // get the bech32m encoding of the shielded address\n// const bech32m_addr = Buffer.from(partialResponse.slice(0, bech32m_len))\n\n// return {\n// raw_pkd,\n// bech32m_len,\n// bech32m_addr,\n// returnCode,\n// errorMessage: errorCodeToString(returnCode),\n// }\n// }\n\n// function processIncomingViewingKeyResponse(response: Buffer) {\n// console.log(\"Processing get IVK response\")\n\n// const partialResponse = response\n\n// const errorCodeData = partialResponse.slice(-2)\n// const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n// //get public key len (variable)\n// const raw_ivk = Buffer.from(partialResponse.slice(0, 32))\n\n// return {\n// raw_ivk,\n// returnCode,\n// errorMessage: errorCodeToString(returnCode),\n// }\n// }\n\n// function processNullifierResponse(response: Buffer) {\n// console.log(\"Processing get nullifier response\")\n\n// const partialResponse = response\n\n// const errorCodeData = partialResponse.slice(-2)\n// const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n// const raw_nf = Buffer.from(partialResponse.slice(0, 32))\n\n// return {\n// raw_nf,\n// returnCode,\n// errorMessage: errorCodeToString(returnCode),\n// }\n// }\n\n// function processOutgoingViewingKeyResponse(response: Buffer) {\n// console.log(\"Processing get OVK response\")\n\n// const partialResponse = response\n\n// const errorCodeData = partialResponse.slice(-2)\n// const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n// //get public key len (variable)\n// const raw_ovk = Buffer.from(partialResponse.slice(0, 32))\n\n// return {\n// raw_ovk,\n// returnCode,\n// errorMessage: errorCodeToString(returnCode),\n// }\n// }\n"]} \ No newline at end of file +{"version":3,"file":"processResponses.js","source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E;AAE5E,aAAa;AACb,eAAe;AACf,mBAAmB;AACnB,oBAAoB;AACpB,kBAAkB;AAClB,mDAAmD;AACnD,MAAM;AACN,IAAI;AAEJ,iEAAiE;AACjE,+CAA+C;AAE/C,qCAAqC;AAErC,oDAAoD;AACpD,iEAAiE;AAEjE,oCAAoC;AACpC,8DAA8D;AAE9D,aAAa;AACb,eAAe;AACf,kBAAkB;AAClB,mDAAmD;AACnD,MAAM;AACN,IAAI;AAEJ,wDAAwD;AACxD,qDAAqD;AAErD,qCAAqC;AAErC,oDAAoD;AACpD,iEAAiE;AAEjE,6DAA6D;AAE7D,aAAa;AACb,cAAc;AACd,kBAAkB;AAClB,mDAAmD;AACnD,MAAM;AACN,IAAI;AAEJ,iEAAiE;AACjE,+CAA+C;AAE/C,qCAAqC;AAErC,oDAAoD;AACpD,iEAAiE;AAEjE,oCAAoC;AACpC,8DAA8D;AAE9D,aAAa;AACb,eAAe;AACf,kBAAkB;AAClB,mDAAmD;AACnD,MAAM;AACN,IAAI","sourcesContent":["/** ******************************************************************************\n * (c) 2018 - 2022 Zondax AG\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ******************************************************************************* */\n\nimport { errorCodeToString } from './common'\nimport { PK_LEN_PLUS_TAG, SALT_LEN, SIG_LEN_PLUS_TAG } from './config'\nimport { ISignature } from './types'\n\nexport function getSignatureResponse(response: Buffer): ISignature {\n console.log('Processing get signature response')\n\n // App sign response: [ pubkey(33) | raw_salt(8) | raw_signature(65) | wrapper_salt(8) | wrapper_signature(65) |\n // raw_indices_len(1) | wrapper_indices_len(1) | indices(wrapper_indices_len) ]\n let offset = 0;\n const pubkey = Buffer.from(response.subarray(offset, offset + PK_LEN_PLUS_TAG));\n\n offset += PK_LEN_PLUS_TAG;\n const raw_salt = Buffer.from(response.subarray(offset, offset + SALT_LEN));\n offset += SALT_LEN;\n const raw_signature = Buffer.from(response.subarray(offset, offset + SIG_LEN_PLUS_TAG));\n\n offset += SIG_LEN_PLUS_TAG;\n const wrapper_salt = Buffer.from(response.subarray(offset, offset + SALT_LEN));\n offset += SALT_LEN;\n const wrapper_signature = Buffer.from(response.subarray(offset, offset + SIG_LEN_PLUS_TAG));\n\n offset += SIG_LEN_PLUS_TAG;\n const raw_indices_len = response[offset];\n offset += 1;\n const wrapper_indices_len = response[offset];\n\n offset += 1;\n const raw_indices = Buffer.from(response.subarray(offset, offset + raw_indices_len))\n const wrapper_indices = Buffer.from(response.subarray(offset, offset + wrapper_indices_len))\n\n return {\n pubkey,\n raw_salt,\n raw_signature,\n wrapper_salt,\n wrapper_signature,\n raw_indices,\n wrapper_indices,\n }\n}\n\nexport function processGetAddrResponse(response: Buffer) {\n console.log('Processing get address response')\n\n const errorCodeData = response.subarray(-2)\n const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n const publicKey = Buffer.from(response.subarray(0, PK_LEN_PLUS_TAG))\n const address = Buffer.from(response.subarray(PK_LEN_PLUS_TAG, -2))\n\n return {\n publicKey,\n address,\n returnCode,\n errorMessage: errorCodeToString(returnCode),\n }\n}\n\n// Not used yet\n// function processGetShieldedAddrResponse(response: Buffer) {\n// console.log(\"Processing get address response\")\n\n// let partialResponse = response\n\n// const errorCodeData = partialResponse.slice(-2)\n// const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n// //get public key len (variable)\n// const raw_pkd = Buffer.from(partialResponse.slice(0, 32))\n\n// //\"advance\" buffer\n// partialResponse = partialResponse.slice(32)\n\n// // get the length of the bech32m address\n// const bech32m_len = partialResponse[0]\n\n// //\"advance\" buffer\n// partialResponse = partialResponse.slice(1)\n\n// // get the bech32m encoding of the shielded address\n// const bech32m_addr = Buffer.from(partialResponse.slice(0, bech32m_len))\n\n// return {\n// raw_pkd,\n// bech32m_len,\n// bech32m_addr,\n// returnCode,\n// errorMessage: errorCodeToString(returnCode),\n// }\n// }\n\n// function processIncomingViewingKeyResponse(response: Buffer) {\n// console.log(\"Processing get IVK response\")\n\n// const partialResponse = response\n\n// const errorCodeData = partialResponse.slice(-2)\n// const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n// //get public key len (variable)\n// const raw_ivk = Buffer.from(partialResponse.slice(0, 32))\n\n// return {\n// raw_ivk,\n// returnCode,\n// errorMessage: errorCodeToString(returnCode),\n// }\n// }\n\n// function processNullifierResponse(response: Buffer) {\n// console.log(\"Processing get nullifier response\")\n\n// const partialResponse = response\n\n// const errorCodeData = partialResponse.slice(-2)\n// const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n// const raw_nf = Buffer.from(partialResponse.slice(0, 32))\n\n// return {\n// raw_nf,\n// returnCode,\n// errorMessage: errorCodeToString(returnCode),\n// }\n// }\n\n// function processOutgoingViewingKeyResponse(response: Buffer) {\n// console.log(\"Processing get OVK response\")\n\n// const partialResponse = response\n\n// const errorCodeData = partialResponse.slice(-2)\n// const returnCode = errorCodeData[0] * 256 + errorCodeData[1]\n\n// //get public key len (variable)\n// const raw_ovk = Buffer.from(partialResponse.slice(0, 32))\n\n// return {\n// raw_ovk,\n// returnCode,\n// errorMessage: errorCodeToString(returnCode),\n// }\n// }\n"]} \ No newline at end of file diff --git a/packages/ledger-namada/dist/types.d.ts b/packages/ledger-namada/dist/types.d.ts index 34b5eff4715..a3da084048e 100644 --- a/packages/ledger-namada/dist/types.d.ts +++ b/packages/ledger-namada/dist/types.d.ts @@ -1,5 +1,5 @@ /// -import { LedgerError, SignatureType } from './common'; +import { LedgerError } from './common'; export interface ResponseBase { errorMessage: string; returnCode: LedgerError; @@ -47,24 +47,25 @@ export interface ResponseNullifier extends ResponseBase { raw_nf: Buffer; } export interface ISignature { - raw: Buffer; - secIndices: Buffer; - sigType: SignatureType; - singlesig: Buffer | null; - multisigIndices: Buffer; - multisig: Buffer[]; + pubkey: Buffer; + raw_salt: Buffer; + raw_signature: Buffer; + wrapper_salt: Buffer; + wrapper_signature: Buffer; + raw_indices: Buffer; + wrapper_indices: Buffer; } export declare class Signature implements ISignature { - raw: Buffer; - secIndices: Buffer; - sigType: SignatureType; - singlesig: Buffer | null; - multisigIndices: Buffer; - multisig: Buffer[]; + pubkey: Buffer; + raw_salt: Buffer; + raw_signature: Buffer; + wrapper_salt: Buffer; + wrapper_signature: Buffer; + raw_indices: Buffer; + wrapper_indices: Buffer; isFilled: boolean; constructor(signature?: ISignature); } export interface ResponseSign extends ResponseBase { - wrapperSignature: Signature; - rawSignature: Signature; + signature?: Signature; } diff --git a/packages/ledger-namada/dist/types.js b/packages/ledger-namada/dist/types.js index 0983ac24709..fb9110ed429 100644 --- a/packages/ledger-namada/dist/types.js +++ b/packages/ledger-namada/dist/types.js @@ -5,21 +5,23 @@ class Signature { constructor(signature) { if (signature == null) { this.isFilled = false; - this.raw = Buffer.from([]); - this.secIndices = Buffer.from([]); - this.sigType = 0 /* SignatureType.RawSignature */; - this.singlesig = null; - this.multisigIndices = Buffer.from([]); - this.multisig = []; + this.pubkey = Buffer.from([]); + this.raw_salt = Buffer.from([]); + this.raw_signature = Buffer.from([]); + this.wrapper_salt = Buffer.from([]); + this.wrapper_signature = Buffer.from([]); + this.raw_indices = Buffer.from([]); + this.wrapper_indices = Buffer.from([]); } else { this.isFilled = true; - this.raw = signature.raw; - this.secIndices = signature.secIndices; - this.sigType = signature.sigType; - this.singlesig = signature.singlesig; - this.multisigIndices = signature.multisigIndices; - this.multisig = signature.multisig; + this.pubkey = signature.pubkey; + this.raw_salt = signature.raw_salt; + this.raw_signature = signature.raw_signature; + this.wrapper_salt = signature.wrapper_salt; + this.wrapper_signature = signature.wrapper_signature; + this.raw_indices = signature.raw_indices; + this.wrapper_indices = signature.wrapper_indices; } } } diff --git a/packages/ledger-namada/dist/types.js.map b/packages/ledger-namada/dist/types.js.map index 33a018bd63b..c2960ae6e0e 100644 --- a/packages/ledger-namada/dist/types.js.map +++ b/packages/ledger-namada/dist/types.js.map @@ -1 +1 @@ -{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAiEA,MAAa,SAAS;IAUpB,YAAY,SAAsB;QAChC,IAAI,SAAS,IAAI,IAAI,EAAE;YACrB,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAA;YACrB,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YAC1B,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YACjC,IAAI,CAAC,OAAO,qCAA6B,CAAA;YACzC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAA;YACrB,IAAI,CAAC,eAAe,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YACtC,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;SACnB;aAAM;YACL,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAA;YACpB,IAAI,CAAC,GAAG,GAAG,SAAS,CAAC,GAAG,CAAA;YACxB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC,UAAU,CAAA;YACtC,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC,OAAO,CAAA;YAChC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,SAAS,CAAA;YACpC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC,eAAe,CAAA;YAChD,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAAA;SACnC;IACH,CAAC;CACF;AA7BD,8BA6BC","sourcesContent":["import { LedgerError, SignatureType } from './common'\n\nexport interface ResponseBase {\n errorMessage: string\n returnCode: LedgerError\n}\n\nexport interface ResponseAddress extends ResponseBase {\n publicKey: Buffer\n address: Buffer\n}\n\nexport interface ResponseVersion extends ResponseBase {\n testMode: boolean\n major: number\n minor: number\n patch: number\n deviceLocked: boolean\n targetId: string\n}\n\nexport interface ResponseAppInfo extends ResponseBase {\n appName: string\n appVersion: string\n flagLen: number\n flagsValue: number\n flagRecovery: boolean\n flagSignedMcuCode: boolean\n flagOnboarded: boolean\n flagPINValidated: boolean\n}\n\nexport interface ResponseDeviceInfo extends ResponseBase {\n targetId: string\n seVersion: string\n flag: string\n mcuVersion: string\n}\n\nexport interface ResponseShieldedAddress extends ResponseBase {\n raw_pkd: Buffer\n bech32m_len: number\n bech32m_addr: Buffer\n}\n\nexport interface ResponseIncomingViewingKey extends ResponseBase {\n raw_ivk: Buffer\n}\n\nexport interface ResponseOutgoingViewingKey extends ResponseBase {\n raw_ovk: Buffer\n}\n\nexport interface ResponseNullifier extends ResponseBase {\n raw_nf: Buffer\n}\n\nexport interface ISignature {\n raw: Buffer\n secIndices: Buffer\n sigType: SignatureType\n singlesig: Buffer | null\n multisigIndices: Buffer\n multisig: Buffer[]\n}\nexport class Signature implements ISignature {\n raw: Buffer\n secIndices: Buffer\n sigType: SignatureType\n singlesig: Buffer | null\n multisigIndices: Buffer\n multisig: Buffer[]\n\n isFilled: boolean\n\n constructor(signature?: ISignature) {\n if (signature == null) {\n this.isFilled = false\n this.raw = Buffer.from([])\n this.secIndices = Buffer.from([])\n this.sigType = SignatureType.RawSignature\n this.singlesig = null\n this.multisigIndices = Buffer.from([])\n this.multisig = []\n } else {\n this.isFilled = true\n this.raw = signature.raw\n this.secIndices = signature.secIndices\n this.sigType = signature.sigType\n this.singlesig = signature.singlesig\n this.multisigIndices = signature.multisigIndices\n this.multisig = signature.multisig\n }\n }\n}\n\nexport interface ResponseSign extends ResponseBase {\n wrapperSignature: Signature\n rawSignature: Signature\n}\n"]} \ No newline at end of file +{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAkEA,MAAa,SAAS;IAUpB,YAAY,SAAsB;QAChC,IAAI,SAAS,IAAI,IAAI,EAAE;YACrB,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAA;YACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YAC7B,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YAC/B,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YACpC,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YACnC,IAAI,CAAC,iBAAiB,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YACxC,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YAClC,IAAI,CAAC,eAAe,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;SACvC;aAAM;YACL,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAA;YACpB,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC,MAAM,CAAA;YAC9B,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAAA;YAClC,IAAI,CAAC,aAAa,GAAG,SAAS,CAAC,aAAa,CAAA;YAC5C,IAAI,CAAC,YAAY,GAAG,SAAS,CAAC,YAAY,CAAA;YAC1C,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC,iBAAiB,CAAA;YACpD,IAAI,CAAC,WAAW,GAAG,SAAS,CAAC,WAAW,CAAA;YACxC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC,eAAe,CAAA;SACjD;IACH,CAAC;CACF;AA/BD,8BA+BC","sourcesContent":["import { LedgerError } from './common'\n\nexport interface ResponseBase {\n errorMessage: string\n returnCode: LedgerError\n}\n\nexport interface ResponseAddress extends ResponseBase {\n publicKey: Buffer\n address: Buffer\n}\n\nexport interface ResponseVersion extends ResponseBase {\n testMode: boolean\n major: number\n minor: number\n patch: number\n deviceLocked: boolean\n targetId: string\n}\n\nexport interface ResponseAppInfo extends ResponseBase {\n appName: string\n appVersion: string\n flagLen: number\n flagsValue: number\n flagRecovery: boolean\n flagSignedMcuCode: boolean\n flagOnboarded: boolean\n flagPINValidated: boolean\n}\n\nexport interface ResponseDeviceInfo extends ResponseBase {\n targetId: string\n seVersion: string\n flag: string\n mcuVersion: string\n}\n\nexport interface ResponseShieldedAddress extends ResponseBase {\n raw_pkd: Buffer\n bech32m_len: number\n bech32m_addr: Buffer\n}\n\nexport interface ResponseIncomingViewingKey extends ResponseBase {\n raw_ivk: Buffer\n}\n\nexport interface ResponseOutgoingViewingKey extends ResponseBase {\n raw_ovk: Buffer\n}\n\nexport interface ResponseNullifier extends ResponseBase {\n raw_nf: Buffer\n}\n\nexport interface ISignature {\n pubkey: Buffer\n raw_salt: Buffer\n raw_signature: Buffer\n wrapper_salt: Buffer\n wrapper_signature: Buffer\n raw_indices: Buffer\n wrapper_indices: Buffer\n}\nexport class Signature implements ISignature {\n pubkey: Buffer\n raw_salt: Buffer\n raw_signature: Buffer\n wrapper_salt: Buffer\n wrapper_signature: Buffer\n raw_indices: Buffer\n wrapper_indices: Buffer\n isFilled: boolean\n\n constructor(signature?: ISignature) {\n if (signature == null) {\n this.isFilled = false\n this.pubkey = Buffer.from([])\n this.raw_salt = Buffer.from([])\n this.raw_signature = Buffer.from([])\n this.wrapper_salt = Buffer.from([])\n this.wrapper_signature = Buffer.from([])\n this.raw_indices = Buffer.from([])\n this.wrapper_indices = Buffer.from([])\n } else {\n this.isFilled = true\n this.pubkey = signature.pubkey\n this.raw_salt = signature.raw_salt\n this.raw_signature = signature.raw_signature\n this.wrapper_salt = signature.wrapper_salt\n this.wrapper_signature = signature.wrapper_signature\n this.raw_indices = signature.raw_indices\n this.wrapper_indices = signature.wrapper_indices\n }\n }\n}\n\nexport interface ResponseSign extends ResponseBase {\n signature?: Signature\n}\n"]} \ No newline at end of file diff --git a/packages/shared/lib/Cargo.lock b/packages/shared/lib/Cargo.lock index 3aafb227dd7..c432b64f5c9 100644 --- a/packages/shared/lib/Cargo.lock +++ b/packages/shared/lib/Cargo.lock @@ -2944,7 +2944,7 @@ checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" [[package]] name = "namada" version = "0.22.0" -source = "git+https://github.com/anoma/namada#9b67281e359ebff5467cad57c866fbcf91eb80c8" +source = "git+https://github.com/anoma/namada?rev=6eff4a928b3dbef3b3ba52351b6a4d4520931e2f#6eff4a928b3dbef3b3ba52351b6a4d4520931e2f" dependencies = [ "async-trait", "bimap", @@ -2993,7 +2993,7 @@ dependencies = [ [[package]] name = "namada_core" version = "0.22.0" -source = "git+https://github.com/anoma/namada#9b67281e359ebff5467cad57c866fbcf91eb80c8" +source = "git+https://github.com/anoma/namada?rev=6eff4a928b3dbef3b3ba52351b6a4d4520931e2f#6eff4a928b3dbef3b3ba52351b6a4d4520931e2f" dependencies = [ "ark-bls12-381", "ark-ec", @@ -3045,7 +3045,7 @@ dependencies = [ [[package]] name = "namada_ethereum_bridge" version = "0.22.0" -source = "git+https://github.com/anoma/namada#9b67281e359ebff5467cad57c866fbcf91eb80c8" +source = "git+https://github.com/anoma/namada?rev=6eff4a928b3dbef3b3ba52351b6a4d4520931e2f#6eff4a928b3dbef3b3ba52351b6a4d4520931e2f" dependencies = [ "borsh 0.9.4", "ethers", @@ -3066,7 +3066,7 @@ dependencies = [ [[package]] name = "namada_macros" version = "0.22.0" -source = "git+https://github.com/anoma/namada#9b67281e359ebff5467cad57c866fbcf91eb80c8" +source = "git+https://github.com/anoma/namada?rev=6eff4a928b3dbef3b3ba52351b6a4d4520931e2f#6eff4a928b3dbef3b3ba52351b6a4d4520931e2f" dependencies = [ "proc-macro2", "quote", @@ -3076,7 +3076,7 @@ dependencies = [ [[package]] name = "namada_proof_of_stake" version = "0.22.0" -source = "git+https://github.com/anoma/namada#9b67281e359ebff5467cad57c866fbcf91eb80c8" +source = "git+https://github.com/anoma/namada?rev=6eff4a928b3dbef3b3ba52351b6a4d4520931e2f#6eff4a928b3dbef3b3ba52351b6a4d4520931e2f" dependencies = [ "borsh 0.9.4", "data-encoding", diff --git a/packages/shared/lib/Cargo.toml b/packages/shared/lib/Cargo.toml index f7a5577d001..91e3fdf5360 100644 --- a/packages/shared/lib/Cargo.toml +++ b/packages/shared/lib/Cargo.toml @@ -23,7 +23,7 @@ gloo-utils = { version = "0.1.5", features = ["serde"] } js-sys = "0.3.60" masp_primitives = { git = "https://github.com/anoma/masp", rev = "50acc5028fbcd52a05970fe7991c7850ab04358e" } masp_proofs = { git = "https://github.com/anoma/masp", rev = "50acc5028fbcd52a05970fe7991c7850ab04358e", default-features = false, features = ["local-prover"] } -namada = { git = "https://github.com/anoma/namada", version = "0.22.0", default-features = false, features = ["abciplus", "namada-sdk"] } +namada = { git = "https://github.com/anoma/namada", rev = "6eff4a928b3dbef3b3ba52351b6a4d4520931e2f", default-features = false, features = ["abciplus", "namada-sdk"] } prost = "0.9.0" prost-types = "0.9.0" rand = "0.8.5" diff --git a/packages/shared/lib/src/sdk/mod.rs b/packages/shared/lib/src/sdk/mod.rs index d9e42768f48..fb19c95344b 100644 --- a/packages/shared/lib/src/sdk/mod.rs +++ b/packages/shared/lib/src/sdk/mod.rs @@ -163,10 +163,9 @@ impl Sdk { &mut self, tx_msg: &[u8], tx_bytes: &[u8], - raw_sig_bytes: &[u8], - wrapper_sig_bytes: &[u8], + sig_msg_bytes: &[u8], ) -> Result<(), JsError> { - let reveal_pk_tx = self.sign_tx(tx_bytes, raw_sig_bytes, wrapper_sig_bytes)?; + let reveal_pk_tx = self.sign_tx(tx_bytes, sig_msg_bytes)?; let args = tx::tx_args_from_slice(&tx_msg)?; namada::ledger::tx::process_tx(&self.client, &mut self.wallet, &args, reveal_pk_tx).await?; @@ -224,7 +223,6 @@ impl Sdk { &gas_payer, ) .await?; - reveal_pk } TxType::Transfer => { @@ -287,7 +285,6 @@ impl Sdk { gas_payer, ) .await?; - withdraw } }; @@ -296,18 +293,26 @@ impl Sdk { } // Append signatures and return tx bytes - fn sign_tx( - &self, - tx_bytes: &[u8], - raw_sig_bytes: &[u8], - wrapper_sig_bytes: &[u8], - ) -> Result { + fn sign_tx(&self, tx_bytes: &[u8], sig_msg_bytes: &[u8]) -> Result { let mut tx: Tx = Tx::try_from_slice(tx_bytes)?; - - let raw_sig_section = signature::construct_signature(raw_sig_bytes, &tx)?; + let signature::SignatureMsg { + pubkey, + raw_indices, + raw_signature, + wrapper_indices, + wrapper_signature, + } = signature::SignatureMsg::try_from_slice(&sig_msg_bytes)?; + + let raw_sig_section = + signature::construct_signature_section(&pubkey, &raw_indices, &raw_signature, &tx)?; tx.add_section(raw_sig_section); - let wrapper_sig_section = signature::construct_signature(wrapper_sig_bytes, &tx)?; + let wrapper_sig_section = signature::construct_signature_section( + &pubkey, + &wrapper_indices, + &wrapper_signature, + &tx, + )?; tx.add_section(wrapper_sig_section); tx.protocol_filter(); @@ -320,10 +325,9 @@ impl Sdk { &mut self, tx_msg: &[u8], tx_bytes: &[u8], - raw_sig_bytes: &[u8], - wrapper_sig_bytes: &[u8], + sig_msg_bytes: &[u8], ) -> Result<(), JsError> { - let transfer_tx = self.sign_tx(tx_bytes, raw_sig_bytes, wrapper_sig_bytes)?; + let transfer_tx = self.sign_tx(tx_bytes, sig_msg_bytes)?; let args = tx::tx_args_from_slice(tx_msg)?; namada::ledger::tx::process_tx(&self.client, &mut self.wallet, &args, transfer_tx).await?; @@ -345,7 +349,7 @@ impl Sdk { &self.client, &mut self.wallet, &args.tx.clone(), - &Some(effective_address.clone()), + Some(effective_address.clone()), default_signer, ) .await?; @@ -378,7 +382,7 @@ impl Sdk { &self.client, &mut self.wallet, &args.tx.clone(), - &Some(source.clone()), + Some(source.clone()), default_signer, ) .await?; @@ -411,7 +415,7 @@ impl Sdk { &self.client, &mut self.wallet, &args.tx.clone(), - &Some(sender.clone()), + Some(sender.clone()), default_signer, ) .await?; @@ -444,7 +448,7 @@ impl Sdk { &self.client, &mut self.wallet, &args.tx.clone(), - &source, + source, default_signer, ) .await?; @@ -477,7 +481,7 @@ impl Sdk { &self.client, &mut self.wallet, &args.tx.clone(), - &source, + source, default_signer, ) .await?; @@ -509,7 +513,7 @@ impl Sdk { &self.client, &mut self.wallet, &args.tx.clone(), - &source, + source, default_signer, ) .await?; diff --git a/packages/shared/lib/src/sdk/signature.rs b/packages/shared/lib/src/sdk/signature.rs index 384d4e09f0d..b42452744ee 100644 --- a/packages/shared/lib/src/sdk/signature.rs +++ b/packages/shared/lib/src/sdk/signature.rs @@ -1,84 +1,48 @@ use borsh::{BorshDeserialize, BorshSerialize}; -use namada::proto::{MultiSignature, Section, Signature, Tx}; +use namada::{ + ledger::pos::common::Signature, + proto::{CompressedSignature, Section, Signer, Tx}, + types::key::common::PublicKey, +}; +use std::collections::BTreeMap; use wasm_bindgen::JsError; -#[derive(Copy, Clone, Debug, BorshSerialize, BorshDeserialize)] -pub enum SignatureType { - Raw = 0, - Wrapper = 1, -} - #[derive(BorshSerialize, BorshDeserialize)] pub struct SignatureMsg { - sec_indices: Vec, - singlesig: Option>, - sig_type: SignatureType, - multisig_indices: Vec, - multisig: Vec>, + pub pubkey: Vec, + pub raw_indices: Vec, + pub raw_signature: Vec, + pub wrapper_indices: Vec, + pub wrapper_signature: Vec, } -/// Reconstructs a proto::Signature using the provided indices to retrieve hashes from Tx +/// Reconstructs a proto::Section signature using the provided indices to retrieve hashes +/// from Tx /// /// # Arguments //// -/// * `sig_msg` - A Borshed serialized SignatureMsg struct +/// * `pubkey` - Public key bytes +/// * `sec_indices` - Indices indicating hash location +/// * `signature` - Signature bytes /// * `tx` - A proto::Tx /// /// # Errors /// /// Returns JsError if the sig_msg can't be deserialized or /// Rust structs can't be created. -pub fn construct_signature(sig_msg: &[u8], tx: &Tx) -> Result { - let SignatureMsg { - sec_indices, - singlesig, - sig_type, - multisig_indices, - multisig, - } = SignatureMsg::try_from_slice(sig_msg)?; - - // Start with the number of section indices with a pad - let indices = vec![sec_indices.len() as u8, 0, 0, 0]; - let mut sig = indices; - - // Which is followed by the hash of each section in the order specified - for i in 0..sec_indices.len() { - let sechash = match sec_indices[i] { - 0 => tx.header_hash(), - _ => tx.sections[sec_indices[i] as usize - 1].get_hash(), - }; - - sig.extend_from_slice(&sechash.to_vec()); - } - - match sig_type { - SignatureType::Wrapper => { - // Indicates that a signature follows - sig.extend_from_slice(&vec![0x01]); - - // Followed by the signature - match singlesig { - Some(v) => { - sig.extend_from_slice(&v); - } - // This shouldn't happen: - None => panic!("singlesig is required for SignatureType::Wrapper"), - } - Ok(Section::Signature(Signature::try_from_slice(&sig)?)) - } - SignatureType::Raw => { - // Multisigs start with the number of signatures - sig.extend_from_slice(&vec![multisig_indices.len() as u8, 0, 0, 0]); - // Followed by a sequence of signature - index pairs - for (signature, idx) in multisig.iter().zip(multisig_indices) { - // Add the bytes of the signature - sig.extend_from_slice(&signature); - // Add a byte representing the index of the signature - sig.push(idx); - } - let multisignature = MultiSignature::try_from_slice(&sig)?; - - Ok(Section::SectionSignature(multisignature)) - } - } +pub fn construct_signature_section( + pubkey: &[u8], + sec_indices: &[u8], + signature: &[u8], + tx: &Tx, +) -> Result { + let signatures = BTreeMap::from([(0, Signature::try_from_slice(signature)?)]); + + let compressed_signature = CompressedSignature { + targets: sec_indices.to_vec(), + signer: Signer::PubKeys(vec![PublicKey::try_from_slice(pubkey)?]), + signatures, + }; + + Ok(Section::Signature(compressed_signature.expand(&tx))) } diff --git a/packages/types/src/tx/schema/signature.ts b/packages/types/src/tx/schema/signature.ts index c168663c302..53bfc352a98 100644 --- a/packages/types/src/tx/schema/signature.ts +++ b/packages/types/src/tx/schema/signature.ts @@ -1,23 +1,22 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { field, option, vec } from "@dao-xyz/borsh"; -import { SignatureType } from "@namada/ledger-namada"; +import { field, vec } from "@dao-xyz/borsh"; import { SignatureProps } from "../types"; export class SignatureMsgValue { @field({ type: vec("u8") }) - secIndices!: Uint8Array; + pubkey!: Uint8Array; - @field({ type: option(vec("u8")) }) - singlesig!: Uint8Array; + @field({ type: vec("u8") }) + rawIndices!: Uint8Array; - @field({ type: "u8" }) - sigType!: SignatureType; + @field({ type: vec("u8") }) + rawSignature!: Uint8Array; @field({ type: vec("u8") }) - multisigIndices!: Uint8Array; + wrapperIndices!: Uint8Array; - @field({ type: vec(vec("u8")) }) - multisig!: Uint8Array[]; + @field({ type: vec("u8") }) + wrapperSignature!: Uint8Array; constructor(data: SignatureProps) { Object.assign(this, data); diff --git a/packages/types/src/tx/types.ts b/packages/types/src/tx/types.ts index 5e3b6a317fa..684c3f981ad 100644 --- a/packages/types/src/tx/types.ts +++ b/packages/types/src/tx/types.ts @@ -1,5 +1,4 @@ import BigNumber from "bignumber.js"; -import { SignatureType } from "@namada/ledger-namada" export type SubmitBondProps = { validator: string; @@ -70,9 +69,9 @@ export type BridgeTransferProps = { }; export type SignatureProps = { - secIndices: Uint8Array; - singlesig?: Uint8Array; - sigType: SignatureType; - multisigIndices: Uint8Array; - multisig: Uint8Array[]; + pubkey: Uint8Array; + rawIndices: Uint8Array; + rawSignature: Uint8Array; + wrapperIndices: Uint8Array; + wrapperSignature: Uint8Array; };