Skip to content

Commit

Permalink
Ledger refactor (#218)
Browse files Browse the repository at this point in the history
* Ledger refactor

* Remove hack

* Remove console.log

* Change body

* Throw instead of return

* Remove verify on import

* Translate error

* Add type

* Add type

* Add udev error

* Fixed chatgpt incompetence

* Fixed my incompetence
  • Loading branch information
Duddino authored Oct 6, 2023
1 parent f4fd2ea commit f83df59
Show file tree
Hide file tree
Showing 15 changed files with 203 additions and 134 deletions.
4 changes: 4 additions & 0 deletions locale/de/translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,7 @@ export default {

INTERNAL_ERROR: 'Interner Fehler, bitte versuche es später erneut', //Internal error, please try again later
FAILED_TO_IMPORT: '<b>Import fehlgeschlagen!</b> Falsches Passwort', //<b>Failed to import!</b> Invalid password
FAILED_TO_IMPORT_HARDWARE: '', // <b> Failed to import Hardware Wallet</b>.
UNSUPPORTED_CHARACTER:
'Das Zeichen {char} ist nicht erlaubt in der Adresse! (Nicht Base58 kompatibel)', //The character '{char}' is unsupported in addresses! (Not Base58 compatible)
UNSUPPORTED_WEBWORKERS:
Expand Down Expand Up @@ -435,6 +436,9 @@ export default {
WALLET_CONFIRM_L: 'Bestätige den Import auf deinem Ledger', //Confirm the import on your Ledger
WALLET_NO_HARDWARE:
'<b>Kein Gerät verfügbar</b><br>Es wurde keine Hardware-Geldbörse gefunden, bitte stecke es ein und entsperre es!', //<b>No device available</b><br>Couldn't find a hardware wallet; please plug it in and unlock!
WALLET_HARDWARE_UDEV: '', // <b>The OS denied access</b> Did you add the udev rules?
WALLET_HARDWARE_NO_ACCESS: '', // <b>The OS denied access</b> Please check your Operating System settings.

WALLET_HARDWARE_CONNECTION_LOST:
'<b>Verbindung zum {hardwareWallet} verloren</b><br>So wie es scheint, wurde das {hardwareWalletProductionName} im Prozess abgezogen, oops!', //<b>Lost connection to {hardwareWallet} </b><br>It seems the {hardwareWalletProductionName} was unplugged mid-operation, oops!
WALLET_HARDWARE_BUSY:
Expand Down
5 changes: 5 additions & 0 deletions locale/en/translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ export default {

INTERNAL_ERROR: 'Internal error, please try again later',
FAILED_TO_IMPORT: '<b>Failed to import!</b> Invalid password',
FAILED_TO_IMPORT_HARDWARE: '<b> Failed to import Hardware Wallet</b>.',
TESTNET_ENCRYPTION_DISABLED:
'<b>Testnet Mode is ON!</b><br>Wallet encryption disabled',
PASSWORD_TOO_SMALL:
Expand Down Expand Up @@ -424,6 +425,10 @@ export default {
WALLET_CONFIRM_L: 'Confirm the import on your Ledger',
WALLET_NO_HARDWARE:
"<b>No device available</b><br>Couldn't find a hardware wallet; please plug it in and unlock!",
WALLET_HARDWARE_UDEV:
'<b>The OS denied access</b> Did you add the udev rules?',
WALLET_HARDWARE_NO_ACCESS:
'<b>The OS denied access</b> Please check your Operating System settings.',
WALLET_HARDWARE_CONNECTION_LOST:
'<b>Lost connection to {hardwareWallet} </b><br>It seems the {hardwareWallet} was unplugged mid-operation, oops!',
WALLET_HARDWARE_BUSY:
Expand Down
3 changes: 3 additions & 0 deletions locale/es-mx/translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ export default {

INTERNAL_ERROR: 'Error interno, vuelve a intentarlo más tarde', //Internal error, please try again later
FAILED_TO_IMPORT: '<b>¡No se ha podido importar!</b> Contraseña inválida', //<b>Failed to import!</b> Invalid password
FAILED_TO_IMPORT_HARDWARE: '', // <b> Failed to import Hardware Wallet</b>.
UNSUPPORTED_CHARACTER:
'¡El carácter {char} no está soportado en las direcciones! (No compatible con Base58)', //The character '{char}' is unsupported in addresses! (Not Base58 compatible)
UNSUPPORTED_WEBWORKERS:
Expand Down Expand Up @@ -422,6 +423,8 @@ export default {
WALLET_CONFIRM_L: 'Confirma la importación en tu Ledger', //Confirm the import on your Ledger
WALLET_NO_HARDWARE:
'<b>No hay ningún dispositivo disponible</b><br>No se pudo encontrar una wallet de hardware; ¡Conéctala y desbloquéala!', //<b>No device available</b><br>Couldn't find a hardware wallet; please plug it in and unlock!
WALLET_HARDWARE_UDEV: '', // <b>The OS denied access</b> Did you add the udev rules?
WALLET_HARDWARE_NO_ACCESS: '', // <b>The OS denied access</b> Please check your Operating System settings.
WALLET_HARDWARE_CONNECTION_LOST:
'<b>Se perdió la conexión con {hardwareWallet} </b><br>Parece que {hardwareWalletProductionName} se desconectó en mitad de la operación, ¡ups!', //<b>Lost connection to {hardwareWallet} </b><br>It seems the {hardwareWalletProductionName} was unplugged mid-operation, oops!
WALLET_HARDWARE_BUSY:
Expand Down
3 changes: 3 additions & 0 deletions locale/fr/translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ export default {

INTERNAL_ERROR: 'Erreur interne, veuillez réessayer plus tard', //Internal error, please try again later
FAILED_TO_IMPORT: "<b>Échec de l'importation !</b> Mot de passe invalide", //<b>Failed to import!</b> Invalid password
FAILED_TO_IMPORT_HARDWARE: '', // <b> Failed to import Hardware Wallet</b>.
UNSUPPORTED_CHARACTER:
"Le caractère {char} n'est pas pris en charge dans les adresses ! (Non compatible avec Base58)", //The character '{char}' is unsupported in addresses! (Not Base58 compatible)
UNSUPPORTED_WEBWORKERS:
Expand Down Expand Up @@ -426,6 +427,8 @@ export default {
WALLET_CONFIRM_L: "Confirmez l'importation dans votre Ledger", //Confirm the import on your Ledger
WALLET_NO_HARDWARE:
"<b>Aucun dispositif disponible</b><br>Il n'a pas été possible de trouver un portefeuille de hardware; brancher et déverrouiller!", //<b>No device available</b><br>Couldn't find a hardware wallet; please plug it in and unlock!
WALLET_HARDWARE_UDEV: '', // <b>The OS denied access</b> Did you add the udev rules?
WALLET_HARDWARE_NO_ACCESS: '', // <b>The OS denied access</b> Please check your Operating System settings.
WALLET_HARDWARE_CONNECTION_LOST:
"<b>Perte de connexion avec le {hardwareWallet} </b><br>Oops! Il semble que {hardwareWalletProductionName} a été déconnecté au milieu de l'opération.", //<b>Lost connection to {hardwareWallet} </b><br>It seems the {hardwareWalletProductionName} was unplugged mid-operation, oops!
WALLET_HARDWARE_BUSY:
Expand Down
7 changes: 7 additions & 0 deletions locale/it/translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,8 @@ export default {

INTERNAL_ERROR: 'Errore interno, rirova più tardi', //Internal error, please try again later
FAILED_TO_IMPORT: '<b>Impossibile importare!</b> Password non valida', //<b>Failed to import!</b> Invalid password
FAILED_TO_IMPORT_HARDWARE:
'<b>Impossibile importare il wallet Hardware!</b>', // <b> Failed to import Hardware Wallet</b>.
UNSUPPORTED_CHARACTER:
"Il carattere '{char}' non è supportato negli indirizzi! (Non compatibile con Base58)", //The character '{char}' is unsupported in addresses! (Not Base58 compatible)
UNSUPPORTED_WEBWORKERS:
Expand Down Expand Up @@ -400,6 +402,11 @@ export default {
WALLET_CONFIRM_L: "Conferma l'importo sulla tua Ledger", //Confirm the import on your Ledger
WALLET_NO_HARDWARE:
'<b>Nessun dispositivo disponibile</b><br>Impossibile trovare un wallet hardware; per favore collegalo e sbloccalo!', //<b>No device available</b><br>Couldn't find a hardware wallet; please plug it in and unlock!
WALLET_HARDWARE_UDEV:
"<b> Il Sistema operativo ha negato l'accesso </b> Hai aggiunto le regole udev?", // <b>The OS denied access</b> Did you add the udev rules?
WALLET_HARDWARE_NO_ACCESS:
"<b> Il Sistema Operativo ha negato l'accesso </b> Perfavore, controlla le impostazioni del tuo sistema operativo.", // <b>The OS denied access</b> Please check your Operating System settings.

WALLET_HARDWARE_CONNECTION_LOST:
"<b>Connessione a {hardwareWallet} persa </b><br>Sembra che {hardwareWalletProductionName} sia stato scollegato durante l'operazione, ops!", //<b>Lost connection to {hardwareWallet} </b><br>It seems the {hardwareWalletProductionName} was unplugged mid-operation, oops!
WALLET_HARDWARE_BUSY:
Expand Down
2 changes: 2 additions & 0 deletions locale/ph/translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,8 @@ export default {
WALLET_CONFIRM_L: 'Kumpirmahin ang import sa iyong Ledger', //Confirm the import on your Ledger
WALLET_NO_HARDWARE:
'<b>Walang pwedeng magamit na device</b><br>Hindi makahanap ng hardware wallet; pakiusap i-plug in ito at buksan!', //<b>No device available</b><br>Couldn't find a hardware wallet; please plug it in and unlock!
WALLET_HARDWARE_UDEV: '', // <b>The OS denied access</b> Did you add the udev rules?
WALLET_HARDWARE_NO_ACCESS: '', // <b>The OS denied access</b> Please check your Operating System settings.
WALLET_HARDWARE_CONNECTION_LOST:
'<b>Nawala ang koneksyon sa {hardwareWallet} </b><br>Parang ang {hardwareWalletProductionName} ay na-unplug sa kalagitnaan ng operasyon, oops!', //<b>Lost connection to {hardwareWallet} </b><br>It seems the {hardwareWalletProductionName} was unplugged mid-operation, oops!
WALLET_HARDWARE_BUSY:
Expand Down
2 changes: 2 additions & 0 deletions locale/pt-br/translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,8 @@ export default {
WALLET_CONFIRM_L: 'Confirme a importação na sua Ledger', //Confirm the import on your Ledger",
WALLET_NO_HARDWARE:
'<b>Nenhum dispositivo disponível</b><br>Não foi possível encontrar uma carteira de hardware; conecte-a e desbloqueie-a!', //<b>No device available</b><br>Couldn't find a hardware wallet; please plug it in and unlock!
WALLET_HARDWARE_UDEV: '', // <b>The OS denied access</b> Did you add the udev rules?
WALLET_HARDWARE_NO_ACCESS: '', // <b>The OS denied access</b> Please check your Operating System settings.
WALLET_HARDWARE_CONNECTION_LOST:
'<b>Conexão perdida com a {hardwareWallet} </b><br>Oops! Parece que a {hardwareWalletProductionName} foi desconectada no meio da operação.', //<b>Lost connection to {hardwareWallet} </b><br>It seems the {hardwareWalletProductionName} was unplugged mid-operation, oops!
WALLET_HARDWARE_BUSY:
Expand Down
2 changes: 2 additions & 0 deletions locale/pt-pt/translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,8 @@ export default {
WALLET_CONFIRM_L: 'Confirme a importação na sua Ledger', //Confirm the import on your Ledger",
WALLET_NO_HARDWARE:
'<b>Nenhum dispositivo disponível</b><br>Não foi possível encontrar uma carteira de hardware; conecte-a e desbloqueie-a!', //<b>No device available</b><br>Couldn't find a hardware wallet; please plug it in and unlock!
WALLET_HARDWARE_UDEV: '', // <b>The OS denied access</b> Did you add the udev rules?
WALLET_HARDWARE_NO_ACCESS: '', // <b>The OS denied access</b> Please check your Operating System settings.
WALLET_HARDWARE_CONNECTION_LOST:
'<b>Conexão perdida com a {hardwareWallet} </b><br>Oops! Parece que a {hardwareWalletProductionName} foi desconectado no meio da operação.', //<b>Lost connection to {hardwareWallet} </b><br>It seems the {hardwareWalletProductionName} was unplugged mid-operation, oops!
WALLET_HARDWARE_BUSY:
Expand Down
3 changes: 3 additions & 0 deletions locale/template/translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ export default {

INTERNAL_ERROR: '', //Internal error, please try again later
FAILED_TO_IMPORT: '', //<b>Failed to import!</b> Invalid password
FAILED_TO_IMPORT_HARDWARE: '', // <b> Failed to import Hardware Wallet</b>.
UNSUPPORTED_CHARACTER: '', //The character '{char}' is unsupported in addresses! (Not Base58 compatible)
UNSUPPORTED_WEBWORKERS: '', //This browser doesn\'t support Web Workers (multi-threaded JS), unfortunately you cannot generate Vanity wallets!
INVALID_ADDRESS: '', //<b>Invalid PIVX address!</b><br> {address}
Expand Down Expand Up @@ -369,6 +370,8 @@ export default {
WALLET_CONFIRM_L: '', //Confirm the import on your Ledger
WALLET_NO_HARDWARE: '', //<b>No device available</b><br>Couldn't find a hardware wallet; please plug it in and unlock!
WALLET_HARDWARE_CONNECTION_LOST: '', //<b>Lost connection to {hardwareWallet} </b><br>It seems the {hardwareWalletProductionName} was unplugged mid-operation, oops!
WALLET_HARDWARE_UDEV: '', // <b>The OS denied access</b> Did you add the udev rules?
WALLET_HARDWARE_NO_ACCESS: '', // <b>The OS denied access</b> Please check your Operating System settings.
WALLET_HARDWARE_BUSY: '', //<b>{hardwareWallet} is waiting</b><br>Please unlock your {hardwareWalletProductionName} or finish it's current prompt
WALLET_HARDWARE_ERROR: '', //<b> {hardwareWallet} </b><br> {error}

Expand Down
4 changes: 4 additions & 0 deletions locale/uwu/translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,10 @@ export default {
"<b>No device avaiwable ☹</b><br>Couldn't find a hawdware wawwet; pwease pwug it in and unwock!", //"<b>No device available</b><br>Couldn't find a hardware wallet; please plug it in and unlock!",
WALLET_HARDWARE_CONNECTION_LOST:
'<b>Wost connection to da {hardwareWallet} </b><br>It seems da {hardwareWalletProductionName} was unpwugged mid-opewation, oops!!', // "<b>Lost connection to {hardwareWallet} </b><br>It seems the {hardwareWalletProductionName} was unplugged mid-operation, oops!",
WALLET_HARDWARE_UDEV:
'<b>Onii-chan noticed the OS denied access~ OwO Did you add the udev rules? UwU</b>', // <b>The OS denied access</b> Did you add the udev rules?
WALLET_HARDWARE_NO_ACCESS:
'<b>Nyaa~ The OS denied access, nya~</b> Please purr-retty please check your Operating System settings, nya~ UwU', // <b>The OS denied access</b> Please check your Operating System settings.
WALLET_HARDWARE_BUSY:
"<b>{hardwareWallet} is waiting!</b><br>Pwease unwock yowour {hardwareWalletProductionName} or finish it's cuwwent pwompt", //"<b>{hardwareWallet} is waiting</b><br>Please unlock your {hardwareWalletProductionName} or finish it's current prompt",
WALLET_HARDWARE_ERROR: '<b> {hardwareWallet} </b><br> {error}', //"<b> {hardwareWallet} </b><br> {error}"
Expand Down
1 change: 1 addition & 0 deletions scripts/global.js
Original file line number Diff line number Diff line change
Expand Up @@ -1610,6 +1610,7 @@ export async function wipePrivateData() {
* @returns {Promise<boolean>} - If the unlock was successful or rejected
*/
export async function restoreWallet(strReason = '') {
if (wallet.isHardwareWallet()) return true;
// Build up the UI elements based upon conditions for the unlock prompt
let strHTML = '';

Expand Down
57 changes: 32 additions & 25 deletions scripts/ledger.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,23 @@ import createXpub from 'create-xpub';
import { ALERTS, tr } from './i18n.js';
import AppBtc from '@ledgerhq/hw-app-btc';
import TransportWebUSB from '@ledgerhq/hw-transport-webusb';
import { createAlert, sleep } from './misc.js';
import { createAlert } from './misc.js';

/**
* @type{TransportWebUSB}
*/
let transport;
/**
* @type {AppBtc?}
*/
export let cHardwareWallet = null;
export let strHardwareName = '';
export async function getHardwareWalletKeys(
path,
xpub = false,
verify = false,
_attempts = 0
) {
/**
* Get hardware wallet keys.
* @param {string} path - bip32 path to the key
* @returns {Promise<string?>}
*/
export async function getHardwareWalletKeys(path, xpub = false, verify = true) {
try {
// Check if we haven't setup a connection yet OR the previous connection disconnected
if (!cHardwareWallet || transport._disconnectEmitted) {
Expand Down Expand Up @@ -46,13 +52,13 @@ export async function getHardwareWalletKeys(
} catch (e) {
if (e.message.includes('denied by the user')) {
// User denied an operation
return false;
return null;
}

// If there's no device, nudge the user to plug it in.
if (e.message.toLowerCase().includes('no device selected')) {
createAlert('info', ALERTS.WALLET_NO_HARDWARE, 10000);
return false;
return null;
}

// If the device is unplugged, or connection lost through other means (such as spontanious device explosion)
Expand All @@ -66,19 +72,7 @@ export async function getHardwareWalletKeys(
]),
10000
);
return false;
}
if (_attempts < 10) {
// This is an ugly hack :(
// in the event where multiple parts of the code decide to ask for an address, just
// Retry at most 10 times waiting 200ms each time
await sleep(200);
return await getHardwareWalletKeys(
path,
xpub,
verify,
_attempts + 1
);
return null;
}

// If the ledger is busy, just nudge the user.
Expand All @@ -92,15 +86,28 @@ export async function getHardwareWalletKeys(
]),
7500
);
return false;
return null;
}

// This is when the OS denies access to the WebUSB
// It's likely caused by faulty udev rules on linux
if (e instanceof DOMException && e.message.includes('Access Denied')) {
if (navigator.userAgent.toLowerCase().includes('linux')) {
createAlert('warning', ALERTS.WALLET_HARDWARE_UDEV, 5500);
} else {
createAlert('warning', ALERTS.WALLET_HARDWARE_NO_ACCESS, 5500);
}

console.error(e);
return;
}

// Check if this is an expected error
if (!e.statusCode || !LEDGER_ERRS.has(e.statusCode)) {
console.error(
'MISSING LEDGER ERROR-CODE TRANSLATION! - Please report this below error on our GitHub so we can handle it more nicely!'
);
console.error(e);
throw e;
}

// Translate the error to a user-friendly string (if possible)
Expand All @@ -117,7 +124,7 @@ export async function getHardwareWalletKeys(
5500
);

return false;
return null;
}
}

Expand Down
Loading

0 comments on commit f83df59

Please sign in to comment.