Compare commits

..
47 Commits
Author SHA1 Message Date
Craig Raw c8d997fbf0 v1.4.2 2021-06-23 12:51:38 +02:00
Craig Raw 911ed3a718 improve background text 2021-06-23 12:30:58 +02:00
Craig Raw dbfed31432 add format toggle to message signing dialog (electrum or trezor) 2021-06-22 16:00:15 +02:00
Craig Raw 6f3d4e224e add context menu item to copy transaction hex 2021-06-22 11:47:56 +02:00
Craig Raw 4d6609990c fix error messages on subclassed importers/exporters 2021-06-22 10:13:37 +02:00
Craig Raw 5482196cc7 dark theme improvements 2021-06-22 08:36:16 +02:00
Craig Raw 09f6c9ef81 ensure cleanup of migrated wallets when importing 2021-06-21 11:50:58 +02:00
Craig Raw 9b8f97c041 fix import of sparrow wallet with seed, alphabetically sort import and export choices 2021-06-21 11:25:47 +02:00
Craig Raw c68c713a4b add orig files for keystone and seedsigner 2021-06-18 13:31:08 +02:00
Craig Raw 02e144f802 set keystore label, model and source type when importing a wallet from specter desktop 2021-06-18 11:21:53 +02:00
Craig Raw a9ab4d6c78 Handle importing a wallet from a crypto-account QR using the File > Import Wallet dialog 2021-06-17 14:34:11 +02:00
Craig Raw 5df4e5761c add seedsigner keystore import 2021-06-16 14:46:55 +02:00
Craig Raw 6d8b8579ba followup 2021-06-16 09:37:35 +02:00
Craig Raw eaa5190502 various db persistence improvements 2021-06-16 09:35:26 +02:00
Craig Raw 445db6a4d6 reduce file reads on db files to avoid locking exception on windows 2021-06-15 17:58:25 +02:00
Craig Raw 7f178b5f67 jpms related changes for v1.4.2-beta 2021-06-15 16:50:05 +02:00
Craig Raw 1208baf00e use mempool.space onion address for fee rates if tor proxy enabled 2021-06-15 09:31:12 +02:00
Craig Raw 655a473cd5 update send selected button when freezing or unfreezing utxos 2021-06-14 16:58:05 +02:00
Craig Raw e6c536930b highlight default button and allow actioning from keyboard when only one usb device is listed 2021-06-14 16:55:01 +02:00
Craig Raw f1510de360 update encrypted seeds and private keys when wallet password changes 2021-06-14 14:54:40 +02:00
Craig Raw cfac2768ae use varbinary rather than fixed binary column types where length is variable 2021-06-14 11:52:12 +02:00
Craig Raw ab41f2e80e upgrade to h2 HEAD 2021-06-11 15:45:16 +02:00
Craig Raw 9ebabecfbe use json persistence for sparrow wallet export, add sparrow wallet import to wallets dir 2021-06-11 11:29:54 +02:00
Craig Raw 8914acff68 minor followup 2021-06-10 17:02:32 +02:00
Craig Raw 4a0ecba716 add keystone hww import and export 2021-06-10 16:37:41 +02:00
Craig Raw e99b1d4171 upgrade to hwi 2.0.2 and relocate hwi to sparrow home folder on osx to avoid partial installation deletions in tmpdir 2021-06-10 14:06:14 +02:00
Craig Raw a59d5d3086 introduce database persistence with automatic migration of existing wallets 2021-06-10 12:08:35 +02:00
Craig Raw 600a77da3a allow psbts without utxo data to be loaded if utxos are provided in an existing psbt 2021-05-28 11:09:23 +02:00
craigrawandGitHub bc83f6fa22 Merge pull request #134 from haakonn/mnemonic-entry
Make mnemonic entry more efficient
2021-05-27 16:18:39 +02:00
Haakon Nilsen 4cbde7e7aa When entering mnemonic words, don't close dropdown when a prefix is encountered, and move focus to the next field upon completion 2021-05-27 10:56:47 +02:00
craigrawandGitHub 3ae63408e6 Merge pull request #133 from haakonn/save-tx-menuitems
Fixes around transaction saving menu items
2021-05-27 09:58:11 +02:00
Haakon Nilsen e740c6d162 Disable transaction saving menu items after a transaction tab is closed and no other tabs are open 2021-05-27 09:15:36 +02:00
Haakon Nilsen f7f5852476 Disable the "Save transaction" menu item when starting app without any open tabs 2021-05-26 18:57:07 +02:00
Haakon Nilsen 447e2ab264 Disable the keyboard shortcut for saving PSBT binary when its parent menu is disabled 2021-05-26 18:54:20 +02:00
craigrawandGitHub 8a77f22158 Merge pull request #132 from haakonn/close-on-escape
Close "About" and "Introduction" when Escape key is pressed
2021-05-26 08:39:16 +02:00
Haakon Nilsen c096327be4 Close "About" and "Introduction" when Escape key is pressed 2021-05-25 22:13:51 +02:00
Craig Raw 911153e1aa fix receive to address context menu actions 2021-05-25 08:21:17 +02:00
Craig Raw a60eadf8fc add export to specter diy 2021-05-24 14:20:08 +02:00
Craig Raw 9ebbf2557f support electrs batching and improve batching read timeout handling 2021-05-24 13:39:06 +02:00
Craig Raw 42b279d22a add specter desktop reimport usb wallets warning 2021-05-24 12:29:57 +02:00
Craig Raw 1a452db4cf add tooltip to send utxos button with directions on how to select multiple utxos 2021-05-24 12:27:30 +02:00
Craig Raw c1cf5be616 add mempool.bisq.services as a broadcaster, broadcast tx twice if possible on mainnet, handle different network broadcaster network capabilities 2021-05-21 11:48:13 +02:00
Craig Raw dd146210ba set send amount to total utxo value when sending selected utxos before an address or label is added 2021-05-21 09:53:00 +02:00
Craig Raw 94088f795c handle invalid values from mempool.get_fee_histogram 2021-05-21 08:44:55 +02:00
Craig Raw c5b09189df explicitly place decorationpane in the scene graph to avoid app resizing issues 2021-05-20 17:27:33 +02:00
Craig Raw 197c44bb07 update null and empty labels, clear script hash cache on increasing gap limit 2021-05-20 14:49:16 +02:00
Craig Raw c202a941b9 add mempool.emzy.de as another broadcaster 2021-05-20 14:48:01 +02:00
121 changed files with 3266 additions and 566 deletions
+14 -2
View File
@@ -5,7 +5,7 @@ plugins {
id 'org.beryx.jlink' version '2.22.0'
}
def sparrowVersion = '1.4.1'
def sparrowVersion = '1.4.2'
def os = org.gradle.internal.os.OperatingSystem.current()
def osName = os.getFamilyName()
if(os.macOsX) {
@@ -44,6 +44,13 @@ dependencies {
}
implementation('com.google.guava:guava:28.2-jre')
implementation('com.google.code.gson:gson:2.8.6')
implementation('com.h2database:h2:1.4.201-SNAPSHOT')
implementation('com.zaxxer:HikariCP:4.0.3')
implementation('org.jdbi:jdbi3-core:3.20.0') {
exclude group: 'org.slf4j'
}
implementation('org.jdbi:jdbi3-sqlobject:3.20.0')
implementation('org.flywaydb:flyway-core:7.10.5-SNAPSHOT')
implementation('org.fxmisc.richtext:richtextfx:0.10.4')
implementation('no.tornado:tornadofx-controls:1.0.4')
implementation('com.google.zxing:javase:3.4.0')
@@ -105,6 +112,7 @@ run {
"--add-opens=javafx.base/com.sun.javafx.event=org.controlsfx.controls",
"--add-opens=javafx.controls/javafx.scene.control.cell=com.sparrowwallet.sparrow",
"--add-opens=org.controlsfx.controls/impl.org.controlsfx.skin=com.sparrowwallet.sparrow",
"--add-opens=org.controlsfx.controls/impl.org.controlsfx.skin=javafx.fxml",
"--add-opens=javafx.graphics/com.sun.javafx.tk=centerdevice.nsmenufx",
"--add-opens=javafx.graphics/com.sun.javafx.tk.quantum=centerdevice.nsmenufx",
"--add-opens=javafx.graphics/com.sun.glass.ui=centerdevice.nsmenufx",
@@ -130,6 +138,8 @@ jlink {
requires 'com.fasterxml.jackson.databind'
requires 'jdk.crypto.cryptoki'
requires 'java.management'
uses 'org.flywaydb.core.extensibility.FlywayExtension'
uses 'org.flywaydb.core.internal.database.DatabaseType'
}
options = ['--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages', '--ignore-signing-information', '--exclude-files', '**.png']
@@ -143,6 +153,7 @@ jlink {
"--add-opens=javafx.base/com.sun.javafx.event=org.controlsfx.controls",
"--add-opens=javafx.controls/javafx.scene.control.cell=com.sparrowwallet.sparrow",
"--add-opens=org.controlsfx.controls/impl.org.controlsfx.skin=com.sparrowwallet.sparrow",
"--add-opens=org.controlsfx.controls/impl.org.controlsfx.skin=javafx.fxml",
"--add-opens=javafx.graphics/com.sun.javafx.tk=com.sparrowwallet.merged.module",
"--add-opens=javafx.graphics/com.sun.javafx.tk.quantum=com.sparrowwallet.merged.module",
"--add-opens=javafx.graphics/com.sun.glass.ui=com.sparrowwallet.merged.module",
@@ -152,7 +163,8 @@ jlink {
"--add-opens=javafx.graphics/com.sun.javafx.application=com.sparrowwallet.sparrow",
"--add-opens=java.base/java.net=com.sparrowwallet.sparrow",
"--add-reads=com.sparrowwallet.merged.module=java.desktop",
"--add-reads=com.sparrowwallet.merged.module=java.sql"]
"--add-reads=com.sparrowwallet.merged.module=java.sql",
"--add-reads=com.sparrowwallet.merged.module=com.sparrowwallet.sparrow"]
if(os.macOsX) {
jvmArgs += "--add-opens=javafx.graphics/com.sun.glass.ui.mac=com.sparrowwallet.merged.module"
+1 -1
Submodule drongo updated: 567294a4b0...c021300797
+1 -1
View File
@@ -21,7 +21,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.4.1</string>
<string>1.4.2</string>
<key>CFBundleSignature</key>
<string>????</string>
<!-- See https://developer.apple.com/app-store/categories/ for list of AppStore categories -->
@@ -12,7 +12,7 @@ public class AboutController {
private Label title;
public void initializeView() {
title.setText(MainApp.APP_NAME + " " + MainApp.APP_VERSION);
title.setText(MainApp.APP_NAME + " " + MainApp.APP_VERSION + MainApp.APP_VERSION_SUFFIX);
}
public void setStage(Stage stage) {
@@ -18,6 +18,7 @@ import com.sparrowwallet.drongo.protocol.Transaction;
import com.sparrowwallet.drongo.psbt.PSBT;
import com.sparrowwallet.drongo.psbt.PSBTInput;
import com.sparrowwallet.drongo.psbt.PSBTParseException;
import com.sparrowwallet.drongo.psbt.PSBTSignatureException;
import com.sparrowwallet.drongo.wallet.*;
import com.sparrowwallet.sparrow.control.*;
import com.sparrowwallet.sparrow.event.*;
@@ -87,6 +88,9 @@ public class AppController implements Initializable {
@FXML
private Menu savePSBT;
@FXML
private MenuItem savePSBTBinary;
@FXML
private MenuItem exportWallet;
@@ -232,6 +236,8 @@ public class AppController implements Initializable {
if(tabs.getTabs().isEmpty()) {
Stage tabStage = (Stage)tabs.getScene().getWindow();
tabStage.setTitle("Sparrow");
saveTransaction.setVisible(true);
saveTransaction.setDisable(true);
}
}
});
@@ -266,7 +272,9 @@ public class AppController implements Initializable {
showTxHex.setSelected(Config.get().isShowTransactionHex());
showLoadingLog.setSelected(Config.get().isShowLoadingLog());
showUtxosChart.setSelected(Config.get().isShowUtxosChart());
saveTransaction.setDisable(true);
savePSBT.visibleProperty().bind(saveTransaction.visibleProperty().not());
savePSBTBinary.disableProperty().bind(saveTransaction.visibleProperty());
exportWallet.setDisable(true);
refreshWallet.disableProperty().bind(Bindings.or(exportWallet.disableProperty(), Bindings.or(serverToggle.disableProperty(), AppServices.onlineProperty().not())));
sendToMany.disableProperty().bind(exportWallet.disableProperty());
@@ -351,7 +359,9 @@ public class AppController implements Initializable {
stage.setTitle("About " + MainApp.APP_NAME);
stage.initStyle(org.controlsfx.tools.Platform.getCurrent() == org.controlsfx.tools.Platform.OSX ? StageStyle.UNDECORATED : StageStyle.DECORATED);
stage.setResizable(false);
stage.setScene(new Scene(root));
Scene scene = new Scene(root);
AppServices.onEscapePressed(scene, stage::close);
stage.setScene(scene);
controller.setStage(stage);
controller.initializeView();
setStageIcon(stage);
@@ -752,12 +762,11 @@ public class AppController implements Initializable {
public void openWalletFile(File file, boolean forceSameWindow) {
try {
Storage storage = new Storage(file);
FileType fileType = IOUtils.getFileType(file);
if(FileType.JSON.equals(fileType)) {
if(!storage.isEncrypted()) {
WalletBackupAndKey walletBackupAndKey = storage.loadUnencryptedWallet();
openWallet(storage, walletBackupAndKey, this, forceSameWindow);
} else if(FileType.BINARY.equals(fileType)) {
WalletPasswordDialog dlg = new WalletPasswordDialog(file.getName(), WalletPasswordDialog.PasswordRequirement.LOAD);
} else {
WalletPasswordDialog dlg = new WalletPasswordDialog(storage.getWalletName(null), WalletPasswordDialog.PasswordRequirement.LOAD);
Optional<SecureString> optionalPassword = dlg.showAndWait();
if(optionalPassword.isEmpty()) {
return;
@@ -766,12 +775,12 @@ public class AppController implements Initializable {
SecureString password = optionalPassword.get();
Storage.LoadWalletService loadWalletService = new Storage.LoadWalletService(storage, password);
loadWalletService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(storage.getWalletFile(), TimedEvent.Action.END, "Done"));
EventManager.get().post(new StorageEvent(storage.getWalletId(null), TimedEvent.Action.END, "Done"));
WalletBackupAndKey walletBackupAndKey = loadWalletService.getValue();
openWallet(storage, walletBackupAndKey, this, forceSameWindow);
});
loadWalletService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(storage.getWalletFile(), TimedEvent.Action.END, "Failed"));
EventManager.get().post(new StorageEvent(storage.getWalletId(null), TimedEvent.Action.END, "Failed"));
Throwable exception = loadWalletService.getException();
if(exception instanceof InvalidPasswordException) {
Optional<ButtonType> optResponse = showErrorDialog("Invalid Password", "The wallet password was invalid. Try again?", ButtonType.CANCEL, ButtonType.OK);
@@ -786,11 +795,11 @@ public class AppController implements Initializable {
password.clear();
}
});
EventManager.get().post(new StorageEvent(storage.getWalletFile(), TimedEvent.Action.START, "Decrypting wallet..."));
EventManager.get().post(new StorageEvent(storage.getWalletId(null), TimedEvent.Action.START, "Decrypting wallet..."));
loadWalletService.start();
} else {
throw new IOException("Unsupported file type");
}
} catch(StorageException e) {
showErrorDialog("Error Opening Wallet", e.getMessage());
} catch(Exception e) {
if(!attemptImportWallet(file, null)) {
log.error("Error opening wallet", e);
@@ -812,6 +821,7 @@ public class AppController implements Initializable {
}
Platform.runLater(() -> selectTab(walletBackupAndKey.getWallet()));
} catch(Exception e) {
log.error("Error opening wallet", e);
showErrorDialog("Error Opening Wallet", e.getMessage());
} finally {
walletBackupAndKey.clear();
@@ -886,7 +896,8 @@ public class AppController implements Initializable {
new Electrum(),
new SpecterDesktop(),
new CoboVaultSinglesig(), new CoboVaultMultisig(),
new PassportSinglesig());
new PassportSinglesig(),
new KeystoneSinglesig(), new KeystoneMultisig());
for(WalletImport importer : walletImporters) {
try(FileInputStream inputStream = new FileInputStream(file)) {
if(importer.isEncrypted(file) && password == null) {
@@ -950,6 +961,10 @@ public class AppController implements Initializable {
walletFile.delete();
}
if(wallet.isEncrypted()) {
throw new IllegalArgumentException("Imported wallet must be unencrypted");
}
Storage storage = new Storage(Storage.getWalletFile(wallet.getName()));
WalletPasswordDialog dlg = new WalletPasswordDialog(wallet.getName(), WalletPasswordDialog.PasswordRequirement.UPDATE_NEW);
Optional<SecureString> password = dlg.showAndWait();
@@ -958,14 +973,16 @@ public class AppController implements Initializable {
try {
storage.setEncryptionPubKey(Storage.NO_PASSWORD_KEY);
storage.saveWallet(wallet);
checkWalletNetwork(wallet);
restorePublicKeysFromSeed(wallet, null);
addWalletTabOrWindow(storage, wallet, null, false);
} catch(IOException e) {
} catch(IOException | StorageException | MnemonicException e) {
log.error("Error saving imported wallet", e);
}
} else {
Storage.KeyDerivationService keyDerivationService = new Storage.KeyDerivationService(storage, password.get());
keyDerivationService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(Storage.getWalletFile(wallet.getName()), TimedEvent.Action.END, "Done"));
EventManager.get().post(new StorageEvent(Storage.getWalletFile(wallet.getName()).getAbsolutePath(), TimedEvent.Action.END, "Done"));
ECKey encryptionFullKey = keyDerivationService.getValue();
Key key = null;
@@ -975,8 +992,10 @@ public class AppController implements Initializable {
wallet.encrypt(key);
storage.setEncryptionPubKey(encryptionPubKey);
storage.saveWallet(wallet);
checkWalletNetwork(wallet);
restorePublicKeysFromSeed(wallet, key);
addWalletTabOrWindow(storage, wallet, null, false);
} catch(IOException e) {
} catch(IOException | StorageException | MnemonicException e) {
log.error("Error saving imported wallet", e);
} finally {
encryptionFullKey.clear();
@@ -986,10 +1005,10 @@ public class AppController implements Initializable {
}
});
keyDerivationService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(Storage.getWalletFile(wallet.getName()), TimedEvent.Action.END, "Failed"));
EventManager.get().post(new StorageEvent(Storage.getWalletFile(wallet.getName()).getAbsolutePath(), TimedEvent.Action.END, "Failed"));
showErrorDialog("Error encrypting wallet", keyDerivationService.getException().getMessage());
});
EventManager.get().post(new StorageEvent(Storage.getWalletFile(wallet.getName()), TimedEvent.Action.START, "Encrypting wallet..."));
EventManager.get().post(new StorageEvent(Storage.getWalletFile(wallet.getName()).getAbsolutePath(), TimedEvent.Action.START, "Encrypting wallet..."));
keyDerivationService.start();
}
}
@@ -1070,12 +1089,12 @@ public class AppController implements Initializable {
walletTabData.getStorage().backupTempWallet();
wallet.clearHistory();
AppServices.clearTransactionHistoryCache(wallet);
EventManager.get().post(new WalletAddressesChangedEvent(wallet, pastWallet, walletTabData.getStorage().getWalletFile()));
EventManager.get().post(new WalletHistoryClearedEvent(wallet, pastWallet, walletTabData.getWalletForm().getWalletId()));
}
}
public AppController addWalletTabOrWindow(Storage storage, Wallet wallet, Wallet backupWallet, boolean forceSameWindow) {
Window existingWalletWindow = AppServices.get().getWindowForWallet(storage);
Window existingWalletWindow = AppServices.get().getWindowForWallet(storage.getWalletId(wallet));
if(existingWalletWindow instanceof Stage) {
Stage existingWalletStage = (Stage)existingWalletWindow;
existingWalletStage.toFront();
@@ -1099,10 +1118,7 @@ public class AppController implements Initializable {
public void addWalletTab(Storage storage, Wallet wallet, Wallet backupWallet) {
try {
String name = storage.getWalletFile().getName();
if(name.endsWith(".json")) {
name = name.substring(0, name.lastIndexOf('.'));
}
String name = storage.getWalletName(wallet);
if(!name.equals(wallet.getName())) {
wallet.setName(name);
}
@@ -1167,7 +1183,8 @@ public class AppController implements Initializable {
private void addTransactionTab(String name, File file, byte[] bytes) throws PSBTParseException, ParseException, TransactionParseException {
if(PSBT.isPSBT(bytes)) {
PSBT psbt = new PSBT(bytes);
//Don't verify signatures here - provided PSBT may omit UTXO data that can be found when combining with an existing PSBT
PSBT psbt = new PSBT(bytes, false);
addTransactionTab(name, file, psbt);
} else if(Transaction.isTransaction(bytes)) {
try {
@@ -1243,6 +1260,16 @@ public class AppController implements Initializable {
}
}
if(psbt != null) {
try {
//Any PSBTs that have reached this point could not be combined with an existing PSBT. Verify signatures before continuing
psbt.verifySignatures();
} catch(PSBTSignatureException e) {
AppServices.showErrorDialog("Invalid PSBT", e.getMessage());
return;
}
}
try {
String tabName = name;
@@ -1483,7 +1510,7 @@ public class AppController implements Initializable {
TabData tabData = (TabData)tab.getUserData();
if(tabData instanceof WalletTabData) {
WalletTabData walletTabData = (WalletTabData)tabData;
if(walletTabData.getWalletForm().getWalletFile().equals(event.getWalletFile())) {
if(walletTabData.getWalletForm().getWalletId().equals(event.getWalletId())) {
exportWallet.setDisable(!event.getWallet().isValid());
}
}
@@ -1798,6 +1825,17 @@ public class AppController implements Initializable {
@Subscribe
public void viewWallet(ViewWalletEvent event) {
if(tabs.getScene().getWindow().equals(event.getWindow())) {
for(Tab tab : tabs.getTabs()) {
TabData tabData = (TabData) tab.getUserData();
if(tabData.getType() == TabData.TabType.WALLET) {
WalletTabData walletTabData = (WalletTabData) tabData;
if(event.getStorage().getWalletId(event.getWallet()).equals(walletTabData.getWalletForm().getWalletId())) {
tabs.getSelectionModel().select(tab);
return;
}
}
}
for(Tab tab : tabs.getTabs()) {
TabData tabData = (TabData) tab.getUserData();
if(tabData.getType() == TabData.TabType.WALLET) {
@@ -1884,4 +1922,4 @@ public class AppController implements Initializable {
public void recieveAction(ReceiveActionEvent event) {
selectTab(event.getWallet());
}
}
}
@@ -31,6 +31,7 @@ import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.text.Font;
import javafx.stage.Screen;
import javafx.stage.Stage;
@@ -372,6 +373,10 @@ public class AppServices {
return Tor.getDefault() != null;
}
public static boolean isUsingProxy() {
return isTorRunning() || Config.get().isUseProxy();
}
public static Proxy getProxy() {
return getProxy(TOR_DEFAULT_PROXY_CIRCUIT_ID);
}
@@ -449,6 +454,14 @@ public class AppServices {
stage.hide();
}
public static void onEscapePressed(Scene scene, Runnable runnable) {
scene.setOnKeyPressed(event -> {
if(event.getCode() == KeyCode.ESCAPE) {
runnable.run();
}
});
}
public Map<Wallet, Storage> getOpenWallets() {
Map<Wallet, Storage> openWallets = new LinkedHashMap<>();
for(List<WalletTabData> walletTabDataList : walletWindows.values()) {
@@ -460,8 +473,8 @@ public class AppServices {
return openWallets;
}
public Window getWindowForWallet(Storage storage) {
Optional<Window> optWindow = walletWindows.entrySet().stream().filter(entry -> entry.getValue().stream().anyMatch(walletTabData -> walletTabData.getStorage().getWalletFile().equals(storage.getWalletFile()))).map(Map.Entry::getKey).findFirst();
public Window getWindowForWallet(String walletId) {
Optional<Window> optWindow = walletWindows.entrySet().stream().filter(entry -> entry.getValue().stream().anyMatch(walletTabData -> walletTabData.getWalletForm().getWalletId().equals(walletId))).map(Map.Entry::getKey).findFirst();
return optWindow.orElse(null);
}
@@ -535,8 +548,7 @@ public class AppServices {
}
public static boolean isWalletFile(File file) {
FileType fileType = IOUtils.getFileType(file);
return FileType.JSON.equals(fileType) || FileType.BINARY.equals(fileType);
return Storage.isWalletFile(file);
}
public static Optional<ButtonType> showWarningDialog(String title, String content, ButtonType... buttons) {
@@ -573,7 +585,7 @@ public class AppServices {
String[] lines = content.split("\r\n|\r|\n");
if(lines.length > 3) {
alert.getDialogPane().setPrefHeight(180 + lines.length * 20);
alert.getDialogPane().setPrefHeight(200 + lines.length * 20);
}
moveToActiveWindowScreen(alert);
@@ -607,10 +619,6 @@ public class AppServices {
}
}
public void moveToWalletWindowScreen(Storage storage, Dialog<?> dialog) {
moveToWindowScreen(getWindowForWallet(storage), dialog);
}
public static void moveToWindowScreen(Window currentWindow, Dialog<?> dialog) {
Window newWindow = dialog.getDialogPane().getScene().getWindow();
DialogPane dialogPane = dialog.getDialogPane();
@@ -828,7 +836,10 @@ public class AppServices {
@Subscribe
public void openWallets(OpenWalletsEvent event) {
if(event.getWalletTabDataList().isEmpty()) {
walletWindows.remove(event.getWindow());
List<WalletTabData> closedTabData = walletWindows.remove(event.getWindow());
if(closedTabData != null && !closedTabData.isEmpty()) {
EventManager.get().post(new WalletTabsClosedEvent(closedTabData));
}
} else {
walletWindows.put(event.getWindow(), event.getWalletTabDataList());
}
@@ -854,10 +865,6 @@ public class AppServices {
deviceEnumerateService = createDeviceEnumerateService();
}
if(deviceEnumerateService.isRunning()) {
deviceEnumerateService.cancel();
}
if(deviceEnumerateService.getState() == Worker.State.CANCELLED) {
deviceEnumerateService.reset();
}
@@ -7,8 +7,6 @@ import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5Brands;
import com.sparrowwallet.sparrow.io.Config;
import com.sparrowwallet.sparrow.io.FileType;
import com.sparrowwallet.sparrow.io.IOUtils;
import com.sparrowwallet.sparrow.io.Storage;
import com.sparrowwallet.sparrow.net.Bwt;
import com.sparrowwallet.sparrow.net.PublicElectrumServer;
@@ -33,7 +31,8 @@ import java.util.stream.Collectors;
public class MainApp extends Application {
public static final String APP_ID = "com.sparrowwallet.sparrow";
public static final String APP_NAME = "Sparrow";
public static final String APP_VERSION = "1.4.1";
public static final String APP_VERSION = "1.4.2";
public static final String APP_VERSION_SUFFIX = "";
public static final String APP_HOME_PROPERTY = "sparrow.home";
public static final String NETWORK_ENV_PROPERTY = "SPARROW_NETWORK";
@@ -99,9 +98,8 @@ public class MainApp extends Application {
List<File> recentWalletFiles = Config.get().getRecentWalletFiles();
if(recentWalletFiles != null) {
//Re-sort to preserve wallet order as far as possible. Unencrypted wallets will still be opened first.
List<File> encryptedWalletFiles = recentWalletFiles.stream().filter(file -> FileType.BINARY.equals(IOUtils.getFileType(file))).collect(Collectors.toList());
Collections.reverse(encryptedWalletFiles);
//Preserve wallet order as far as possible. Unencrypted wallets will still be opened first.
List<File> encryptedWalletFiles = recentWalletFiles.stream().filter(Storage::isEncrypted).collect(Collectors.toList());
List<File> sortedWalletFiles = new ArrayList<>(recentWalletFiles);
sortedWalletFiles.removeAll(encryptedWalletFiles);
sortedWalletFiles.addAll(encryptedWalletFiles);
@@ -12,6 +12,7 @@ public class WelcomeDialog extends Dialog<Mode> {
public WelcomeDialog() {
final DialogPane dialogPane = getDialogPane();
AppServices.setStageIcon(dialogPane.getScene().getWindow());
AppServices.onEscapePressed(dialogPane.getScene(), this::close);
try {
FXMLLoader welcomeLoader = new FXMLLoader(AppServices.class.getResource("welcome.fxml"));
@@ -3,6 +3,7 @@ package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.drongo.address.Address;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.wallet.Entry;
import com.sparrowwallet.sparrow.wallet.NodeEntry;
import com.sparrowwallet.sparrow.wallet.UtxoEntry;
import javafx.geometry.Pos;
import javafx.scene.control.ContentDisplay;
@@ -32,7 +33,7 @@ public class AddressCell extends TreeTableCell<Entry, Entry> {
UtxoEntry utxoEntry = (UtxoEntry)entry;
Address address = utxoEntry.getAddress();
setText(address.toString());
setContextMenu(new EntryCell.AddressContextMenu(address, utxoEntry.getOutputDescriptor(), null));
setContextMenu(new EntryCell.AddressContextMenu(address, utxoEntry.getOutputDescriptor(), new NodeEntry(utxoEntry.getWallet(), utxoEntry.getNode())));
Tooltip tooltip = new Tooltip();
tooltip.setText(getTooltipText(utxoEntry));
setTooltip(tooltip);
@@ -5,8 +5,8 @@ import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.event.WalletDataChangedEvent;
import com.sparrowwallet.sparrow.event.WalletHistoryClearedEvent;
import com.sparrowwallet.sparrow.event.WalletHistoryStatusEvent;
import com.sparrowwallet.sparrow.event.WalletAddressesChangedEvent;
import com.sparrowwallet.sparrow.io.Config;
import com.sparrowwallet.sparrow.io.Storage;
import com.sparrowwallet.sparrow.net.ServerType;
@@ -92,7 +92,7 @@ public class CoinTreeTable extends TreeTableView<Entry> {
EventManager.get().post(new WalletDataChangedEvent(wallet));
//Trigger full wallet rescan
wallet.clearHistory();
EventManager.get().post(new WalletAddressesChangedEvent(wallet, pastWallet, storage.getWalletFile()));
EventManager.get().post(new WalletHistoryClearedEvent(wallet, pastWallet, storage.getWalletId(wallet)));
}
});
if(wallet.getBirthDate() == null) {
@@ -25,8 +25,8 @@ public class DeviceAddressDialog extends DeviceDialog<String> {
}
@Override
protected DevicePane getDevicePane(Device device) {
return new DevicePane(wallet, outputDescriptor, device);
protected DevicePane getDevicePane(Device device, boolean defaultDevice) {
return new DevicePane(wallet, outputDescriptor, device, defaultDevice);
}
@Subscribe
@@ -22,6 +22,7 @@ import java.util.Objects;
public abstract class DeviceDialog<R> extends Dialog<R> {
private final List<String> operationFingerprints;
private final Accordion deviceAccordion;
private final Button scanButton;
private final VBox scanBox;
private final Label scanLabel;
@@ -57,18 +58,19 @@ public abstract class DeviceDialog<R> extends Dialog<R> {
Glyph usb = new Glyph(FontAwesome5Brands.FONT_NAME, FontAwesome5Brands.Glyph.USB);
usb.setFontSize(50);
scanLabel = new Label("Connect Hardware Wallet");
Button button = new Button("Scan...");
button.setPrefSize(120, 60);
button.setOnAction(event -> {
scanButton = new Button("Scan...");
scanButton.setPrefSize(120, 60);
scanButton.setOnAction(event -> {
scan();
});
scanBox.getChildren().addAll(usb, scanLabel, button);
scanBox.getChildren().addAll(usb, scanLabel, scanButton);
scanBox.managedProperty().bind(scanBox.visibleProperty());
stackPane.getChildren().addAll(anchorPane, scanBox);
List<Device> devices = AppServices.getDevices();
if(devices == null || devices.isEmpty()) {
scanButton.setDefaultButton(true);
scanBox.setVisible(true);
} else {
Platform.runLater(() -> setDevices(devices));
@@ -97,15 +99,21 @@ public abstract class DeviceDialog<R> extends Dialog<R> {
private void scan() {
Hwi.EnumerateService enumerateService = new Hwi.EnumerateService(null);
enumerateService.setOnSucceeded(workerStateEvent -> {
scanButton.setText("Scan...");
List<Device> devices = enumerateService.getValue();
setDevices(devices);
Platform.runLater(() -> EventManager.get().post(new UsbDeviceEvent(devices)));
});
enumerateService.setOnFailed(workerStateEvent -> {
scanButton.setText("Scan...");
deviceAccordion.getPanes().clear();
scanButton.setDefaultButton(true);
scanBox.setVisible(true);
scanLabel.setText(workerStateEvent.getSource().getException().getMessage());
});
enumerateService.setOnRunning(workerStateEvent -> {
scanButton.setText("Scanning...");
});
enumerateService.start();
}
@@ -122,16 +130,17 @@ public abstract class DeviceDialog<R> extends Dialog<R> {
deviceAccordion.getPanes().clear();
if(dialogDevices.isEmpty()) {
scanButton.setDefaultButton(true);
scanBox.setVisible(true);
scanLabel.setText("No matching devices found");
} else {
scanBox.setVisible(false);
for(Device device : dialogDevices) {
DevicePane devicePane = getDevicePane(device);
DevicePane devicePane = getDevicePane(device, dialogDevices.size() == 1);
deviceAccordion.getPanes().add(devicePane);
}
}
}
protected abstract DevicePane getDevicePane(Device device);
protected abstract DevicePane getDevicePane(Device device, boolean defaultDevice);
}
@@ -59,7 +59,9 @@ public class DevicePane extends TitledDescriptionPane {
private final SimpleStringProperty passphrase = new SimpleStringProperty("");
public DevicePane(Wallet wallet, Device device) {
private boolean defaultDevice;
public DevicePane(Wallet wallet, Device device, boolean defaultDevice) {
super(device.getModel().toDisplayString(), "", "", "image/" + device.getType() + ".png");
this.deviceOperation = DeviceOperation.IMPORT;
this.wallet = wallet;
@@ -68,6 +70,7 @@ public class DevicePane extends TitledDescriptionPane {
this.keyDerivation = null;
this.message = null;
this.device = device;
this.defaultDevice = defaultDevice;
setDefaultStatus();
showHideLink.setVisible(false);
@@ -80,7 +83,7 @@ public class DevicePane extends TitledDescriptionPane {
buttonBox.getChildren().addAll(setPassphraseButton, importButton);
}
public DevicePane(PSBT psbt, Device device) {
public DevicePane(PSBT psbt, Device device, boolean defaultDevice) {
super(device.getModel().toDisplayString(), "", "", "image/" + device.getType() + ".png");
this.deviceOperation = DeviceOperation.SIGN;
this.wallet = null;
@@ -89,6 +92,7 @@ public class DevicePane extends TitledDescriptionPane {
this.keyDerivation = null;
this.message = null;
this.device = device;
this.defaultDevice = defaultDevice;
setDefaultStatus();
showHideLink.setVisible(false);
@@ -101,7 +105,7 @@ public class DevicePane extends TitledDescriptionPane {
buttonBox.getChildren().addAll(setPassphraseButton, signButton);
}
public DevicePane(Wallet wallet, OutputDescriptor outputDescriptor, Device device) {
public DevicePane(Wallet wallet, OutputDescriptor outputDescriptor, Device device, boolean defaultDevice) {
super(device.getModel().toDisplayString(), "", "", "image/" + device.getType() + ".png");
this.deviceOperation = DeviceOperation.DISPLAY_ADDRESS;
this.wallet = wallet;
@@ -110,6 +114,7 @@ public class DevicePane extends TitledDescriptionPane {
this.keyDerivation = null;
this.message = null;
this.device = device;
this.defaultDevice = defaultDevice;
setDefaultStatus();
showHideLink.setVisible(false);
@@ -122,7 +127,7 @@ public class DevicePane extends TitledDescriptionPane {
buttonBox.getChildren().addAll(setPassphraseButton, displayAddressButton);
}
public DevicePane(Wallet wallet, String message, KeyDerivation keyDerivation, Device device) {
public DevicePane(Wallet wallet, String message, KeyDerivation keyDerivation, Device device, boolean defaultDevice) {
super(device.getModel().toDisplayString(), "", "", "image/" + device.getType() + ".png");
this.deviceOperation = DeviceOperation.SIGN_MESSAGE;
this.wallet = wallet;
@@ -131,6 +136,7 @@ public class DevicePane extends TitledDescriptionPane {
this.keyDerivation = keyDerivation;
this.message = message;
this.device = device;
this.defaultDevice = defaultDevice;
setDefaultStatus();
showHideLink.setVisible(false);
@@ -145,6 +151,7 @@ public class DevicePane extends TitledDescriptionPane {
private void initialise(Device device) {
if(device.isNeedsPinSent()) {
unlockButton.setDefaultButton(defaultDevice);
unlockButton.setVisible(true);
} else if(device.isNeedsPassphraseSent()) {
setPassphraseButton.setVisible(true);
@@ -229,7 +236,6 @@ public class DevicePane extends TitledDescriptionPane {
private void createSignButton() {
signButton = new Button("Sign");
signButton.setDefaultButton(true);
signButton.setAlignment(Pos.CENTER_RIGHT);
signButton.setMinWidth(44);
signButton.setOnAction(event -> {
@@ -242,7 +248,6 @@ public class DevicePane extends TitledDescriptionPane {
private void createDisplayAddressButton() {
displayAddressButton = new Button("Display Address");
displayAddressButton.setDefaultButton(true);
displayAddressButton.setAlignment(Pos.CENTER_RIGHT);
displayAddressButton.setOnAction(event -> {
displayAddressButton.setDisable(true);
@@ -259,7 +264,6 @@ public class DevicePane extends TitledDescriptionPane {
private void createSignMessageButton() {
signMessageButton = new Button("Sign Message");
signMessageButton.setDefaultButton(true);
signMessageButton.setAlignment(Pos.CENTER_RIGHT);
signMessageButton.setOnAction(event -> {
signMessageButton.setDisable(true);
@@ -284,7 +288,9 @@ public class DevicePane extends TitledDescriptionPane {
vBox.setMaxHeight(120);
vBox.setSpacing(42);
pinField = (CustomPasswordField)TextFields.createClearablePasswordField();
Platform.runLater(() -> pinField.requestFocus());
enterPinButton = new Button("Enter PIN");
enterPinButton.setDefaultButton(true);
enterPinButton.setOnAction(event -> {
enterPinButton.setDisable(true);
sendPin(pinField.getText());
@@ -324,9 +330,15 @@ public class DevicePane extends TitledDescriptionPane {
CustomPasswordField passphraseField = (CustomPasswordField)TextFields.createClearablePasswordField();
passphrase.bind(passphraseField.textProperty());
HBox.setHgrow(passphraseField, Priority.ALWAYS);
passphraseField.setOnAction(event -> {
setExpanded(false);
setDescription("Confirm passphrase on device...");
sendPassphrase(passphrase.get());
});
SplitMenuButton sendPassphraseButton = new SplitMenuButton();
sendPassphraseButton.setText("Send Passphrase");
sendPassphraseButton.getStyleClass().add("default-button");
sendPassphraseButton.setOnAction(event -> {
setExpanded(false);
setDescription("Confirm passphrase on device...");
@@ -604,17 +616,23 @@ public class DevicePane extends TitledDescriptionPane {
private void showOperationButton() {
if(deviceOperation.equals(DeviceOperation.IMPORT)) {
if(defaultDevice) {
importButton.getStyleClass().add("default-button");
}
importButton.setVisible(true);
showHideLink.setText("Show derivation...");
showHideLink.setVisible(true);
setContent(getDerivationEntry(wallet.getScriptType() == null ? ScriptType.P2WPKH.getDefaultDerivation() : wallet.getScriptType().getDefaultDerivation()));
} else if(deviceOperation.equals(DeviceOperation.SIGN)) {
signButton.setDefaultButton(defaultDevice);
signButton.setVisible(true);
showHideLink.setVisible(false);
} else if(deviceOperation.equals(DeviceOperation.DISPLAY_ADDRESS)) {
displayAddressButton.setDefaultButton(defaultDevice);
displayAddressButton.setVisible(true);
showHideLink.setVisible(false);
} else if(deviceOperation.equals(DeviceOperation.SIGN_MESSAGE)) {
signMessageButton.setDefaultButton(defaultDevice);
signMessageButton.setVisible(true);
showHideLink.setVisible(false);
}
@@ -627,11 +645,11 @@ public class DevicePane extends TitledDescriptionPane {
HBox.setHgrow(derivationField, Priority.ALWAYS);
ValidationSupport validationSupport = new ValidationSupport();
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(derivationField, Validator.combine(
Validator.createEmptyValidator("Derivation is required"),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Invalid derivation", !KeyDerivation.isValid(newValue))
));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
Button importDerivationButton = new Button("Import");
importDerivationButton.setOnAction(event -> {
@@ -22,8 +22,8 @@ public class DeviceSignDialog extends DeviceDialog<PSBT> {
}
@Override
protected DevicePane getDevicePane(Device device) {
return new DevicePane(psbt, device);
protected DevicePane getDevicePane(Device device, boolean defaultDevice) {
return new DevicePane(psbt, device, defaultDevice);
}
@Subscribe
@@ -26,8 +26,8 @@ public class DeviceSignMessageDialog extends DeviceDialog<String> {
}
@Override
protected DevicePane getDevicePane(Device device) {
return new DevicePane(wallet, message, keyDerivation, device);
protected DevicePane getDevicePane(Device device, boolean defaultDevice) {
return new DevicePane(wallet, message, keyDerivation, device, defaultDevice);
}
@Subscribe
@@ -103,7 +103,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> {
NodeEntry nodeEntry = (NodeEntry)entry;
Address address = nodeEntry.getAddress();
setText(address.toString());
setContextMenu(new AddressContextMenu(address, nodeEntry.getOutputDescriptor(), null));
setContextMenu(new AddressContextMenu(address, nodeEntry.getOutputDescriptor(), nodeEntry));
Tooltip tooltip = new Tooltip();
tooltip.setText(nodeEntry.getNode().getDerivationPath().replace("m", ".."));
setTooltip(tooltip);
@@ -4,6 +4,7 @@ import com.google.gson.JsonParseException;
import com.sparrowwallet.drongo.crypto.InvalidPasswordException;
import com.sparrowwallet.drongo.protocol.ScriptType;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.KeystoreSource;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
@@ -172,11 +173,15 @@ public abstract class FileImportPane extends TitledDescriptionPane {
if(wallets != null) {
for(Wallet wallet : wallets) {
if(scriptType.equals(wallet.getScriptType()) && !wallet.getKeystores().isEmpty()) {
return wallet.getKeystores().get(0);
Keystore keystore = wallet.getKeystores().get(0);
keystore.setLabel(importer.getName().replace(" Multisig", ""));
keystore.setSource(KeystoreSource.HW_AIRGAPPED);
keystore.setWalletModel(importer.getWalletModel());
return keystore;
}
}
throw new ImportException("Script type " + scriptType + " is not supported");
throw new ImportException("Script type " + scriptType.getDescription() + " is not supported in this QR. Check you are displaying the correct QR code.");
}
return null;
@@ -9,10 +9,7 @@ import com.sparrowwallet.sparrow.event.StorageEvent;
import com.sparrowwallet.sparrow.event.TimedEvent;
import com.sparrowwallet.sparrow.event.WalletExportEvent;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.io.CoboVaultMultisig;
import com.sparrowwallet.sparrow.io.PassportMultisig;
import com.sparrowwallet.sparrow.io.Storage;
import com.sparrowwallet.sparrow.io.WalletExport;
import com.sparrowwallet.sparrow.io.*;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Control;
@@ -83,8 +80,8 @@ public class FileWalletExportPane extends TitledDescriptionPane {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Export " + exporter.getWalletModel().toDisplayString() + " File");
String extension = exporter.getExportFileExtension(wallet);
fileChooser.setInitialFileName(wallet.getName() + "-" +
exporter.getWalletModel().toDisplayString().toLowerCase().replace(" ", "") +
fileChooser.setInitialFileName(wallet.getName() +
(exporter instanceof Sparrow ? "" : "-" + exporter.getWalletModel().toDisplayString().toLowerCase().replace(" ", "")) +
(extension == null || extension.isEmpty() ? "" : "." + extension));
AppServices.moveToActiveWindowScreen(window, 800, 450);
@@ -100,10 +97,10 @@ public class FileWalletExportPane extends TitledDescriptionPane {
WalletPasswordDialog dlg = new WalletPasswordDialog(wallet.getName(), WalletPasswordDialog.PasswordRequirement.LOAD);
Optional<SecureString> password = dlg.showAndWait();
if(password.isPresent()) {
final File walletFile = AppServices.get().getOpenWallets().get(wallet).getWalletFile();
final String walletId = AppServices.get().getOpenWallets().get(wallet).getWalletId(wallet);
Storage.DecryptWalletService decryptWalletService = new Storage.DecryptWalletService(copy, password.get());
decryptWalletService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(walletFile, TimedEvent.Action.END, "Done"));
EventManager.get().post(new StorageEvent(walletId, TimedEvent.Action.END, "Done"));
Wallet decryptedWallet = decryptWalletService.getValue();
try {
@@ -113,10 +110,10 @@ public class FileWalletExportPane extends TitledDescriptionPane {
}
});
decryptWalletService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(walletFile, TimedEvent.Action.END, "Failed"));
EventManager.get().post(new StorageEvent(walletId, TimedEvent.Action.END, "Failed"));
setError("Export Error", decryptWalletService.getException().getMessage());
});
EventManager.get().post(new StorageEvent(walletFile, TimedEvent.Action.START, "Decrypting wallet..."));
EventManager.get().post(new StorageEvent(walletId, TimedEvent.Action.START, "Decrypting wallet..."));
decryptWalletService.start();
}
} else {
@@ -137,7 +134,7 @@ public class FileWalletExportPane extends TitledDescriptionPane {
QRDisplayDialog qrDisplayDialog;
if(exporter instanceof CoboVaultMultisig) {
qrDisplayDialog = new QRDisplayDialog(RegistryType.BYTES.toString(), outputStream.toByteArray(), true);
} else if(exporter instanceof PassportMultisig) {
} else if(exporter instanceof PassportMultisig || exporter instanceof KeystoneMultisig) {
qrDisplayDialog = new QRDisplayDialog(RegistryType.BYTES.toString(), outputStream.toByteArray(), false);
} else {
qrDisplayDialog = new QRDisplayDialog(outputStream.toString(StandardCharsets.UTF_8));
@@ -1,6 +1,7 @@
package com.sparrowwallet.sparrow.control;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import com.google.gson.JsonParseException;
import com.sparrowwallet.drongo.policy.Policy;
import com.sparrowwallet.drongo.policy.PolicyType;
@@ -27,6 +28,8 @@ import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;
public class FileWalletKeystoreImportPane extends FileImportPane {
private static final Logger log = LoggerFactory.getLogger(FileWalletKeystoreImportPane.class);
@@ -42,35 +45,62 @@ public class FileWalletKeystoreImportPane extends FileImportPane {
protected void importFile(String fileName, InputStream inputStream, String password) throws ImportException {
this.fileName = fileName;
try {
fileBytes = ByteStreams.toByteArray(inputStream);
} catch(IOException e) {
throw new ImportException("Could not read file", e);
List<ScriptType> scriptTypes = ScriptType.getAddressableScriptTypes(PolicyType.SINGLE);
if(wallets != null && !wallets.isEmpty()) {
if(wallets.size() == 1 && scriptTypes.contains(wallets.get(0).getScriptType())) {
Wallet wallet = wallets.get(0);
wallet.setPolicyType(PolicyType.SINGLE);
wallet.setDefaultPolicy(Policy.getPolicy(PolicyType.SINGLE, wallet.getScriptType(), wallet.getKeystores(), null));
wallet.setName(importer.getName());
EventManager.get().post(new WalletImportEvent(wallets.get(0)));
} else {
scriptTypes.retainAll(wallets.stream().map(Wallet::getScriptType).collect(Collectors.toList()));
if(scriptTypes.isEmpty()) {
throw new ImportException("No singlesig script types present in QR code");
}
}
} else {
try {
fileBytes = ByteStreams.toByteArray(inputStream);
} catch(IOException e) {
throw new ImportException("Could not read file", e);
}
}
setContent(getScriptTypeEntry());
setContent(getScriptTypeEntry(scriptTypes));
setExpanded(true);
importButton.setDisable(true);
}
private void importWallet(ScriptType scriptType) throws ImportException {
ByteArrayInputStream bais = new ByteArrayInputStream(fileBytes);
Keystore keystore = importer.getKeystore(scriptType, bais, "");
if(wallets != null && !wallets.isEmpty()) {
Wallet wallet = wallets.stream().filter(wallet1 -> wallet1.getScriptType() == scriptType).findFirst().orElseThrow(ImportException::new);
wallet.setName(importer.getName());
wallet.setPolicyType(PolicyType.SINGLE);
wallet.setDefaultPolicy(Policy.getPolicy(PolicyType.SINGLE, wallet.getScriptType(), wallet.getKeystores(), null));
EventManager.get().post(new WalletImportEvent(wallet));
} else {
ByteArrayInputStream bais = new ByteArrayInputStream(fileBytes);
Keystore keystore = importer.getKeystore(scriptType, bais, "");
Wallet wallet = new Wallet();
wallet.setName(fileName);
wallet.setPolicyType(PolicyType.SINGLE);
wallet.setScriptType(scriptType);
wallet.getKeystores().add(keystore);
wallet.setDefaultPolicy(Policy.getPolicy(PolicyType.SINGLE, scriptType, wallet.getKeystores(), null));
Wallet wallet = new Wallet();
wallet.setName(Files.getNameWithoutExtension(fileName));
wallet.setPolicyType(PolicyType.SINGLE);
wallet.setScriptType(scriptType);
wallet.getKeystores().add(keystore);
wallet.setDefaultPolicy(Policy.getPolicy(PolicyType.SINGLE, scriptType, wallet.getKeystores(), null));
EventManager.get().post(new WalletImportEvent(wallet));
EventManager.get().post(new WalletImportEvent(wallet));
}
}
private Node getScriptTypeEntry() {
private Node getScriptTypeEntry(List<ScriptType> scriptTypes) {
Label label = new Label("Script Type:");
ComboBox<ScriptType> scriptTypeComboBox = new ComboBox<>(FXCollections.observableArrayList(ScriptType.getAddressableScriptTypes(PolicyType.SINGLE)));
scriptTypeComboBox.setValue(ScriptType.P2WPKH);
ComboBox<ScriptType> scriptTypeComboBox = new ComboBox<>(FXCollections.observableArrayList(scriptTypes));
if(scriptTypes.contains(ScriptType.P2WPKH)) {
scriptTypeComboBox.setValue(ScriptType.P2WPKH);
}
HelpLabel helpLabel = new HelpLabel();
helpLabel.setHelpText("P2WPKH is a Native Segwit type and is usually the best choice for new wallets.\nP2SH-P2WPKH is a Wrapped Segwit type and is a reasonable choice for the widest compatibility.\nP2PKH is a Legacy type and should be avoided for new wallets.\nFor existing wallets, be sure to choose the type that matches the wallet you are importing.");
@@ -24,6 +24,7 @@ import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import org.controlsfx.control.SegmentedButton;
import org.controlsfx.validation.ValidationResult;
import org.controlsfx.validation.ValidationSupport;
import org.controlsfx.validation.decoration.StyleClassValidationDecoration;
@@ -44,6 +45,9 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
private final TextField address;
private final TextArea message;
private final TextArea signature;
private final ToggleGroup formatGroup;
private final ToggleButton formatTrezor;
private final ToggleButton formatElectrum;
private final Wallet wallet;
private WalletNode walletNode;
private boolean electrumSignatureFormat;
@@ -144,7 +148,22 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
signature.setWrapText(true);
signatureField.getInputs().add(signature);
fieldset.getChildren().addAll(addressField, messageField, signatureField);
Field formatField = new Field();
formatField.setText("Format:");
formatGroup = new ToggleGroup();
formatElectrum = new ToggleButton("Standard (Electrum)");
formatTrezor = new ToggleButton("BIP137 (Trezor)");
SegmentedButton formatButtons = new SegmentedButton(formatElectrum, formatTrezor);
formatButtons.setToggleGroup(formatGroup);
formatField.getInputs().add(formatButtons);
formatGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
electrumSignatureFormat = (newValue == formatElectrum);
});
formatButtons.setDisable(wallet != null && walletNode != null && wallet.getScriptType() == ScriptType.P2PKH);
fieldset.getChildren().addAll(addressField, messageField, signatureField, formatField);
form.getChildren().add(fieldset);
dialogPane.setContent(form);
@@ -153,6 +172,7 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
address.setEditable(false);
message.setEditable(false);
signature.setEditable(false);
formatButtons.setDisable(true);
}
ButtonType signButtonType = new javafx.scene.control.ButtonType("Sign", ButtonBar.ButtonData.BACK_PREVIOUS);
@@ -193,8 +213,8 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
ValidationSupport validationSupport = new ValidationSupport();
Platform.runLater(() -> {
validationSupport.registerValidator(address, (Control c, String newValue) -> ValidationResult.fromErrorIf(c, "Invalid address", !isValidAddress()));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(address, (Control c, String newValue) -> ValidationResult.fromErrorIf(c, "Invalid address", !isValidAddress()));
});
address.textProperty().addListener((observable, oldValue, newValue) -> {
@@ -225,6 +245,16 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
AppServices.moveToActiveWindowScreen(this);
setResultConverter(dialogButton -> dialogButton == signButtonType || dialogButton == verifyButtonType ? ButtonBar.ButtonData.APPLY : dialogButton.getButtonData());
Platform.runLater(() -> {
if(address.getText().isEmpty()) {
address.requestFocus();
} else if(message.getText().isEmpty()) {
message.requestFocus();
}
formatGroup.selectToggle(formatElectrum);
});
}
private Address getAddress()throws InvalidAddressException {
@@ -241,6 +271,7 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
* @param electrumSignatureFormat
*/
public void setElectrumSignatureFormat(boolean electrumSignatureFormat) {
formatGroup.selectToggle(electrumSignatureFormat ? formatElectrum : formatTrezor);
this.electrumSignatureFormat = electrumSignatureFormat;
}
@@ -368,16 +399,16 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
if(password.isPresent()) {
Storage.DecryptWalletService decryptWalletService = new Storage.DecryptWalletService(wallet.copy(), password.get());
decryptWalletService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(storage.getWalletFile(), TimedEvent.Action.END, "Done"));
EventManager.get().post(new StorageEvent(storage.getWalletId(wallet), TimedEvent.Action.END, "Done"));
Wallet decryptedWallet = decryptWalletService.getValue();
signUnencryptedKeystore(decryptedWallet);
decryptedWallet.clearPrivate();
});
decryptWalletService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(storage.getWalletFile(), TimedEvent.Action.END, "Failed"));
EventManager.get().post(new StorageEvent(storage.getWalletId(wallet), TimedEvent.Action.END, "Failed"));
AppServices.showErrorDialog("Incorrect Password", decryptWalletService.getException().getMessage());
});
EventManager.get().post(new StorageEvent(storage.getWalletFile(), TimedEvent.Action.START, "Decrypting wallet..."));
EventManager.get().post(new StorageEvent(storage.getWalletId(wallet), TimedEvent.Action.START, "Decrypting wallet..."));
decryptWalletService.start();
}
}
@@ -36,7 +36,6 @@ import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class MnemonicKeystoreImportPane extends TitledDescriptionPane {
@@ -159,15 +158,20 @@ public class MnemonicKeystoreImportPane extends TitledDescriptionPane {
ObservableList<String> wordEntryList = FXCollections.observableArrayList(words);
wordEntriesProperty = new SimpleListProperty<>(wordEntryList);
List<WordEntry> wordEntries = new ArrayList<>(numWords);
for(int i = 0; i < numWords; i++) {
WordEntry wordEntry = new WordEntry(i, wordEntryList);
wordsPane.getChildren().add(wordEntry);
wordEntries.add(new WordEntry(i, wordEntryList));
}
for(int i = 0; i < numWords - 1; i++) {
wordEntries.get(i).setNext(wordEntries.get(i + 1).getEditor());
}
wordsPane.getChildren().addAll(wordEntries);
vBox.getChildren().add(wordsPane);
if(!displayWordsOnly) {
PassphraseEntry passphraseEntry = new PassphraseEntry();
wordEntries.get(wordEntries.size() - 1).setNext(passphraseEntry.getEditor());
passphraseEntry.setPadding(new Insets(0, 26, 10, 10));
vBox.getChildren().add(passphraseEntry);
@@ -397,6 +401,7 @@ public class MnemonicKeystoreImportPane extends TitledDescriptionPane {
private static class WordEntry extends HBox {
private static List<String> wordList;
private final TextField wordField;
private Node next;
public WordEntry(int wordNumber, ObservableList<String> wordEntryList) {
super();
@@ -425,13 +430,18 @@ public class MnemonicKeystoreImportPane extends TitledDescriptionPane {
wordList = Bip39MnemonicCode.INSTANCE.getWordList();
AutoCompletionBinding<String> autoCompletionBinding = TextFields.bindAutoCompletion(wordField, new WordlistSuggestionProvider(wordList));
autoCompletionBinding.setDelay(50);
autoCompletionBinding.setOnAutoCompleted(event -> {
if (next != null) {
next.requestFocus();
}
});
ValidationSupport validationSupport = new ValidationSupport();
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(wordField, Validator.combine(
Validator.createEmptyValidator("Word is required"),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Invalid word", !wordList.contains(newValue))
));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
wordField.textProperty().addListener((observable, oldValue, newValue) -> {
wordEntryList.set(wordNumber, newValue);
@@ -444,6 +454,10 @@ public class MnemonicKeystoreImportPane extends TitledDescriptionPane {
return wordField;
}
public void setNext(Node node) {
next = node;
}
public static boolean isValid(String word) {
return wordList.contains(word);
}
@@ -461,10 +475,6 @@ public class MnemonicKeystoreImportPane extends TitledDescriptionPane {
List<String> suggestions = new ArrayList<>();
if(!request.getUserText().isEmpty()) {
for(String word : wordList) {
if(word.equals(request.getUserText())) {
return Collections.emptyList();
}
if(word.startsWith(request.getUserText())) {
suggestions.add(word);
}
@@ -476,13 +486,15 @@ public class MnemonicKeystoreImportPane extends TitledDescriptionPane {
}
private class PassphraseEntry extends HBox {
private final CustomTextField passphraseField;
public PassphraseEntry() {
super();
setAlignment(Pos.CENTER_LEFT);
setSpacing(10);
Label passphraseLabel = new Label("Passphrase:");
CustomTextField passphraseField = (CustomTextField) TextFields.createClearableTextField();
passphraseField = (CustomTextField) TextFields.createClearableTextField();
passphraseProperty.bind(passphraseField.textProperty());
passphraseField.setPromptText("Leave blank for none");
@@ -492,6 +504,10 @@ public class MnemonicKeystoreImportPane extends TitledDescriptionPane {
getChildren().addAll(passphraseLabel, passphraseField, helpLabel);
}
public TextField getEditor() {
return passphraseField;
}
}
private Node getDerivationEntry(List<ChildNumber> derivation) {
@@ -501,11 +517,11 @@ public class MnemonicKeystoreImportPane extends TitledDescriptionPane {
HBox.setHgrow(derivationField, Priority.ALWAYS);
ValidationSupport validationSupport = new ValidationSupport();
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(derivationField, Validator.combine(
Validator.createEmptyValidator("Derivation is required"),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Invalid derivation", !KeyDerivation.isValid(newValue))
));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
Button importDerivationButton = new Button("Import Custom Derivation Keystore");
importDerivationButton.setDisable(true);
@@ -180,7 +180,7 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
}
} else {
decoder.receivePart(qrtext);
Platform.runLater(() -> percentComplete.setValue(decoder.getEstimatedPercentComplete()));
Platform.runLater(() -> percentComplete.setValue(decoder.getProcessedPartsCount() > 0 ? decoder.getEstimatedPercentComplete() : 0));
if(decoder.getResult() != null) {
URDecoder.Result urResult = decoder.getResult();
@@ -209,7 +209,7 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
if(parts.stream().filter(Objects::nonNull).count() == n) {
String complete = String.join("", parts);
try {
PSBT psbt = PSBT.fromString(complete);
PSBT psbt = PSBT.fromString(complete, false);
result = new Result(psbt);
return;
} catch(PSBTParseException e) {
@@ -261,7 +261,7 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
}
try {
psbt = PSBT.fromString(qrtext);
psbt = PSBT.fromString(qrtext, false);
result = new Result(psbt);
return;
} catch(PSBTParseException e) {
@@ -273,7 +273,7 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
}
try {
psbt = new PSBT(qrResult.getRawBytes());
psbt = new PSBT(qrResult.getRawBytes(), false);
result = new Result(psbt);
return;
} catch(Exception e) {
@@ -298,7 +298,7 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
//Try Base43 used by Electrum
try {
psbt = new PSBT(Base43.decode(qrtext));
psbt = new PSBT(Base43.decode(qrtext), false);
result = new Result(psbt);
return;
} catch(Exception e) {
@@ -324,7 +324,7 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
if(urRegistryType.equals(RegistryType.BYTES)) {
byte[] urBytes = (byte[])ur.decodeFromRegistry();
try {
PSBT psbt = new PSBT(urBytes);
PSBT psbt = new PSBT(urBytes, false);
return new Result(psbt);
} catch(PSBTParseException e) {
if(PSBT.isPSBT(urBytes)) {
@@ -354,7 +354,7 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
} else if(urRegistryType.equals(RegistryType.CRYPTO_PSBT)) {
CryptoPSBT cryptoPSBT = (CryptoPSBT)ur.decodeFromRegistry();
try {
PSBT psbt = new PSBT(cryptoPSBT.getPsbt());
PSBT psbt = new PSBT(cryptoPSBT.getPsbt(), false);
return new Result(psbt);
} catch(Exception e) {
log.error("Error parsing PSBT from UR type " + urRegistryType, e);
@@ -469,7 +469,7 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
ExtendedKey extendedKey = outputDescriptor.getSingletonExtendedPublicKey();
wallet.setScriptType(outputDescriptor.getScriptType());
Keystore keystore = new Keystore();
keystore.setKeyDerivation(new KeyDerivation(masterFingerprint, outputDescriptor.getKeyDerivation(extendedKey).getDerivationPath()));
keystore.setKeyDerivation(new KeyDerivation(masterFingerprint, KeyDerivation.writePath(outputDescriptor.getKeyDerivation(extendedKey).getDerivation())));
keystore.setExtendedPublicKey(extendedKey);
wallet.getKeystores().add(keystore);
wallets.add(wallet);
@@ -16,6 +16,7 @@ import java.util.Arrays;
import java.util.OptionalDouble;
public class TitledDescriptionPane extends TitledPane {
private Label mainLabel;
private Label descriptionLabel;
protected Hyperlink showHideLink;
protected HBox buttonBox;
@@ -50,7 +51,7 @@ public class TitledDescriptionPane extends TitledPane {
VBox labelsBox = new VBox();
labelsBox.setSpacing(5);
labelsBox.setAlignment(Pos.CENTER_LEFT);
Label mainLabel = new Label();
mainLabel = new Label();
mainLabel.setText(title);
mainLabel.getStyleClass().add("main-label");
labelsBox.getChildren().add(mainLabel);
@@ -99,6 +100,10 @@ public class TitledDescriptionPane extends TitledPane {
return null;
}
public String getTitle() {
return mainLabel.getText();
}
protected void setDescription(String text) {
descriptionLabel.getStyleClass().remove("description-error");
descriptionLabel.getStyleClass().add("description-label");
@@ -4,7 +4,11 @@ import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.drongo.protocol.*;
import javafx.application.Platform;
import javafx.geometry.Point2D;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.stage.Popup;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.event.MouseOverTextEvent;
@@ -33,7 +37,8 @@ public class TransactionHexArea extends CodeArea {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transaction.bitcoinSerializeToStream(baos);
String hex = Utils.bytesToHex(baos.toByteArray());
String fullHex = Utils.bytesToHex(baos.toByteArray());
String hex = fullHex;
if(hex.length() > TRUNCATE_AT) {
hex = hex.substring(0, TRUNCATE_AT);
hex += "[truncated]";
@@ -42,6 +47,7 @@ public class TransactionHexArea extends CodeArea {
clear();
appendText(hex);
previousSegmentList = new ArrayList<>();
setContextMenu(new TransactionHexContextMenu(fullHex));
} catch (IOException e) {
throw new IllegalStateException("Can't happen");
}
@@ -266,4 +272,18 @@ public class TransactionHexArea extends CodeArea {
return Objects.hash(start, length, style);
}
}
private static class TransactionHexContextMenu extends ContextMenu {
public TransactionHexContextMenu(String hex) {
MenuItem copy = new MenuItem("Copy All");
copy.setOnAction(AE -> {
hide();
ClipboardContent content = new ClipboardContent();
content.putString(hex);
Clipboard.getSystemClipboard().setContent(content);
});
getItems().add(copy);
}
}
}
@@ -45,12 +45,12 @@ public class TransactionIdDialog extends Dialog<Sha256Hash> {
ValidationSupport validationSupport = new ValidationSupport();
Platform.runLater(() -> {
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(txid, Validator.combine(
Validator.createEmptyValidator("Transaction id is required"),
(Control c, String newValue) -> ValidationResult.fromErrorIf(c, "Transaction ID length incorrect", newValue.length() != 64),
(Control c, String newValue) -> ValidationResult.fromErrorIf(c, "Transaction ID must be hexadecimal", !Utils.isHex(newValue))
));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
});
final ButtonType okButtonType = new javafx.scene.control.ButtonType("Open Transaction", ButtonBar.ButtonData.OK_DONE);
@@ -52,10 +52,10 @@ public class WalletBirthDateDialog extends Dialog<Date> {
ValidationSupport validationSupport = new ValidationSupport();
Platform.runLater( () -> {
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(birthDatePicker, Validator.combine(
(Control c, LocalDate newValue) -> ValidationResult.fromErrorIf( c, "Birth date not specified", newValue == null)
));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
});
final ButtonType okButtonType = new javafx.scene.control.ButtonType("Rescan Wallet", ButtonBar.ButtonData.OK_DONE);
@@ -11,6 +11,7 @@ import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import java.util.Comparator;
import java.util.List;
public class WalletExportDialog extends Dialog<Wallet> {
@@ -43,7 +44,7 @@ public class WalletExportDialog extends Dialog<Wallet> {
if(wallet.getPolicyType() == PolicyType.SINGLE) {
exporters = List.of(new Electrum(), new SpecterDesktop(), new Sparrow());
} else if(wallet.getPolicyType() == PolicyType.MULTI) {
exporters = List.of(new ColdcardMultisig(), new CoboVaultMultisig(), new Electrum(), new PassportMultisig(), new SpecterDesktop(), new BlueWalletMultisig(), new Sparrow());
exporters = List.of(new ColdcardMultisig(), new CoboVaultMultisig(), new Electrum(), new KeystoneMultisig(), new PassportMultisig(), new SpecterDesktop(), new BlueWalletMultisig(), new SpecterDIY(), new Sparrow());
} else {
throw new UnsupportedOperationException("Cannot export wallet with policy type " + wallet.getPolicyType());
}
@@ -53,6 +54,8 @@ public class WalletExportDialog extends Dialog<Wallet> {
FileWalletExportPane exportPane = new FileWalletExportPane(wallet, exporter);
exportAccordion.getPanes().add(exportPane);
}
exportAccordion.getPanes().sort(Comparator.comparing(o -> ((TitledDescriptionPane) o).getTitle()));
scrollPane.setContent(exportAccordion);
final ButtonType cancelButtonType = new javafx.scene.control.ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
@@ -16,6 +16,7 @@ import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import org.controlsfx.glyphfont.Glyph;
import java.util.Comparator;
import java.util.List;
public class WalletImportDialog extends Dialog<Wallet> {
@@ -47,17 +48,19 @@ public class WalletImportDialog extends Dialog<Wallet> {
AnchorPane.setRightAnchor(scrollPane, 0.0);
importAccordion = new Accordion();
List<KeystoreFileImport> keystoreImporters = List.of(new ColdcardSinglesig(), new CoboVaultSinglesig(), new PassportSinglesig());
List<KeystoreFileImport> keystoreImporters = List.of(new ColdcardSinglesig(), new CoboVaultSinglesig(), new KeystoneSinglesig(), new PassportSinglesig(), new SeedSigner(), new SpecterDIY());
for(KeystoreFileImport importer : keystoreImporters) {
FileWalletKeystoreImportPane importPane = new FileWalletKeystoreImportPane(importer);
importAccordion.getPanes().add(importPane);
}
List<WalletImport> walletImporters = List.of(new ColdcardMultisig(), new CoboVaultMultisig(), new Electrum(), new SpecterDesktop(), new BlueWalletMultisig());
List<WalletImport> walletImporters = List.of(new ColdcardMultisig(), new CoboVaultMultisig(), new Electrum(), new KeystoneMultisig(), new SpecterDesktop(), new BlueWalletMultisig(), new Sparrow());
for(WalletImport importer : walletImporters) {
FileWalletImportPane importPane = new FileWalletImportPane(importer);
importAccordion.getPanes().add(importPane);
}
importAccordion.getPanes().sort(Comparator.comparing(o -> ((TitledDescriptionPane) o).getTitle()));
scrollPane.setContent(importAccordion);
final ButtonType cancelButtonType = new javafx.scene.control.ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
@@ -92,7 +95,7 @@ public class WalletImportDialog extends Dialog<Wallet> {
List<Device> devices = enumerateService.getValue();
importAccordion.getPanes().removeIf(titledPane -> titledPane instanceof DevicePane);
for(Device device : devices) {
DevicePane devicePane = new DevicePane(new Wallet(), device);
DevicePane devicePane = new DevicePane(new Wallet(), device, devices.size() == 1);
importAccordion.getPanes().add(0, devicePane);
}
Platform.runLater(() -> EventManager.get().post(new UsbDeviceEvent(devices)));
@@ -93,6 +93,7 @@ public class WalletNameDialog extends Dialog<WalletNameDialog.NameAndBirthDate>
ValidationSupport validationSupport = new ValidationSupport();
Platform.runLater( () -> {
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(name, Validator.combine(
Validator.createEmptyValidator("Wallet name is required"),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Wallet name is not unique", Storage.walletExists(newValue))
@@ -100,7 +101,6 @@ public class WalletNameDialog extends Dialog<WalletNameDialog.NameAndBirthDate>
validationSupport.registerValidator(existingPicker, Validator.combine(
(Control c, LocalDate newValue) -> ValidationResult.fromErrorIf( c, "Birth date not specified", existingCheck.isSelected() && newValue == null)
));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
});
final ButtonType okButtonType = new javafx.scene.control.ButtonType("Create Wallet", ButtonBar.ButtonData.OK_DONE);
@@ -77,8 +77,8 @@ public class WalletPasswordDialog extends Dialog<SecureString> {
ValidationSupport validationSupport = new ValidationSupport();
Platform.runLater( () -> {
validationSupport.registerValidator(passwordConfirm, (Control c, String newValue) -> ValidationResult.fromErrorIf(c, "Password confirmation does not match", !passwordConfirm.getText().equals(password.getText())));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(passwordConfirm, (Control c, String newValue) -> ValidationResult.fromErrorIf(c, "Password confirmation does not match", !passwordConfirm.getText().equals(password.getText())));
});
okButtonType = new javafx.scene.control.ButtonType(requirement.okButtonText, ButtonBar.ButtonData.OK_DONE);
@@ -135,11 +135,11 @@ public class XprvKeystoreImportPane extends TitledDescriptionPane {
}
ValidationSupport validationSupport = new ValidationSupport();
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(xprvField, Validator.combine(
Validator.createEmptyValidator("xprv is required"),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Invalid private key", !ExtendedKey.isValid(newValue) || ExtendedKey.fromDescriptor(newValue).getKey().isPubKeyOnly())
));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
Button importXprvButton = new Button("Import");
importXprvButton.setMinWidth(80);
@@ -176,11 +176,11 @@ public class XprvKeystoreImportPane extends TitledDescriptionPane {
HBox.setHgrow(derivationField, Priority.ALWAYS);
ValidationSupport validationSupport = new ValidationSupport();
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(derivationField, Validator.combine(
Validator.createEmptyValidator("Derivation is required"),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Invalid derivation", !KeyDerivation.isValid(newValue))
));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
Button importDerivationButton = new Button("Import Custom Derivation Keystore");
importDerivationButton.setDisable(true);
@@ -0,0 +1,19 @@
package com.sparrowwallet.sparrow.event;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.Wallet;
import java.util.List;
public class KeystoreEncryptionChangedEvent extends WalletSettingsChangedEvent {
private List<Keystore> changedKeystores;
public KeystoreEncryptionChangedEvent(Wallet wallet, Wallet pastWallet, String walletId, List<Keystore> changedKeystores) {
super(wallet, pastWallet, walletId);
this.changedKeystores = changedKeystores;
}
public List<Keystore> getChangedKeystores() {
return changedKeystores;
}
}
@@ -0,0 +1,22 @@
package com.sparrowwallet.sparrow.event;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.Wallet;
import java.util.List;
/**
* This event is trigger when one or more keystores on a wallet are updated, and the wallet is saved
*/
public class KeystoreLabelsChangedEvent extends WalletSettingsChangedEvent {
private final List<Keystore> changedKeystores;
public KeystoreLabelsChangedEvent(Wallet wallet, Wallet pastWallet, String walletId, List<Keystore> changedKeystores) {
super(wallet, pastWallet, walletId);
this.changedKeystores = changedKeystores;
}
public List<Keystore> getChangedKeystores() {
return changedKeystores;
}
}
@@ -8,9 +8,9 @@ import java.util.Map;
public class StorageEvent extends TimedEvent {
private static boolean firstRunDone = false;
private static final Map<File, Long> eventTime = new HashMap<>();
private static final Map<String, Long> eventTime = new HashMap<>();
public StorageEvent(File file, Action action, String status) {
public StorageEvent(String walletId, Action action, String status) {
super(action, status);
Integer keyDerivationPeriod = Config.get().getKeyDerivationPeriod();
@@ -19,10 +19,10 @@ public class StorageEvent extends TimedEvent {
}
if(action == Action.START) {
eventTime.put(file, System.currentTimeMillis());
eventTime.put(walletId, System.currentTimeMillis());
timeMills = keyDerivationPeriod;
} else if(action == Action.END) {
long start = eventTime.get(file);
long start = eventTime.get(walletId);
if(firstRunDone) {
keyDerivationPeriod = (int)(System.currentTimeMillis() - start);
Config.get().setKeyDerivationPeriod(keyDerivationPeriod);
@@ -11,8 +11,8 @@ import java.io.File;
* This is because any failure in saving the wallet must be immediately reported to the user.
* Note that all wallet detail controllers that share a WalletForm, and that class posts WalletNodesChangedEvent once it has cleared it's entry caches.
*/
public class WalletAddressesChangedEvent extends WalletSettingsChangedEvent {
public WalletAddressesChangedEvent(Wallet wallet, Wallet pastWallet, File walletFile) {
super(wallet, pastWallet, walletFile);
public class WalletAddressesChangedEvent extends WalletHistoryClearedEvent {
public WalletAddressesChangedEvent(Wallet wallet, Wallet pastWallet, String walletId) {
super(wallet, pastWallet, walletId);
}
}
@@ -7,9 +7,8 @@ import java.util.List;
/**
* This event is fired when a wallet entry (transaction, txi or txo) label is changed.
* Extends WalletDataChangedEvent so triggers a background save.
*/
public class WalletEntryLabelsChangedEvent extends WalletDataChangedEvent {
public class WalletEntryLabelsChangedEvent extends WalletChangedEvent {
private final List<Entry> entries;
public WalletEntryLabelsChangedEvent(Wallet wallet, Entry entry) {
@@ -23,8 +23,8 @@ public class WalletHistoryChangedEvent extends WalletChangedEvent {
this.historyChangedNodes = historyChangedNodes;
}
public File getWalletFile() {
return storage.getWalletFile();
public String getWalletId() {
return storage.getWalletId(getWallet());
}
public List<WalletNode> getHistoryChangedNodes() {
@@ -0,0 +1,9 @@
package com.sparrowwallet.sparrow.event;
import com.sparrowwallet.drongo.wallet.Wallet;
public class WalletHistoryClearedEvent extends WalletSettingsChangedEvent {
public WalletHistoryClearedEvent(Wallet wallet, Wallet pastWallet, String walletId) {
super(wallet, pastWallet, walletId);
}
}
@@ -0,0 +1,9 @@
package com.sparrowwallet.sparrow.event;
import com.sparrowwallet.drongo.wallet.Wallet;
public class WalletPasswordChangedEvent extends WalletSettingsChangedEvent {
public WalletPasswordChangedEvent(Wallet wallet, Wallet pastWallet, String walletId) {
super(wallet, pastWallet, walletId);
}
}
@@ -5,25 +5,24 @@ import com.sparrowwallet.drongo.wallet.Wallet;
import java.io.File;
/**
* This event is posted when a wallet's settings are changed in a way that does not update the wallet addresses or history.
* For example, changing the keystore source or label will trigger this event, which updates the wallet but avoids a full wallet refresh.
* It is impossible for the validity of a wallet to change on this event - listen for WalletAddressesChangedEvent for this
* This is the base class for events posted when a wallet's settings are changed
* Do not listen for this event directly - listen for a subclass, for example KeystoreLabelsChangedEvent or WalletAddressesChangedEvent
*/
public class WalletSettingsChangedEvent extends WalletChangedEvent {
private final Wallet pastWallet;
private final File walletFile;
private final String walletId;
public WalletSettingsChangedEvent(Wallet wallet, Wallet pastWallet, File walletFile) {
public WalletSettingsChangedEvent(Wallet wallet, Wallet pastWallet, String walletId) {
super(wallet);
this.pastWallet = pastWallet;
this.walletFile = walletFile;
this.walletId = walletId;
}
public Wallet getPastWallet() {
return pastWallet;
}
public File getWalletFile() {
return walletFile;
public String getWalletId() {
return walletId;
}
}
@@ -3,7 +3,7 @@ package com.sparrowwallet.sparrow.event;
import com.sparrowwallet.drongo.wallet.BlockTransactionHashIndex;
import com.sparrowwallet.drongo.wallet.Wallet;
public class WalletUtxoStatusChangedEvent extends WalletDataChangedEvent {
public class WalletUtxoStatusChangedEvent extends WalletChangedEvent {
private final BlockTransactionHashIndex utxo;
public WalletUtxoStatusChangedEvent(Wallet wallet, BlockTransactionHashIndex utxo) {
@@ -19,6 +19,7 @@ public class FontAwesome5 extends GlyphFont {
ANGLE_DOUBLE_RIGHT('\uf101'),
ARROW_DOWN('\uf063'),
ARROW_UP('\uf062'),
BAN('\uf05e'),
BTC('\uf15a'),
CAMERA('\uf030'),
CHECK_CIRCLE('\uf058'),
@@ -17,6 +17,9 @@
package com.sparrowwallet.sparrow.instance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
@@ -85,6 +88,7 @@ import java.nio.channels.FileLock;
*
*/
public abstract class Instance {
private static final Logger log = LoggerFactory.getLogger(Instance.class);
// starting position of port check
private static final int PORT_START = 7221;
@@ -513,7 +517,7 @@ public abstract class Instance {
* @param exception exception occurring while first instance is listening for subsequent instances
*/
protected void handleException(Exception exception) {
exception.printStackTrace();
log.error("Error listening for instances", exception);
}
/**
@@ -57,8 +57,8 @@ public class CoboVaultSinglesig implements KeystoreFileImport, WalletImport {
return keystore;
} catch (Exception e) {
log.error("Error getting Cobo Vault keystore", e);
throw new ImportException("Error getting Cobo Vault keystore", e);
log.error("Error getting " + getName() + " keystore", e);
throw new ImportException("Error getting " + getName() + " keystore", e);
}
}
@@ -81,7 +81,7 @@ public class CoboVaultSinglesig implements KeystoreFileImport, WalletImport {
try {
wallet.checkWallet();
} catch(InvalidWalletException e) {
throw new ImportException("Imported Cobo Vault wallet was invalid: " + e.getMessage());
throw new ImportException("Imported " + getName() + " wallet was invalid: " + e.getMessage());
}
return wallet;
@@ -145,13 +145,13 @@ public class ColdcardMultisig implements WalletImport, KeystoreFileImport, Walle
wallet.setScriptType(scriptType);
if(!wallet.isValid()) {
throw new IllegalStateException("This file does not describe a valid wallet. Please use the Settings > Multisig Wallets > Export XPUB feature on your Coldcard.");
throw new IllegalStateException("This file does not describe a valid wallet. " + getKeystoreImportDescription());
}
return wallet;
} catch(Exception e) {
log.error("Error importing Coldcard multisig wallet", e);
throw new ImportException("Error importing Coldcard multisig wallet", e);
log.error("Error importing " + getName() + " wallet", e);
throw new ImportException("Error importing " + getName() + " wallet", e);
}
}
@@ -180,7 +180,7 @@ public class ColdcardMultisig implements WalletImport, KeystoreFileImport, Walle
}
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
writer.append("# " + getName() + " setup file (created by Sparrow)\n");
writer.append("#\n");
writer.append("Name: ").append(wallet.getName()).append("\n");
@@ -203,8 +203,8 @@ public class ColdcardMultisig implements WalletImport, KeystoreFileImport, Walle
writer.flush();
} catch(Exception e) {
log.error("Error exporting Coldcard multisig wallet", e);
throw new ExportException("Error exporting Coldcard multisig wallet", e);
log.error("Error exporting " + getName() + " wallet", e);
throw new ExportException("Error exporting " + getName() + " wallet", e);
}
}
@@ -86,8 +86,8 @@ public class ColdcardSinglesig implements KeystoreFileImport, WalletImport {
}
}
} catch (Exception e) {
log.error("Error getting Coldcard keystore", e);
throw new ImportException("Error getting Coldcard keystore", e);
log.error("Error getting " + getName() + " keystore", e);
throw new ImportException("Error getting " + getName() + " keystore", e);
}
throw new ImportException("Correct derivation not found for script type: " + scriptType);
@@ -30,7 +30,10 @@ import java.util.zip.ZipInputStream;
public class Hwi {
private static final Logger log = LoggerFactory.getLogger(Hwi.class);
private static final String VERSION_PREFIX = "hwi-2.0.1";
private static final String HWI_HOME_DIR = "hwi";
private static final String HWI_VERSION_PREFIX = "hwi-";
private static final String HWI_VERSION = "2.0.2";
private static final String HWI_VERSION_DIR = HWI_VERSION_PREFIX + HWI_VERSION;
private static boolean isPromptActive = false;
@@ -51,7 +54,7 @@ public class Hwi {
}
return Arrays.stream(devices).filter(device -> device != null && device.getModel() != null).collect(Collectors.toList());
} catch(IOException e) {
log.error("Error executing " + VERSION_PREFIX, e);
log.error("Error executing " + HWI_VERSION_DIR, e);
throw new ImportException(e);
} finally {
isPromptActive = false;
@@ -222,11 +225,12 @@ public class Hwi {
private synchronized File getHwiExecutable(Command command) {
File hwiExecutable = Config.get().getHwi();
if(hwiExecutable != null && hwiExecutable.exists()) {
File homeDir = getHwiHomeDir();
String tmpDir = System.getProperty("java.io.tmpdir");
String hwiPath = hwiExecutable.getAbsolutePath();
if(command.isTestFirst() && hwiPath.startsWith(tmpDir) && (!hwiPath.contains(VERSION_PREFIX) || !testHwi(hwiExecutable))) {
if(command.isTestFirst() && (hwiPath.contains(tmpDir) || hwiPath.startsWith(homeDir.getAbsolutePath())) && (!hwiPath.contains(HWI_VERSION_DIR) || !testHwi(hwiExecutable))) {
if(Platform.getCurrent() == Platform.OSX) {
deleteDirectory(hwiExecutable.getParentFile());
IOUtils.deleteDirectory(hwiExecutable.getParentFile());
} else {
hwiExecutable.delete();
}
@@ -243,55 +247,65 @@ public class Hwi {
//The check will still happen on first invocation, but will not thereafter
//See https://github.com/bitcoin-core/HWI/issues/327 for details
if(platform == Platform.OSX) {
InputStream inputStream = Hwi.class.getResourceAsStream("/native/osx/x64/" + VERSION_PREFIX + "-mac-amd64-signed.zip");
Path tempHwiDirPath = Files.createTempDirectory(VERSION_PREFIX, PosixFilePermissions.asFileAttribute(ownerExecutableWritable));
File tempHwiDir = tempHwiDirPath.toFile();
//tempHwiDir.deleteOnExit();
log.debug("Using temp HWI path: " + tempHwiDir.getAbsolutePath());
File tempExec = null;
ZipInputStream zis = new ZipInputStream(inputStream);
ZipEntry zipEntry = zis.getNextEntry();
while(zipEntry != null) {
if(zipEntry.isDirectory()) {
newDirectory(tempHwiDir, zipEntry, ownerExecutableWritable);
} else {
File newFile = newFile(tempHwiDir, zipEntry, ownerExecutableWritable);
//newFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(newFile);
ByteStreams.copy(zis, new FileOutputStream(newFile));
fos.flush();
fos.close();
if(zipEntry.getName().equals("hwi")) {
tempExec = newFile;
}
}
zipEntry = zis.getNextEntry();
InputStream inputStream = Hwi.class.getResourceAsStream("/native/osx/x64/" + HWI_VERSION_DIR + "-mac-amd64-signed.zip");
if(inputStream == null) {
throw new IllegalStateException("Cannot load " + HWI_VERSION_DIR + " from classpath");
}
zis.closeEntry();
zis.close();
hwiExecutable = tempExec;
File hwiHomeDir = getHwiHomeDir();
File hwiVersionDir = new File(hwiHomeDir, HWI_VERSION_DIR);
if(!hwiVersionDir.exists()) {
Files.createDirectories(hwiVersionDir.toPath(), PosixFilePermissions.asFileAttribute(ownerExecutableWritable));
}
log.debug("Using HWI path: " + hwiVersionDir.getAbsolutePath());
File hwiExec = null;
try(ZipInputStream zis = new ZipInputStream(inputStream)) {
ZipEntry zipEntry = zis.getNextEntry();
while(zipEntry != null) {
if(zipEntry.isDirectory()) {
newDirectory(hwiVersionDir, zipEntry, ownerExecutableWritable);
} else {
File newFile = newFile(hwiVersionDir, zipEntry, ownerExecutableWritable);
try(FileOutputStream fos = new FileOutputStream(newFile)) {
ByteStreams.copy(zis, new FileOutputStream(newFile));
fos.flush();
};
if(zipEntry.getName().equals("hwi")) {
hwiExec = newFile;
}
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
}
hwiExecutable = hwiExec;
} else {
InputStream inputStream;
Path tempExecPath;
if(platform == Platform.WINDOWS) {
inputStream = Hwi.class.getResourceAsStream("/native/windows/x64/hwi.exe");
tempExecPath = Files.createTempFile(VERSION_PREFIX, null);
tempExecPath = Files.createTempFile(HWI_VERSION_DIR, null);
} else {
inputStream = Hwi.class.getResourceAsStream("/native/linux/x64/hwi");
tempExecPath = Files.createTempFile(VERSION_PREFIX, null, PosixFilePermissions.asFileAttribute(ownerExecutableWritable));
tempExecPath = Files.createTempFile(HWI_VERSION_DIR, null, PosixFilePermissions.asFileAttribute(ownerExecutableWritable));
}
if(inputStream == null) {
throw new IllegalStateException("Cannot load " + HWI_VERSION_DIR + " from classpath");
}
File tempExec = tempExecPath.toFile();
tempExec.deleteOnExit();
OutputStream tempExecStream = new BufferedOutputStream(new FileOutputStream(tempExec));
ByteStreams.copy(inputStream, tempExecStream);
inputStream.close();
tempExecStream.flush();
tempExecStream.close();
try(OutputStream tempExecStream = new BufferedOutputStream(new FileOutputStream(tempExec))) {
ByteStreams.copy(inputStream, tempExecStream);
inputStream.close();
tempExecStream.flush();
};
hwiExecutable = tempExec;
}
@@ -305,6 +319,14 @@ public class Hwi {
return hwiExecutable;
}
private File getHwiHomeDir() {
if(Platform.getCurrent() == Platform.OSX) {
return new File(Storage.getSparrowDir(), HWI_HOME_DIR);
}
return new File(System.getProperty("java.io.tmpdir"));
}
private boolean testHwi(File hwiExecutable) {
try {
List<String> command = List.of(hwiExecutable.getAbsolutePath(), "--version");
@@ -317,17 +339,6 @@ public class Hwi {
}
}
private boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}
public static File newDirectory(File destinationDir, ZipEntry zipEntry, Set<PosixFilePermission> setFilePermissions) throws IOException {
String destDirPath = destinationDir.getCanonicalPath();
@@ -1,8 +1,17 @@
package com.sparrowwallet.sparrow.io;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class IOUtils {
public static FileType getFileType(File file) {
@@ -16,10 +25,12 @@ public class IOUtils {
if(file.exists()) {
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
String line = br.readLine();
if(line.startsWith("01000000") || line.startsWith("cHNid")) {
return FileType.TEXT;
} else if(line.startsWith("{")) {
return FileType.JSON;
if(line != null) {
if(line.startsWith("01000000") || line.startsWith("cHNid")) {
return FileType.TEXT;
} else if(line.startsWith("{")) {
return FileType.JSON;
}
}
}
}
@@ -36,4 +47,75 @@ public class IOUtils {
return FileType.UNKNOWN;
}
/**
* List directory contents for a resource folder. Not recursive.
* This is basically a brute-force implementation.
* Works for regular files, JARs and Java modules.
*
* @param clazz Any java class that lives in the same place as the resources you want.
* @param path Should end with "/", but not start with one.
* @return Just the name of each member item, not the full paths.
* @throws URISyntaxException
* @throws IOException
*/
public static String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException {
URL dirURL = clazz.getClassLoader().getResource(path);
if(dirURL != null && dirURL.getProtocol().equals("file")) {
/* A file path: easy enough */
return new File(dirURL.toURI()).list();
}
if(dirURL == null) {
/*
* In case of a jar file, we can't actually find a directory.
* Have to assume the same jar as clazz.
*/
String me = clazz.getName().replace(".", "/")+".class";
dirURL = clazz.getClassLoader().getResource(me);
}
if(dirURL.getProtocol().equals("jar")) {
/* A JAR path */
String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
while(entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if(name.startsWith(path)) { //filter according to the path
String entry = name.substring(path.length());
int checkSubdir = entry.indexOf("/");
if (checkSubdir >= 0) {
// if it is a subdirectory, we just return the directory name
entry = entry.substring(0, checkSubdir);
}
result.add(entry);
}
}
return result.toArray(new String[result.size()]);
}
if(dirURL.getProtocol().equals("jrt")) {
java.nio.file.FileSystem jrtFs = FileSystems.newFileSystem(URI.create("jrt:/"), Collections.emptyMap());
Path resourcePath = jrtFs.getPath("modules/com.sparrowwallet.sparrow", path);
return Files.list(resourcePath).map(filePath -> filePath.getFileName().toString()).toArray(String[]::new);
}
throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
public static boolean deleteDirectory(File directory) {
try {
Files.walk(directory.toPath())
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
} catch(IOException e) {
return false;
}
return true;
}
}
@@ -18,6 +18,7 @@ import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
@@ -34,58 +35,77 @@ public class JsonPersistence implements Persistence {
this.gson = getGson();
}
public Wallet loadWallet(File jsonFile) throws IOException {
try(Reader reader = new FileReader(jsonFile)) {
return gson.fromJson(reader, Wallet.class);
@Override
public WalletBackupAndKey loadWallet(Storage storage) throws IOException, StorageException {
Wallet wallet;
try(Reader reader = new FileReader(storage.getWalletFile())) {
wallet = gson.fromJson(reader, Wallet.class);
}
Map<Storage, WalletBackupAndKey> childWallets = loadChildWallets(storage, wallet, null);
wallet.setChildWallets(childWallets.values().stream().map(WalletBackupAndKey::getWallet).collect(Collectors.toList()));
File backupFile = storage.getTempBackup();
Wallet backupWallet = backupFile == null ? null : loadWallet(backupFile, null);
return new WalletBackupAndKey(wallet, backupWallet, null, null, childWallets);
}
public WalletBackupAndKey loadWallet(File walletFile, CharSequence password) throws IOException, StorageException {
@Override
public WalletBackupAndKey loadWallet(Storage storage, CharSequence password) throws IOException, StorageException {
return loadWallet(storage, password, null);
}
@Override
public WalletBackupAndKey loadWallet(Storage storage, CharSequence password, ECKey alreadyDerivedKey) throws IOException, StorageException {
Wallet wallet;
ECKey encryptionKey;
try(InputStream fileStream = new FileInputStream(walletFile)) {
encryptionKey = getEncryptionKey(password, fileStream, null);
try(InputStream fileStream = new FileInputStream(storage.getWalletFile())) {
encryptionKey = getEncryptionKey(password, fileStream, alreadyDerivedKey);
Reader reader = new InputStreamReader(new InflaterInputStream(new ECIESInputStream(fileStream, encryptionKey, getEncryptionMagic())), StandardCharsets.UTF_8);
wallet = gson.fromJson(reader, Wallet.class);
}
return new WalletBackupAndKey(wallet, null, encryptionKey, keyDeriver, null);
Map<Storage, WalletBackupAndKey> childWallets = loadChildWallets(storage, wallet, encryptionKey);
wallet.setChildWallets(childWallets.values().stream().map(WalletBackupAndKey::getWallet).collect(Collectors.toList()));
File backupFile = storage.getTempBackup();
Wallet backupWallet = backupFile == null ? null : loadWallet(backupFile, encryptionKey);
return new WalletBackupAndKey(wallet, backupWallet, encryptionKey, keyDeriver, childWallets);
}
public Map<File, Wallet> loadWallets(File[] walletFiles, ECKey encryptionKey) throws IOException, StorageException {
Map<File, Wallet> walletsMap = new LinkedHashMap<>();
for(File file : walletFiles) {
if(encryptionKey != null) {
try(InputStream fileStream = new FileInputStream(file)) {
encryptionKey = getEncryptionKey(null, fileStream, encryptionKey);
Reader reader = new InputStreamReader(new InflaterInputStream(new ECIESInputStream(fileStream, encryptionKey, getEncryptionMagic())), StandardCharsets.UTF_8);
walletsMap.put(file, gson.fromJson(reader, Wallet.class));
}
} else {
walletsMap.put(file, loadWallet(file));
}
}
return walletsMap;
}
public Map<Storage, WalletBackupAndKey> loadChildWallets(File walletFile, Wallet masterWallet, ECKey encryptionKey) throws IOException, StorageException {
File[] walletFiles = getChildWalletFiles(walletFile, masterWallet);
private Map<Storage, WalletBackupAndKey> loadChildWallets(Storage storage, Wallet masterWallet, ECKey encryptionKey) throws IOException, StorageException {
File[] walletFiles = getChildWalletFiles(storage.getWalletFile(), masterWallet);
Map<Storage, WalletBackupAndKey> childWallets = new LinkedHashMap<>();
Map<File, Wallet> loadedWallets = loadWallets(walletFiles, encryptionKey);
for(Map.Entry<File, Wallet> entry : loadedWallets.entrySet()) {
Storage storage = new Storage(entry.getKey());
storage.setEncryptionPubKey(encryptionKey == null ? Storage.NO_PASSWORD_KEY : ECKey.fromPublicOnly(encryptionKey));
storage.setKeyDeriver(getKeyDeriver());
Wallet childWallet = entry.getValue();
for(File childFile : walletFiles) {
Wallet childWallet = loadWallet(childFile, encryptionKey);
Storage childStorage = new Storage(childFile);
childStorage.setEncryptionPubKey(encryptionKey == null ? Storage.NO_PASSWORD_KEY : ECKey.fromPublicOnly(encryptionKey));
childStorage.setKeyDeriver(getKeyDeriver());
childWallet.setMasterWallet(masterWallet);
childWallets.put(storage, new WalletBackupAndKey(childWallet, null, encryptionKey, keyDeriver, Collections.emptyMap()));
childWallets.put(childStorage, new WalletBackupAndKey(childWallet, null, encryptionKey, keyDeriver, Collections.emptyMap()));
}
return childWallets;
}
private Wallet loadWallet(File walletFile, ECKey encryptionKey) throws IOException, StorageException {
if(encryptionKey != null) {
try(InputStream fileStream = new FileInputStream(walletFile)) {
encryptionKey = getEncryptionKey(null, fileStream, encryptionKey);
Reader reader = new InputStreamReader(new InflaterInputStream(new ECIESInputStream(fileStream, encryptionKey, getEncryptionMagic())), StandardCharsets.UTF_8);
return gson.fromJson(reader, Wallet.class);
}
} else {
try(Reader reader = new FileReader(walletFile)) {
return gson.fromJson(reader, Wallet.class);
}
}
}
private File[] getChildWalletFiles(File walletFile, Wallet masterWallet) {
File childDir = new File(walletFile.getParentFile(), masterWallet.getName() + "-child");
if(!childDir.exists()) {
@@ -100,14 +120,12 @@ public class JsonPersistence implements Persistence {
return childFiles == null ? new File[0] : childFiles;
}
public File storeWallet(File walletFile, Wallet wallet) throws IOException {
File parent = walletFile.getParentFile();
if(!parent.exists() && !Storage.createOwnerOnlyDirectory(parent)) {
throw new IOException("Could not create folder " + parent);
}
@Override
public File storeWallet(Storage storage, Wallet wallet) throws IOException {
File walletFile = storage.getWalletFile();
if(!walletFile.getName().endsWith(".json")) {
File jsonFile = new File(parent, walletFile.getName() + ".json");
File jsonFile = new File(walletFile.getParentFile(), walletFile.getName() + ".json");
if(walletFile.exists()) {
if(!walletFile.renameTo(jsonFile)) {
throw new IOException("Could not rename " + walletFile.getName() + " to " + jsonFile.getName());
@@ -127,14 +145,12 @@ public class JsonPersistence implements Persistence {
return walletFile;
}
public File storeWallet(File walletFile, Wallet wallet, ECKey encryptionPubKey) throws IOException {
File parent = walletFile.getParentFile();
if(!parent.exists() && !Storage.createOwnerOnlyDirectory(parent)) {
throw new IOException("Could not create folder " + parent);
}
@Override
public File storeWallet(Storage storage, Wallet wallet, ECKey encryptionPubKey) throws IOException {
File walletFile = storage.getWalletFile();
if(walletFile.getName().endsWith(".json")) {
File noJsonFile = new File(parent, walletFile.getName().substring(0, walletFile.getName().lastIndexOf('.')));
File noJsonFile = new File(walletFile.getParentFile(), walletFile.getName().substring(0, walletFile.getName().lastIndexOf('.')));
if(walletFile.exists()) {
if(!walletFile.renameTo(noJsonFile)) {
throw new IOException("Could not rename " + walletFile.getName() + " to " + noJsonFile.getName());
@@ -158,6 +174,16 @@ public class JsonPersistence implements Persistence {
return walletFile;
}
@Override
public void updateWallet(Storage storage, Wallet wallet) throws IOException {
storeWallet(storage, wallet);
}
@Override
public void updateWallet(Storage storage, Wallet wallet, ECKey encryptionPubKey) throws IOException {
storeWallet(storage, wallet, encryptionPubKey);
}
private void writeBinaryHeader(OutputStream outputStream) throws IOException {
ByteBuffer buf = ByteBuffer.allocate(21);
buf.put(HEADER_MAGIC_1.getBytes(StandardCharsets.UTF_8));
@@ -174,6 +200,7 @@ public class JsonPersistence implements Persistence {
return "BIE1".getBytes(StandardCharsets.UTF_8);
}
@Override
public ECKey getEncryptionKey(CharSequence password) throws IOException, StorageException {
return getEncryptionKey(password, null, null);
}
@@ -187,10 +214,12 @@ public class JsonPersistence implements Persistence {
return alreadyDerivedKey == null ? keyDeriver.deriveECKey(password) : alreadyDerivedKey;
}
@Override
public AsymmetricKeyDeriver getKeyDeriver() {
return keyDeriver;
}
@Override
public void setKeyDeriver(AsymmetricKeyDeriver keyDeriver) {
this.keyDeriver = keyDeriver;
}
@@ -232,10 +261,53 @@ public class JsonPersistence implements Persistence {
return new Argon2KeyDeriver(salt);
}
@Override
public PersistenceType getType() {
return PersistenceType.JSON;
}
@Override
public boolean isEncrypted(File walletFile) throws IOException {
FileType fileType = IOUtils.getFileType(walletFile);
if(FileType.JSON.equals(fileType)) {
return false;
} else if(FileType.BINARY.equals(fileType)) {
try(FileInputStream fileInputStream = new FileInputStream(walletFile)) {
getWalletKeyDeriver(fileInputStream);
return true;
} catch(StorageException e) {
return false;
}
}
throw new IOException("Unsupported file type");
}
@Override
public String getWalletId(Storage storage, Wallet wallet) {
return storage.getWalletFile().getParentFile().getAbsolutePath() + File.separator + getWalletName(storage.getWalletFile(), null) + ":" + (wallet == null || wallet.isMasterWallet() ? "master" : wallet.getName());
}
@Override
public String getWalletName(File walletFile, Wallet wallet) {
String name = walletFile.getName();
if(name.endsWith("." + getType().getExtension())) {
name = name.substring(0, name.lastIndexOf('.'));
}
return name;
}
@Override
public void copyWallet(File walletFile, OutputStream outputStream) throws IOException {
com.google.common.io.Files.copy(walletFile, outputStream);
}
@Override
public void close() {
//Nothing required
}
public static Gson getGson() {
return getGson(true);
}
@@ -261,7 +333,7 @@ public class JsonPersistence implements Persistence {
gsonBuilder.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes field) {
return field.getDeclaringClass() == Wallet.class && field.getName().equals("masterWallet");
return field.getName().equals("id") || field.getName().equals("masterWallet") || field.getName().equals("childWallets");
}
@Override
@@ -0,0 +1,70 @@
package com.sparrowwallet.sparrow.io;
import com.sparrowwallet.drongo.protocol.ScriptType;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletModel;
import java.io.InputStream;
public class KeystoneMultisig extends ColdcardMultisig {
@Override
public String getName() {
return "Keystone Multisig";
}
@Override
public WalletModel getWalletModel() {
return WalletModel.KEYSTONE;
}
@Override
public Keystore getKeystore(ScriptType scriptType, InputStream inputStream, String password) throws ImportException {
Keystore keystore = super.getKeystore(scriptType, inputStream, password);
keystore.setLabel("Keystone");
keystore.setWalletModel(getWalletModel());
return keystore;
}
@Override
public String getKeystoreImportDescription() {
return "Import file or QR created by using the Multisig Wallet > ... > Show/Export XPUB feature on your Keystone.";
}
@Override
public Wallet importWallet(InputStream inputStream, String password) throws ImportException {
Wallet wallet = super.importWallet(inputStream, password);
for(Keystore keystore : wallet.getKeystores()) {
keystore.setLabel(keystore.getLabel().replace("Coldcard", "Keystone"));
keystore.setWalletModel(WalletModel.KEYSTONE);
}
return wallet;
}
@Override
public String getWalletImportDescription() {
return "Import file or QR created by using the Multisig Wallet > ... > Create Multisig Wallet feature on your Keystone.";
}
@Override
public String getWalletExportDescription() {
return "Export file or QR that can be read by your Keystone using the Multisig Wallet > ... > Import Multisig Wallet feature.";
}
@Override
public boolean isWalletImportScannable() {
return true;
}
@Override
public boolean isKeystoreImportScannable() {
return true;
}
@Override
public boolean isWalletExportScannable() {
return true;
}
}
@@ -0,0 +1,112 @@
package com.sparrowwallet.sparrow.io;
import com.google.gson.Gson;
import com.sparrowwallet.drongo.ExtendedKey;
import com.sparrowwallet.drongo.KeyDerivation;
import com.sparrowwallet.drongo.OutputDescriptor;
import com.sparrowwallet.drongo.policy.Policy;
import com.sparrowwallet.drongo.policy.PolicyType;
import com.sparrowwallet.drongo.protocol.ScriptType;
import com.sparrowwallet.drongo.wallet.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
public class KeystoneSinglesig implements KeystoreFileImport, WalletImport {
private static final Logger log = LoggerFactory.getLogger(KeystoneSinglesig.class);
@Override
public String getName() {
return "Keystone";
}
@Override
public String getKeystoreImportDescription() {
return "Import file or QR created by using the My Keystone > ... > Export Wallet feature on your Keystone. Make sure to set the Watch-only Wallet to Sparrow in the Settings first.";
}
@Override
public WalletModel getWalletModel() {
return WalletModel.KEYSTONE;
}
@Override
public Keystore getKeystore(ScriptType scriptType, InputStream inputStream, String password) throws ImportException {
try {
String outputDescriptor = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n"));
OutputDescriptor descriptor = OutputDescriptor.getOutputDescriptor(outputDescriptor);
if(descriptor.isMultisig()) {
throw new IllegalArgumentException("Output descriptor describes a multisig wallet");
}
if(descriptor.getScriptType() != scriptType) {
throw new IllegalArgumentException("Output descriptor describes a " + descriptor.getScriptType().getDescription() + " wallet");
}
ExtendedKey xpub = descriptor.getSingletonExtendedPublicKey();
KeyDerivation keyDerivation = descriptor.getKeyDerivation(xpub);
Keystore keystore = new Keystore();
keystore.setLabel(getName());
keystore.setSource(KeystoreSource.HW_AIRGAPPED);
keystore.setWalletModel(WalletModel.KEYSTONE);
keystore.setKeyDerivation(keyDerivation);
keystore.setExtendedPublicKey(xpub);
return keystore;
} catch (IllegalArgumentException e) {
log.error("Error getting " + getName() + " keystore - not an output descriptor");
throw new ImportException("Error getting " + getName() + " keystore", e);
} catch (Exception e) {
log.error("Error getting " + getName() + " keystore", e);
throw new ImportException("Error getting " + getName() + " keystore", e);
}
}
@Override
public String getWalletImportDescription() {
return getKeystoreImportDescription();
}
@Override
public Wallet importWallet(InputStream inputStream, String password) throws ImportException {
//Use default of P2WPKH
Keystore keystore = getKeystore(ScriptType.P2WPKH, inputStream, "");
Wallet wallet = new Wallet();
wallet.setPolicyType(PolicyType.SINGLE);
wallet.setScriptType(ScriptType.P2WPKH);
wallet.getKeystores().add(keystore);
wallet.setDefaultPolicy(Policy.getPolicy(PolicyType.SINGLE, ScriptType.P2WPKH, wallet.getKeystores(), null));
try {
wallet.checkWallet();
} catch(InvalidWalletException e) {
throw new ImportException("Imported " + getName() + " wallet was invalid: " + e.getMessage());
}
return wallet;
}
@Override
public boolean isEncrypted(File file) {
return false;
}
@Override
public boolean isWalletImportScannable() {
return true;
}
@Override
public boolean isKeystoreImportScannable() {
return true;
}
}
@@ -6,17 +6,23 @@ import com.sparrowwallet.drongo.wallet.Wallet;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.io.OutputStream;
public interface Persistence {
Wallet loadWallet(File walletFile) throws IOException;
WalletBackupAndKey loadWallet(File walletFile, CharSequence password) throws IOException, StorageException;
Map<File, Wallet> loadWallets(File[] walletFiles, ECKey encryptionKey) throws IOException, StorageException;
Map<Storage, WalletBackupAndKey> loadChildWallets(File walletFile, Wallet masterWallet, ECKey encryptionKey) throws IOException, StorageException;
File storeWallet(File walletFile, Wallet wallet) throws IOException;
File storeWallet(File walletFile, Wallet wallet, ECKey encryptionPubKey) throws IOException;
WalletBackupAndKey loadWallet(Storage storage) throws IOException, StorageException;
WalletBackupAndKey loadWallet(Storage storage, CharSequence password) throws IOException, StorageException;
WalletBackupAndKey loadWallet(Storage storage, CharSequence password, ECKey alreadyDerivedKey) throws IOException, StorageException;
File storeWallet(Storage storage, Wallet wallet) throws IOException, StorageException;
File storeWallet(Storage storage, Wallet wallet, ECKey encryptionPubKey) throws IOException, StorageException;
void updateWallet(Storage storage, Wallet wallet) throws IOException, StorageException;
void updateWallet(Storage storage, Wallet wallet, ECKey encryptionPubKey) throws IOException, StorageException;
ECKey getEncryptionKey(CharSequence password) throws IOException, StorageException;
AsymmetricKeyDeriver getKeyDeriver();
void setKeyDeriver(AsymmetricKeyDeriver keyDeriver);
PersistenceType getType();
boolean isEncrypted(File walletFile) throws IOException;
String getWalletId(Storage storage, Wallet wallet);
String getWalletName(File walletFile, Wallet wallet);
void copyWallet(File walletFile, OutputStream outputStream) throws IOException;
void close();
}
@@ -1,7 +1,30 @@
package com.sparrowwallet.sparrow.io;
import com.sparrowwallet.sparrow.io.db.DbPersistence;
public enum PersistenceType {
JSON("json");
JSON("json") {
@Override
public String getExtension() {
return getName();
}
@Override
public Persistence getInstance() {
return new JsonPersistence();
}
},
DB("db") {
@Override
public String getExtension() {
return "mv.db";
}
@Override
public Persistence getInstance() {
return new DbPersistence();
}
};
private final String name;
@@ -13,7 +36,7 @@ public enum PersistenceType {
return name;
}
public String getExtension() {
return getName();
}
public abstract String getExtension();
public abstract Persistence getInstance();
}
@@ -0,0 +1,20 @@
package com.sparrowwallet.sparrow.io;
import com.sparrowwallet.drongo.wallet.WalletModel;
public class SeedSigner extends SpecterDIY {
@Override
public String getName() {
return "SeedSigner";
}
@Override
public String getKeystoreImportDescription() {
return "Import QR created on your SeedSigner by selecting Generate XPUB in the Signing Tools menu. Note that SeedSigner currently only supports P2WSH Multisig wallets.";
}
@Override
public WalletModel getWalletModel() {
return WalletModel.SEEDSIGNER;
}
}
@@ -1,15 +1,19 @@
package com.sparrowwallet.sparrow.io;
import com.google.common.io.Files;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletModel;
import com.sparrowwallet.sparrow.AppServices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Sparrow implements WalletExport {
public class Sparrow implements WalletImport, WalletExport {
private static final Logger log = LoggerFactory.getLogger(Sparrow.class);
@Override
@@ -26,8 +30,14 @@ public class Sparrow implements WalletExport {
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
try {
Storage storage = AppServices.get().getOpenWallets().get(wallet);
Files.copy(storage.getWalletFile().toPath(), outputStream);
File tempFile = File.createTempFile(wallet.getName(), null);
Storage tempStorage = new Storage(PersistenceType.JSON, tempFile);
tempStorage.setKeyDeriver(storage.getKeyDeriver());
tempStorage.setEncryptionPubKey(storage.getEncryptionPubKey());
tempStorage.saveWallet(wallet);
Files.copy(tempStorage.getWalletFile(), outputStream);
outputStream.flush();
tempStorage.getWalletFile().delete();
} catch(Exception e) {
log.error("Error exporting Sparrow wallet file", e);
throw new ExportException("Error exporting Sparrow wallet file", e);
@@ -36,14 +46,16 @@ public class Sparrow implements WalletExport {
@Override
public String getWalletExportDescription() {
return "Exports a copy of your Sparrow wallet file, which can be loaded in another Sparrow instance running on any supported platform.";
return "Exports your Sparrow wallet file, which can be imported into another Sparrow instance running on any supported platform. If the wallet is encrypted, the same password is used to encrypt the exported file.";
}
@Override
public String getExportFileExtension(Wallet wallet) {
Storage storage = AppServices.get().getOpenWallets().get(wallet);
if(storage != null && (storage.getEncryptionPubKey() == null || Storage.NO_PASSWORD_KEY.equals(storage.getEncryptionPubKey()))) {
return "json";
try {
Storage storage = AppServices.get().getOpenWallets().get(wallet);
return storage.isEncrypted() ? "" : PersistenceType.JSON.getExtension();
} catch(IOException e) {
//ignore
}
return "";
@@ -58,4 +70,58 @@ public class Sparrow implements WalletExport {
public boolean walletExportRequiresDecryption() {
return false;
}
@Override
public boolean isEncrypted(File file) {
return Storage.isEncrypted(file);
}
@Override
public String getWalletImportDescription() {
return "Imports an exported Sparrow wallet file into Sparrow's wallets folder.";
}
@Override
public Wallet importWallet(InputStream inputStream, String password) throws ImportException {
Storage storage = null;
Wallet wallet = null;
File tempFile = null;
try {
tempFile = File.createTempFile("sparrow", null);
java.nio.file.Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
storage = new Storage(PersistenceType.JSON, tempFile);
if(!isEncrypted(tempFile)) {
wallet = storage.loadUnencryptedWallet().getWallet();
} else {
WalletBackupAndKey walletBackupAndKey = storage.loadEncryptedWallet(password);
wallet = walletBackupAndKey.getWallet();
wallet.decrypt(walletBackupAndKey.getKey());
}
return wallet;
} catch(IOException | StorageException e) {
log.error("Error importing Sparrow wallet", e);
throw new ImportException("Error importing Sparrow wallet", e);
} finally {
if(storage != null) {
storage.close();
}
if(tempFile != null) {
if(wallet != null) {
File migratedWalletFile = Storage.getExistingWallet(tempFile.getParentFile(), wallet.getName());
if(migratedWalletFile != null) {
migratedWalletFile.delete();
}
}
tempFile.delete();
}
}
}
@Override
public boolean isWalletImportScannable() {
return false;
}
}
@@ -10,13 +10,10 @@ import com.sparrowwallet.drongo.wallet.WalletModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class SpecterDIY implements KeystoreFileImport {
public class SpecterDIY implements KeystoreFileImport, WalletExport {
private static final Logger log = LoggerFactory.getLogger(SpecterDIY.class);
@Override
@@ -38,8 +35,8 @@ public class SpecterDIY implements KeystoreFileImport {
return keystore;
} catch(IOException e) {
log.error("Error getting Specter DIY keystore", e);
throw new ImportException("Error getting Specter DIY keystore", e);
log.error("Error getting " + getName() + " keystore", e);
throw new ImportException("Error getting " + getName() + " keystore", e);
}
}
@@ -67,4 +64,36 @@ public class SpecterDIY implements KeystoreFileImport {
public WalletModel getWalletModel() {
return WalletModel.SPECTER_DIY;
}
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
writer.append("addwallet ").append(wallet.getName()).append("&").append(OutputDescriptor.getOutputDescriptor(wallet).toString().replace('\'', 'h')).append("\n");
writer.flush();
} catch(Exception e) {
log.error("Error exporting " + getName() + " wallet", e);
throw new ExportException("Error exporting " + getName() + " wallet", e);
}
}
@Override
public String getWalletExportDescription() {
return "Export file or QR that can be read by your Specter DIY using the Wallets > Add Wallet feature.";
}
@Override
public String getExportFileExtension(Wallet wallet) {
return "txt";
}
@Override
public boolean isWalletExportScannable() {
return true;
}
@Override
public boolean walletExportRequiresDecryption() {
return false;
}
}
@@ -3,10 +3,7 @@ package com.sparrowwallet.sparrow.io;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sparrowwallet.drongo.OutputDescriptor;
import com.sparrowwallet.drongo.wallet.BlockTransactionHash;
import com.sparrowwallet.drongo.wallet.InvalidWalletException;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletModel;
import com.sparrowwallet.drongo.wallet.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -15,6 +12,7 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class SpecterDesktop implements WalletImport, WalletExport {
private static final Logger log = LoggerFactory.getLogger(SpecterDesktop.class);
@@ -32,8 +30,8 @@ public class SpecterDesktop implements WalletImport, WalletExport {
outputStream.write(json.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
} catch(Exception e) {
log.error("Error exporting Specter Desktop wallet", e);
throw new ExportException("Error exporting Specter Desktop wallet", e);
log.error("Error exporting " + getName() + " wallet", e);
throw new ExportException("Error exporting " + getName() + " wallet", e);
}
}
@@ -49,7 +47,7 @@ public class SpecterDesktop implements WalletImport, WalletExport {
@Override
public String getWalletImportDescription() {
return "Import a Specter wallet created by using the Wallets > Settings > Export to Wallet Software in Specter Desktop";
return "Import a Specter wallet created by using the Wallets > Settings > Export to Wallet Software in Specter Desktop. Note Connected (USB) Hardware Wallets may need to be reimported separately as the export file may not contain this information.";
}
@Override
@@ -63,20 +61,43 @@ public class SpecterDesktop implements WalletImport, WalletExport {
Wallet wallet = outputDescriptor.toWallet();
wallet.setName(specterWallet.label);
if(specterWallet.devices != null && specterWallet.devices.size() == wallet.getKeystores().size()) {
boolean uniqueLabels = specterWallet.devices.stream().map(d -> d.label).distinct().count() == specterWallet.devices.size();
for(int i = 0; i < specterWallet.devices.size(); i++) {
SpecterWalletDevice device = specterWallet.devices.get(i);
Keystore keystore = wallet.getKeystores().get(i);
keystore.setLabel(device.label + (uniqueLabels ? "" : " " + i));
WalletModel walletModel = device.getWalletModel();
if(walletModel != null) {
keystore.setWalletModel(walletModel);
if(walletModel == WalletModel.TREZOR_1 || walletModel == WalletModel.TREZOR_T || walletModel == WalletModel.KEEPKEY ||
walletModel == WalletModel.LEDGER_NANO_S || walletModel == WalletModel.LEDGER_NANO_X ||
walletModel == WalletModel.BITBOX_02 || walletModel == WalletModel.COLDCARD) {
keystore.setSource(KeystoreSource.HW_USB);
} else if(walletModel == WalletModel.BITCOIN_CORE) {
keystore.setSource(KeystoreSource.SW_WATCH);
} else {
keystore.setSource(KeystoreSource.HW_AIRGAPPED);
}
}
}
}
try {
wallet.checkWallet();
} catch(InvalidWalletException e) {
throw new ImportException("Imported Specter wallet was invalid: " + e.getMessage());
throw new ImportException("Imported " + getName() + " wallet was invalid: " + e.getMessage());
}
return wallet;
}
} catch(Exception e) {
log.error("Error importing Specter Desktop wallet", e);
throw new ImportException("Error importing Specter Desktop wallet", e);
log.error("Error importing " + getName() + " wallet", e);
throw new ImportException("Error importing " + getName() + " wallet", e);
}
throw new ImportException("File was not a valid Specter Desktop wallet");
throw new ImportException("File was not a valid " + getName() + " wallet");
}
@Override
@@ -113,5 +134,32 @@ public class SpecterDesktop implements WalletImport, WalletExport {
public String label;
public Integer blockheight;
public String descriptor;
public List<SpecterWalletDevice> devices;
}
public static class SpecterWalletDevice {
public String type;
public String label;
public WalletModel getWalletModel() {
if(type != null) {
String model = type;
if(model.equals("cobo")) {
model = "cobovault";
}
WalletModel walletModel = WalletModel.fromType(model);
if(walletModel == WalletModel.SPECTER_DESKTOP) {
walletModel = WalletModel.SPECTER_DIY;
}
if(walletModel == WalletModel.TREZOR_1) {
walletModel = WalletModel.TREZOR_T;
}
return walletModel;
}
return null;
}
}
}
@@ -36,14 +36,24 @@ public class Storage {
public static final String WALLETS_DIR = "wallets";
public static final String WALLETS_BACKUP_DIR = "backup";
public static final String CERTS_DIR = "certs";
public static final String TEMP_BACKUP_EXTENSION = "tmp";
public static final String TEMP_BACKUP_PREFIX = "tmp";
public static final List<String> RESERVED_WALLET_NAMES = List.of("temp");
private final Persistence persistence;
private Persistence persistence;
private File walletFile;
private ECKey encryptionPubKey;
public Storage(File walletFile) {
this.persistence = new JsonPersistence();
this(!walletFile.exists() || walletFile.getName().endsWith("." + PersistenceType.DB.getExtension()) ? PersistenceType.DB : PersistenceType.JSON, walletFile);
}
public Storage(PersistenceType persistenceType, File walletFile) {
this.persistence = persistenceType.getInstance();
this.walletFile = walletFile;
}
public Storage(Persistence persistence, File walletFile) {
this.persistence = persistence;
this.walletFile = walletFile;
}
@@ -51,45 +61,63 @@ public class Storage {
return walletFile;
}
public WalletBackupAndKey loadUnencryptedWallet() throws IOException, StorageException {
Wallet wallet = persistence.loadWallet(walletFile);
Wallet backupWallet = loadBackupWallet(null);
Map<Storage, WalletBackupAndKey> childWallets = persistence.loadChildWallets(walletFile, wallet, null);
public boolean isEncrypted() throws IOException {
return persistence.isEncrypted(walletFile);
}
public String getWalletId(Wallet wallet) {
return persistence.getWalletId(this, wallet);
}
public String getWalletName(Wallet wallet) {
return persistence.getWalletName(walletFile, wallet);
}
public String getWalletFileExtension() {
if(walletFile.getName().endsWith("." + getType().getExtension())) {
return getType().getExtension();
}
return "";
}
public WalletBackupAndKey loadUnencryptedWallet() throws IOException, StorageException {
WalletBackupAndKey masterWalletAndKey = persistence.loadWallet(this);
encryptionPubKey = NO_PASSWORD_KEY;
return new WalletBackupAndKey(wallet, backupWallet, null, null, childWallets);
return migrateToDb(masterWalletAndKey);
}
public WalletBackupAndKey loadEncryptedWallet(CharSequence password) throws IOException, StorageException {
WalletBackupAndKey masterWalletAndKey = persistence.loadWallet(walletFile, password);
Wallet backupWallet = loadBackupWallet(masterWalletAndKey.getEncryptionKey());
Map<Storage, WalletBackupAndKey> childWallets = persistence.loadChildWallets(walletFile, masterWalletAndKey.getWallet(), masterWalletAndKey.getEncryptionKey());
WalletBackupAndKey masterWalletAndKey = persistence.loadWallet(this, password);
encryptionPubKey = ECKey.fromPublicOnly(masterWalletAndKey.getEncryptionKey());
return new WalletBackupAndKey(masterWalletAndKey.getWallet(), backupWallet, masterWalletAndKey.getEncryptionKey(), persistence.getKeyDeriver(), childWallets);
return migrateToDb(masterWalletAndKey);
}
protected Wallet loadBackupWallet(ECKey encryptionKey) throws IOException, StorageException {
Map<File, Wallet> backupWallets;
if(encryptionKey != null) {
File[] backups = getBackups(TEMP_BACKUP_EXTENSION, persistence.getType().getExtension() + "." + TEMP_BACKUP_EXTENSION);
backupWallets = persistence.loadWallets(backups, encryptionKey);
return backupWallets.isEmpty() ? null : backupWallets.values().iterator().next();
} else {
File[] backups = getBackups(persistence.getType().getExtension() + "." + TEMP_BACKUP_EXTENSION);
backupWallets = persistence.loadWallets(backups, null);
public void saveWallet(Wallet wallet) throws IOException, StorageException {
File parent = walletFile.getParentFile();
if(!parent.exists() && !Storage.createOwnerOnlyDirectory(parent)) {
throw new IOException("Could not create folder " + parent);
}
return backupWallets.isEmpty() ? null : backupWallets.values().iterator().next();
}
public void saveWallet(Wallet wallet) throws IOException {
if(encryptionPubKey != null && !NO_PASSWORD_KEY.equals(encryptionPubKey)) {
walletFile = persistence.storeWallet(walletFile, wallet, encryptionPubKey);
walletFile = persistence.storeWallet(this, wallet, encryptionPubKey);
return;
}
walletFile = persistence.storeWallet(walletFile, wallet);
walletFile = persistence.storeWallet(this, wallet);
}
public void updateWallet(Wallet wallet) throws IOException, StorageException {
if(encryptionPubKey != null && !NO_PASSWORD_KEY.equals(encryptionPubKey)) {
persistence.updateWallet(this, wallet, encryptionPubKey);
} else {
persistence.updateWallet(this, wallet);
}
}
public void close() {
ClosePersistenceService closePersistenceService = new ClosePersistenceService();
closePersistenceService.start();
}
public void backupWallet() throws IOException {
@@ -100,34 +128,36 @@ public class Storage {
public void backupTempWallet() {
try {
backupWallet(TEMP_BACKUP_EXTENSION);
backupWallet(TEMP_BACKUP_PREFIX);
} catch(IOException e) {
log.error("Error creating ." + TEMP_BACKUP_EXTENSION + " backup wallet", e);
log.error("Error creating " + TEMP_BACKUP_PREFIX + " backup wallet", e);
}
}
private void backupWallet(String extension) throws IOException {
private void backupWallet(String prefix) throws IOException {
File backupDir = getWalletsBackupDir();
Date backupDate = new Date();
String backupName = walletFile.getName();
String walletName = persistence.getWalletName(walletFile, null);
String dateSuffix = "-" + BACKUP_DATE_FORMAT.format(backupDate);
int lastDot = backupName.lastIndexOf('.');
if(lastDot > 0) {
backupName = backupName.substring(0, lastDot) + dateSuffix + backupName.substring(lastDot);
} else {
backupName += dateSuffix;
}
String backupName = walletName + dateSuffix + walletFile.getName().substring(walletName.length());
if(extension != null) {
backupName += "." + extension;
if(prefix != null) {
backupName = prefix + "_" + backupName;
}
File backupFile = new File(backupDir, backupName);
if(!backupFile.exists()) {
createOwnerOnlyFile(backupFile);
}
com.google.common.io.Files.copy(walletFile, backupFile);
try(FileOutputStream outputStream = new FileOutputStream(backupFile)) {
copyWallet(outputStream);
}
}
public void copyWallet(OutputStream outputStream) throws IOException {
persistence.copyWallet(walletFile, outputStream);
}
public void deleteBackups() {
@@ -135,27 +165,29 @@ public class Storage {
}
public void deleteTempBackups() {
deleteBackups(Storage.TEMP_BACKUP_EXTENSION);
deleteBackups(Storage.TEMP_BACKUP_PREFIX);
}
private void deleteBackups(String extension) {
File[] backups = getBackups(extension);
private void deleteBackups(String prefix) {
File[] backups = getBackups(prefix);
for(File backup : backups) {
backup.delete();
}
}
private File[] getBackups(String extension) {
return getBackups(extension, null);
public File getTempBackup() {
File[] backups = getBackups(TEMP_BACKUP_PREFIX);
return backups.length == 0 ? null : backups[0];
}
private File[] getBackups(String extension, String notExtension) {
File[] getBackups(String prefix) {
File backupDir = getWalletsBackupDir();
String walletName = persistence.getWalletName(walletFile, null);
String extension = walletFile.getName().substring(walletName.length());
File[] backups = backupDir.listFiles((dir, name) -> {
return name.startsWith(com.google.common.io.Files.getNameWithoutExtension(walletFile.getName()) + "-") &&
return name.startsWith((prefix == null ? "" : prefix + "_") + walletName + "-") &&
getBackupDate(name) != null &&
(extension == null || name.endsWith("." + extension)) &&
(notExtension == null || !name.endsWith("." + notExtension));
(extension.isEmpty() || name.endsWith(extension));
});
backups = backups == null ? new File[0] : backups;
@@ -173,6 +205,49 @@ public class Storage {
return null;
}
private WalletBackupAndKey migrateToDb(WalletBackupAndKey masterWalletAndKey) throws IOException, StorageException {
if(getType() == PersistenceType.JSON) {
log.info("Migrating " + masterWalletAndKey.getWallet().getName() + " from JSON to DB persistence");
masterWalletAndKey = migrateType(PersistenceType.DB, masterWalletAndKey.getWallet(), masterWalletAndKey.getEncryptionKey());
}
return masterWalletAndKey;
}
private WalletBackupAndKey migrateType(PersistenceType type, Wallet wallet, ECKey encryptionKey) throws IOException, StorageException {
File existingFile = walletFile;
try {
AsymmetricKeyDeriver keyDeriver = persistence.getKeyDeriver();
persistence = type.getInstance();
persistence.setKeyDeriver(keyDeriver);
walletFile = new File(walletFile.getParentFile(), wallet.getName() + "." + type.getExtension());
if(walletFile.exists()) {
walletFile.delete();
}
saveWallet(wallet);
if(type == PersistenceType.DB) {
for(Wallet childWallet : wallet.getChildWallets()) {
saveWallet(childWallet);
}
}
if(NO_PASSWORD_KEY.equals(encryptionPubKey)) {
return persistence.loadWallet(this);
}
return persistence.loadWallet(this, null, encryptionKey);
} catch(Exception e) {
existingFile = null;
throw e;
} finally {
if(existingFile != null) {
existingFile.delete();
}
}
}
public ECKey getEncryptionPubKey() {
return encryptionPubKey;
}
@@ -193,6 +268,10 @@ public class Storage {
persistence.setKeyDeriver(keyDeriver);
}
public PersistenceType getType() {
return persistence.getType();
}
public static boolean walletExists(String walletName) {
File encrypted = new File(getWalletsDir(), walletName.trim());
if(encrypted.exists()) {
@@ -206,17 +285,21 @@ public class Storage {
}
}
return false;
return RESERVED_WALLET_NAMES.contains(walletName);
}
public static File getExistingWallet(String walletName) {
File encrypted = new File(getWalletsDir(), walletName.trim());
return getExistingWallet(getWalletsDir(), walletName);
}
public static File getExistingWallet(File walletsDir, String walletName) {
File encrypted = new File(walletsDir, walletName.trim());
if(encrypted.exists()) {
return encrypted;
}
for(PersistenceType persistenceType : PersistenceType.values()) {
File unencrypted = new File(getWalletsDir(), walletName.trim() + "." + persistenceType.getExtension());
File unencrypted = new File(walletsDir, walletName.trim() + "." + persistenceType.getExtension());
if(unencrypted.exists()) {
return unencrypted;
}
@@ -230,6 +313,38 @@ public class Storage {
return new File(getWalletsDir(), walletName);
}
public static boolean isWalletFile(File walletFile) {
for(PersistenceType type : PersistenceType.values()) {
if(walletFile.getName().endsWith("." + type.getExtension())) {
return true;
}
try {
if(type == PersistenceType.JSON && type.getInstance().isEncrypted(walletFile)) {
return true;
}
} catch(IOException e) {
//ignore
}
}
return false;
}
public static boolean isEncrypted(File walletFile) {
try {
for(PersistenceType type : PersistenceType.values()) {
if(walletFile.getName().endsWith("." + type.getExtension())) {
return type.getInstance().isEncrypted(walletFile);
}
}
} catch(IOException e) {
//ignore
}
return FileType.BINARY.equals(IOUtils.getFileType(walletFile));
}
public static File getWalletsBackupDir() {
File walletsBackupDir = new File(getWalletsDir(), WALLETS_BACKUP_DIR);
if(!walletsBackupDir.exists()) {
@@ -432,4 +547,16 @@ public class Storage {
};
}
}
public class ClosePersistenceService extends Service<Void> {
@Override
protected Task<Void> createTask() {
return new Task<>() {
protected Void call() {
persistence.close();
return null;
}
};
}
}
}
@@ -0,0 +1,60 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.protocol.Sha256Hash;
import com.sparrowwallet.drongo.wallet.BlockTransaction;
import com.sparrowwallet.drongo.wallet.Wallet;
import org.jdbi.v3.sqlobject.config.RegisterRowMapper;
import org.jdbi.v3.sqlobject.customizer.Bind;
import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
import java.util.Date;
import java.util.Map;
public interface BlockTransactionDao {
@SqlQuery("select id, txid, hash, height, date, fee, label, transaction, blockHash from blockTransaction where wallet = ? order by id")
@RegisterRowMapper(BlockTransactionMapper.class)
Map<Sha256Hash, BlockTransaction> getForWalletId(Long id);
@SqlQuery("select id, txid, hash, height, date, fee, label, transaction, blockHash from blockTransaction where txid = ?")
@RegisterRowMapper(BlockTransactionMapper.class)
Map<Sha256Hash, BlockTransaction> getForTxId(byte[] id);
@SqlUpdate("insert into blockTransaction (txid, hash, height, date, fee, label, transaction, blockHash, wallet) values (?, ?, ?, ?, ?, ?, ?, ?, ?)")
@GetGeneratedKeys("id")
long insertBlockTransaction(byte[] txid, byte[] hash, int height, Date date, Long fee, String label, byte[] transaction, byte[] blockHash, long wallet);
@SqlUpdate("update blockTransaction set txid = ?, hash = ?, height = ?, date = ?, fee = ?, label = ?, transaction = ?, blockHash = ?, wallet = ? where id = ?")
void updateBlockTransaction(byte[] txid, byte[] hash, int height, Date date, Long fee, String label, byte[] transaction, byte[] blockHash, long wallet, long id);
@SqlUpdate("update blockTransaction set label = :label where id = :id")
void updateLabel(@Bind("id") long id, @Bind("label") String label);
@SqlUpdate("delete from blockTransaction where wallet = ?")
void clear(long wallet);
default void addBlockTransactions(Wallet wallet) {
for(Map.Entry<Sha256Hash, BlockTransaction> blkTxEntry : wallet.getTransactions().entrySet()) {
blkTxEntry.getValue().setId(null);
addOrUpdate(wallet, blkTxEntry.getKey(), blkTxEntry.getValue());
}
}
default void addOrUpdate(Wallet wallet, Sha256Hash txid, BlockTransaction blkTx) {
Map<Sha256Hash, BlockTransaction> existing = getForTxId(txid.getBytes());
if(existing.isEmpty() && blkTx.getId() == null) {
long id = insertBlockTransaction(txid.getBytes(), blkTx.getHash().getBytes(), blkTx.getHeight(), blkTx.getDate(), blkTx.getFee(), blkTx.getLabel(),
blkTx.getTransaction() == null ? null : blkTx.getTransaction().bitcoinSerialize(),
blkTx.getBlockHash() == null ? null : blkTx.getBlockHash().getBytes(), wallet.getId());
blkTx.setId(id);
} else {
Long existingId = existing.get(txid) != null ? existing.get(txid).getId() : blkTx.getId();
updateBlockTransaction(txid.getBytes(), blkTx.getHash().getBytes(), blkTx.getHeight(), blkTx.getDate(), blkTx.getFee(), blkTx.getLabel(),
blkTx.getTransaction() == null ? null : blkTx.getTransaction().bitcoinSerialize(),
blkTx.getBlockHash() == null ? null : blkTx.getBlockHash().getBytes(), wallet.getId(), existingId);
blkTx.setId(existingId);
}
}
}
@@ -0,0 +1,26 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.protocol.Sha256Hash;
import com.sparrowwallet.drongo.wallet.BlockTransactionHashIndex;
import com.sparrowwallet.drongo.wallet.Status;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BlockTransactionHashIndexMapper implements RowMapper<BlockTransactionHashIndex> {
@Override
public BlockTransactionHashIndex map(ResultSet rs, StatementContext ctx) throws SQLException {
BlockTransactionHashIndex blockTransactionHashIndex = new BlockTransactionHashIndex(Sha256Hash.wrap(rs.getBytes("blockTransactionHashIndex.hash")),
rs.getInt("blockTransactionHashIndex.height"), rs.getTimestamp("blockTransactionHashIndex.date"), rs.getLong("blockTransactionHashIndex.fee"),
rs.getLong("blockTransactionHashIndex.index"), rs.getLong("blockTransactionHashIndex.outputValue"), null, rs.getString("blockTransactionHashIndex.label"));
blockTransactionHashIndex.setId(rs.getLong("blockTransactionHashIndex.id"));
int statusIndex = rs.getInt("blockTransactionHashIndex.status");
if(!rs.wasNull()) {
blockTransactionHashIndex.setStatus(Status.values()[statusIndex]);
}
return blockTransactionHashIndex;
}
}
@@ -0,0 +1,51 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.protocol.Sha256Hash;
import com.sparrowwallet.drongo.protocol.Transaction;
import com.sparrowwallet.drongo.wallet.BlockTransaction;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
public class BlockTransactionMapper implements RowMapper<Map.Entry<Sha256Hash, BlockTransaction>> {
@Override
public Map.Entry<Sha256Hash, BlockTransaction> map(ResultSet rs, StatementContext ctx) throws SQLException {
Sha256Hash txid = Sha256Hash.wrap(rs.getBytes("txid"));
byte[] txBytes = rs.getBytes("transaction");
Transaction transaction = null;
if(txBytes != null) {
transaction = new Transaction(txBytes);
}
Long fee = rs.getLong("fee");
if(rs.wasNull()) {
fee = null;
}
BlockTransaction blockTransaction = new BlockTransaction(Sha256Hash.wrap(rs.getBytes("hash")), rs.getInt("height"), rs.getTimestamp("date"),
fee, transaction, rs.getBytes("blockHash") == null ? null : Sha256Hash.wrap(rs.getBytes("blockHash")), rs.getString("label"));
blockTransaction.setId(rs.getLong("id"));
return new Map.Entry<>() {
@Override
public Sha256Hash getKey() {
return txid;
}
@Override
public BlockTransaction getValue() {
return blockTransaction;
}
@Override
public BlockTransaction setValue(BlockTransaction value) {
return null;
}
};
}
}
@@ -0,0 +1,653 @@
package com.sparrowwallet.sparrow.io.db;
import com.google.common.eventbus.Subscribe;
import com.google.common.io.Files;
import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.drongo.crypto.Argon2KeyDeriver;
import com.sparrowwallet.drongo.crypto.AsymmetricKeyDeriver;
import com.sparrowwallet.drongo.crypto.ECKey;
import com.sparrowwallet.drongo.crypto.InvalidPasswordException;
import com.sparrowwallet.drongo.protocol.Sha256Hash;
import com.sparrowwallet.drongo.wallet.*;
import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.event.*;
import com.sparrowwallet.sparrow.io.*;
import com.sparrowwallet.sparrow.wallet.*;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.pool.HikariPool;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.exception.FlywayValidateException;
import org.h2.tools.ChangeFileEncryption;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.h2.H2DatabasePlugin;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.StandardCopyOption;
import java.security.SecureRandom;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class DbPersistence implements Persistence {
private static final Logger log = LoggerFactory.getLogger(DbPersistence.class);
static final String DEFAULT_SCHEMA = "PUBLIC";
private static final String WALLET_SCHEMA_PREFIX = "wallet_";
private static final String MASTER_SCHEMA = WALLET_SCHEMA_PREFIX + "master";
private static final byte[] H2_ENCRYPT_HEADER = "H2encrypt\n".getBytes(StandardCharsets.UTF_8);
private static final int H2_ENCRYPT_SALT_LENGTH_BYTES = 8;
private static final int SALT_LENGTH_BYTES = 16;
public static final byte[] HEADER_MAGIC_1 = "SPRW1\n".getBytes(StandardCharsets.UTF_8);
private static final String H2_USER = "sa";
private static final String H2_PASSWORD = "";
public static final String MIGRATION_RESOURCES_DIR = "com/sparrowwallet/sparrow/sql/";
private HikariDataSource dataSource;
private AsymmetricKeyDeriver keyDeriver;
private Wallet masterWallet;
private final Map<Wallet, DirtyPersistables> dirtyPersistablesMap = new HashMap<>();
public DbPersistence() {
EventManager.get().register(this);
}
@Override
public WalletBackupAndKey loadWallet(Storage storage) throws IOException, StorageException {
return loadWallet(storage, null, null);
}
@Override
public WalletBackupAndKey loadWallet(Storage storage, CharSequence password) throws IOException, StorageException {
return loadWallet(storage, password, null);
}
@Override
public WalletBackupAndKey loadWallet(Storage storage, CharSequence password, ECKey alreadyDerivedKey) throws IOException, StorageException {
ECKey encryptionKey = getEncryptionKey(password, storage.getWalletFile(), alreadyDerivedKey);
migrate(storage, MASTER_SCHEMA, encryptionKey);
Jdbi jdbi = getJdbi(storage, getFilePassword(encryptionKey));
masterWallet = jdbi.withHandle(handle -> {
WalletDao walletDao = handle.attach(WalletDao.class);
return walletDao.getMainWallet(MASTER_SCHEMA);
});
File backupFile = storage.getTempBackup();
Wallet backupWallet = null;
if(backupFile != null) {
Persistence backupPersistence = PersistenceType.DB.getInstance();
backupPersistence.setKeyDeriver(keyDeriver);
backupWallet = backupPersistence.loadWallet(new Storage(backupPersistence, backupFile), password, encryptionKey).getWallet();
}
Map<Storage, WalletBackupAndKey> childWallets = loadChildWallets(storage, masterWallet, backupWallet, encryptionKey);
masterWallet.setChildWallets(childWallets.values().stream().map(WalletBackupAndKey::getWallet).collect(Collectors.toList()));
return new WalletBackupAndKey(masterWallet, backupWallet, encryptionKey, keyDeriver, childWallets);
}
private Map<Storage, WalletBackupAndKey> loadChildWallets(Storage storage, Wallet masterWallet, Wallet backupWallet, ECKey encryptionKey) throws StorageException {
Jdbi jdbi = getJdbi(storage, getFilePassword(encryptionKey));
List<String> schemas = jdbi.withHandle(handle -> {
return handle.createQuery("show schemas").mapTo(String.class).list();
});
List<String> childSchemas = schemas.stream().filter(schema -> schema.startsWith(WALLET_SCHEMA_PREFIX) && !schema.equals(MASTER_SCHEMA)).collect(Collectors.toList());
Map<Storage, WalletBackupAndKey> childWallets = new LinkedHashMap<>();
for(String schema : childSchemas) {
migrate(storage, schema, encryptionKey);
Jdbi childJdbi = getJdbi(storage, getFilePassword(encryptionKey));
Wallet wallet = childJdbi.withHandle(handle -> {
WalletDao walletDao = handle.attach(WalletDao.class);
Wallet childWallet = walletDao.getMainWallet(schema);
childWallet.setName(schema.substring(WALLET_SCHEMA_PREFIX.length()));
childWallet.setMasterWallet(masterWallet);
return childWallet;
});
Wallet backupChildWallet = backupWallet == null ? null : backupWallet.getChildWallets().stream().filter(child -> wallet.getName().equals(child.getName())).findFirst().orElse(null);
childWallets.put(storage, new WalletBackupAndKey(wallet, backupChildWallet, encryptionKey, keyDeriver, Collections.emptyMap()));
}
return childWallets;
}
@Override
public File storeWallet(Storage storage, Wallet wallet) throws IOException, StorageException {
File walletFile = storage.getWalletFile();
walletFile = renameToDbFile(walletFile);
updatePassword(storage, null);
cleanAndAddWallet(storage, wallet, null);
return walletFile;
}
@Override
public File storeWallet(Storage storage, Wallet wallet, ECKey encryptionPubKey) throws IOException, StorageException {
File walletFile = storage.getWalletFile();
walletFile = renameToDbFile(walletFile);
boolean existing = walletFile.exists();
updatePassword(storage, encryptionPubKey);
cleanAndAddWallet(storage, wallet, getFilePassword(encryptionPubKey));
if(!existing) {
writeBinaryHeader(walletFile);
}
return walletFile;
}
@Override
public void updateWallet(Storage storage, Wallet wallet) throws StorageException {
updateWallet(storage, wallet, null);
}
@Override
public void updateWallet(Storage storage, Wallet wallet, ECKey encryptionPubKey) throws StorageException {
updatePassword(storage, encryptionPubKey);
update(storage, wallet, getFilePassword(encryptionPubKey));
}
private File renameToDbFile(File walletFile) throws IOException {
if(!walletFile.getName().endsWith("." + getType().getExtension())) {
File dbFile = new File(walletFile.getParentFile(), walletFile.getName() + "." + getType().getExtension());
if(walletFile.exists()) {
if(!walletFile.renameTo(dbFile)) {
throw new IOException("Could not rename " + walletFile.getName() + " to " + dbFile.getName());
}
}
return dbFile;
}
return walletFile;
}
private void update(Storage storage, Wallet wallet, String password) throws StorageException {
DirtyPersistables dirtyPersistables = dirtyPersistablesMap.get(wallet);
if(dirtyPersistables == null) {
return;
}
log.debug("Updating " + wallet.getName() + " on " + Thread.currentThread().getName());
log.debug(dirtyPersistables.toString());
Jdbi jdbi = getJdbi(storage, password);
jdbi.useHandle(handle -> {
WalletDao walletDao = handle.attach(WalletDao.class);
try {
walletDao.setSchema(getSchema(wallet));
if(dirtyPersistables.clearHistory) {
WalletNodeDao walletNodeDao = handle.attach(WalletNodeDao.class);
BlockTransactionDao blockTransactionDao = handle.attach(BlockTransactionDao.class);
walletNodeDao.clearHistory(wallet);
blockTransactionDao.clear(wallet.getId());
}
if(!dirtyPersistables.historyNodes.isEmpty()) {
WalletNodeDao walletNodeDao = handle.attach(WalletNodeDao.class);
BlockTransactionDao blockTransactionDao = handle.attach(BlockTransactionDao.class);
Set<Sha256Hash> referencedTxIds = new HashSet<>();
for(WalletNode addressNode : dirtyPersistables.historyNodes) {
if(addressNode.getId() == null) {
WalletNode purposeNode = wallet.getNode(addressNode.getKeyPurpose());
if(purposeNode.getId() == null) {
long purposeNodeId = walletNodeDao.insertWalletNode(purposeNode.getDerivationPath(), purposeNode.getLabel(), wallet.getId(), null);
purposeNode.setId(purposeNodeId);
}
long nodeId = walletNodeDao.insertWalletNode(addressNode.getDerivationPath(), addressNode.getLabel(), wallet.getId(), purposeNode.getId());
addressNode.setId(nodeId);
}
Set<BlockTransactionHashIndex> txos = addressNode.getTransactionOutputs().stream().flatMap(txo -> txo.isSpent() ? Stream.of(txo, txo.getSpentBy()) : Stream.of(txo)).collect(Collectors.toSet());
List<Long> existingIds = txos.stream().map(Persistable::getId).filter(Objects::nonNull).collect(Collectors.toList());
referencedTxIds.addAll(txos.stream().map(BlockTransactionHash::getHash).collect(Collectors.toSet()));
walletNodeDao.deleteNodeTxosNotInList(addressNode, existingIds.isEmpty() ? List.of(-1L) : existingIds);
for(BlockTransactionHashIndex txo : addressNode.getTransactionOutputs()) {
walletNodeDao.addOrUpdate(addressNode, txo);
}
}
for(Sha256Hash txid : referencedTxIds) {
BlockTransaction blkTx = wallet.getTransactions().get(txid);
blockTransactionDao.addOrUpdate(wallet, txid, blkTx);
}
}
if(dirtyPersistables.blockHeight != null) {
walletDao.updateStoredBlockHeight(wallet.getId(), dirtyPersistables.blockHeight);
}
if(!dirtyPersistables.labelEntries.isEmpty()) {
BlockTransactionDao blockTransactionDao = handle.attach(BlockTransactionDao.class);
WalletNodeDao walletNodeDao = handle.attach(WalletNodeDao.class);
for(Entry entry : dirtyPersistables.labelEntries) {
if(entry instanceof TransactionEntry && ((TransactionEntry)entry).getBlockTransaction().getId() != null) {
blockTransactionDao.updateLabel(((TransactionEntry)entry).getBlockTransaction().getId(), entry.getLabel());
} else if(entry instanceof NodeEntry && ((NodeEntry)entry).getNode().getId() != null) {
walletNodeDao.updateNodeLabel(((NodeEntry)entry).getNode().getId(), entry.getLabel());
} else if(entry instanceof HashIndexEntry && ((HashIndexEntry)entry).getHashIndex().getId() != null) {
walletNodeDao.updateTxoLabel(((HashIndexEntry)entry).getHashIndex().getId(), entry.getLabel());
}
}
}
if(!dirtyPersistables.utxoStatuses.isEmpty()) {
WalletNodeDao walletNodeDao = handle.attach(WalletNodeDao.class);
for(BlockTransactionHashIndex utxo : dirtyPersistables.utxoStatuses) {
walletNodeDao.updateTxoStatus(utxo.getId(), utxo.getStatus() == null ? null : utxo.getStatus().ordinal());
}
}
if(!dirtyPersistables.labelKeystores.isEmpty()) {
KeystoreDao keystoreDao = handle.attach(KeystoreDao.class);
for(Keystore keystore : dirtyPersistables.labelKeystores) {
keystoreDao.updateLabel(keystore.getLabel(), keystore.getId());
}
}
if(!dirtyPersistables.encryptionKeystores.isEmpty()) {
KeystoreDao keystoreDao = handle.attach(KeystoreDao.class);
for(Keystore keystore : dirtyPersistables.encryptionKeystores) {
keystoreDao.updateKeystoreEncryption(keystore);
}
}
dirtyPersistablesMap.remove(wallet);
} finally {
walletDao.setSchema(DEFAULT_SCHEMA);
}
});
}
private void cleanAndAddWallet(Storage storage, Wallet wallet, String password) throws StorageException {
String schema = getSchema(wallet);
cleanAndMigrate(storage, schema, password);
Jdbi jdbi = getJdbi(storage, password);
jdbi.useHandle(handle -> {
WalletDao walletDao = handle.attach(WalletDao.class);
walletDao.addWallet(schema, wallet);
});
if(wallet.isMasterWallet()) {
masterWallet = wallet;
}
}
private void migrate(Storage storage, String schema, ECKey encryptionKey) throws StorageException {
File migrationDir = getMigrationDir();
try {
Flyway flyway = getFlyway(storage, schema, getFilePassword(encryptionKey), migrationDir);
flyway.migrate();
} catch(FlywayValidateException e) {
log.error("Failed to open wallet file. Validation error during schema migration.", e);
throw new StorageException("Failed to open wallet file. Validation error during schema migration.", e);
} catch(FlywayException e) {
log.error("Failed to open wallet file. ", e);
throw new StorageException("Failed to open wallet file.\n" + e.getMessage(), e);
} finally {
IOUtils.deleteDirectory(migrationDir);
}
}
private void cleanAndMigrate(Storage storage, String schema, String password) throws StorageException {
File migrationDir = getMigrationDir();
try {
Flyway flyway = getFlyway(storage, schema, password, migrationDir);
flyway.clean();
flyway.migrate();
} catch(FlywayException e) {
log.error("Failed to save wallet file.", e);
throw new StorageException("Failed to save wallet file.\n" + e.getMessage(), e);
} finally {
IOUtils.deleteDirectory(migrationDir);
}
}
private String getSchema(Wallet wallet) {
return wallet.isMasterWallet() ? MASTER_SCHEMA : WALLET_SCHEMA_PREFIX + wallet.getName();
}
private String getFilePassword(ECKey encryptionKey) {
if(encryptionKey == null) {
return null;
}
return Utils.bytesToHex(encryptionKey.getPubKey());
}
private void writeBinaryHeader(File walletFile) throws IOException {
if(dataSource != null && !dataSource.isClosed()) {
dataSource.close();
}
ByteBuffer header = ByteBuffer.allocate(HEADER_MAGIC_1.length + SALT_LENGTH_BYTES);
header.put(HEADER_MAGIC_1);
header.put(keyDeriver.getSalt());
header.flip();
try(FileChannel fileChannel = new RandomAccessFile(walletFile, "rwd").getChannel()) {
fileChannel.position(H2_ENCRYPT_HEADER.length + H2_ENCRYPT_SALT_LENGTH_BYTES);
fileChannel.write(header);
}
}
private void updatePassword(Storage storage, ECKey encryptionPubKey) {
String newPassword = getFilePassword(encryptionPubKey);
String currentPassword = getDatasourcePassword();
//The password only needs to be changed if the datasource is not null - if we have not loaded the wallet from a datasource, it is a new wallet and the database is still to be created
if(dataSource != null && !Objects.equals(currentPassword, newPassword)) {
if(!dataSource.isClosed()) {
dataSource.close();
}
try {
File walletFile = storage.getWalletFile();
ChangeFileEncryption.execute(walletFile.getParent(), getWalletName(walletFile, null), "AES",
currentPassword == null ? null : currentPassword.toCharArray(),
newPassword == null ? null : newPassword.toCharArray(), true);
if(newPassword != null) {
writeBinaryHeader(walletFile);
}
//This sets the new password on the datasource for the next updatePassword check
getDataSource(storage, newPassword);
} catch(Exception e) {
log.error("Error changing database password", e);
}
}
}
private String getDatasourcePassword() {
if(dataSource != null) {
String dsPassword = dataSource.getPassword();
if(dsPassword.isEmpty()) {
return null;
}
return dsPassword.substring(0, dsPassword.length() - (" " + H2_PASSWORD).length());
}
return null;
}
@Override
public ECKey getEncryptionKey(CharSequence password) throws IOException {
return getEncryptionKey(password, null, null);
}
private ECKey getEncryptionKey(CharSequence password, File walletFile, ECKey alreadyDerivedKey) throws IOException {
if(alreadyDerivedKey != null) {
return alreadyDerivedKey;
} else if(password == null) {
return null;
} else if(password.equals("")) {
return Storage.NO_PASSWORD_KEY;
}
AsymmetricKeyDeriver keyDeriver = getKeyDeriver(walletFile);
return keyDeriver.deriveECKey(password);
}
@Override
public AsymmetricKeyDeriver getKeyDeriver() {
return keyDeriver;
}
@Override
public void setKeyDeriver(AsymmetricKeyDeriver keyDeriver) {
this.keyDeriver = keyDeriver;
}
private AsymmetricKeyDeriver getKeyDeriver(File walletFile) throws IOException {
if(keyDeriver == null) {
keyDeriver = getWalletKeyDeriver(walletFile);
}
return keyDeriver;
}
private AsymmetricKeyDeriver getWalletKeyDeriver(File walletFile) throws IOException {
if(keyDeriver == null) {
byte[] salt = new byte[SALT_LENGTH_BYTES];
if(walletFile != null && walletFile.exists()) {
try(InputStream inputStream = new FileInputStream(walletFile)) {
inputStream.skip(H2_ENCRYPT_HEADER.length + H2_ENCRYPT_SALT_LENGTH_BYTES + HEADER_MAGIC_1.length);
inputStream.read(salt, 0, salt.length);
}
} else {
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(salt);
}
return new Argon2KeyDeriver(salt);
}
return keyDeriver;
}
@Override
public boolean isEncrypted(File walletFile) throws IOException {
if(dataSource != null) {
return getDatasourcePassword() != null;
}
byte[] header = new byte[H2_ENCRYPT_HEADER.length];
try(InputStream inputStream = new FileInputStream(walletFile)) {
inputStream.read(header, 0, H2_ENCRYPT_HEADER.length);
return Arrays.equals(H2_ENCRYPT_HEADER, header);
}
}
@Override
public String getWalletId(Storage storage, Wallet wallet) {
return storage.getWalletFile().getParentFile().getAbsolutePath() + File.separator + getWalletName(storage.getWalletFile(), null) + ":" + (wallet == null || wallet.isMasterWallet() ? "master" : wallet.getName());
}
@Override
public String getWalletName(File walletFile, Wallet wallet) {
if(wallet != null && wallet.getMasterWallet() != null) {
return wallet.getName();
}
String name = walletFile.getName();
if(name.endsWith("." + getType().getExtension())) {
name = name.substring(0, name.length() - getType().getExtension().length() - 1);
}
return name;
}
@Override
public PersistenceType getType() {
return PersistenceType.DB;
}
@Override
public void copyWallet(File walletFile, OutputStream outputStream) throws IOException {
if(dataSource != null && !dataSource.isClosed()) {
dataSource.close();
}
com.google.common.io.Files.copy(walletFile, outputStream);
}
@Override
public void close() {
EventManager.get().unregister(this);
if(dataSource != null && !dataSource.isClosed()) {
dataSource.close();
}
}
private Jdbi getJdbi(Storage storage, String password) throws StorageException {
Jdbi jdbi = Jdbi.create(getDataSource(storage, password));
jdbi.installPlugin(new H2DatabasePlugin());
jdbi.installPlugin(new SqlObjectPlugin());
return jdbi;
}
private Flyway getFlyway(Storage storage, String schema, String password, File resourcesDir) throws StorageException {
return Flyway.configure().dataSource(getDataSource(storage, password)).locations("filesystem:" + resourcesDir.getAbsolutePath()).schemas(schema).failOnMissingLocations(true).load();
}
//Flyway does not support JPMS yet, so the migration files are extracted to a temp dir in order to avoid classloader encapsulation issues
private File getMigrationDir() {
File migrationDir = Files.createTempDir();
try {
String[] files = IOUtils.getResourceListing(DbPersistence.class, MIGRATION_RESOURCES_DIR);
for(String name : files) {
File targetFile = new File(migrationDir, name);
try(InputStream inputStream = DbPersistence.class.getResourceAsStream("/" + MIGRATION_RESOURCES_DIR + name)) {
if(inputStream != null) {
java.nio.file.Files.copy(inputStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} else {
log.error("Could not load resource at /" + MIGRATION_RESOURCES_DIR + name);
}
}
}
} catch(Exception e) {
log.error("Could not extract migration resources", e);
}
return migrationDir;
}
private HikariDataSource getDataSource(Storage storage, String password) throws StorageException {
if(dataSource == null || dataSource.isClosed()) {
dataSource = createDataSource(storage.getWalletFile(), password);
}
return dataSource;
}
private HikariDataSource createDataSource(File walletFile, String password) throws StorageException {
try {
Class.forName("org.h2.Driver");
HikariConfig config = new HikariConfig();
config.setJdbcUrl(getUrl(walletFile, password));
config.setUsername(H2_USER);
config.setPassword(password == null ? H2_PASSWORD : password + " " + H2_PASSWORD);
return new HikariDataSource(config);
} catch(ClassNotFoundException e) {
log.error("Cannot find H2 driver", e);
throw new StorageException("Cannot find H2 driver", e);
} catch(HikariPool.PoolInitializationException e) {
if(e.getMessage() != null && e.getMessage().contains("Database may be already in use")) {
log.error("Wallet file may already be in use. Make sure the application is not running elsewhere.", e);
throw new StorageException("Wallet file may already be in use. Make sure the application is not running elsewhere.", e);
} else if(e.getMessage() != null && (e.getMessage().contains("Wrong user name or password") || e.getMessage().contains("Encryption error in file"))) {
throw new InvalidPasswordException("Incorrect password for wallet file " + walletFile.getAbsolutePath(), e);
} else {
log.error("Failed to open database file", e);
throw new StorageException("Failed to open database file.\n" + e.getMessage(), e);
}
}
}
private String getUrl(File walletFile, String password) {
return "jdbc:h2:" + walletFile.getAbsolutePath().replace("." + getType().getExtension(), "") + ";INIT=SET TRACE_LEVEL_FILE=4;TRACE_LEVEL_FILE=4;DATABASE_TO_UPPER=false" + (password == null ? "" : ";CIPHER=AES");
}
private boolean persistsFor(Wallet wallet) {
if(masterWallet != null) {
if(wallet == masterWallet) {
return true;
}
return masterWallet.getChildWallets().contains(wallet);
}
return false;
}
@Subscribe
public void walletHistoryCleared(WalletHistoryClearedEvent event) {
if(persistsFor(event.getWallet())) {
dirtyPersistablesMap.computeIfAbsent(event.getWallet(), key -> new DirtyPersistables()).clearHistory = true;
}
}
@Subscribe
public void walletHistoryChanged(WalletHistoryChangedEvent event) {
if(persistsFor(event.getWallet())) {
dirtyPersistablesMap.computeIfAbsent(event.getWallet(), key -> new DirtyPersistables()).historyNodes.addAll(event.getHistoryChangedNodes());
}
}
@Subscribe
public void walletBlockHeightChanged(WalletBlockHeightChangedEvent event) {
if(persistsFor(event.getWallet())) {
dirtyPersistablesMap.computeIfAbsent(event.getWallet(), key -> new DirtyPersistables()).blockHeight = event.getBlockHeight();
}
}
@Subscribe
public void walletEntryLabelsChanged(WalletEntryLabelsChangedEvent event) {
if(persistsFor(event.getWallet())) {
dirtyPersistablesMap.computeIfAbsent(event.getWallet(), key -> new DirtyPersistables()).labelEntries.addAll(event.getEntries());
}
}
@Subscribe
public void walletUtxoStatusChanged(WalletUtxoStatusChangedEvent event) {
if(persistsFor(event.getWallet())) {
dirtyPersistablesMap.computeIfAbsent(event.getWallet(), key -> new DirtyPersistables()).utxoStatuses.add(event.getUtxo());
}
}
@Subscribe
public void keystoreLabelsChanged(KeystoreLabelsChangedEvent event) {
if(persistsFor(event.getWallet())) {
dirtyPersistablesMap.computeIfAbsent(event.getWallet(), key -> new DirtyPersistables()).labelKeystores.addAll(event.getChangedKeystores());
}
}
@Subscribe
public void keystoreEncryptionChanged(KeystoreEncryptionChangedEvent event) {
if(persistsFor(event.getWallet())) {
dirtyPersistablesMap.computeIfAbsent(event.getWallet(), key -> new DirtyPersistables()).encryptionKeystores.addAll(event.getChangedKeystores());
}
}
private static class DirtyPersistables {
public boolean clearHistory;
public final List<WalletNode> historyNodes = new ArrayList<>();
public Integer blockHeight = null;
public final List<Entry> labelEntries = new ArrayList<>();
public final List<BlockTransactionHashIndex> utxoStatuses = new ArrayList<>();
public final List<Keystore> labelKeystores = new ArrayList<>();
public final List<Keystore> encryptionKeystores = new ArrayList<>();
public String toString() {
return "Dirty Persistables" +
"\nClear history:" + clearHistory +
"\nNodes:" + historyNodes +
"\nBlockHeight:" + blockHeight +
"\nTx labels:" + labelEntries.stream().filter(entry -> entry instanceof TransactionEntry).map(entry -> ((TransactionEntry)entry).getBlockTransaction().getHash().toString()).collect(Collectors.toList()) +
"\nAddress labels:" + labelEntries.stream().filter(entry -> entry instanceof NodeEntry).map(entry -> ((NodeEntry)entry).getNode().toString() + " " + entry.getLabel()).collect(Collectors.toList()) +
"\nUTXO labels:" + labelEntries.stream().filter(entry -> entry instanceof HashIndexEntry).map(entry -> ((HashIndexEntry)entry).getHashIndex().toString()).collect(Collectors.toList()) +
"\nUTXO statuses:" + utxoStatuses +
"\nKeystore labels:" + labelKeystores.stream().map(Keystore::getLabel).collect(Collectors.toList()) +
"\nKeystore encryptions:" + encryptionKeystores.stream().map(Keystore::getLabel).collect(Collectors.toList());
}
}
}
@@ -0,0 +1,102 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.crypto.EncryptedData;
import com.sparrowwallet.drongo.wallet.DeterministicSeed;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.MasterPrivateExtendedKey;
import com.sparrowwallet.drongo.wallet.Wallet;
import org.jdbi.v3.sqlobject.config.RegisterRowMapper;
import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
import java.util.List;
public interface KeystoreDao {
@SqlQuery("select keystore.id, keystore.label, keystore.source, keystore.walletModel, keystore.masterFingerprint, keystore.derivationPath, keystore.extendedPublicKey, " +
"masterPrivateExtendedKey.id, masterPrivateExtendedKey.privateKey, masterPrivateExtendedKey.chainCode, masterPrivateExtendedKey.initialisationVector, masterPrivateExtendedKey.encryptedBytes, masterPrivateExtendedKey.keySalt, masterPrivateExtendedKey.deriver, masterPrivateExtendedKey.crypter, " +
"seed.id, seed.type, seed.mnemonicString, seed.initialisationVector, seed.encryptedBytes, seed.keySalt, seed.deriver, seed.crypter, seed.needsPassphrase, seed.creationTimeSeconds " +
"from keystore left join masterPrivateExtendedKey on keystore.masterPrivateExtendedKey = masterPrivateExtendedKey.id left join seed on keystore.seed = seed.id where keystore.wallet = ? order by keystore.index asc")
@RegisterRowMapper(KeystoreMapper.class)
List<Keystore> getForWalletId(Long id);
@SqlUpdate("insert into keystore (label, source, walletModel, masterFingerprint, derivationPath, extendedPublicKey, masterPrivateExtendedKey, seed, wallet, index) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
@GetGeneratedKeys("id")
long insert(String label, int source, int walletModel, String masterFingerprint, String derivationPath, String extendedPublicKey, Long masterPrivateExtendedKey, Long seed, long wallet, int index);
@SqlUpdate("insert into masterPrivateExtendedKey (privateKey, chainCode, initialisationVector, encryptedBytes, keySalt, deriver, crypter, creationTimeSeconds) values (?, ?, ?, ?, ?, ?, ?, ?)")
@GetGeneratedKeys("id")
long insertMasterPrivateExtendedKey(byte[] privateKey, byte[] chainCode, byte[] initialisationVector, byte[] encryptedBytes, byte[] keySalt, Integer deriver, Integer crypter, long creationTimeSeconds);
@SqlUpdate("update masterPrivateExtendedKey set privateKey = ?, chainCode = ?, initialisationVector = ?, encryptedBytes = ?, keySalt = ?, deriver = ?, crypter = ?, creationTimeSeconds = ? where id = ?")
void updateMasterPrivateExtendedKey(byte[] privateKey, byte[] chainCode, byte[] initialisationVector, byte[] encryptedBytes, byte[] keySalt, Integer deriver, Integer crypter, long creationTimeSeconds, long id);
@SqlUpdate("insert into seed (type, mnemonicString, initialisationVector, encryptedBytes, keySalt, deriver, crypter, needsPassphrase, creationTimeSeconds) values (?, ?, ?, ?, ?, ?, ?, ?, ?)")
@GetGeneratedKeys("id")
long insertSeed(int type, String mnemonicString, byte[] initialisationVector, byte[] encryptedBytes, byte[] keySalt, Integer deriver, Integer crypter, boolean needsPassphrase, long creationTimeSeconds);
@SqlUpdate("update seed set type = ?, mnemonicString = ?, initialisationVector = ?, encryptedBytes = ?, keySalt = ?, deriver = ?, crypter = ?, needsPassphrase = ?, creationTimeSeconds = ? where id = ?")
void updateSeed(int type, String mnemonicString, byte[] initialisationVector, byte[] encryptedBytes, byte[] keySalt, Integer deriver, Integer crypter, boolean needsPassphrase, long creationTimeSeconds, long id);
@SqlUpdate("update keystore set label = ? where id = ?")
void updateLabel(String label, long id);
default void addKeystores(Wallet wallet) {
for(int i = 0; i < wallet.getKeystores().size(); i++) {
Keystore keystore = wallet.getKeystores().get(i);
if(keystore.hasMasterPrivateExtendedKey()) {
MasterPrivateExtendedKey mpek = keystore.getMasterPrivateExtendedKey();
if(mpek.isEncrypted()) {
EncryptedData data = mpek.getEncryptedData();
long id = insertMasterPrivateExtendedKey(null, null, data.getInitialisationVector(), data.getEncryptedBytes(), data.getKeySalt(), data.getEncryptionType().getDeriver().ordinal(), data.getEncryptionType().getCrypter().ordinal(), mpek.getCreationTimeSeconds());
mpek.setId(id);
} else {
long id = insertMasterPrivateExtendedKey(mpek.getPrivateKey().getPrivKeyBytes(), mpek.getPrivateKey().getChainCode(), null, null, null, null, null, mpek.getCreationTimeSeconds());
mpek.setId(id);
}
}
if(keystore.hasSeed()) {
DeterministicSeed seed = keystore.getSeed();
if(seed.isEncrypted()) {
EncryptedData data = seed.getEncryptedData();
long id = insertSeed(seed.getType().ordinal(), null, data.getInitialisationVector(), data.getEncryptedBytes(), data.getKeySalt(), data.getEncryptionType().getDeriver().ordinal(), data.getEncryptionType().getCrypter().ordinal(), seed.needsPassphrase(), seed.getCreationTimeSeconds());
seed.setId(id);
} else {
long id = insertSeed(seed.getType().ordinal(), seed.getMnemonicString().asString(), null, null, null, null, null, seed.needsPassphrase(), seed.getCreationTimeSeconds());
seed.setId(id);
}
}
long id = insert(keystore.getLabel(), keystore.getSource().ordinal(), keystore.getWalletModel().ordinal(),
keystore.hasPrivateKey() ? null : keystore.getKeyDerivation().getMasterFingerprint(),
keystore.getKeyDerivation().getDerivationPath(),
keystore.hasPrivateKey() ? null : keystore.getExtendedPublicKey().toString(),
keystore.getMasterPrivateExtendedKey() == null ? null : keystore.getMasterPrivateExtendedKey().getId(),
keystore.getSeed() == null ? null : keystore.getSeed().getId(), wallet.getId(), i);
keystore.setId(id);
}
}
default void updateKeystoreEncryption(Keystore keystore) {
if(keystore.hasMasterPrivateExtendedKey()) {
MasterPrivateExtendedKey mpek = keystore.getMasterPrivateExtendedKey();
if(mpek.isEncrypted()) {
EncryptedData data = mpek.getEncryptedData();
updateMasterPrivateExtendedKey(null, null, data.getInitialisationVector(), data.getEncryptedBytes(), data.getKeySalt(), data.getEncryptionType().getDeriver().ordinal(), data.getEncryptionType().getCrypter().ordinal(), mpek.getCreationTimeSeconds(), mpek.getId());
} else {
updateMasterPrivateExtendedKey(mpek.getPrivateKey().getPrivKeyBytes(), mpek.getPrivateKey().getChainCode(), null, null, null, null, null, mpek.getCreationTimeSeconds(), mpek.getId());
}
}
if(keystore.hasSeed()) {
DeterministicSeed seed = keystore.getSeed();
if(seed.isEncrypted()) {
EncryptedData data = seed.getEncryptedData();
updateSeed(seed.getType().ordinal(), null, data.getInitialisationVector(), data.getEncryptedBytes(), data.getKeySalt(), data.getEncryptionType().getDeriver().ordinal(), data.getEncryptionType().getCrypter().ordinal(), seed.needsPassphrase(), seed.getCreationTimeSeconds(), seed.getId());
} else {
updateSeed(seed.getType().ordinal(), seed.getMnemonicString().asString(), null, null, null, null, null, seed.needsPassphrase(), seed.getCreationTimeSeconds(), seed.getId());
}
}
}
}
@@ -0,0 +1,58 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.ExtendedKey;
import com.sparrowwallet.drongo.KeyDerivation;
import com.sparrowwallet.drongo.crypto.EncryptedData;
import com.sparrowwallet.drongo.crypto.EncryptionType;
import com.sparrowwallet.drongo.wallet.*;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
public class KeystoreMapper implements RowMapper<Keystore> {
@Override
public Keystore map(ResultSet rs, StatementContext ctx) throws SQLException {
Keystore keystore = new Keystore(rs.getString("keystore.label"));
keystore.setId(rs.getLong("keystore.id"));
keystore.setSource(KeystoreSource.values()[rs.getInt("keystore.source")]);
keystore.setWalletModel(WalletModel.values()[rs.getInt("keystore.walletModel")]);
keystore.setKeyDerivation(new KeyDerivation(rs.getString("keystore.masterFingerprint"), rs.getString("keystore.derivationPath")));
keystore.setExtendedPublicKey(rs.getString("keystore.extendedPublicKey") == null ? null : ExtendedKey.fromDescriptor(rs.getString("keystore.extendedPublicKey")));
if(rs.getBytes("masterPrivateExtendedKey.privateKey") != null) {
MasterPrivateExtendedKey masterPrivateExtendedKey = new MasterPrivateExtendedKey(rs.getBytes("masterPrivateExtendedKey.privateKey"), rs.getBytes("masterPrivateExtendedKey.chainCode"));
masterPrivateExtendedKey.setId(rs.getLong("masterPrivateExtendedKey.id"));
keystore.setMasterPrivateExtendedKey(masterPrivateExtendedKey);
} else if(rs.getBytes("masterPrivateExtendedKey.encryptedBytes") != null) {
EncryptedData encryptedData = new EncryptedData(rs.getBytes("masterPrivateExtendedKey.initialisationVector"),
rs.getBytes("masterPrivateExtendedKey.encryptedBytes"), rs.getBytes("masterPrivateExtendedKey.keySalt"),
EncryptionType.Deriver.values()[rs.getInt("masterPrivateExtendedKey.deriver")],
EncryptionType.Crypter.values()[rs.getInt("masterPrivateExtendedKey.crypter")]);
MasterPrivateExtendedKey masterPrivateExtendedKey = new MasterPrivateExtendedKey(encryptedData);
masterPrivateExtendedKey.setId(rs.getLong("masterPrivateExtendedKey.id"));
keystore.setMasterPrivateExtendedKey(masterPrivateExtendedKey);
}
if(rs.getString("seed.mnemonicString") != null) {
List<String> mnemonicCode = Arrays.asList(rs.getString("seed.mnemonicString").split(" "));
DeterministicSeed seed = new DeterministicSeed(mnemonicCode, rs.getBoolean("seed.needsPassphrase"), rs.getLong("seed.creationTimeSeconds"), DeterministicSeed.Type.values()[rs.getInt("seed.type")]);
seed.setId(rs.getLong("seed.id"));
keystore.setSeed(seed);
} else if(rs.getBytes("seed.encryptedBytes") != null) {
EncryptedData encryptedData = new EncryptedData(rs.getBytes("seed.initialisationVector"),
rs.getBytes("seed.encryptedBytes"), rs.getBytes("seed.keySalt"),
EncryptionType.Deriver.values()[rs.getInt("seed.deriver")],
EncryptionType.Crypter.values()[rs.getInt("seed.crypter")]);
DeterministicSeed seed = new DeterministicSeed(encryptedData, rs.getBoolean("seed.needsPassphrase"), rs.getLong("seed.creationTimeSeconds"), DeterministicSeed.Type.values()[rs.getInt("seed.type")]);
seed.setId(rs.getLong("seed.id"));
keystore.setSeed(seed);
}
return keystore;
}
}
@@ -0,0 +1,22 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.policy.Policy;
import org.jdbi.v3.sqlobject.config.RegisterRowMapper;
import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
public interface PolicyDao {
@SqlQuery("select * from policy where id = ?")
@RegisterRowMapper(PolicyMapper.class)
Policy getPolicy(long id);
@SqlUpdate("insert into policy (name, script) values (?, ?)")
@GetGeneratedKeys("id")
long insert(String name, String script);
default void addPolicy(Policy policy) {
long id = insert(policy.getName(), policy.getMiniscript().getScript());
policy.setId(id);
}
}
@@ -0,0 +1,18 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.policy.Miniscript;
import com.sparrowwallet.drongo.policy.Policy;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PolicyMapper implements RowMapper<Policy> {
@Override
public Policy map(ResultSet rs, StatementContext ctx) throws SQLException {
Policy policy = new Policy(rs.getString("name"), new Miniscript(rs.getString("script")));
policy.setId(rs.getLong("id"));
return policy;
}
}
@@ -0,0 +1,106 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.protocol.Sha256Hash;
import com.sparrowwallet.drongo.wallet.BlockTransaction;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletNode;
import org.jdbi.v3.sqlobject.CreateSqlObject;
import org.jdbi.v3.sqlobject.config.RegisterRowMapper;
import org.jdbi.v3.sqlobject.customizer.Bind;
import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public interface WalletDao {
@CreateSqlObject
PolicyDao createPolicyDao();
@CreateSqlObject
KeystoreDao createKeystoreDao();
@CreateSqlObject
WalletNodeDao createWalletNodeDao();
@CreateSqlObject
BlockTransactionDao createBlockTransactionDao();
@SqlQuery("select wallet.id, wallet.name, wallet.network, wallet.policyType, wallet.scriptType, wallet.storedBlockHeight, wallet.gapLimit, wallet.birthDate, policy.id, policy.name, policy.script from wallet left join policy on wallet.defaultPolicy = policy.id")
@RegisterRowMapper(WalletMapper.class)
List<Wallet> loadAllWallets();
@SqlQuery("select wallet.id, wallet.name, wallet.network, wallet.policyType, wallet.scriptType, wallet.storedBlockHeight, wallet.gapLimit, wallet.birthDate, policy.id, policy.name, policy.script from wallet left join policy on wallet.defaultPolicy = policy.id where wallet.id = 1")
@RegisterRowMapper(WalletMapper.class)
Wallet loadMainWallet();
@SqlQuery("select wallet.id, wallet.name, wallet.network, wallet.policyType, wallet.scriptType, wallet.storedBlockHeight, wallet.gapLimit, wallet.birthDate, policy.id, policy.name, policy.script from wallet left join policy on wallet.defaultPolicy = policy.id where wallet.id != 1")
@RegisterRowMapper(WalletMapper.class)
List<Wallet> loadChildWallets();
@SqlUpdate("insert into wallet (name, network, policyType, scriptType, storedBlockHeight, gapLimit, birthDate, defaultPolicy) values (?, ?, ?, ?, ?, ?, ?, ?)")
@GetGeneratedKeys("id")
long insert(String name, int network, int policyType, int scriptType, Integer storedBlockHeight, Integer gapLimit, Date birthDate, long defaultPolicy);
@SqlUpdate("update wallet set storedBlockHeight = :blockHeight where id = :id")
void updateStoredBlockHeight(@Bind("id") long id, @Bind("blockHeight") Integer blockHeight);
@SqlUpdate("set schema ?")
int setSchema(String schema);
default Wallet getMainWallet(String schema) {
try {
setSchema(schema);
Wallet mainWallet = loadMainWallet();
if(mainWallet != null) {
loadWallet(mainWallet);
}
return mainWallet;
} finally {
setSchema(DbPersistence.DEFAULT_SCHEMA);
}
}
default List<Wallet> getChildWallets(String schema) {
try {
List<Wallet> childWallets = loadChildWallets();
for(Wallet childWallet : childWallets) {
loadWallet(childWallet);
}
return childWallets;
} finally {
setSchema(DbPersistence.DEFAULT_SCHEMA);
}
}
default void loadWallet(Wallet wallet) {
wallet.getKeystores().addAll(createKeystoreDao().getForWalletId(wallet.getId()));
List<WalletNode> walletNodes = createWalletNodeDao().getForWalletId(wallet.getId());
wallet.getPurposeNodes().addAll(walletNodes.stream().filter(walletNode -> walletNode.getDerivation().size() == 1).collect(Collectors.toList()));
Map<Sha256Hash, BlockTransaction> blockTransactions = createBlockTransactionDao().getForWalletId(wallet.getId()); //.stream().collect(Collectors.toMap(BlockTransaction::getHash, Function.identity(), (existing, replacement) -> existing, LinkedHashMap::new));
wallet.updateTransactions(blockTransactions);
}
default void addWallet(String schema, Wallet wallet) {
try {
setSchema(schema);
createPolicyDao().addPolicy(wallet.getDefaultPolicy());
long id = insert(wallet.getName(), wallet.getNetwork().ordinal(), wallet.getPolicyType().ordinal(), wallet.getScriptType().ordinal(), wallet.getStoredBlockHeight(), wallet.gapLimit(), wallet.getBirthDate(), wallet.getDefaultPolicy().getId());
wallet.setId(id);
createKeystoreDao().addKeystores(wallet);
createWalletNodeDao().addWalletNodes(wallet);
createBlockTransactionDao().addBlockTransactions(wallet);
} finally {
setSchema(DbPersistence.DEFAULT_SCHEMA);
}
}
}
@@ -0,0 +1,37 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.Network;
import com.sparrowwallet.drongo.policy.Miniscript;
import com.sparrowwallet.drongo.policy.Policy;
import com.sparrowwallet.drongo.policy.PolicyType;
import com.sparrowwallet.drongo.protocol.ScriptType;
import com.sparrowwallet.drongo.wallet.Wallet;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
import java.sql.ResultSet;
import java.sql.SQLException;
public class WalletMapper implements RowMapper<Wallet> {
@Override
public Wallet map(ResultSet rs, StatementContext ctx) throws SQLException {
Wallet wallet = new Wallet(rs.getString("wallet.name"));
wallet.setId(rs.getLong("wallet.id"));
wallet.setNetwork(Network.values()[rs.getInt("wallet.network")]);
wallet.setPolicyType(PolicyType.values()[rs.getInt("wallet.policyType")]);
wallet.setScriptType(ScriptType.values()[rs.getInt("wallet.scriptType")]);
Policy policy = new Policy(rs.getString("policy.name"), new Miniscript(rs.getString("policy.script")));
policy.setId(rs.getLong("policy.id"));
wallet.setDefaultPolicy(policy);
int storedBlockHeight = rs.getInt("wallet.storedBlockHeight");
wallet.setStoredBlockHeight(rs.wasNull() ? null : storedBlockHeight);
int gapLimit = rs.getInt("wallet.gapLimit");
wallet.gapLimit(rs.wasNull() ? null : gapLimit);
wallet.setBirthDate(rs.getTimestamp("wallet.birthDate"));
return wallet;
}
}
@@ -0,0 +1,116 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.wallet.BlockTransactionHashIndex;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletNode;
import org.jdbi.v3.sqlobject.config.RegisterRowMapper;
import org.jdbi.v3.sqlobject.customizer.Bind;
import org.jdbi.v3.sqlobject.customizer.BindList;
import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
import org.jdbi.v3.sqlobject.statement.UseRowReducer;
import java.util.Date;
import java.util.List;
public interface WalletNodeDao {
@SqlQuery("select walletNode.id, walletNode.derivationPath, walletNode.label, walletNode.parent, " +
"blockTransactionHashIndex.id, blockTransactionHashIndex.hash, blockTransactionHashIndex.height, blockTransactionHashIndex.date, blockTransactionHashIndex.fee, blockTransactionHashIndex.label, " +
"blockTransactionHashIndex.index, blockTransactionHashIndex.outputValue, blockTransactionHashIndex.status, blockTransactionHashIndex.spentBy, blockTransactionHashIndex.node " +
"from walletNode left join blockTransactionHashIndex on walletNode.id = blockTransactionHashIndex.node where walletNode.wallet = ? order by walletNode.parent asc nulls first, blockTransactionHashIndex.spentBy asc nulls first")
@RegisterRowMapper(WalletNodeMapper.class)
@RegisterRowMapper(BlockTransactionHashIndexMapper.class)
@UseRowReducer(WalletNodeReducer.class)
List<WalletNode> getForWalletId(Long id);
@SqlUpdate("insert into walletNode (derivationPath, label, wallet, parent) values (?, ?, ?, ?)")
@GetGeneratedKeys("id")
long insertWalletNode(String derivationPath, String label, long wallet, Long parent);
@SqlUpdate("insert into blockTransactionHashIndex (hash, height, date, fee, label, index, outputValue, status, spentBy, node) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
@GetGeneratedKeys("id")
long insertBlockTransactionHashIndex(byte[] hash, int height, Date date, Long fee, String label, long index, long value, Integer status, Long spentBy, long node);
@SqlUpdate("update blockTransactionHashIndex set hash = ?, height = ?, date = ?, fee = ?, label = ?, index = ?, outputValue = ?, status = ?, spentBy = ?, node = ? where id = ?")
void updateBlockTransactionHashIndex(byte[] hash, int height, Date date, Long fee, String label, long index, long value, Integer status, Long spentBy, long node, long id);
@SqlUpdate("update walletNode set label = :label where id = :id")
void updateNodeLabel(@Bind("id") long id, @Bind("label") String label);
@SqlUpdate("update blockTransactionHashIndex set label = :label where id = :id")
void updateTxoLabel(@Bind("id") long id, @Bind("label") String label);
@SqlUpdate("update blockTransactionHashIndex set status = :status where id = :id")
void updateTxoStatus(@Bind("id") long id, @Bind("status") Integer status);
@SqlUpdate("delete from blockTransactionHashIndex where blockTransactionHashIndex.node in (select walletNode.id from walletNode where walletNode.wallet = ?)")
void clearHistory(long wallet);
@SqlUpdate("delete from blockTransactionHashIndex where blockTransactionHashIndex.node in (select walletNode.id from walletNode where walletNode.wallet = ?) and blockTransactionHashIndex.spentBy is not null")
void clearSpentHistory(long wallet);
@SqlUpdate("delete from blockTransactionHashIndex where node = :nodeId and id not in (<ids>)")
void deleteUnreferencedNodeTxos(@Bind("nodeId") Long nodeId, @BindList("ids") List<Long> ids);
@SqlUpdate("delete from blockTransactionHashIndex where node = :nodeId and id not in (<ids>) and spentBy is not null")
void deleteUnreferencedNodeSpentTxos(@Bind("nodeId") Long nodeId, @BindList("ids") List<Long> ids);
default void addWalletNodes(Wallet wallet) {
for(WalletNode purposeNode : wallet.getPurposeNodes()) {
long purposeNodeId = insertWalletNode(purposeNode.getDerivationPath(), purposeNode.getLabel(), wallet.getId(), null);
purposeNode.setId(purposeNodeId);
for(WalletNode addressNode : purposeNode.getChildren()) {
long addressNodeId = insertWalletNode(addressNode.getDerivationPath(), addressNode.getLabel(), wallet.getId(), purposeNodeId);
addressNode.setId(addressNodeId);
addTransactionOutputs(addressNode);
}
}
}
default void addTransactionOutputs(WalletNode addressNode) {
for(BlockTransactionHashIndex txo : addressNode.getTransactionOutputs()) {
txo.setId(null);
if(txo.isSpent()) {
txo.getSpentBy().setId(null);
}
addOrUpdate(addressNode, txo);
}
}
default void addOrUpdate(WalletNode addressNode, BlockTransactionHashIndex txo) {
Long spentById = null;
if(txo.isSpent()) {
BlockTransactionHashIndex spentBy = txo.getSpentBy();
if(spentBy.getId() == null) {
spentById = insertBlockTransactionHashIndex(spentBy.getHash().getBytes(), spentBy.getHeight(), spentBy.getDate(), spentBy.getFee(), spentBy.getLabel(), spentBy.getIndex(), spentBy.getValue(),
spentBy.getStatus() == null ? null : spentBy.getStatus().ordinal(), null, addressNode.getId());
spentBy.setId(spentById);
} else {
updateBlockTransactionHashIndex(spentBy.getHash().getBytes(), spentBy.getHeight(), spentBy.getDate(), spentBy.getFee(), spentBy.getLabel(), spentBy.getIndex(), spentBy.getValue(),
spentBy.getStatus() == null ? null : spentBy.getStatus().ordinal(), null, addressNode.getId(), spentBy.getId());
spentById = spentBy.getId();
}
}
if(txo.getId() == null) {
long txoId = insertBlockTransactionHashIndex(txo.getHash().getBytes(), txo.getHeight(), txo.getDate(), txo.getFee(), txo.getLabel(), txo.getIndex(), txo.getValue(),
txo.getStatus() == null ? null : txo.getStatus().ordinal(), spentById, addressNode.getId());
txo.setId(txoId);
} else {
updateBlockTransactionHashIndex(txo.getHash().getBytes(), txo.getHeight(), txo.getDate(), txo.getFee(), txo.getLabel(), txo.getIndex(), txo.getValue(),
txo.getStatus() == null ? null : txo.getStatus().ordinal(), spentById, addressNode.getId(), txo.getId());
}
}
default void deleteNodeTxosNotInList(WalletNode addressNode, List<Long> txoIds) {
deleteUnreferencedNodeSpentTxos(addressNode.getId(), txoIds);
deleteUnreferencedNodeTxos(addressNode.getId(), txoIds);
}
default void clearHistory(Wallet wallet) {
clearSpentHistory(wallet.getId());
clearHistory(wallet.getId());
}
}
@@ -0,0 +1,19 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.wallet.WalletNode;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;
import java.sql.ResultSet;
import java.sql.SQLException;
public class WalletNodeMapper implements RowMapper<WalletNode> {
@Override
public WalletNode map(ResultSet rs, StatementContext ctx) throws SQLException {
WalletNode walletNode = new WalletNode(rs.getString("walletNode.derivationPath"));
walletNode.setId(rs.getLong("walletNode.id"));
walletNode.setLabel(rs.getString("walletNode.label"));
return walletNode;
}
}
@@ -0,0 +1,30 @@
package com.sparrowwallet.sparrow.io.db;
import com.sparrowwallet.drongo.wallet.BlockTransactionHashIndex;
import com.sparrowwallet.drongo.wallet.WalletNode;
import org.jdbi.v3.core.result.LinkedHashMapRowReducer;
import org.jdbi.v3.core.result.RowView;
import java.util.Map;
public class WalletNodeReducer implements LinkedHashMapRowReducer<Long, WalletNode> {
@Override
public void accumulate(Map<Long, WalletNode> map, RowView rowView) {
WalletNode walletNode = map.computeIfAbsent(rowView.getColumn("walletNode.id", Long.class), id -> rowView.getRow(WalletNode.class));
if(rowView.getColumn("walletNode.parent", Long.class) != null) {
WalletNode parentNode = map.get(rowView.getColumn("walletNode.parent", Long.class));
parentNode.getChildren().add(walletNode);
}
if(rowView.getColumn("blockTransactionHashIndex.node", Long.class) != null) {
BlockTransactionHashIndex blockTransactionHashIndex = rowView.getRow(BlockTransactionHashIndex.class);
if(rowView.getColumn("blockTransactionHashIndex.spentBy", Long.class) != null) {
BlockTransactionHashIndex spentBy = walletNode.getTransactionOutputs().stream().filter(ref -> ref.getId().equals(rowView.getColumn("blockTransactionHashIndex.spentBy", Long.class))).findFirst().orElseThrow();
blockTransactionHashIndex.setSpentBy(spentBy);
walletNode.getTransactionOutputs().remove(spentBy);
}
walletNode.getTransactionOutputs().add(blockTransactionHashIndex);
}
}
}
@@ -2,11 +2,13 @@ package com.sparrowwallet.sparrow.keystoreimport;
import com.sparrowwallet.drongo.policy.PolicyType;
import com.sparrowwallet.sparrow.control.FileKeystoreImportPane;
import com.sparrowwallet.sparrow.control.TitledDescriptionPane;
import com.sparrowwallet.sparrow.io.*;
import javafx.fxml.FXML;
import javafx.scene.control.Accordion;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class HwAirgappedController extends KeystoreImportDetailController {
@@ -16,14 +18,16 @@ public class HwAirgappedController extends KeystoreImportDetailController {
public void initializeView() {
List<KeystoreFileImport> importers = Collections.emptyList();
if(getMasterController().getWallet().getPolicyType().equals(PolicyType.SINGLE)) {
importers = List.of(new ColdcardSinglesig(), new CoboVaultSinglesig(), new PassportSinglesig(), new SpecterDIY());
importers = List.of(new ColdcardSinglesig(), new CoboVaultSinglesig(), new KeystoneSinglesig(), new PassportSinglesig(), new SeedSigner(), new SpecterDIY());
} else if(getMasterController().getWallet().getPolicyType().equals(PolicyType.MULTI)) {
importers = List.of(new ColdcardMultisig(), new CoboVaultMultisig(), new PassportMultisig(), new SpecterDIY());
importers = List.of(new ColdcardMultisig(), new CoboVaultMultisig(), new KeystoneMultisig(), new PassportMultisig(), new SeedSigner(), new SpecterDIY());
}
for(KeystoreImport importer : importers) {
FileKeystoreImportPane importPane = new FileKeystoreImportPane(getMasterController().getWallet(), (KeystoreFileImport)importer);;
importAccordion.getPanes().add(importPane);
}
importAccordion.getPanes().sort(Comparator.comparing(o -> ((TitledDescriptionPane) o).getTitle()));
}
}
@@ -2,7 +2,6 @@ package com.sparrowwallet.sparrow.keystoreimport;
import com.sparrowwallet.sparrow.control.DevicePane;
import com.sparrowwallet.sparrow.io.Device;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.Accordion;
@@ -14,7 +13,7 @@ public class HwUsbDevicesController extends KeystoreImportDetailController {
public void initializeView(List<Device> devices) {
for(Device device : devices) {
DevicePane devicePane = new DevicePane(getMasterController().getWallet(), device);
DevicePane devicePane = new DevicePane(getMasterController().getWallet(), device, devices.size() == 1);
deviceAccordion.getPanes().add(devicePane);
}
}
@@ -14,14 +14,15 @@ import com.sparrowwallet.sparrow.event.WalletHistoryStatusEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
public class BatchedElectrumServerRpc implements ElectrumServerRpc {
private static final Logger log = LoggerFactory.getLogger(BatchedElectrumServerRpc.class);
private static final int MAX_RETRIES = 3;
private static final int RETRY_DELAY = 0;
private static final int MAX_RETRIES = 5;
private static final int RETRY_DELAY = 1;
private final AtomicLong idCounter = new AtomicLong();
@@ -81,7 +82,7 @@ public class BatchedElectrumServerRpc implements ElectrumServerRpc {
}
try {
return new RetryLogic<Map<String, ScriptHashTx[]>>(MAX_RETRIES, RETRY_DELAY, IllegalStateException.class).getResult(batchRequest::execute);
return new RetryLogic<Map<String, ScriptHashTx[]>>(MAX_RETRIES, RETRY_DELAY, List.of(IllegalStateException.class, IllegalArgumentException.class)).getResult(batchRequest::execute);
} catch (JsonRpcBatchException e) {
if(failOnError) {
throw new ElectrumServerRpcException("Failed to retrieve transaction history for paths: " + getScriptHashesAbbreviation((Collection<String>)e.getErrors().keySet()), e);
@@ -109,7 +110,7 @@ public class BatchedElectrumServerRpc implements ElectrumServerRpc {
}
try {
return new RetryLogic<Map<String, ScriptHashTx[]>>(MAX_RETRIES, RETRY_DELAY, IllegalStateException.class).getResult(batchRequest::execute);
return new RetryLogic<Map<String, ScriptHashTx[]>>(MAX_RETRIES, RETRY_DELAY, List.of(IllegalStateException.class, IllegalArgumentException.class)).getResult(batchRequest::execute);
} catch(JsonRpcBatchException e) {
if(failOnError) {
throw new ElectrumServerRpcException("Failed to retrieve mempool transactions for paths: " + getScriptHashesAbbreviation((Collection<String>)e.getErrors().keySet()), e);
@@ -138,7 +139,7 @@ public class BatchedElectrumServerRpc implements ElectrumServerRpc {
}
try {
return new RetryLogic<Map<String, String>>(MAX_RETRIES, RETRY_DELAY, IllegalStateException.class).getResult(batchRequest::execute);
return new RetryLogic<Map<String, String>>(MAX_RETRIES, RETRY_DELAY, List.of(IllegalStateException.class, IllegalArgumentException.class)).getResult(batchRequest::execute);
} catch(JsonRpcBatchException e) {
//Even if we have some successes, failure to subscribe for all script hashes will result in outdated wallet view. Don't proceed.
throw new ElectrumServerRpcException("Failed to subscribe to paths: " + getScriptHashesAbbreviation((Collection<String>)e.getErrors().keySet()), e);
@@ -208,7 +209,7 @@ public class BatchedElectrumServerRpc implements ElectrumServerRpc {
//The server may return an error if the transaction has not yet been broadcasted - this is a valid state so only try once
return new RetryLogic<Map<String, VerboseTransaction>>(1, RETRY_DELAY, IllegalStateException.class).getResult(batchRequest::execute);
} catch(JsonRpcBatchException e) {
log.warn("Some errors retrieving transactions: " + e.getErrors());
log.debug("Some errors retrieving transactions: " + e.getErrors());
return (Map<String, VerboseTransaction>)e.getSuccesses();
} catch(Exception e) {
throw new ElectrumServerRpcException("Failed to retrieve verbose transactions for txids: " + txids, e);
@@ -236,12 +237,14 @@ public class BatchedElectrumServerRpc implements ElectrumServerRpc {
public Map<Long, Long> getFeeRateHistogram(Transport transport) {
try {
JsonRpcClient client = new JsonRpcClient(transport);
Long[][] feesArray = new RetryLogic<Long[][]>(MAX_RETRIES, RETRY_DELAY, IllegalStateException.class).getResult(() ->
client.createRequest().returnAs(Long[][].class).method("mempool.get_fee_histogram").id(idCounter.incrementAndGet()).execute());
BigInteger[][] feesArray = new RetryLogic<BigInteger[][]>(MAX_RETRIES, RETRY_DELAY, IllegalStateException.class).getResult(() ->
client.createRequest().returnAs(BigInteger[][].class).method("mempool.get_fee_histogram").id(idCounter.incrementAndGet()).execute());
Map<Long, Long> feeRateHistogram = new TreeMap<>();
for(Long[] feePair : feesArray) {
feeRateHistogram.put(feePair[0], feePair[1]);
for(BigInteger[] feePair : feesArray) {
if(feePair[0].longValue() > 0) {
feeRateHistogram.put(feePair[0].longValue(), feePair[1].longValue());
}
}
return feeRateHistogram;
@@ -266,7 +269,7 @@ public class BatchedElectrumServerRpc implements ElectrumServerRpc {
try {
JsonRpcClient client = new JsonRpcClient(transport);
return new RetryLogic<String>(MAX_RETRIES, RETRY_DELAY, IllegalStateException.class).getResult(() ->
client.createRequest().returnAs(String.class).method("blockchain.transaction.broadcast").id(idCounter.incrementAndGet()).param("raw_tx", txHex).execute());
client.createRequest().returnAs(String.class).method("blockchain.transaction.broadcast").id(idCounter.incrementAndGet()).params(txHex).execute());
} catch(JsonRpcException e) {
throw new ElectrumServerRpcException(e.getErrorMessage().getMessage(), e);
} catch(Exception e) {
@@ -15,6 +15,7 @@ import java.net.Proxy;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.List;
public enum BroadcastSource {
BLOCKSTREAM_INFO("blockstream.info", "https://blockstream.info", "http://explorerzydxu5ecjrkwceayqybizmpjjznk5izmitf2modhcusuqlid.onion") {
@@ -24,6 +25,11 @@ public enum BroadcastSource {
return postTransactionData(data);
}
@Override
public List<Network> getSupportedNetworks() {
return List.of(Network.MAINNET, Network.TESTNET);
}
protected URL getURL(Proxy proxy) throws MalformedURLException {
if(Network.get() == Network.MAINNET) {
return new URL(getBaseUrl(proxy) + "/api/tx");
@@ -40,6 +46,53 @@ public enum BroadcastSource {
return postTransactionData(data);
}
@Override
public List<Network> getSupportedNetworks() {
return List.of(Network.MAINNET, Network.TESTNET, Network.SIGNET);
}
protected URL getURL(Proxy proxy) throws MalformedURLException {
if(Network.get() == Network.MAINNET) {
return new URL(getBaseUrl(proxy) + "/api/tx");
} else if(Network.get() == Network.TESTNET) {
return new URL(getBaseUrl(proxy) + "/testnet/api/tx");
} else {
throw new IllegalStateException("Cannot broadcast transaction to " + getName() + " on network " + Network.get());
}
}
},
MEMPOOL_EMZY_DE("mempool.emzy.de", "https://mempool.emzy.de", "http://mempool4t6mypeemozyterviq3i5de4kpoua65r3qkn5i3kknu5l2cad.onion") {
public Sha256Hash broadcastTransaction(Transaction transaction) throws BroadcastException {
String data = Utils.bytesToHex(transaction.bitcoinSerialize());
return postTransactionData(data);
}
@Override
public List<Network> getSupportedNetworks() {
return List.of(Network.MAINNET);
}
protected URL getURL(Proxy proxy) throws MalformedURLException {
if(Network.get() == Network.MAINNET) {
return new URL(getBaseUrl(proxy) + "/api/tx");
} else if(Network.get() == Network.TESTNET) {
return new URL(getBaseUrl(proxy) + "/testnet/api/tx");
} else {
throw new IllegalStateException("Cannot broadcast transaction to " + getName() + " on network " + Network.get());
}
}
},
MEMPOOL_BISQ_SERVICES("mempool.bisq.services", "https://mempool.bisq.services", "http://mempoolcutehjtynu4k4rd746acmssvj2vz4jbz4setb72clbpx2dfqd.onion") {
public Sha256Hash broadcastTransaction(Transaction transaction) throws BroadcastException {
String data = Utils.bytesToHex(transaction.bitcoinSerialize());
return postTransactionData(data);
}
@Override
public List<Network> getSupportedNetworks() {
return List.of(Network.MAINNET);
}
protected URL getURL(Proxy proxy) throws MalformedURLException {
if(Network.get() == Network.MAINNET) {
return new URL(getBaseUrl(proxy) + "/api/tx");
@@ -82,6 +135,8 @@ public enum BroadcastSource {
public abstract Sha256Hash broadcastTransaction(Transaction transaction) throws BroadcastException;
public abstract List<Network> getSupportedNetworks();
protected abstract URL getURL(Proxy proxy) throws MalformedURLException;
public Sha256Hash postTransactionData(String data) throws BroadcastException {
@@ -37,11 +37,15 @@ public class ElectrumServer {
private static final String[] SUPPORTED_VERSIONS = new String[]{"1.3", "1.4.2"};
private static final Version ELECTRS_MIN_BATCHING_VERSION = new Version("0.9.0");
private static final int MINIMUM_BROADCASTS = 2;
public static final BlockTransaction UNFETCHABLE_BLOCK_TRANSACTION = new BlockTransaction(Sha256Hash.ZERO_HASH, 0, null, null, null);
private static Transport transport;
private static final Map<String, Set<String>> subscribedScriptHashes = Collections.synchronizedMap(new HashMap<>());
private static final Map<String, List<String>> subscribedScriptHashes = Collections.synchronizedMap(new HashMap<>());
private static String previousServerAddress;
@@ -818,26 +822,45 @@ public class ElectrumServer {
return Utils.bytesToHex(reversed);
}
public static Map<String, Set<String>> getSubscribedScriptHashes() {
public static Map<String, List<String>> getSubscribedScriptHashes() {
return subscribedScriptHashes;
}
public static String getSubscribedScriptHashStatus(String scriptHash) {
Set<String> existingStatuses = subscribedScriptHashes.get(scriptHash);
if(existingStatuses != null) {
return Iterables.getLast(existingStatuses);
List<String> existingStatuses = subscribedScriptHashes.get(scriptHash);
if(existingStatuses != null && !existingStatuses.isEmpty()) {
return existingStatuses.get(existingStatuses.size() - 1);
}
return null;
}
public static void updateSubscribedScriptHashStatus(String scriptHash, String status) {
Set<String> existingStatuses = subscribedScriptHashes.computeIfAbsent(scriptHash, k -> new LinkedHashSet<>());
List<String> existingStatuses = subscribedScriptHashes.computeIfAbsent(scriptHash, k -> new ArrayList<>());
existingStatuses.add(status);
}
public static boolean supportsBatching(List<String> serverVersion) {
return serverVersion.size() > 0 && serverVersion.get(0).toLowerCase().contains("electrumx");
if(serverVersion.size() > 0) {
String server = serverVersion.get(0).toLowerCase();
if(server.contains("electrumx")) {
return true;
}
if(server.startsWith("electrs/")) {
String electrsVersion = server.substring("electrs/".length());
try {
Version version = new Version(electrsVersion);
if(version.compareTo(ELECTRS_MIN_BATCHING_VERSION) >= 0) {
return true;
}
} catch(Exception e) {
//ignore
}
}
}
return false;
}
public static class ServerVersionService extends Service<List<String>> {
@@ -1124,11 +1147,22 @@ public class ElectrumServer {
electrumServer.calculateNodeHistory(wallet, nodeTransactionMap);
//Add all of the script hashes we have now fetched the history for so we don't need to fetch again until the script hash status changes
for(WalletNode node : nodeTransactionMap.keySet()) {
for(WalletNode node : (nodes == null ? nodeTransactionMap.keySet() : nodes)) {
String scriptHash = getScriptHash(wallet, node);
retrievedScriptHashes.put(scriptHash, getSubscribedScriptHashStatus(scriptHash));
}
//Clear transaction outputs for nodes that have no history - this is useful when a transaction is replaced in the mempool
if(nodes != null) {
for(WalletNode node : nodes) {
String scriptHash = getScriptHash(wallet, node);
if(retrievedScriptHashes.get(scriptHash) == null && !node.getTransactionOutputs().isEmpty()) {
log.debug("Clearing transaction history for " + node);
node.getTransactionOutputs().clear();
}
}
}
return true;
}
@@ -1294,16 +1328,24 @@ public class ElectrumServer {
return new Task<>() {
protected Sha256Hash call() throws ServerException {
//If Tor proxy is configured, try all external broadcast sources in random order before falling back to connected Electrum server
if(AppServices.getProxy() != null) {
List<BroadcastSource> broadcastSources = new ArrayList<>(Arrays.asList(BroadcastSource.values()));
while(!broadcastSources.isEmpty()) {
if(AppServices.isUsingProxy()) {
List<BroadcastSource> broadcastSources = Arrays.stream(BroadcastSource.values()).filter(src -> src.getSupportedNetworks().contains(Network.get())).collect(Collectors.toList());
Sha256Hash txid = null;
for(int i = 1; !broadcastSources.isEmpty(); i++) {
try {
BroadcastSource broadcastSource = broadcastSources.remove(new Random().nextInt(broadcastSources.size()));
return broadcastSource.broadcastTransaction(transaction);
txid = broadcastSource.broadcastTransaction(transaction);
if(Network.get() != Network.MAINNET || i >= MINIMUM_BROADCASTS || broadcastSources.isEmpty()) {
return txid;
}
} catch(BroadcastSource.BroadcastException e) {
//ignore, already logged
}
}
if(txid != null) {
return txid;
}
}
ElectrumServer electrumServer = new ElectrumServer();
@@ -25,7 +25,7 @@ public enum FeeRatesSource {
MEMPOOL_SPACE("mempool.space") {
@Override
public Map<Integer, Double> getBlockTargetFeeRates(Map<Integer, Double> defaultblockTargetFeeRates) {
String url = "https://mempool.space/api/v1/fees/recommended";
String url = AppServices.isUsingProxy() ? "http://mempoolhqx4isw62xs7abwphsq7ldayuidyx2v2oethdhhj6mlo2r6ad.onion/api/v1/fees/recommended" : "https://mempool.space/api/v1/fees/recommended";
return getThreeTierFeeRates(defaultblockTargetFeeRates, url);
}
},
@@ -1,6 +1,7 @@
package com.sparrowwallet.sparrow.net;
import java.util.List;
import java.util.Random;
/**
* Generic retry logic. Delegate must throw the specified exception type to trigger the retry logic.
@@ -21,7 +22,7 @@ public class RetryLogic<T> {
public RetryLogic(int maxAttempts, int retryWaitSeconds, @SuppressWarnings("rawtypes") List<Class> retryExceptionTypes) {
this.maxAttempts = maxAttempts;
this.retryWaitSeconds = retryWaitSeconds;
this.retryWaitSeconds = Math.max(retryWaitSeconds, 1);
this.retryExceptionTypes = retryExceptionTypes;
}
@@ -37,7 +38,8 @@ public class RetryLogic<T> {
throw new ServerException("Retries exhausted", e);
} else {
try {
Thread.sleep((1000 * retryWaitSeconds));
//Sleep with a +/- 2 seconds random wait time to avoid simultaneous retries
Thread.sleep((1000L * (retryWaitSeconds - 1)) + new Random().nextInt(2000));
} catch(InterruptedException ie) {
//ignore
}
@@ -13,6 +13,7 @@ import com.sparrowwallet.sparrow.event.WalletHistoryStatusEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
@@ -257,12 +258,14 @@ public class SimpleElectrumServerRpc implements ElectrumServerRpc {
public Map<Long, Long> getFeeRateHistogram(Transport transport) {
try {
JsonRpcClient client = new JsonRpcClient(transport);
Long[][] feesArray = new RetryLogic<Long[][]>(MAX_RETRIES, RETRY_DELAY, IllegalStateException.class).getResult(() ->
client.createRequest().returnAs(Long[][].class).method("mempool.get_fee_histogram").id(idCounter.incrementAndGet()).execute());
BigInteger[][] feesArray = new RetryLogic<BigInteger[][]>(MAX_RETRIES, RETRY_DELAY, IllegalStateException.class).getResult(() ->
client.createRequest().returnAs(BigInteger[][].class).method("mempool.get_fee_histogram").id(idCounter.incrementAndGet()).execute());
Map<Long, Long> feeRateHistogram = new TreeMap<>();
for(Long[] feePair : feesArray) {
feeRateHistogram.put(feePair[0], feePair[1]);
for(BigInteger[] feePair : feesArray) {
if(feePair[0].longValue() > 0) {
feeRateHistogram.put(feePair[0].longValue(), feePair[1].longValue());
}
}
return feeRateHistogram;
@@ -12,7 +12,7 @@ import javafx.application.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import java.util.List;
@JsonRpcService
public class SubscriptionService {
@@ -25,16 +25,11 @@ public class SubscriptionService {
@JsonRpcMethod("blockchain.scripthash.subscribe")
public void scriptHashStatusUpdated(@JsonRpcParam("scripthash") final String scriptHash, @JsonRpcOptional @JsonRpcParam("status") final String status) {
if(status == null) {
//Mempool transaction was replaced returning change/consolidation script hash status to null, ignore this update
return;
}
Set<String> existingStatuses = ElectrumServer.getSubscribedScriptHashes().get(scriptHash);
List<String> existingStatuses = ElectrumServer.getSubscribedScriptHashes().get(scriptHash);
if(existingStatuses == null) {
log.debug("Received script hash status update for unsubscribed script hash: " + scriptHash);
ElectrumServer.updateSubscribedScriptHashStatus(scriptHash, status);
} else if(existingStatuses.contains(status)) {
} else if(status != null && existingStatuses.contains(status)) {
log.debug("Received script hash status update, but status has not changed");
return;
} else {
@@ -2,6 +2,7 @@ package com.sparrowwallet.sparrow.net;
import com.github.arteam.simplejsonrpc.client.Transport;
import com.github.arteam.simplejsonrpc.server.JsonRpcServer;
import com.google.common.base.Splitter;
import com.google.common.net.HostAndPort;
import com.google.gson.Gson;
import com.sparrowwallet.sparrow.io.Config;
@@ -24,7 +25,8 @@ public class TcpTransport implements Transport, Closeable {
private static final Logger log = LoggerFactory.getLogger(TcpTransport.class);
public static final int DEFAULT_PORT = 50001;
private static final int[] READ_TIMEOUT_SECS = {3, 8, 16, 34};
private static final int[] BASE_READ_TIMEOUT_SECS = {3, 8, 16, 34};
public static final long PER_REQUEST_READ_TIMEOUT_MILLIS = 50;
public static final int SOCKET_READ_TIMEOUT_MILLIS = 5000;
protected final HostAndPort server;
@@ -42,6 +44,7 @@ public class TcpTransport implements Transport, Closeable {
private volatile boolean reading = true;
private boolean firstRead = true;
private int readTimeoutIndex;
private int requestIdCount = 1;
private final JsonRpcServer jsonRpcServer = new JsonRpcServer();
private final SubscriptionService subscriptionService = new SubscriptionService();
@@ -66,6 +69,8 @@ public class TcpTransport implements Transport, Closeable {
Rpc recvRpc;
String recv;
//Count number of requests in batched query to increase read timeout appropriately
requestIdCount = Splitter.on("\"id\"").splitToList(request).size() - 1;
writeRequest(request);
do {
recv = readResponse();
@@ -86,16 +91,16 @@ public class TcpTransport implements Transport, Closeable {
private String readResponse() throws IOException {
try {
if(!readLock.tryLock(READ_TIMEOUT_SECS[readTimeoutIndex], TimeUnit.SECONDS)) {
readTimeoutIndex = Math.min(readTimeoutIndex + 1, READ_TIMEOUT_SECS.length - 1);
log.debug("No response from server, setting read timeout to " + READ_TIMEOUT_SECS[readTimeoutIndex] + " secs");
if(!readLock.tryLock((BASE_READ_TIMEOUT_SECS[readTimeoutIndex] * 1000) + (requestIdCount * PER_REQUEST_READ_TIMEOUT_MILLIS), TimeUnit.MILLISECONDS)) {
readTimeoutIndex = Math.min(readTimeoutIndex + 1, BASE_READ_TIMEOUT_SECS.length - 1);
log.info("No response from server, setting read timeout to " + BASE_READ_TIMEOUT_SECS[readTimeoutIndex] + " secs");
throw new IOException("No response from server");
}
} catch(InterruptedException e) {
throw new IOException("Read thread interrupted");
}
if(readTimeoutIndex == READ_TIMEOUT_SECS.length - 1) {
if(readTimeoutIndex == BASE_READ_TIMEOUT_SECS.length - 1) {
readTimeoutIndex--;
}
@@ -0,0 +1,54 @@
package com.sparrowwallet.sparrow.net;
public class Version implements Comparable<Version> {
private final String version;
public final String get() {
return this.version;
}
public Version(String version) {
if(version == null) {
throw new IllegalArgumentException("Version can not be null");
}
if(!version.matches("[0-9]+(\\.[0-9]+)*")) {
throw new IllegalArgumentException("Invalid version format");
}
this.version = version;
}
@Override
public int compareTo(Version that) {
if(that == null) {
return 1;
}
String[] thisParts = this.get().split("\\.");
String[] thatParts = that.get().split("\\.");
int length = Math.max(thisParts.length, thatParts.length);
for(int i = 0; i < length; i++) {
int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0;
int thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0;
if(thisPart < thatPart) {
return -1;
}
if(thisPart > thatPart) {
return 1;
}
}
return 0;
}
@Override
public boolean equals(Object that) {
if(this == that) {
return true;
}
if(that == null) {
return false;
}
if(this.getClass() != that.getClass()) {
return false;
}
return this.compareTo((Version) that) == 0;
}
}
@@ -100,56 +100,4 @@ public class VersionCheckService extends ScheduledService<VersionUpdatedEvent> {
public Map<String, String> signatures;
}
public static class Version implements Comparable<Version> {
private final String version;
public final String get() {
return this.version;
}
public Version(String version) {
if(version == null) {
throw new IllegalArgumentException("Version can not be null");
}
if(!version.matches("[0-9]+(\\.[0-9]+)*")) {
throw new IllegalArgumentException("Invalid version format");
}
this.version = version;
}
@Override
public int compareTo(Version that) {
if(that == null) {
return 1;
}
String[] thisParts = this.get().split("\\.");
String[] thatParts = that.get().split("\\.");
int length = Math.max(thisParts.length, thatParts.length);
for(int i = 0; i < length; i++) {
int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0;
int thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0;
if(thisPart < thatPart) {
return -1;
}
if(thisPart > thatPart) {
return 1;
}
}
return 0;
}
@Override
public boolean equals(Object that) {
if(this == that) {
return true;
}
if(that == null) {
return false;
}
if(this.getClass() != that.getClass()) {
return false;
}
return this.compareTo((Version)that) == 0;
}
}
}
@@ -580,6 +580,8 @@ public class ServerPreferencesController extends PreferencesDetailController {
}
private void setupValidation() {
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(publicProxyHost, Validator.combine(
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Proxy host required", publicUseProxy.isSelected() && newValue.isEmpty()),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Invalid host name", getHost(newValue) == null)
@@ -629,8 +631,6 @@ public class ServerPreferencesController extends PreferencesDetailController {
validationSupport.registerValidator(electrumCertificate, Validator.combine(
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Invalid certificate file", newValue != null && !newValue.isEmpty() && getCertificate(newValue) == null)
));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
}
@NotNull
@@ -709,7 +709,7 @@ public class HeadersController extends TransactionFormController implements Init
}
Wallet copy = headersForm.getSigningWallet().copy();
File file = headersForm.getAvailableWallets().get(headersForm.getSigningWallet()).getWalletFile();
String walletId = headersForm.getAvailableWallets().get(headersForm.getSigningWallet()).getWalletId(headersForm.getSigningWallet());
if(copy.isEncrypted()) {
WalletPasswordDialog dlg = new WalletPasswordDialog(copy.getName(), WalletPasswordDialog.PasswordRequirement.LOAD);
@@ -717,15 +717,15 @@ public class HeadersController extends TransactionFormController implements Init
if(password.isPresent()) {
Storage.DecryptWalletService decryptWalletService = new Storage.DecryptWalletService(copy, password.get());
decryptWalletService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(file, TimedEvent.Action.END, "Done"));
EventManager.get().post(new StorageEvent(walletId, TimedEvent.Action.END, "Done"));
Wallet decryptedWallet = decryptWalletService.getValue();
signUnencryptedKeystores(decryptedWallet);
});
decryptWalletService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(file, TimedEvent.Action.END, "Failed"));
EventManager.get().post(new StorageEvent(walletId, TimedEvent.Action.END, "Failed"));
AppServices.showErrorDialog("Incorrect Password", decryptWalletService.getException().getMessage());
});
EventManager.get().post(new StorageEvent(file, TimedEvent.Action.START, "Decrypting wallet..."));
EventManager.get().post(new StorageEvent(walletId, TimedEvent.Action.START, "Decrypting wallet..."));
decryptWalletService.start();
}
} else {
@@ -26,8 +26,10 @@ public class HashIndexEntry extends Entry implements Comparable<HashIndexEntry>
this.keyPurpose = keyPurpose;
labelProperty().addListener((observable, oldValue, newValue) -> {
hashIndex.setLabel(newValue);
EventManager.get().post(new WalletEntryLabelsChangedEvent(wallet, this));
if(!Objects.equals(hashIndex.getLabel(), newValue)) {
hashIndex.setLabel(newValue);
EventManager.get().post(new WalletEntryLabelsChangedEvent(wallet, this));
}
});
}
@@ -219,6 +219,8 @@ public class KeystoreController extends WalletFormController implements Initiali
}
private void setupValidation() {
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(label, Validator.combine(
Validator.createEmptyValidator("Label is required"),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Label is not unique", walletForm.getWallet().getKeystores().stream().filter(k -> k != keystore).map(Keystore::getLabel).collect(Collectors.toList()).contains(newValue)),
@@ -240,8 +242,6 @@ public class KeystoreController extends WalletFormController implements Initiali
Validator.createEmptyValidator("Master fingerprint is required"),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Master fingerprint is invalid", (newValue == null || newValue.length() != 8 || !Utils.isHex(newValue)))
));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
}
private void updateType() {
@@ -346,15 +346,15 @@ public class KeystoreController extends WalletFormController implements Initiali
if(password.isPresent()) {
Storage.DecryptWalletService decryptWalletService = new Storage.DecryptWalletService(copy, password.get());
decryptWalletService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(getWalletForm().getWalletFile(), TimedEvent.Action.END, "Done"));
EventManager.get().post(new StorageEvent(getWalletForm().getWalletId(), TimedEvent.Action.END, "Done"));
Wallet decryptedWallet = decryptWalletService.getValue();
showPrivate(decryptedWallet.getKeystores().get(keystoreIndex));
});
decryptWalletService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(getWalletForm().getWalletFile(), TimedEvent.Action.END, "Failed"));
EventManager.get().post(new StorageEvent(getWalletForm().getWalletId(), TimedEvent.Action.END, "Failed"));
AppServices.showErrorDialog("Incorrect Password", decryptWalletService.getException().getMessage());
});
EventManager.get().post(new StorageEvent(getWalletForm().getWalletFile(), TimedEvent.Action.START, "Decrypting wallet..."));
EventManager.get().post(new StorageEvent(getWalletForm().getWalletId(), TimedEvent.Action.START, "Decrypting wallet..."));
decryptWalletService.start();
}
} else {
@@ -2,14 +2,14 @@ package com.sparrowwallet.sparrow.wallet;
import com.sparrowwallet.drongo.address.Address;
import com.sparrowwallet.drongo.protocol.Script;
import com.sparrowwallet.drongo.wallet.BlockTransactionHashIndex;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletNode;
import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.event.WalletEntryLabelsChangedEvent;
import com.sparrowwallet.sparrow.io.Config;
import java.util.List;
import java.util.Objects;
import java.util.*;
import java.util.stream.Collectors;
public class NodeEntry extends Entry implements Comparable<NodeEntry> {
@@ -20,8 +20,10 @@ public class NodeEntry extends Entry implements Comparable<NodeEntry> {
this.node = node;
labelProperty().addListener((observable, oldValue, newValue) -> {
node.setLabel(newValue);
EventManager.get().post(new WalletEntryLabelsChangedEvent(wallet, this));
if(!Objects.equals(node.getLabel(), newValue)) {
node.setLabel(newValue);
EventManager.get().post(new WalletEntryLabelsChangedEvent(wallet, this));
}
});
}
@@ -78,4 +80,45 @@ public class NodeEntry extends Entry implements Comparable<NodeEntry> {
public int compareTo(NodeEntry other) {
return node.compareTo(other.node);
}
public Set<Entry> copyLabels(WalletNode pastNode) {
if(pastNode == null) {
return Collections.emptySet();
}
Set<Entry> changedEntries = new LinkedHashSet<>();
if(node.getLabel() == null && pastNode.getLabel() != null) {
node.setLabel(pastNode.getLabel());
labelProperty().set(pastNode.getLabel());
changedEntries.add(this);
}
for(Entry childEntry : getChildren()) {
if(childEntry instanceof HashIndexEntry) {
HashIndexEntry hashIndexEntry = (HashIndexEntry)childEntry;
BlockTransactionHashIndex txo = hashIndexEntry.getHashIndex();
Optional<BlockTransactionHashIndex> optPastTxo = pastNode.getTransactionOutputs().stream().filter(pastTxo -> pastTxo.equals(txo)).findFirst();
if(optPastTxo.isPresent()) {
BlockTransactionHashIndex pastTxo = optPastTxo.get();
if(txo.getLabel() == null && pastTxo.getLabel() != null) {
txo.setLabel(pastTxo.getLabel());
changedEntries.add(childEntry);
}
if(txo.isSpent() && pastTxo.isSpent() && txo.getSpentBy().getLabel() == null && pastTxo.getSpentBy().getLabel() != null) {
txo.getSpentBy().setLabel(pastTxo.getSpentBy().getLabel());
changedEntries.add(childEntry);
}
}
}
if(childEntry instanceof NodeEntry) {
NodeEntry childNodeEntry = (NodeEntry)childEntry;
Optional<WalletNode> optPastChildNodeEntry = pastNode.getChildren().stream().filter(childNodeEntry.node::equals).findFirst();
optPastChildNodeEntry.ifPresent(pastChildNode -> changedEntries.addAll(childNodeEntry.copyLabels(pastChildNode)));
}
}
return changedEntries;
}
}
@@ -278,7 +278,9 @@ public class PaymentController extends WalletFormController implements Initializ
public void setPayment(Payment payment) {
if(getRecipientValueSats() == null || payment.getAmount() != getRecipientValueSats()) {
address.setText(payment.getAddress().toString());
if(payment.getAddress() != null) {
address.setText(payment.getAddress().toString());
}
if(payment.getLabel() != null && !label.getText().equals(payment.getLabel())) {
label.setText(payment.getLabel());
}
@@ -92,7 +92,7 @@ public class ReceiveController extends WalletFormController implements Initializ
}
});
Platform.runLater(this::refreshAddress);
refreshAddress();
}
public void setNodeEntry(NodeEntry nodeEntry) {
@@ -255,6 +255,9 @@ public class ReceiveController extends WalletFormController implements Initializ
messageSignDialog.setElectrumSignatureFormat(true);
Stage stage = (Stage)messageSignDialog.getDialogPane().getScene().getWindow();
stage.setAlwaysOnTop(true);
messageSignDialog.setOnShown(event -> {
stage.setAlwaysOnTop(false);
});
Optional<ButtonBar.ButtonData> buttonData = messageSignDialog.showAndWait();
if(buttonData.isPresent() && buttonData.get() == ButtonBar.ButtonData.OK_DONE) {
Address address = getWalletForm().getWallet().getAddress(currentEntry.getNode());
@@ -401,13 +401,13 @@ public class SendController extends WalletFormController implements Initializabl
private void addValidation() {
validationSupport = new ValidationSupport();
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(fee, Validator.combine(
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Insufficient Inputs", userFeeSet.get() && insufficientInputsProperty.get()),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Insufficient Fee", getFeeValueSats() != null && getFeeValueSats() == 0),
(Control c, String newValue) -> ValidationResult.fromErrorIf( c, "Insufficient Fee Rate", isInsufficientFeeRate())
));
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.setErrorDecorationEnabled(false);
}
@@ -1063,6 +1063,9 @@ public class SendController extends WalletFormController implements Initializabl
if(event.getPayments() != null) {
clear(null);
setPayments(event.getPayments());
} else if(paymentTabs.getTabs().size() == 1) {
Payment payment = new Payment(null, null, event.getUtxos().stream().mapToLong(BlockTransactionHashIndex::getValue).sum(), true);
setPayments(List.of(payment));
}
if(event.getFee() != null) {
@@ -17,6 +17,7 @@ import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.control.*;
import com.sparrowwallet.sparrow.event.*;
import com.sparrowwallet.sparrow.io.Storage;
import com.sparrowwallet.sparrow.io.StorageException;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
@@ -399,7 +400,16 @@ public class SettingsController extends WalletFormController implements Initiali
Optional<Wallet> optWallet = AppServices.get().getOpenWallets().entrySet().stream().filter(entry -> walletForm.getWalletFile().equals(entry.getValue().getWalletFile())).map(Map.Entry::getKey).findFirst();
if(optWallet.isPresent()) {
WalletExportDialog dlg = new WalletExportDialog(optWallet.get());
Wallet wallet = optWallet.get();
if(!walletForm.getWallet().getName().equals(wallet.getName())) {
wallet = wallet.getChildWallet(walletForm.getWallet().getName());
}
if(wallet == null) {
throw new IllegalStateException("Cannot find child wallet " + walletForm.getWallet().getName() + " to export");
}
WalletExportDialog dlg = new WalletExportDialog(wallet);
dlg.showAndWait();
} else {
AppServices.showErrorDialog("Cannot export wallet", "Wallet cannot be exported, please save it first.");
@@ -442,7 +452,7 @@ public class SettingsController extends WalletFormController implements Initiali
@Subscribe
public void walletSettingsChanged(WalletSettingsChangedEvent event) {
if(event.getWalletFile().equals(walletForm.getWalletFile())) {
if(event.getWalletId().equals(walletForm.getWalletId())) {
export.setDisable(!event.getWallet().isValid());
scanDescriptorQR.setVisible(!event.getWallet().isValid());
}
@@ -450,16 +460,20 @@ public class SettingsController extends WalletFormController implements Initiali
@Subscribe
public void walletAddressesChanged(WalletAddressesChangedEvent event) {
updateBirthDate(event.getWalletFile(), event.getWallet());
if(event.getWalletId().equals(walletForm.getWalletId())) {
updateBirthDate(event.getWallet());
}
}
@Subscribe
public void walletHistoryChanged(WalletHistoryChangedEvent event) {
updateBirthDate(event.getWalletFile(), event.getWallet());
if(event.getWalletId().equals(walletForm.getWalletId())) {
updateBirthDate(event.getWallet());
}
}
private void updateBirthDate(File walletFile, Wallet wallet) {
if(walletFile.equals(walletForm.getWalletFile()) && !Objects.equals(wallet.getBirthDate(), walletForm.getWallet().getBirthDate())) {
private void updateBirthDate(Wallet wallet) {
if(!Objects.equals(wallet.getBirthDate(), walletForm.getWallet().getBirthDate())) {
walletForm.getWallet().setBirthDate(wallet.getBirthDate());
}
}
@@ -509,7 +523,7 @@ public class SettingsController extends WalletFormController implements Initiali
walletForm.getStorage().setEncryptionPubKey(Storage.NO_PASSWORD_KEY);
walletForm.saveAndRefresh();
EventManager.get().post(new RequestOpenWalletsEvent());
} catch (IOException e) {
} catch (IOException | StorageException e) {
log.error("Error saving wallet", e);
AppServices.showErrorDialog("Error saving wallet", e.getMessage());
revert.setDisable(false);
@@ -518,7 +532,7 @@ public class SettingsController extends WalletFormController implements Initiali
} else {
Storage.KeyDerivationService keyDerivationService = new Storage.KeyDerivationService(walletForm.getStorage(), password.get());
keyDerivationService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(walletForm.getWalletFile(), TimedEvent.Action.END, "Done"));
EventManager.get().post(new StorageEvent(walletForm.getWalletId(), TimedEvent.Action.END, "Done"));
ECKey encryptionFullKey = keyDerivationService.getValue();
Key key = null;
@@ -541,6 +555,9 @@ public class SettingsController extends WalletFormController implements Initiali
walletForm.getStorage().setEncryptionPubKey(null);
walletForm.getWallet().decrypt(key);
for(Wallet childWallet : walletForm.getWallet().getChildWallets()) {
childWallet.decrypt(key);
}
saveWallet(true, false);
return;
}
@@ -550,6 +567,9 @@ public class SettingsController extends WalletFormController implements Initiali
}
walletForm.getWallet().encrypt(key);
for(Wallet childWallet : walletForm.getWallet().getChildWallets()) {
childWallet.encrypt(key);
}
walletForm.getStorage().setEncryptionPubKey(encryptionPubKey);
walletForm.saveAndRefresh();
EventManager.get().post(new RequestOpenWalletsEvent());
@@ -566,12 +586,12 @@ public class SettingsController extends WalletFormController implements Initiali
}
});
keyDerivationService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(walletForm.getWalletFile(), TimedEvent.Action.END, "Failed"));
EventManager.get().post(new StorageEvent(walletForm.getWalletId(), TimedEvent.Action.END, "Failed"));
AppServices.showErrorDialog("Error saving wallet", keyDerivationService.getException().getMessage());
revert.setDisable(false);
apply.setDisable(false);
});
EventManager.get().post(new StorageEvent(walletForm.getWalletFile(), TimedEvent.Action.START, "Encrypting wallet..."));
EventManager.get().post(new StorageEvent(walletForm.getWalletId(), TimedEvent.Action.START, "Encrypting wallet..."));
keyDerivationService.start();
}
} else {
@@ -1,15 +1,22 @@
package com.sparrowwallet.sparrow.wallet;
import com.sparrowwallet.drongo.policy.Policy;
import com.sparrowwallet.drongo.wallet.DeterministicSeed;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.MasterPrivateExtendedKey;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.event.KeystoreEncryptionChangedEvent;
import com.sparrowwallet.sparrow.event.KeystoreLabelsChangedEvent;
import com.sparrowwallet.sparrow.event.WalletAddressesChangedEvent;
import com.sparrowwallet.sparrow.event.WalletSettingsChangedEvent;
import com.sparrowwallet.sparrow.event.WalletPasswordChangedEvent;
import com.sparrowwallet.sparrow.io.Storage;
import com.sparrowwallet.sparrow.io.StorageException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
@@ -40,30 +47,74 @@ public class SettingsWalletForm extends WalletForm {
}
@Override
public void saveAndRefresh() throws IOException {
Wallet pastWallet = null;
public void saveAndRefresh() throws IOException, StorageException {
Wallet pastWallet = wallet.copy();
boolean refreshAll = isRefreshNecessary(wallet, walletCopy);
if(refreshAll) {
pastWallet = wallet.copy();
save(); //Save here for the temp backup in case password has been changed
if(AppServices.isConnected()) {
getStorage().backupTempWallet();
if(isRefreshNecessary(wallet, walletCopy)) {
boolean addressChange = isAddressChange();
if(wallet.isValid()) {
//Don't create temp backup on changing addresses - there are no labels to lose
if(!addressChange) {
backgroundUpdate(); //Save existing wallet here for the temp backup in case password has been changed - this will update the password on the existing wallet
if(AppServices.isConnected()) {
//Backup the wallet so labels will survive application shutdown
getStorage().backupTempWallet();
}
}
//Clear transaction history cache before we clear the nodes
AppServices.clearTransactionHistoryCache(wallet);
}
//Clear node tree
walletCopy.clearNodes();
}
wallet = walletCopy.copy();
save();
Integer childIndex = wallet.isMasterWallet() ? null : wallet.getMasterWallet().getChildWallets().indexOf(wallet);
if(refreshAll) {
EventManager.get().post(new WalletAddressesChangedEvent(wallet, pastWallet, getWalletFile()));
//Replace the SettingsWalletForm wallet reference - note that this reference is only shared with the WalletForm wallet with WalletAddressesChangedEvent below
wallet = walletCopy.copy();
if(wallet.isMasterWallet()) {
wallet.getChildWallets().forEach(childWallet -> childWallet.setMasterWallet(wallet));
} else if(childIndex != null) {
wallet.getMasterWallet().getChildWallets().set(childIndex, wallet);
}
save();
EventManager.get().post(new WalletAddressesChangedEvent(wallet, addressChange ? null : pastWallet, getWalletId()));
} else {
EventManager.get().post(new WalletSettingsChangedEvent(wallet, pastWallet, getWalletFile()));
List<Keystore> labelChangedKeystores = getLabelChangedKeystores(wallet, walletCopy);
if(!labelChangedKeystores.isEmpty()) {
EventManager.get().post(new KeystoreLabelsChangedEvent(wallet, pastWallet, getWalletId(), labelChangedKeystores));
}
List<Keystore> encryptionChangedKeystores = getEncryptionChangedKeystores(wallet, walletCopy);
if(!encryptionChangedKeystores.isEmpty()) {
EventManager.get().post(new KeystoreEncryptionChangedEvent(wallet, pastWallet, getWalletId(), encryptionChangedKeystores));
}
for(Wallet childWallet : wallet.getChildWallets()) {
Wallet childWalletCopy = walletCopy.getChildWallet(childWallet.getName());
if(childWalletCopy != null) {
Wallet pastChildWallet = childWallet.copy();
List<Keystore> childEncryptionChangedKeystores = getEncryptionChangedKeystores(childWallet, childWalletCopy);
if(!childEncryptionChangedKeystores.isEmpty()) {
EventManager.get().post(new KeystoreEncryptionChangedEvent(childWallet, pastChildWallet, getStorage().getWalletId(childWallet), childEncryptionChangedKeystores));
}
}
}
if(labelChangedKeystores.isEmpty() && encryptionChangedKeystores.isEmpty()) {
//Can only be a wallet password change on a wallet without private keys
EventManager.get().post(new WalletPasswordChangedEvent(wallet, pastWallet, getWalletId()));
}
}
}
//Returns true for any change, other than a keystore label change, to trigger a full wallet refresh
//Even though this is not strictly necessary for some changes, it it better to refresh on saving so background transaction history updates on the old wallet have no effect/are not lost
private boolean isRefreshNecessary(Wallet original, Wallet changed) {
if(!original.isValid() || !changed.isValid()) {
return true;
@@ -73,6 +124,27 @@ public class SettingsWalletForm extends WalletForm {
return true;
}
for(int i = 0; i < original.getKeystores().size(); i++) {
Keystore originalKeystore = original.getKeystores().get(i);
Keystore changedKeystore = changed.getKeystores().get(i);
if(originalKeystore.getSource() != changedKeystore.getSource()) {
return true;
}
if(originalKeystore.getWalletModel() != changedKeystore.getWalletModel()) {
return true;
}
if((originalKeystore.getSeed() == null && changedKeystore.getSeed() != null) || (originalKeystore.getSeed() != null && changedKeystore.getSeed() == null)) {
return true;
}
if((originalKeystore.getMasterPrivateExtendedKey() == null && changedKeystore.getMasterPrivateExtendedKey() != null) || (originalKeystore.getMasterPrivateExtendedKey() != null && changedKeystore.getMasterPrivateExtendedKey() == null)) {
return true;
}
}
if(original.getGapLimit() != changed.getGapLimit()) {
return true;
}
@@ -126,4 +198,47 @@ public class SettingsWalletForm extends WalletForm {
private Integer getNumSignaturesRequired(Policy policy) {
return policy == null ? null : policy.getNumSignaturesRequired();
}
private List<Keystore> getLabelChangedKeystores(Wallet original, Wallet changed) {
List<Keystore> changedKeystores = new ArrayList<>();
for(int i = 0; i < original.getKeystores().size(); i++) {
Keystore originalKeystore = original.getKeystores().get(i);
Keystore changedKeystore = changed.getKeystores().get(i);
if(!Objects.equals(originalKeystore.getLabel(), changedKeystore.getLabel())) {
originalKeystore.setLabel(changedKeystore.getLabel());
changedKeystores.add(originalKeystore);
}
}
return changedKeystores;
}
private List<Keystore> getEncryptionChangedKeystores(Wallet original, Wallet changed) {
List<Keystore> changedKeystores = new ArrayList<>();
for(int i = 0; i < original.getKeystores().size(); i++) {
Keystore originalKeystore = original.getKeystores().get(i);
Keystore changedKeystore = changed.getKeystores().get(i);
if(originalKeystore.hasSeed() && changedKeystore.hasSeed()) {
if(!Objects.equals(originalKeystore.getSeed().getEncryptedData(), changedKeystore.getSeed().getEncryptedData())) {
DeterministicSeed changedSeed = changedKeystore.getSeed().copy();
changedSeed.setId(originalKeystore.getSeed().getId());
originalKeystore.setSeed(changedSeed);
changedKeystores.add(originalKeystore);
}
}
if(originalKeystore.hasMasterPrivateExtendedKey() && changedKeystore.hasMasterPrivateExtendedKey()) {
if(!Objects.equals(originalKeystore.getMasterPrivateExtendedKey().getEncryptedData(), changedKeystore.getMasterPrivateExtendedKey().getEncryptedData())) {
MasterPrivateExtendedKey changedMpek = changedKeystore.getMasterPrivateExtendedKey().copy();
changedMpek.setId(originalKeystore.getMasterPrivateExtendedKey().getId());
originalKeystore.setMasterPrivateExtendedKey(changedMpek);
changedKeystores.add(originalKeystore);
}
}
}
return changedKeystores;
}
}
@@ -5,6 +5,7 @@ import com.sparrowwallet.drongo.KeyPurpose;
import com.sparrowwallet.drongo.protocol.TransactionInput;
import com.sparrowwallet.drongo.protocol.TransactionOutput;
import com.sparrowwallet.drongo.wallet.*;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.WalletTabData;
import com.sparrowwallet.sparrow.event.WalletBlockHeightChangedEvent;
@@ -30,8 +31,10 @@ public class TransactionEntry extends Entry implements Comparable<TransactionEnt
this.blockTransaction = blockTransaction;
labelProperty().addListener((observable, oldValue, newValue) -> {
blockTransaction.setLabel(newValue);
EventManager.get().post(new WalletEntryLabelsChangedEvent(wallet, this));
if(!Objects.equals(blockTransaction.getLabel(), newValue)) {
blockTransaction.setLabel(newValue);
EventManager.get().post(new WalletEntryLabelsChangedEvent(wallet, this));
}
});
setConfirmations(calculateConfirmations());
@@ -68,7 +71,7 @@ public class TransactionEntry extends Entry implements Comparable<TransactionEnt
}
public int calculateConfirmations() {
return blockTransaction.getConfirmations(getWallet().getStoredBlockHeight());
return blockTransaction.getConfirmations(AppServices.getCurrentBlockHeight() == null ? getWallet().getStoredBlockHeight() : AppServices.getCurrentBlockHeight());
}
public String getConfirmationsDescription() {
@@ -161,8 +161,11 @@ public class TransactionsController extends WalletFormController implements Init
String date = LOG_DATE_FORMAT.format(new Date());
String logLine = "\n" + date + " " + logMessage;
Platform.runLater(() -> {
loadingLog.appendText(logLine);
loadingLog.setScrollLeft(0);
int lastLineStart = loadingLog.getText().lastIndexOf("\n");
if(lastLineStart < 0 || !loadingLog.getText().substring(lastLineStart).equals(logLine)) {
loadingLog.appendText(logLine);
loadingLog.setScrollLeft(0);
}
});
}
}
@@ -16,6 +16,7 @@ import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import java.net.URL;
import java.util.List;
@@ -44,6 +45,7 @@ public class UtxosController extends WalletFormController implements Initializab
utxosTable.initialize(getWalletForm().getWalletUtxosEntry());
utxosChart.initialize(getWalletForm().getWalletUtxosEntry());
sendSelected.setDisable(true);
sendSelected.setTooltip(new Tooltip("Send selected UTXOs. Use " + (org.controlsfx.tools.Platform.getCurrent() == org.controlsfx.tools.Platform.OSX ? "Cmd" : "Ctrl") + "+click to select multiple." ));
utxosTable.getSelectionModel().getSelectedIndices().addListener((ListChangeListener<Integer>) c -> {
List<Entry> selectedEntries = utxosTable.getSelectionModel().getSelectedCells().stream().map(tp -> tp.getTreeItem().getValue()).collect(Collectors.toList());
@@ -163,6 +165,7 @@ public class UtxosController extends WalletFormController implements Initializab
public void walletUtxoStatusChanged(WalletUtxoStatusChangedEvent event) {
if(event.getWallet().equals(getWalletForm().getWallet())) {
utxosTable.refresh();
updateSendSelected(Config.get().getBitcoinUnit());
}
}
@@ -107,7 +107,7 @@ public class WalletController extends WalletFormController implements Initializa
@Subscribe
public void walletAddressesChanged(WalletAddressesChangedEvent event) {
if(event.getWalletFile().equals(walletForm.getWalletFile())) {
if(event.getWalletId().equals(walletForm.getWalletId())) {
configure(event.getWallet().isValid());
}
}
@@ -12,6 +12,7 @@ import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.WalletTabData;
import com.sparrowwallet.sparrow.event.*;
import com.sparrowwallet.sparrow.io.Config;
import com.sparrowwallet.sparrow.io.StorageException;
import com.sparrowwallet.sparrow.net.ElectrumServer;
import com.sparrowwallet.sparrow.io.Storage;
import com.sparrowwallet.sparrow.net.ServerType;
@@ -22,6 +23,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
public class WalletForm {
private static final Logger log = LoggerFactory.getLogger(WalletForm.class);
@@ -60,6 +62,10 @@ public class WalletForm {
return storage;
}
public String getWalletId() {
return storage.getWalletId(wallet);
}
public File getWalletFile() {
return storage.getWalletFile();
}
@@ -72,11 +78,11 @@ public class WalletForm {
throw new UnsupportedOperationException("Only SettingsWalletForm supports revert");
}
public void save() throws IOException {
public void save() throws IOException, StorageException {
storage.saveWallet(wallet);
}
public void saveAndRefresh() throws IOException {
public void saveAndRefresh() throws IOException, StorageException {
Wallet pastWallet = wallet.copy();
storage.backupTempWallet();
wallet.clearHistory();
@@ -88,6 +94,15 @@ public class WalletForm {
storage.backupWallet();
}
protected void backgroundUpdate() {
try {
storage.updateWallet(wallet);
} catch (IOException | StorageException e) {
//Background save failed
log.error("Background wallet save failed", e);
}
}
public void deleteBackups() {
storage.deleteBackups();
}
@@ -127,36 +142,61 @@ public class WalletForm {
wallet.setStoredBlockHeight(blockHeight);
}
boolean labelsChanged = false;
//After the wallet settings are changed, the previous wallet is copied to pastWallet and used here to copy labels from past nodes, txos and txes
Set<Entry> labelChangedEntries = Collections.emptySet();
if(pastWallet != null) {
labelsChanged = copyLabels(pastWallet);
labelChangedEntries = copyLabels(pastWallet);
}
notifyIfChanged(blockHeight, previousWallet, labelsChanged);
notifyIfChanged(blockHeight, previousWallet, labelChangedEntries);
}
private boolean copyLabels(Wallet pastWallet) {
boolean changed = wallet.getNode(KeyPurpose.RECEIVE).copyLabels(pastWallet.getNode(KeyPurpose.RECEIVE));
changed |= wallet.getNode(KeyPurpose.CHANGE).copyLabels(pastWallet.getNode(KeyPurpose.CHANGE));
private Set<Entry> copyLabels(Wallet pastWallet) {
Set<Entry> changedEntries = new LinkedHashSet<>();
//On a full wallet refresh, walletUtxosEntry and walletTransactionsEntry will have no children yet, but AddressesController may have created accountEntries on a walletNodesChangedEvent
//Copy nodeEntry labels
List<KeyPurpose> keyPurposes = List.of(KeyPurpose.RECEIVE, KeyPurpose.CHANGE);
for(KeyPurpose keyPurpose : keyPurposes) {
NodeEntry purposeEntry = getNodeEntry(keyPurpose);
changedEntries.addAll(purposeEntry.copyLabels(pastWallet.getNode(purposeEntry.getNode().getKeyPurpose())));
}
//Copy node and txo labels
for(KeyPurpose keyPurpose : keyPurposes) {
if(wallet.getNode(keyPurpose).copyLabels(pastWallet.getNode(keyPurpose))) {
changedEntries.add(getWalletUtxosEntry());
}
}
//Copy tx labels
for(Map.Entry<Sha256Hash, BlockTransaction> txEntry : wallet.getTransactions().entrySet()) {
BlockTransaction pastBlockTransaction = pastWallet.getTransactions().get(txEntry.getKey());
if(pastBlockTransaction != null && txEntry.getValue() != null && txEntry.getValue().getLabel() == null && pastBlockTransaction.getLabel() != null) {
txEntry.getValue().setLabel(pastBlockTransaction.getLabel());
changed = true;
changedEntries.add(getWalletTransactionsEntry());
}
}
storage.deleteTempBackups();
return changed;
return changedEntries;
}
private void notifyIfChanged(Integer blockHeight, Wallet previousWallet, boolean labelsChanged) {
private void notifyIfChanged(Integer blockHeight, Wallet previousWallet, Set<Entry> labelChangedEntries) {
List<WalletNode> historyChangedNodes = new ArrayList<>();
historyChangedNodes.addAll(getHistoryChangedNodes(previousWallet.getNode(KeyPurpose.RECEIVE).getChildren(), wallet.getNode(KeyPurpose.RECEIVE).getChildren()));
historyChangedNodes.addAll(getHistoryChangedNodes(previousWallet.getNode(KeyPurpose.CHANGE).getChildren(), wallet.getNode(KeyPurpose.CHANGE).getChildren()));
boolean changed = labelsChanged;
boolean changed = false;
if(!labelChangedEntries.isEmpty()) {
List<Entry> eventEntries = labelChangedEntries.stream().filter(entry -> entry != getWalletTransactionsEntry() && entry != getWalletUtxosEntry()).collect(Collectors.toList());
if(!eventEntries.isEmpty()) {
Platform.runLater(() -> EventManager.get().post(new WalletEntryLabelsChangedEvent(wallet, eventEntries)));
}
changed = true;
}
if(!historyChangedNodes.isEmpty()) {
Platform.runLater(() -> EventManager.get().post(new WalletHistoryChangedEvent(wallet, storage, historyChangedNodes)));
changed = true;
@@ -257,37 +297,50 @@ public class WalletForm {
@Subscribe
public void walletDataChanged(WalletDataChangedEvent event) {
if(event.getWallet().equals(wallet)) {
backgroundSaveWallet();
}
}
private void backgroundSaveWallet() {
try {
save();
} catch (IOException e) {
//Background save failed
log.error("Background wallet save failed", e);
backgroundUpdate();
}
}
@Subscribe
public void walletSettingsChanged(WalletSettingsChangedEvent event) {
if(event.getWalletFile().equals(storage.getWalletFile())) {
public void walletHistoryCleared(WalletHistoryClearedEvent event) {
if(event.getWalletId().equals(getWalletId())) {
//Replacing the WalletForm's wallet here is only possible because we immediately clear all derived structures and do a full wallet refresh
wallet = event.getWallet();
if(event instanceof WalletAddressesChangedEvent) {
walletTransactionsEntry = null;
walletUtxosEntry = null;
accountEntries.clear();
EventManager.get().post(new WalletNodesChangedEvent(wallet));
walletTransactionsEntry = null;
walletUtxosEntry = null;
accountEntries.clear();
EventManager.get().post(new WalletNodesChangedEvent(wallet));
//It is necessary to save the past wallet because the actual copying of the past labels only occurs on a later ConnectionEvent with bwt
if(Config.get().getServerType() == ServerType.BITCOIN_CORE) {
savedPastWallet = event.getPastWallet();
}
refreshHistory(AppServices.getCurrentBlockHeight(), event.getPastWallet());
//It is necessary to save the past wallet because the actual copying of the past labels only occurs on a later ConnectionEvent with bwt
if(Config.get().getServerType() == ServerType.BITCOIN_CORE) {
savedPastWallet = event.getPastWallet();
}
//Clear the cache - we will need to fetch everything again
AppServices.clearTransactionHistoryCache(wallet);
refreshHistory(AppServices.getCurrentBlockHeight(), event.getPastWallet());
}
}
@Subscribe
public void keystoreLabelsChanged(KeystoreLabelsChangedEvent event) {
if(event.getWalletId().equals(getWalletId())) {
Platform.runLater(() -> EventManager.get().post(new WalletDataChangedEvent(wallet)));
}
}
@Subscribe
public void keystoreEncryptionChanged(KeystoreEncryptionChangedEvent event) {
if(event.getWalletId().equals(getWalletId())) {
Platform.runLater(() -> EventManager.get().post(new WalletDataChangedEvent(wallet)));
}
}
@Subscribe
public void walletPasswordChanged(WalletPasswordChangedEvent event) {
if(event.getWalletId().equals(getWalletId())) {
Platform.runLater(() -> EventManager.get().post(new WalletDataChangedEvent(wallet)));
}
}
@@ -318,13 +371,13 @@ public class WalletForm {
@Subscribe
public void walletHistoryChanged(WalletHistoryChangedEvent event) {
if(event.getWalletFile().equals(storage.getWalletFile())) {
if(event.getWalletId().equals(getWalletId())) {
for(WalletNode changedNode : event.getHistoryChangedNodes()) {
if(changedNode.getLabel() != null && !changedNode.getLabel().isEmpty()) {
List<Entry> changedLabelEntries = new ArrayList<>();
for(BlockTransactionHashIndex receivedRef : changedNode.getTransactionOutputs()) {
BlockTransaction blockTransaction = wallet.getTransactions().get(receivedRef.getHash());
if(blockTransaction != null && blockTransaction.getLabel() == null) {
if(blockTransaction != null && (blockTransaction.getLabel() == null || blockTransaction.getLabel().isEmpty())) {
blockTransaction.setLabel(changedNode.getLabel());
changedLabelEntries.add(new TransactionEntry(event.getWallet(), blockTransaction, Collections.emptyMap(), Collections.emptyMap()));
}
@@ -351,16 +404,16 @@ public class WalletForm {
for(WalletNode childNode : wallet.getNode(keyPurpose).getChildren()) {
for(BlockTransactionHashIndex receivedRef : childNode.getTransactionOutputs()) {
if(receivedRef.getHash().equals(transactionEntry.getBlockTransaction().getHash())) {
if(receivedRef.getLabel() == null) {
if(receivedRef.getLabel() == null || receivedRef.getLabel().isEmpty()) {
receivedRef.setLabel(entry.getLabel() + (keyPurpose == KeyPurpose.CHANGE ? " (change)" : " (received)"));
labelChangedEntries.add(new HashIndexEntry(event.getWallet(), receivedRef, HashIndexEntry.Type.OUTPUT, keyPurpose));
}
if(childNode.getLabel() == null) {
if(childNode.getLabel() == null || childNode.getLabel().isEmpty()) {
childNode.setLabel(entry.getLabel());
labelChangedEntries.add(new NodeEntry(event.getWallet(), childNode));
}
}
if(receivedRef.isSpent() && receivedRef.getSpentBy().getHash().equals(transactionEntry.getBlockTransaction().getHash()) && receivedRef.getSpentBy().getLabel() == null) {
if(receivedRef.isSpent() && receivedRef.getSpentBy().getHash().equals(transactionEntry.getBlockTransaction().getHash()) && (receivedRef.getSpentBy().getLabel() == null || receivedRef.getSpentBy().getLabel().isEmpty())) {
receivedRef.getSpentBy().setLabel(entry.getLabel() + " (input)");
labelChangedEntries.add(new HashIndexEntry(event.getWallet(), receivedRef.getSpentBy(), HashIndexEntry.Type.INPUT, keyPurpose));
}
@@ -372,7 +425,7 @@ public class WalletForm {
NodeEntry nodeEntry = (NodeEntry)entry;
for(BlockTransactionHashIndex receivedRef : nodeEntry.getNode().getTransactionOutputs()) {
BlockTransaction blockTransaction = event.getWallet().getTransactions().get(receivedRef.getHash());
if(blockTransaction.getLabel() == null) {
if(blockTransaction.getLabel() == null || blockTransaction.getLabel().isEmpty()) {
blockTransaction.setLabel(entry.getLabel());
labelChangedEntries.add(new TransactionEntry(event.getWallet(), blockTransaction, Collections.emptyMap(), Collections.emptyMap()));
}
@@ -381,7 +434,7 @@ public class WalletForm {
if(entry instanceof HashIndexEntry) {
HashIndexEntry hashIndexEntry = (HashIndexEntry)entry;
BlockTransaction blockTransaction = hashIndexEntry.getBlockTransaction();
if(blockTransaction.getLabel() == null) {
if(blockTransaction.getLabel() == null || blockTransaction.getLabel().isEmpty()) {
blockTransaction.setLabel(entry.getLabel());
labelChangedEntries.add(new TransactionEntry(event.getWallet(), blockTransaction, Collections.emptyMap(), Collections.emptyMap()));
}
@@ -391,15 +444,29 @@ public class WalletForm {
if(!labelChangedEntries.isEmpty()) {
Platform.runLater(() -> EventManager.get().post(new WalletEntryLabelsChangedEvent(wallet, labelChangedEntries)));
} else {
Platform.runLater(() -> EventManager.get().post(new WalletDataChangedEvent(wallet)));
}
}
}
@Subscribe
public void walletUtxoStatusChanged(WalletUtxoStatusChangedEvent event) {
if(event.getWallet() == wallet) {
Platform.runLater(() -> EventManager.get().post(new WalletDataChangedEvent(wallet)));
}
}
@Subscribe
public void walletTabsClosed(WalletTabsClosedEvent event) {
for(WalletTabData tabData : event.getClosedWalletTabData()) {
if(tabData.getWalletForm() == this) {
AppServices.clearTransactionHistoryCache(wallet);
if(wallet.isMasterWallet()) {
storage.close();
}
if(wallet.isValid()) {
AppServices.clearTransactionHistoryCache(wallet);
}
EventManager.get().unregister(this);
}
}
+6 -1
View File
@@ -23,11 +23,16 @@ open module com.sparrowwallet.sparrow {
requires hummingbird;
requires centerdevice.nsmenufx;
requires jcommander;
requires slf4j.api;
requires org.slf4j;
requires bwt.jni;
requires jtorctl;
requires javacsv;
requires jul.to.slf4j;
requires bridj;
requires com.google.gson;
requires org.jdbi.v3.core;
requires org.jdbi.v3.sqlobject;
requires org.flywaydb.core;
requires com.zaxxer.hikari;
requires com.h2database;
}
@@ -8,6 +8,7 @@
<?import com.sparrowwallet.sparrow.control.UnlabeledToggleSwitch?>
<?import com.sparrowwallet.drongo.BitcoinUnit?>
<?import com.sparrowwallet.sparrow.Theme?>
<?import impl.org.controlsfx.skin.DecorationPane?>
<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="200" minWidth="350" prefHeight="770.0" prefWidth="1020.0" fx:controller="com.sparrowwallet.sparrow.AppController" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1">
<children>
@@ -28,7 +29,7 @@
</Menu>
<MenuItem fx:id="saveTransaction" mnemonicParsing="false" text="Save Transaction..." accelerator="Shortcut+S" onAction="#saveTransaction"/>
<Menu fx:id="savePSBT" mnemonicParsing="false" text="Save PSBT">
<MenuItem text="As Binary..." onAction="#savePSBTBinary" accelerator="Shortcut+S"/>
<MenuItem fx:id="savePSBTBinary" text="As Binary..." onAction="#savePSBTBinary" accelerator="Shortcut+S"/>
<MenuItem text="As Base64..." onAction="#savePSBTText"/>
<MenuItem text="As Binary (No Xpubs)..." onAction="#savePSBTBinaryNoXpubs"/>
<MenuItem text="As Base64 (No Xpubs)..." onAction="#savePSBTTextNoXpubs"/>
@@ -110,11 +111,17 @@
</Menu>
</menus>
</MenuBar>
<StackPane fx:id="rootStack" VBox.vgrow="ALWAYS">
<Rectangle styleClass="background-box" width="400" height="125" />
<Text styleClass="background-text" text="Drag files here to open" />
<DecorationPane fx:id="rootStack" VBox.vgrow="ALWAYS">
<Rectangle styleClass="background-box" width="450" height="170" />
<HBox alignment="CENTER">
<VBox alignment="CENTER_LEFT" spacing="15">
<Text styleClass="background-text" text="File menu → New Wallet or" />
<Text styleClass="background-text" text="File menu → Import Wallet or" />
<Text styleClass="background-text" text="Drag files here to open" />
</VBox>
</HBox>
<TabPane fx:id="tabs" />
</StackPane>
</DecorationPane>
<StatusBar fx:id="statusBar" text="" minHeight="36">
<rightItems>

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