Compare commits

..
122 Commits
Author SHA1 Message Date
Craig Raw 6fc52fdc0e display effective fee rate next to transaction fee rate when constructing a cpfp tx 2024-01-18 09:53:44 +02:00
Craig Raw 1d2081d2a6 transaction tree label tweaks 2024-01-18 09:00:39 +02:00
Craig Raw 4d587cf776 update keystone logo 2024-01-18 08:35:01 +02:00
Craig Raw 14689dd256 add payment labels to transaction tabs for received outputs where available from open wallets 2024-01-17 14:43:24 +02:00
Craig Raw c8a5c1fb86 followup 2024-01-17 13:50:04 +02:00
Craig Raw 734818cd9e adjust transaction tree width for input labelling 2024-01-17 13:43:48 +02:00
Craig Raw 6aa5473b24 add rescan note to warning tooltip for large gap limits 2024-01-17 12:33:55 +02:00
Craig Raw 1b460533f5 followup to reducing server calls on loading transaction tab 2024-01-17 10:48:57 +02:00
Craig Raw ad1ecfb887 fix changing amount bitcoin unit on send tab with comma decimal separator 2024-01-16 12:19:56 +02:00
Craig Raw 6a5060c0c8 cormorant: support coinbase transactions 2024-01-15 17:20:44 +02:00
Craig Raw 02a0a3277b reduce server calls on opening a transaction tab by using open wallet history when performing spent output lookup 2024-01-12 15:35:26 +02:00
Craig Raw 57dba5d6ae improve input and output labels on transaction tree and detail panels 2024-01-12 12:10:38 +02:00
Craig Raw 540424a2e3 followup 2024-01-10 11:18:26 +02:00
craigrawandGitHub e1d9d54da3 Merge pull request #1204 from krzyczak/master
toggle bitcoin unit on clicking a bitcoin value label
2024-01-10 11:15:47 +02:00
Craig Raw 2b8a513adf support reading revised ur tags including v3 output descriptors 2024-01-10 11:05:03 +02:00
Craig Raw 20df1dbd8b fix typo 2024-01-09 11:59:19 +02:00
Craig Raw 04c8017bb5 increase payments tab header width on send tab 2024-01-09 11:58:38 +02:00
Craig Raw be0ac52a09 support creating wallets from descriptors containing master xprvs 2024-01-09 11:38:10 +02:00
Craig Raw 3162371838 fix order of outputs displayed in transaction diagram where there are multiple payments with the same address and amount 2024-01-08 12:12:13 +02:00
Craig Raw b5196d1ac2 encrypt electrum wallet exports including private keys where password is available 2024-01-08 09:16:55 +02:00
krzyczak 343cb2271c feat: Implement bitcoin unit toggle on bitcoin balance 2023-12-22 17:29:22 +00:00
Craig Raw 4feb4a3a79 add airgap vault to airgapped options (draft) 2023-12-06 08:55:09 +02:00
craigrawandGitHub 20b4d5a1b5 Merge pull request #1187 from Toporin/patch-satochip-error-0x9C01
satochip: flush card cache where cache memory is full
2023-12-01 09:12:58 +02:00
Craig Raw 06489d8339 cormorant: round up wallet range to avoid frequent rescans with a large gap limit 2023-12-01 09:09:28 +02:00
Toporin e368782b4c Satochip: Patch error 0x9C01 in cardBip32GetExtendedKey()
This error occurs when the cache memory in the card is full.
We need to flush the cache by sending the same command with the p2 flag set to 0x80.
2023-11-30 21:25:01 +01:00
Craig Raw 6ee3755ce4 cormorant: fix descriptor range calculation and extend range from pruned date only where necessary 2023-11-30 12:54:50 +02:00
Craig Raw d425933189 only allow sweeping from uncompressed keys to legacy script type addresses 2023-11-30 11:42:59 +02:00
Craig Raw 675b7ed4f8 cormorant: default to existing descriptor timestamp when extending range 2023-11-30 08:50:20 +02:00
Craig Raw 6072f6d31a add master fingerprint to passphrase entry dialog in terminal 2023-11-29 10:25:40 +02:00
Craig Raw e1fb674170 avoid showing balance in fiat when exchange source is none 2023-11-29 09:32:01 +02:00
Craig Raw d8839763a4 remove extraneous space character 2023-11-23 07:49:20 +02:00
Craig Raw 64e98cdb35 bump to v1.8.2 2023-11-22 11:59:02 +02:00
Craig Raw bde8fef35e disable rename wallet on transaction tab 2023-11-22 09:17:17 +02:00
Craig Raw 87e7a87e5e exchange source: use closing price where available 2023-11-22 08:12:32 +02:00
Craig Raw 85eb4df7e9 transaction tab: rearrange via transaction tree 2023-11-22 07:59:26 +02:00
Craig Raw bb32a1e7b1 add comment to transactions csv on the approximate nature of the fiat values 2023-11-21 17:59:13 +02:00
Craig Raw f590794589 add qr display (with save to pdf) to output descriptor wallet export options 2023-11-21 10:06:32 +02:00
Craig Raw 1e3ce7eb88 add historical fiat values to transactions csv export 2023-11-21 09:33:47 +02:00
Craig Raw ef3e2ed695 cormorant: handle checking imports and stopping before started 2023-11-20 10:56:06 +02:00
Craig Raw 74c3370277 use fallback fee rate estimates if the connected server returns an error estimating fee rates 2023-11-20 10:29:14 +02:00
Craig Raw 170e7c0abf reduce http error logging 2023-11-17 09:43:22 +02:00
Craig Raw e0486ff4a9 followup 2023-11-16 18:12:19 +02:00
Craig Raw 1d17384152 increase and decrease maximum on fee rate slider where fee rate equals or exceeds current range, set testnet fallback fee rate to 1 sat/vb 2023-11-16 16:58:24 +02:00
Craig Raw aec26d512b add oxt.me as fee rates source 2023-11-16 10:12:41 +02:00
Craig Raw 9e5a6e83d1 set smaller increment amount on fee range slider for key adjustments 2023-11-15 16:22:12 +02:00
Craig Raw eecb90e9b2 cormorant: check wallet gap limit and increase core descriptor range if necessary 2023-11-15 13:29:26 +02:00
Craig Raw b3516063b2 add null safe tests for standard account types 2023-11-15 10:52:05 +02:00
Craig Raw 1d560d6aa6 save mix to wallet index to improve handling of mix out failures 2023-11-15 10:20:58 +02:00
Craig Raw d128401a09 fix transaction diagram output size indicators in transactions with non-address outputs 2023-11-14 15:18:47 +02:00
Craig Raw 9391a397da set dialog minimum height to preferred height (or make resizable) to avoid window sizing bug in some linux environments 2023-11-14 14:29:28 +02:00
Craig Raw a5312374a8 show error dialog on cpfp if no outputs are spendable 2023-11-13 14:37:41 +02:00
Craig Raw c81c42a87c switch from httpurlconnection to jetty http client to avoid spurious dns query 2023-11-10 19:16:03 +02:00
Craig Raw d84ade5b7d add krux to wallet import options 2023-11-10 14:55:00 +02:00
Craig Raw 323d29e34a bump to v1.8.1 2023-11-09 14:37:35 +02:00
Craig Raw 95cb8c4b2c bump to v1.8.0 2023-11-09 12:55:10 +02:00
Craig Raw 2712555c72 followup 2 2023-11-09 12:50:39 +02:00
Craig Raw 72066395d6 followup 2023-11-09 12:31:18 +02:00
Craig Raw 7b3e5f37b9 improve vertical layout sizing on transaction tabs 2023-11-09 12:17:08 +02:00
Craig Raw 870a468584 add bisq segwit misderivation to mnemonic wallet discovery 2023-11-09 09:31:02 +02:00
Craig Raw 0340cba441 fix improvement to renaming wallet keystore labels for uniqueness 2023-11-09 09:10:54 +02:00
Craig Raw 91f845cbbf followup 2023-11-08 17:23:30 +02:00
Craig Raw d0f21eafd1 schedule regular check to indicate proxy status in sparrow terminal 2023-11-08 17:08:44 +02:00
Craig Raw 36c2181a7f remove keyboard shortcut+pageup/pagedown to switch tabs already added by default 2023-11-08 15:22:39 +02:00
Craig Raw 218e751333 display error message when attempting to mix from account 0 and it is not the master wallet 2023-11-08 12:29:54 +02:00
Craig Raw 995d2c5e4e temporarily disconnect from whirlpool if gap limit is increasing rapidly 2023-11-08 11:59:19 +02:00
Craig Raw 0d7ae74f0f fix whirlpool wallets with special characters in the passphrase 2023-11-08 09:27:25 +02:00
Craig Raw e6eea67c4b add search all open wallets functionality, include matches on transaction output addresses 2023-11-07 16:38:33 +02:00
Craig Raw ea3e0ca34a select all text in message sign signature field on mouse click 2023-11-07 15:16:06 +02:00
Craig Raw 3fedd8eb43 support opening multiple wallet and transaction files at once 2023-11-07 14:14:14 +02:00
Craig Raw 30408af719 add fee rate slider to private key sweep dialog 2023-11-07 14:02:17 +02:00
Craig Raw 910a400b18 fix computation of master fingerprint for satochip 2023-11-07 11:58:18 +02:00
Craig Raw f4ac18c3e1 increase gap limit where necessary to sign a psbt where global xpubs match 2023-11-02 12:38:51 +01:00
Craig Raw cb06e1aaf7 freeze and unfreeze utxos in sparrow terminal by pressing f on utxos table 2023-10-31 11:20:10 +01:00
Craig Raw d881e47ec9 indicate if proxy is enabled in sparrow terminal 2023-10-31 10:37:19 +01:00
Craig Raw dbafefb940 reload cormorant wallet if unloaded when polling bitcoind 2023-10-31 10:21:33 +01:00
Craig Raw ee6589991d add initial satochip card support 2023-10-31 09:56:31 +01:00
Craig Raw 24578dcf88 enlarge qr display dialog and increase default qr code density 2023-10-24 17:12:41 +02:00
Craig Raw ddae1a12d8 add keyboard shortcut ctrl+pageup/pagedown to switch tabs on windows/linux 2023-10-24 15:34:20 +02:00
Craig Raw 1c9b6c3eef add keyboard shortcut ctrl/cmd+alt+arrow to switch tabs 2023-10-24 15:06:21 +02:00
Craig Raw 158ecd4ab1 fix thread race issue when connecting to cormorant electrum server 2023-10-24 10:51:09 +02:00
Craig Raw b6bcdef712 minor fixes 2023-10-22 14:43:09 +02:00
Craig Raw 6eefd3f182 add duplicate payment address warning to transaction diagram 2023-10-12 12:37:44 +02:00
Craig Raw 9280504f70 add duplicate payment address warning to transaction diagram 2023-10-12 12:37:41 +02:00
Craig Raw a6a671f687 remove block hash from transaction tab fields, add to context menu for block height and timestamp 2023-10-11 13:08:42 +02:00
Craig Raw 4e3e8b7cc4 add figure caption to overview diagram on transaction tab to describe transaction 2023-10-11 11:44:40 +02:00
Craig Raw 2b8fc3900a followup 2023-10-06 13:50:44 +02:00
Craig Raw cff731dec7 ignore script type change warning when replacing wallet in settings 2023-10-05 12:37:27 +02:00
Craig Raw c9c0c35964 add krux as airgapped hww 2023-10-05 10:35:55 +02:00
Craig Raw afed5c65f5 add additional testnet public server qtornado.com 2023-10-05 08:53:12 +02:00
Craig Raw 0724c38582 add whirlpool postmix to the list of possible accounts that can be added to any legacy or segwit wallet 2023-09-29 14:37:58 +02:00
Craig Raw 31539a27ac improve fullscreen behaviour by setting dialog ownership to parent window 2023-09-29 12:02:14 +02:00
Craig Raw 201900aa0e add airgapped message signing via qr 2023-09-25 13:39:51 +02:00
Craig Raw 3dcbe34485 add scan button to qr display dialog to progress immediately to scanning 2023-09-21 14:07:58 +02:00
Craig Raw 31842cc0f2 update caravan and specter logos 2023-09-21 11:34:04 +02:00
Craig Raw f85349bd36 support hex border wallets grid pdf 2023-09-19 14:05:26 +02:00
Craig Raw a18c24e19f add /usr/lib64 as possible location for linux pcsc lib 2023-09-18 10:44:33 +02:00
Craig Raw e23c1b3872 force selection of a new configured server if currently configured server is deleted 2023-09-04 09:47:41 +02:00
Craig Raw 3c2ef43526 bump to v1.7.10 2023-08-31 13:36:36 +02:00
Craig Raw c81aae0c6a minor account renaming bug fixes 2023-08-31 10:54:16 +02:00
Craig Raw ff1a9e8a52 add or remove tooltip on account tab on renaming 2023-08-31 10:06:46 +02:00
Craig Raw 90bfa47046 add jade multisig wallet import 2023-08-31 09:34:15 +02:00
Craig Raw 6383b8b46f improve renaming wallet keystore labels for uniqueness 2023-08-30 15:21:43 +02:00
Craig Raw 76dc294748 support import and export of keystore labels in crypto-output qr codes 2023-08-30 14:22:18 +02:00
Craig Raw 0bc1dd96ed use port instead of unix socket for internal tor control to avoid bug where unix socket path is too long 2023-08-30 10:39:52 +02:00
Craig Raw 73d2d3cbbc replace hwi 2.3.1 binary with macos 10.13 compiled version 2023-08-30 09:55:08 +02:00
Craig Raw d5fdd6881c followup 2023-08-30 09:32:02 +02:00
Craig Raw b1bc25ba04 propagate transaction label changes to inputs, outputs and addresses where their existing labels were set in the same manner 2023-08-29 16:03:46 +02:00
Craig Raw 2c1204c247 add treetable config classes 2023-08-23 13:52:33 +02:00
Craig Raw 05a1fd8e8d refactor cointreetable column sorting, add default sorting if table was empty 2023-08-23 12:18:02 +02:00
Craig Raw 97f21394a7 add tooltip to account tab where label is truncated 2023-08-23 11:24:24 +02:00
Craig Raw c57a445046 add mempoolfullrbf config variable to enable rbf functionality on mempool transactions without checking sequence flags (default false) 2023-08-17 16:18:27 +02:00
Craig Raw fb981f1548 suggest clearing any existing keystores when script type is changed in settings 2023-08-17 15:35:33 +02:00
Craig Raw 407dde2703 upgrade to hwi 2.3.1 2023-08-17 12:33:03 +02:00
Craig Raw f175139fd3 add wallet summary dialog 2023-08-14 16:11:55 +02:00
Craig Raw bebd7eebe5 handle core bug where listwalletdir returns empty results 2023-08-14 10:02:35 +02:00
Craig Raw e01f6b42b1 add fulcrum.sethforprivacy.com public mainnet electrum server 2023-08-07 13:57:27 +02:00
Craig Raw bd1c6c076e avoid adding inputs when constructing a consolidation transaction replacement, allowing output to decrease 2023-08-07 12:54:29 +02:00
Craig Raw 46b1bd2fd2 improve address resolution error message 2023-08-07 12:20:07 +02:00
Craig Raw 2d7c5dcec7 terminal: check if theme is present to avoid exception on utxo history update 2023-08-07 12:00:58 +02:00
Craig Raw 93bcf6cef9 fix single character multisig threshold parsing issue 2023-07-23 13:13:30 +02:00
Craig Raw 4b6a03ef56 for zbar scans, return scanned characters as raw bytes 2023-07-23 12:48:04 +02:00
Craig Raw 7ff4230e13 bump to v1.7.9 2023-07-18 16:22:43 +02:00
218 changed files with 5816 additions and 1028 deletions
+4 -4
View File
@@ -7,7 +7,7 @@ plugins {
id 'org.beryx.jlink' version '2.26.0'
}
def sparrowVersion = '1.7.8'
def sparrowVersion = '1.8.2'
def os = org.gradle.internal.os.OperatingSystem.current()
def osName = os.getFamilyName()
if(os.macOsX) {
@@ -89,7 +89,7 @@ dependencies {
implementation('com.github.arteam:simple-json-rpc-server:1.3') {
exclude group: 'org.slf4j'
}
implementation('com.sparrowwallet:hummingbird:1.6.7')
implementation('com.sparrowwallet:hummingbird:1.7.3')
implementation('co.nstant.in:cbor:0.9')
implementation("com.nativelibs4java:bridj${targetName}:0.7-20140918-3") {
exclude group: 'com.google.android.tools', module: 'dx'
@@ -121,7 +121,7 @@ dependencies {
implementation('org.slf4j:jul-to-slf4j:1.7.30') {
exclude group: 'org.slf4j'
}
implementation('com.sparrowwallet.nightjar:nightjar:0.2.36')
implementation('com.sparrowwallet.nightjar:nightjar:0.2.39')
implementation('io.reactivex.rxjava2:rxjava:2.2.15')
implementation('io.reactivex.rxjava2:rxjavafx:2.2.2')
implementation('org.apache.commons:commons-lang3:3.7')
@@ -508,7 +508,7 @@ extraJavaModuleInfo {
exports('co.nstant.in.cbor.model')
exports('co.nstant.in.cbor.builder')
}
module('nightjar-0.2.36.jar', 'com.sparrowwallet.nightjar', '0.2.36') {
module('nightjar-0.2.39.jar', 'com.sparrowwallet.nightjar', '0.2.39') {
requires('com.google.common')
requires('net.sourceforge.streamsupport')
requires('org.slf4j')
+1 -1
View File
@@ -82,7 +82,7 @@ sudo apt install -y rpm fakeroot binutils
First, assign a temporary variable in your shell for the specific release you want to build. For the current one specify:
```shell
GIT_TAG="1.7.7"
GIT_TAG="1.8.1"
```
The project can then be initially cloned as follows:
+1 -1
Submodule drongo updated: e15eb7c7f3...42f279e5e7
+1 -1
View File
@@ -21,7 +21,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.7.8</string>
<string>1.8.2</string>
<key>CFBundleSignature</key>
<string>????</string>
<!-- See https://developer.apple.com/app-store/categories/ for list of AppStore categories -->
@@ -107,6 +107,9 @@ public class AppController implements Initializable {
@FXML
private MenuItem exportWallet;
@FXML
private MenuItem renameWallet;
@FXML
private MenuItem deleteWallet;
@@ -166,6 +169,9 @@ public class AppController implements Initializable {
@FXML
private MenuItem lockAllWallets;
@FXML
private MenuItem showWalletSummary;
@FXML
private MenuItem searchWallet;
@@ -324,6 +330,8 @@ public class AppController implements Initializable {
EventManager.get().post(new OpenWalletsEvent(tabs.getScene().getWindow(), Collections.emptyList()));
});
registerShortcuts();
BitcoinUnit unit = Config.get().getBitcoinUnit();
if(unit == null) {
unit = BitcoinUnit.AUTO;
@@ -377,9 +385,11 @@ public class AppController implements Initializable {
savePSBTBinary.disableProperty().bind(saveTransaction.visibleProperty());
showPSBT.visibleProperty().bind(saveTransaction.visibleProperty().not());
exportWallet.setDisable(true);
renameWallet.disableProperty().bind(exportWallet.disableProperty());
deleteWallet.disableProperty().bind(exportWallet.disableProperty());
closeTab.setDisable(true);
lockWallet.setDisable(true);
showWalletSummary.disableProperty().bind(exportWallet.disableProperty());
searchWallet.disableProperty().bind(exportWallet.disableProperty());
refreshWallet.disableProperty().bind(Bindings.or(exportWallet.disableProperty(), Bindings.or(serverToggle.disableProperty(), AppServices.onlineProperty().not())));
sendToMany.disableProperty().bind(exportWallet.disableProperty());
@@ -404,6 +414,22 @@ public class AppController implements Initializable {
setNetworkLabel();
}
private void registerShortcuts() {
org.controlsfx.tools.Platform platform = org.controlsfx.tools.Platform.getCurrent();
if(platform == org.controlsfx.tools.Platform.OSX) {
tabs.getScene().addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if(event.isShortcutDown() && event.isAltDown() && (event.getCode() == KeyCode.LEFT || event.getCode() == KeyCode.RIGHT)) {
int currentIndex = tabs.getSelectionModel().getSelectedIndex();
if(event.getCode() == KeyCode.LEFT && currentIndex > 0) {
tabs.getSelectionModel().select(currentIndex - 1);
} else if(event.getCode() == KeyCode.RIGHT && currentIndex < tabs.getTabs().size() - 1) {
tabs.getSelectionModel().select(currentIndex + 1);
}
}
});
}
}
private void setPlatformApplicationMenu() {
org.controlsfx.tools.Platform platform = org.controlsfx.tools.Platform.getCurrent();
if(platform == org.controlsfx.tools.Platform.OSX) {
@@ -447,6 +473,7 @@ public class AppController implements Initializable {
public void showIntroduction(ActionEvent event) {
WelcomeDialog welcomeDialog = new WelcomeDialog();
welcomeDialog.initOwner(rootStack.getScene().getWindow());
Optional<Mode> optionalMode = welcomeDialog.showAndWait();
if(optionalMode.isPresent() && optionalMode.get().equals(Mode.ONLINE)) {
openPreferences(PreferenceGroup.SERVER);
@@ -534,7 +561,8 @@ public class AppController implements Initializable {
}
public void showInstallUdevMessage() {
TextAreaDialog dialog = new TextAreaDialog("sudo " + Config.get().getHwi().getAbsolutePath() + " installudevrules");
TextAreaDialog dialog = new TextAreaDialog("sudo " + Config.get().getHwi().getAbsolutePath() + " installudevrules", false);
dialog.initOwner(rootStack.getScene().getWindow());
dialog.setTitle("Install Udev Rules");
dialog.getDialogPane().setHeaderText("Installing udev rules ensures devices can connect over USB.\nThis command requires root privileges.\nOpen a shell and enter the following:");
dialog.showAndWait();
@@ -552,9 +580,11 @@ public class AppController implements Initializable {
);
AppServices.moveToActiveWindowScreen(window, 800, 450);
File file = fileChooser.showOpenDialog(window);
if (file != null) {
openTransactionFile(file);
List<File> files = fileChooser.showOpenMultipleDialog(window);
if(files != null) {
for(File file : files) {
openTransactionFile(file);
}
}
}
@@ -603,6 +633,7 @@ public class AppController implements Initializable {
public void openTransactionFromText(ActionEvent event) {
TextAreaDialog dialog = new TextAreaDialog();
dialog.initOwner(rootStack.getScene().getWindow());
dialog.setTitle("Open from text");
dialog.getDialogPane().setHeaderText("Paste a transaction or PSBT:");
Optional<String> text = dialog.showAndWait();
@@ -621,6 +652,7 @@ public class AppController implements Initializable {
public void openTransactionFromId(ActionEvent event) {
TransactionIdDialog dialog = new TransactionIdDialog();
dialog.initOwner(rootStack.getScene().getWindow());
Optional<Sha256Hash> optionalTxId = dialog.showAndWait();
if(optionalTxId.isPresent()) {
Sha256Hash txId = optionalTxId.get();
@@ -648,6 +680,7 @@ public class AppController implements Initializable {
public void openTransactionFromQR(ActionEvent event) {
QRScanDialog qrScanDialog = new QRScanDialog();
qrScanDialog.initOwner(rootStack.getScene().getWindow());
Optional<QRScanDialog.Result> optionalResult = qrScanDialog.showAndWait();
if(optionalResult.isPresent()) {
QRScanDialog.Result result = optionalResult.get();
@@ -711,6 +744,7 @@ public class AppController implements Initializable {
try {
UR ur = UR.fromBytes(transaction.bitcoinSerialize());
QRDisplayDialog qrDisplayDialog = new QRDisplayDialog(ur);
qrDisplayDialog.initOwner(rootStack.getScene().getWindow());
qrDisplayDialog.showAndWait();
} catch(Exception e) {
log.error("Error creating UR", e);
@@ -809,6 +843,7 @@ public class AppController implements Initializable {
CryptoPSBT cryptoPSBT = new CryptoPSBT(transactionTabData.getPsbt().serialize());
QRDisplayDialog qrDisplayDialog = new QRDisplayDialog(cryptoPSBT.toUR());
qrDisplayDialog.initOwner(rootStack.getScene().getWindow());
qrDisplayDialog.show();
}
}
@@ -974,6 +1009,7 @@ public class AppController implements Initializable {
public void newWallet(ActionEvent event) {
WalletNameDialog dlg = new WalletNameDialog();
dlg.initOwner(rootStack.getScene().getWindow());
Optional<WalletNameDialog.NameAndBirthDate> optNameAndBirthDate = dlg.showAndWait();
if(optNameAndBirthDate.isPresent()) {
WalletNameDialog.NameAndBirthDate nameAndBirthDate = optNameAndBirthDate.get();
@@ -995,9 +1031,11 @@ public class AppController implements Initializable {
fileChooser.setInitialDirectory(Storage.getWalletsDir());
AppServices.moveToActiveWindowScreen(window, 800, 450);
File file = fileChooser.showOpenDialog(window);
if(file != null) {
openWalletFile(file, forceSameWindow);
List<File> files = fileChooser.showOpenMultipleDialog(window);
if(files != null) {
for(File file : files) {
openWalletFile(file, forceSameWindow);
}
}
}
@@ -1023,6 +1061,7 @@ public class AppController implements Initializable {
loadWalletService.start();
} else {
WalletPasswordDialog dlg = new WalletPasswordDialog(storage.getWalletName(null), WalletPasswordDialog.PasswordRequirement.LOAD);
dlg.initOwner(rootStack.getScene().getWindow());
Optional<SecureString> optionalPassword = dlg.showAndWait();
if(optionalPassword.isEmpty()) {
return;
@@ -1091,6 +1130,7 @@ public class AppController implements Initializable {
public void importWallet(ActionEvent event) {
List<WalletForm> selectedWalletForms = getSelectedWalletForms();
WalletImportDialog dlg = new WalletImportDialog(selectedWalletForms);
dlg.initOwner(rootStack.getScene().getWindow());
Optional<Wallet> optionalWallet = dlg.showAndWait();
if(optionalWallet.isPresent()) {
Wallet wallet = optionalWallet.get();
@@ -1128,6 +1168,7 @@ public class AppController implements Initializable {
try(FileInputStream inputStream = new FileInputStream(file)) {
if(importer.isEncrypted(file) && password == null) {
WalletPasswordDialog dlg = new WalletPasswordDialog(file.getName(), WalletPasswordDialog.PasswordRequirement.LOAD);
dlg.initOwner(rootStack.getScene().getWindow());
Optional<SecureString> optionalPassword = dlg.showAndWait();
if(optionalPassword.isPresent()) {
password = optionalPassword.get();
@@ -1150,6 +1191,7 @@ public class AppController implements Initializable {
private void addImportedWallet(Wallet wallet) {
WalletNameDialog nameDlg = new WalletNameDialog(wallet.getName(), true, wallet.getBirthDate());
nameDlg.initOwner(rootStack.getScene().getWindow());
Optional<WalletNameDialog.NameAndBirthDate> optNameAndBirthDate = nameDlg.showAndWait();
if(optNameAndBirthDate.isPresent()) {
WalletNameDialog.NameAndBirthDate nameAndBirthDate = optNameAndBirthDate.get();
@@ -1195,6 +1237,7 @@ public class AppController implements Initializable {
Storage storage = new Storage(Storage.getWalletFile(wallet.getName()));
WalletPasswordDialog dlg = new WalletPasswordDialog(wallet.getName(), WalletPasswordDialog.PasswordRequirement.UPDATE_NEW);
dlg.initOwner(rootStack.getScene().getWindow());
Optional<SecureString> password = dlg.showAndWait();
if(password.isPresent()) {
if(password.get().length() == 0) {
@@ -1260,7 +1303,8 @@ public class AppController implements Initializable {
public void exportWallet(ActionEvent event) {
WalletForm selectedWalletForm = getSelectedWalletForm();
if(selectedWalletForm != null) {
WalletExportDialog dlg = new WalletExportDialog(selectedWalletForm.getWallet());
WalletExportDialog dlg = new WalletExportDialog(selectedWalletForm);
dlg.initOwner(rootStack.getScene().getWindow());
Optional<Wallet> wallet = dlg.showAndWait();
if(wallet.isPresent()) {
//Successful export
@@ -1278,6 +1322,7 @@ public class AppController implements Initializable {
private void openPreferences(PreferenceGroup preferenceGroup) {
PreferencesDialog preferencesDialog = new PreferencesDialog(preferenceGroup);
preferencesDialog.initOwner(rootStack.getScene().getWindow());
preferencesDialog.showAndWait();
configureSwitchServer();
serverToggle.setDisable(!Config.get().hasServer());
@@ -1288,8 +1333,7 @@ public class AppController implements Initializable {
WalletForm selectedWalletForm = getSelectedWalletForm();
if(selectedWalletForm != null) {
Wallet wallet = selectedWalletForm.getWallet();
if(wallet.getKeystores().size() == 1 &&
(wallet.getKeystores().get(0).hasPrivateKey() || wallet.getKeystores().get(0).getSource() == KeystoreSource.HW_USB)) {
if(wallet.getKeystores().size() == 1) {
//Can sign and verify
messageSignDialog = new MessageSignDialog(wallet);
}
@@ -1300,6 +1344,7 @@ public class AppController implements Initializable {
messageSignDialog = new MessageSignDialog();
}
messageSignDialog.initOwner(rootStack.getScene().getWindow());
messageSignDialog.showAndWait();
}
@@ -1320,6 +1365,7 @@ public class AppController implements Initializable {
}
sendToManyDialog = new SendToManyDialog(bitcoinUnit);
sendToManyDialog.initOwner(rootStack.getScene().getWindow());
sendToManyDialog.initModality(Modality.NONE);
Optional<List<Payment>> optPayments = sendToManyDialog.showAndWait();
sendToManyDialog = null;
@@ -1340,6 +1386,7 @@ public class AppController implements Initializable {
}
PrivateKeySweepDialog dialog = new PrivateKeySweepDialog(wallet);
dialog.initOwner(rootStack.getScene().getWindow());
Optional<Transaction> optTransaction = dialog.showAndWait();
optTransaction.ifPresent(transaction -> addTransactionTab(null, null, transaction));
}
@@ -1353,6 +1400,7 @@ public class AppController implements Initializable {
if(wallet.isEncrypted()) {
Wallet copy = wallet.copy();
WalletPasswordDialog dlg = new WalletPasswordDialog(copy.getMasterName(), WalletPasswordDialog.PasswordRequirement.LOAD);
dlg.initOwner(rootStack.getScene().getWindow());
Optional<SecureString> password = dlg.showAndWait();
if(password.isPresent()) {
Storage storage = selectedWalletForm.getStorage();
@@ -1366,6 +1414,7 @@ public class AppController implements Initializable {
try {
soroban.setHDWallet(copy);
CounterpartyDialog counterpartyDialog = new CounterpartyDialog(selectedWalletForm.getWalletId(), selectedWalletForm.getWallet());
counterpartyDialog.initOwner(rootStack.getScene().getWindow());
if(Config.get().isSameAppMixing()) {
counterpartyDialog.initModality(Modality.NONE);
}
@@ -1393,6 +1442,7 @@ public class AppController implements Initializable {
} else {
soroban.setHDWallet(wallet);
CounterpartyDialog counterpartyDialog = new CounterpartyDialog(selectedWalletForm.getWalletId(), selectedWalletForm.getWallet());
counterpartyDialog.initOwner(rootStack.getScene().getWindow());
if(Config.get().isSameAppMixing()) {
counterpartyDialog.initModality(Modality.NONE);
}
@@ -1400,6 +1450,7 @@ public class AppController implements Initializable {
}
} else {
CounterpartyDialog counterpartyDialog = new CounterpartyDialog(selectedWalletForm.getWalletId(), selectedWalletForm.getWallet());
counterpartyDialog.initOwner(rootStack.getScene().getWindow());
if(Config.get().isSameAppMixing()) {
counterpartyDialog.initModality(Modality.NONE);
}
@@ -1412,6 +1463,7 @@ public class AppController implements Initializable {
WalletForm selectedWalletForm = getSelectedWalletForm();
if(selectedWalletForm != null) {
PayNymDialog payNymDialog = new PayNymDialog(selectedWalletForm.getWalletId());
payNymDialog.initOwner(rootStack.getScene().getWindow());
payNymDialog.showAndWait();
}
}
@@ -1457,13 +1509,52 @@ public class AppController implements Initializable {
TabPane subTabs = (TabPane) selectedTab.getContent();
List<WalletForm> walletForms = subTabs.getTabs().stream().map(subTab -> ((WalletTabData)subTab.getUserData()).getWalletForm()).collect(Collectors.toList());
if(!walletForms.isEmpty()) {
SearchWalletDialog searchWalletDialog = new SearchWalletDialog(walletForms);
Optional<Entry> optEntry = searchWalletDialog.showAndWait();
if(optEntry.isPresent()) {
Entry entry = optEntry.get();
EventManager.get().post(new FunctionActionEvent(entry.getWalletFunction(), entry.getWallet()));
Platform.runLater(() -> EventManager.get().post(new SelectEntryEvent(entry)));
}
searchWallets(walletForms);
}
}
}
}
public void searchAllWallets(ActionEvent event) {
List<WalletForm> allWalletForms = new ArrayList<>();
for(Tab tab : tabs.getTabs()) {
TabData tabData = (TabData)tab.getUserData();
if(tabData instanceof WalletTabData) {
TabPane subTabs = (TabPane)tab.getContent();
allWalletForms.addAll(subTabs.getTabs().stream().map(subTab -> ((WalletTabData)subTab.getUserData()).getWalletForm())
.filter(walletForm -> walletForm.getWallet().isValid() && !walletForm.isLocked()).collect(Collectors.toList()));
}
}
if(allWalletForms.isEmpty()) {
showErrorDialog("No wallets", "There are no open and unlocked wallets to search.");
} else {
searchWallets(allWalletForms);
}
}
private void searchWallets(List<WalletForm> walletForms) {
SearchWalletDialog searchWalletDialog = new SearchWalletDialog(walletForms);
searchWalletDialog.initOwner(rootStack.getScene().getWindow());
Optional<Entry> optEntry = searchWalletDialog.showAndWait();
if(optEntry.isPresent()) {
Entry entry = optEntry.get();
EventManager.get().post(new FunctionActionEvent(entry.getWalletFunction(), entry.getWallet()));
Platform.runLater(() -> EventManager.get().post(new SelectEntryEvent(entry)));
}
}
public void showWalletSummary(ActionEvent event) {
Tab selectedTab = tabs.getSelectionModel().getSelectedItem();
if(selectedTab != null) {
TabData tabData = (TabData) selectedTab.getUserData();
if(tabData instanceof WalletTabData) {
TabPane subTabs = (TabPane) selectedTab.getContent();
List<WalletForm> walletForms = subTabs.getTabs().stream().map(subTab -> ((WalletTabData)subTab.getUserData()).getWalletForm()).collect(Collectors.toList());
if(!walletForms.isEmpty()) {
WalletSummaryDialog walletSummaryDialog = new WalletSummaryDialog(walletForms);
walletSummaryDialog.initOwner(rootStack.getScene().getWindow());
walletSummaryDialog.showAndWait();
}
}
}
@@ -1635,6 +1726,9 @@ public class AppController implements Initializable {
subTabLabel.setGraphic(getSubTabGlyph(wallet));
subTabLabel.setContentDisplay(ContentDisplay.TOP);
subTabLabel.setAlignment(Pos.TOP_CENTER);
if(isSubTabLabelTruncated(subTabLabel, label)) {
subTabLabel.setTooltip(new Tooltip(label));
}
subTab.setGraphic(subTabLabel);
FXMLLoader walletLoader = new FXMLLoader(getClass().getResource("wallet/wallet.fxml"));
subTab.setContent(walletLoader.load());
@@ -1983,6 +2077,7 @@ public class AppController implements Initializable {
private void renameWallet(WalletForm selectedWalletForm) {
WalletNameDialog walletNameDialog = new WalletNameDialog(selectedWalletForm.getMasterWallet().getName(), false, null, true);
walletNameDialog.initOwner(rootStack.getScene().getWindow());
Optional<WalletNameDialog.NameAndBirthDate> optName = walletNameDialog.showAndWait();
if(optName.isPresent()) {
File walletFile = Storage.getWalletFile(optName.get().getName() + "." + PersistenceType.DB.getExtension());
@@ -2011,6 +2106,7 @@ public class AppController implements Initializable {
Storage storage = selectedWalletForm.getStorage();
if(selectedWalletForm.getMasterWallet().isEncrypted()) {
WalletPasswordDialog dlg = new WalletPasswordDialog(selectedWalletForm.getWallet().getMasterName(), WalletPasswordDialog.PasswordRequirement.LOAD);
dlg.initOwner(rootStack.getScene().getWindow());
Optional<SecureString> password = dlg.showAndWait();
if(password.isPresent()) {
Storage.KeyDerivationService keyDerivationService = new Storage.KeyDerivationService(storage, password.get(), true);
@@ -2078,10 +2174,16 @@ public class AppController implements Initializable {
rename.setOnAction(event -> {
Label subTabLabel = (Label)subTab.getGraphic();
WalletLabelDialog walletLabelDialog = new WalletLabelDialog(subTabLabel.getText());
walletLabelDialog.initOwner(rootStack.getScene().getWindow());
Optional<String> optLabel = walletLabelDialog.showAndWait();
if(optLabel.isPresent()) {
String label = optLabel.get();
subTabLabel.setText(label);
if(isSubTabLabelTruncated(subTabLabel, label)) {
subTabLabel.setTooltip(new Tooltip(label));
} else {
subTabLabel.setTooltip(null);
}
Wallet renamedWallet = AppServices.get().getWallet(walletId);
renamedWallet.setLabel(label);
@@ -2106,9 +2208,18 @@ public class AppController implements Initializable {
contextMenu.getItems().add(delete);
}
contextMenu.setOnShowing(event -> {
Wallet renameWallet = AppServices.get().getWallet(walletId);
rename.setDisable(!renameWallet.isValid());
});
return contextMenu;
}
private boolean isSubTabLabelTruncated(Label subTabLabel, String label) {
return TextUtils.computeTextWidth(subTabLabel.getFont(), label, 0.0D) > (90-6);
}
private void configureSwitchServer() {
switchServer.getItems().clear();
@@ -24,7 +24,6 @@ import com.sparrowwallet.sparrow.control.TrayManager;
import com.sparrowwallet.sparrow.event.*;
import com.sparrowwallet.sparrow.io.*;
import com.sparrowwallet.sparrow.net.*;
import com.sparrowwallet.sparrow.paynym.PayNymService;
import com.sparrowwallet.sparrow.soroban.SorobanServices;
import com.sparrowwallet.sparrow.whirlpool.WhirlpoolServices;
import javafx.application.Application;
@@ -61,7 +60,6 @@ import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.net.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
@@ -85,8 +83,10 @@ public class AppServices {
private static final String TOR_DEFAULT_PROXY_CIRCUIT_ID = "default";
public static final List<Integer> TARGET_BLOCKS_RANGE = List.of(1, 2, 3, 4, 5, 10, 25, 50);
public static final List<Long> FEE_RATES_RANGE = List.of(1L, 2L, 4L, 8L, 16L, 32L, 64L, 128L, 256L, 512L, 1024L);
public static final List<Long> LONG_FEE_RATES_RANGE = List.of(1L, 2L, 4L, 8L, 16L, 32L, 64L, 128L, 256L, 512L, 1024L, 2048L, 4096L, 8192L);
public static final List<Long> FEE_RATES_RANGE = LONG_FEE_RATES_RANGE.subList(0, LONG_FEE_RATES_RANGE.size() - 3);
public static final double FALLBACK_FEE_RATE = 20000d / 1000;
public static final double TESTNET_FALLBACK_FEE_RATE = 1000d / 1000;
private static AppServices INSTANCE;
@@ -96,7 +96,7 @@ public class AppServices {
private InteractionServices interactionServices;
private static PayNymService payNymService;
private static HttpClientService httpClientService;
private final Application application;
@@ -247,8 +247,8 @@ public class AppServices {
versionCheckService.cancel();
}
if(payNymService != null) {
PayNymService.ShutdownService shutdownService = new PayNymService.ShutdownService(payNymService);
if(httpClientService != null) {
HttpClientService.ShutdownService shutdownService = new HttpClientService.ShutdownService(httpClientService);
shutdownService.start();
}
@@ -513,18 +513,18 @@ public class AppServices {
return get().interactionServices;
}
public static PayNymService getPayNymService() {
if(payNymService == null) {
public static HttpClientService getHttpClientService() {
if(httpClientService == null) {
HostAndPort torProxy = getTorProxy();
payNymService = new PayNymService(torProxy);
httpClientService = new HttpClientService(torProxy);
} else {
HostAndPort torProxy = getTorProxy();
if(!Objects.equals(payNymService.getTorProxy(), torProxy)) {
payNymService.setTorProxy(getTorProxy());
if(!Objects.equals(httpClientService.getTorProxy(), torProxy)) {
httpClientService.setTorProxy(getTorProxy());
}
}
return payNymService;
return httpClientService;
}
public static HostAndPort getTorProxy() {
@@ -565,8 +565,17 @@ public class AppServices {
return windowIcon;
}
public static boolean isReducedWindowHeight() {
Window activeWindow = getActiveWindow();
return (activeWindow != null && activeWindow.getHeight() < getReducedWindowHeight());
}
public static boolean isReducedWindowHeight(Node node) {
return (node.getScene() != null && node.getScene().getWindow().getHeight() < 768);
return (node.getScene() != null && node.getScene().getWindow().getHeight() < getReducedWindowHeight());
}
private static double getReducedWindowHeight() {
return org.controlsfx.tools.Platform.getCurrent() != org.controlsfx.tools.Platform.OSX ? 802d : 768d; //Check for menu bar of ~34px
}
public Application getApplication() {
@@ -653,15 +662,19 @@ public class AppServices {
public static Double getDefaultFeeRate() {
int defaultTarget = TARGET_BLOCKS_RANGE.get((TARGET_BLOCKS_RANGE.size() / 2) - 1);
return getTargetBlockFeeRates() == null ? FALLBACK_FEE_RATE : getTargetBlockFeeRates().get(defaultTarget);
return getTargetBlockFeeRates() == null ? getFallbackFeeRate() : getTargetBlockFeeRates().get(defaultTarget);
}
public static Double getMinimumFeeRate() {
Optional<Double> optMinFeeRate = getTargetBlockFeeRates().values().stream().min(Double::compareTo);
Double minRate = optMinFeeRate.orElse(FALLBACK_FEE_RATE);
Double minRate = optMinFeeRate.orElse(getFallbackFeeRate());
return Math.max(minRate, Transaction.DUST_RELAY_TX_FEE);
}
public static double getFallbackFeeRate() {
return Network.get() == Network.MAINNET ? FALLBACK_FEE_RATE : TESTNET_FALLBACK_FEE_RATE;
}
public static Map<Integer, Double> getTargetBlockFeeRates() {
return targetBlockFeeRates;
}
@@ -949,6 +962,7 @@ public class AppServices {
Storage storage = AppServices.get().getOpenWallets().get(wallet);
Wallet copy = wallet.copy();
WalletPasswordDialog dlg = new WalletPasswordDialog(copy.getMasterName(), WalletPasswordDialog.PasswordRequirement.LOAD);
dlg.initOwner(getActiveWindow());
Optional<SecureString> password = dlg.showAndWait();
if(password.isPresent()) {
Storage.KeyDerivationService keyDerivationService = new Storage.KeyDerivationService(storage, password.get(), true);
@@ -1011,6 +1025,7 @@ public class AppServices {
wallet = wallets.iterator().next();
} else {
ChoiceDialog<Wallet> walletChoiceDialog = new ChoiceDialog<>(wallets.iterator().next(), wallets);
walletChoiceDialog.initOwner(getActiveWindow());
walletChoiceDialog.setTitle("Choose Wallet");
walletChoiceDialog.setHeaderText("Choose a wallet to " + actionDescription);
Image image = new Image("/image/sparrow-small.png");
@@ -15,13 +15,13 @@ import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.sparrowwallet.sparrow.AppServices.moveToActiveWindowScreen;
import static com.sparrowwallet.sparrow.AppServices.setStageIcon;
import static com.sparrowwallet.sparrow.AppServices.*;
public class DefaultInteractionServices implements InteractionServices {
@Override
public Optional<ButtonType> showAlert(String title, String content, Alert.AlertType alertType, Node graphic, ButtonType... buttons) {
Alert alert = new Alert(alertType, content, buttons);
alert.initOwner(getActiveWindow());
setStageIcon(alert.getDialogPane().getScene().getWindow());
alert.getDialogPane().getScene().getStylesheets().add(AppServices.class.getResource("general.css").toExternalForm());
alert.setTitle(title);
@@ -62,6 +62,7 @@ public class DefaultInteractionServices implements InteractionServices {
@Override
public Optional<String> requestPassphrase(String walletName, Keystore keystore) {
KeystorePassphraseDialog passphraseDialog = new KeystorePassphraseDialog(walletName, keystore);
passphraseDialog.initOwner(getActiveWindow());
return passphraseDialog.showAndWait();
}
}
@@ -45,6 +45,7 @@ public class SparrowDesktop extends Application {
GlyphFontRegistry.register(new FontAwesome5());
GlyphFontRegistry.register(new FontAwesome5Brands());
Font.loadFont(AppServices.class.getResourceAsStream("/font/RobotoMono-Regular.ttf"), 13);
Font.loadFont(AppServices.class.getResourceAsStream("/font/RobotoMono-Italic.ttf"), 11);
URL.setURLStreamHandlerFactory(protocol -> WalletIcon.PROTOCOL.equals(protocol) ? new WalletIcon.WalletIconStreamHandler() : null);
AppServices.initialize(this);
@@ -18,7 +18,7 @@ import java.util.*;
public class SparrowWallet {
public static final String APP_ID = "com.sparrowwallet.sparrow";
public static final String APP_NAME = "Sparrow";
public static final String APP_VERSION = "1.7.8";
public static final String APP_VERSION = "1.8.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";
@@ -12,6 +12,7 @@ public enum UnitFormat {
private final DecimalFormat satsFormat = new DecimalFormat("#,##0", getDecimalFormatSymbols());
private final DecimalFormat tableBtcFormat = new DecimalFormat("0.00000000", getDecimalFormatSymbols());
private final DecimalFormat currencyFormat = new DecimalFormat("#,##0.00", getDecimalFormatSymbols());
private final DecimalFormat tableCurrencyFormat = new DecimalFormat("0.00", getDecimalFormatSymbols());
public DecimalFormat getBtcFormat() {
btcFormat.setMaximumFractionDigits(8);
@@ -30,6 +31,10 @@ public enum UnitFormat {
return currencyFormat;
}
public DecimalFormat getTableCurrencyFormat() {
return tableCurrencyFormat;
}
public DecimalFormatSymbols getDecimalFormatSymbols() {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
@@ -42,6 +47,7 @@ public enum UnitFormat {
private final DecimalFormat satsFormat = new DecimalFormat("#,##0", getDecimalFormatSymbols());
private final DecimalFormat tableBtcFormat = new DecimalFormat("0.00000000", getDecimalFormatSymbols());
private final DecimalFormat currencyFormat = new DecimalFormat("#,##0.00", getDecimalFormatSymbols());
private final DecimalFormat tableCurrencyFormat = new DecimalFormat("0.00", getDecimalFormatSymbols());
public DecimalFormat getBtcFormat() {
btcFormat.setMaximumFractionDigits(8);
@@ -60,6 +66,10 @@ public enum UnitFormat {
return currencyFormat;
}
public DecimalFormat getTableCurrencyFormat() {
return tableCurrencyFormat;
}
public DecimalFormatSymbols getDecimalFormatSymbols() {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
@@ -78,6 +88,8 @@ public enum UnitFormat {
public abstract DecimalFormat getCurrencyFormat();
public abstract DecimalFormat getTableCurrencyFormat();
public String formatBtcValue(Long amount) {
return getBtcFormat().format(amount.doubleValue() / Transaction.SATOSHIS_PER_BITCOIN);
}
@@ -94,6 +106,10 @@ public enum UnitFormat {
return getCurrencyFormat().format(amount);
}
public String tableFormatCurrencyValue(double amount) {
return getTableCurrencyFormat().format(amount);
}
public String getGroupingSeparator() {
return Character.toString(getDecimalFormatSymbols().getGroupingSeparator());
}
@@ -22,6 +22,7 @@ public class WelcomeDialog extends Dialog<Mode> {
dialogPane.setPrefWidth(600);
dialogPane.setPrefHeight(520);
dialogPane.setMinHeight(dialogPane.getPrefHeight());
AppServices.moveToActiveWindowScreen(this);
dialogPane.getStylesheets().add(AppServices.class.getResource("welcome.css").toExternalForm());
@@ -17,6 +17,8 @@ import org.controlsfx.glyphfont.Glyph;
import java.util.ArrayList;
import java.util.List;
import static com.sparrowwallet.drongo.wallet.StandardAccount.*;
public class AddAccountDialog extends Dialog<List<StandardAccount>> {
private final ComboBox<StandardAccount> standardAccountCombo;
private boolean discoverAccounts = false;
@@ -53,13 +55,15 @@ public class AddAccountDialog extends Dialog<List<StandardAccount>> {
List<StandardAccount> availableAccounts = new ArrayList<>();
for(StandardAccount standardAccount : StandardAccount.values()) {
if(!existingIndexes.contains(standardAccount.getAccountNumber()) && !StandardAccount.WHIRLPOOL_ACCOUNTS.contains(standardAccount)) {
if(!existingIndexes.contains(standardAccount.getAccountNumber()) && !StandardAccount.isWhirlpoolAccount(standardAccount)) {
availableAccounts.add(standardAccount);
}
}
if(WhirlpoolServices.canWalletMix(masterWallet) && !masterWallet.isWhirlpoolMasterWallet()) {
availableAccounts.add(StandardAccount.WHIRLPOOL_PREMIX);
availableAccounts.add(WHIRLPOOL_PREMIX);
} else if(WhirlpoolServices.canWatchPostmix(masterWallet) && !existingIndexes.contains(WHIRLPOOL_POSTMIX.getAccountNumber())) {
availableAccounts.add(WHIRLPOOL_POSTMIX);
}
final ButtonType discoverButtonType = new javafx.scene.control.ButtonType("Discover", ButtonBar.ButtonData.LEFT);
@@ -82,10 +86,14 @@ public class AddAccountDialog extends Dialog<List<StandardAccount>> {
return "None Available";
}
if(StandardAccount.WHIRLPOOL_ACCOUNTS.contains(account)) {
if(account == WHIRLPOOL_PREMIX) {
return "Whirlpool Accounts";
}
if(account == WHIRLPOOL_POSTMIX) {
return "Whirlpool Postmix (No mixing)";
}
return account.getName();
}
@@ -40,7 +40,7 @@ public class AddressCell extends TreeTableCell<Entry, UtxoEntry.AddressStatus> {
if(utxoEntry != null) {
Address address = addressStatus.getAddress();
setText(address.toString());
setContextMenu(new EntryCell.AddressContextMenu(address, utxoEntry.getOutputDescriptor(), new NodeEntry(utxoEntry.getWallet(), utxoEntry.getNode()), false));
setContextMenu(new EntryCell.AddressContextMenu(address, utxoEntry.getOutputDescriptor(), new NodeEntry(utxoEntry.getWallet(), utxoEntry.getNode()), false, getTreeTableView()));
Tooltip tooltip = new Tooltip();
tooltip.setShowDelay(Duration.millis(250));
tooltip.setText(getTooltipText(utxoEntry, addressStatus.isDuplicate(), addressStatus.isDustAttack()));
@@ -4,8 +4,7 @@ import com.google.common.base.Throwables;
import com.sparrowwallet.drongo.KeyDerivation;
import com.sparrowwallet.drongo.crypto.ChildNumber;
import com.sparrowwallet.drongo.protocol.Sha256Hash;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.*;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.event.KeystoreImportEvent;
@@ -36,6 +35,7 @@ import org.slf4j.LoggerFactory;
import javax.smartcardio.CardException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import static com.sparrowwallet.sparrow.io.CardApi.isReaderAvailable;
@@ -74,21 +74,21 @@ public class CardImportPane extends TitledDescriptionPane {
return;
}
if(pin.get().length() < 6) {
setDescription(pin.get().isEmpty() ? "Enter PIN code" : "PIN code too short");
setContent(getPinAndDerivationEntry());
showHideLink.setVisible(false);
setExpanded(true);
importButton.setDisable(false);
return;
}
StringProperty messageProperty = new SimpleStringProperty();
messageProperty.addListener((observable, oldValue, newValue) -> {
Platform.runLater(() -> setDescription(newValue));
});
try {
if(pin.get().length() < importer.getWalletModel().getMinPinLength()) {
setDescription(pin.get().isEmpty() ? (!importer.getWalletModel().hasDefaultPin() && !importer.isInitialized() ? "Choose a PIN code" : "Enter PIN code") : "PIN code too short");
setContent(getPinAndDerivationEntry());
showHideLink.setVisible(false);
setExpanded(true);
importButton.setDisable(false);
return;
}
if(!importer.isInitialized()) {
setDescription("Card not initialized");
setContent(getInitializationPanel(messageProperty));
@@ -121,6 +121,75 @@ public class CardImportPane extends TitledDescriptionPane {
}
private Node getInitializationPanel(StringProperty messageProperty) {
if(importer.getWalletModel().requiresSeedInitialization()) {
return getSeedInitializationPanel(messageProperty);
}
return getEntropyInitializationPanel(messageProperty);
}
private Node getSeedInitializationPanel(StringProperty messageProperty) {
VBox confirmationBox = new VBox(5);
CustomPasswordField confirmationPin = new ViewPasswordField();
confirmationPin.setPromptText("Re-enter chosen PIN");
confirmationBox.getChildren().add(confirmationPin);
Button initializeButton = new Button("Initialize");
initializeButton.setDefaultButton(true);
initializeButton.setOnAction(event -> {
initializeButton.setDisable(true);
if(!pin.get().equals(confirmationPin.getText())) {
setError("PIN Error", "The confirmation PIN did not match");
return;
}
int pinSize = pin.get().length();
if(pinSize < importer.getWalletModel().getMinPinLength() || pinSize > importer.getWalletModel().getMaxPinLength()) {
setError("PIN Error", "PIN length must be between " + importer.getWalletModel().getMinPinLength() + " and " + importer.getWalletModel().getMaxPinLength() + " characters");
return;
}
SeedEntryDialog seedEntryDialog = new SeedEntryDialog(importer.getWalletModel().toDisplayString() + " Seed Words", 12);
seedEntryDialog.initOwner(this.getScene().getWindow());
Optional<List<String>> optWords = seedEntryDialog.showAndWait();
if(optWords.isPresent()) {
try {
List<String> mnemonicWords = optWords.get();
Bip39MnemonicCode.INSTANCE.check(mnemonicWords);
DeterministicSeed seed = new DeterministicSeed(mnemonicWords, "", System.currentTimeMillis(), DeterministicSeed.Type.BIP39);
byte[] seedBytes = seed.getSeedBytes();
CardInitializationService cardInitializationService = new CardInitializationService(importer, pin.get(), seedBytes, messageProperty);
cardInitializationService.setOnSucceeded(successEvent -> {
AppServices.showSuccessDialog("Card Initialized", "The card was successfully initialized.\n\nYou can now import the keystore.");
setDescription("Leave card on reader");
setExpanded(false);
importButton.setDisable(false);
});
cardInitializationService.setOnFailed(failEvent -> {
log.error("Error initializing card", failEvent.getSource().getException());
AppServices.showErrorDialog("Card Initialization Failed", "The card was not initialized.\n\n" + failEvent.getSource().getException().getMessage());
initializeButton.setDisable(false);
});
cardInitializationService.start();
} catch(MnemonicException e) {
log.error("Invalid seed entered", e);
AppServices.showErrorDialog("Invalid seed entered", "The seed was invalid.\n\n" + e.getMessage());
initializeButton.setDisable(false);
}
} else {
initializeButton.setDisable(false);
}
});
HBox contentBox = new HBox(20);
contentBox.getChildren().addAll(confirmationBox, initializeButton);
contentBox.setPadding(new Insets(10, 30, 10, 30));
HBox.setHgrow(confirmationBox, Priority.ALWAYS);
return contentBox;
}
private Node getEntropyInitializationPanel(StringProperty messageProperty) {
VBox initTypeBox = new VBox(5);
RadioButton automatic = new RadioButton("Automatic (Recommended)");
RadioButton advanced = new RadioButton("Advanced");
@@ -1,5 +1,6 @@
package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.drongo.wallet.WalletModel;
import com.sparrowwallet.sparrow.AppServices;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
@@ -22,7 +23,7 @@ public class CardPinDialog extends Dialog<CardPinDialog.CardPinChange> {
private final CheckBox backupFirst;
private final ButtonType okButtonType;
public CardPinDialog(boolean backupOnly) {
public CardPinDialog(WalletModel walletModel, boolean backupOnly) {
this.existingPin = new ViewPasswordField();
this.newPin = new ViewPasswordField();
this.newPinConfirm = new ViewPasswordField();
@@ -71,7 +72,11 @@ public class CardPinDialog extends Dialog<CardPinDialog.CardPinChange> {
if(backupOnly) {
fieldset.getChildren().addAll(currentField);
} else {
fieldset.getChildren().addAll(currentField, newField, confirmField, backupField);
fieldset.getChildren().addAll(currentField, newField, confirmField);
}
if(walletModel.supportsBackup()) {
fieldset.getChildren().add(backupField);
}
form.getChildren().add(fieldset);
@@ -80,8 +85,8 @@ public class CardPinDialog extends Dialog<CardPinDialog.CardPinChange> {
ValidationSupport validationSupport = new ValidationSupport();
Platform.runLater( () -> {
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
validationSupport.registerValidator(existingPin, (Control c, String newValue) -> ValidationResult.fromErrorIf(c, "Incorrect PIN length", existingPin.getText().length() < 6 || existingPin.getText().length() > 32));
validationSupport.registerValidator(newPin, (Control c, String newValue) -> ValidationResult.fromErrorIf(c, "Incorrect PIN length", newPin.getText().length() < 6 || newPin.getText().length() > 32));
validationSupport.registerValidator(existingPin, (Control c, String newValue) -> ValidationResult.fromErrorIf(c, "Incorrect PIN length", existingPin.getText().length() < walletModel.getMinPinLength() || existingPin.getText().length() > walletModel.getMaxPinLength()));
validationSupport.registerValidator(newPin, (Control c, String newValue) -> ValidationResult.fromErrorIf(c, "Incorrect PIN length", newPin.getText().length() < walletModel.getMinPinLength() || newPin.getText().length() > walletModel.getMaxPinLength()));
validationSupport.registerValidator(newPinConfirm, (Control c, String newValue) -> ValidationResult.fromErrorIf(c, "PIN confirmation does not match", !newPinConfirm.getText().equals(newPin.getText())));
});
@@ -89,8 +94,8 @@ public class CardPinDialog extends Dialog<CardPinDialog.CardPinChange> {
dialogPane.getButtonTypes().addAll(okButtonType);
Button okButton = (Button) dialogPane.lookupButton(okButtonType);
okButton.setPrefWidth(130);
BooleanBinding isInvalid = Bindings.createBooleanBinding(() -> existingPin.getText().length() < 6 || existingPin.getText().length() > 32
|| newPin.getText().length() < 6 || newPin.getText().length() > 32
BooleanBinding isInvalid = Bindings.createBooleanBinding(() -> existingPin.getText().length() < walletModel.getMinPinLength() || existingPin.getText().length() > walletModel.getMaxPinLength()
|| newPin.getText().length() < walletModel.getMinPinLength() || newPin.getText().length() > walletModel.getMaxPinLength()
|| !newPin.getText().equals(newPinConfirm.getText()),
existingPin.textProperty(), newPin.textProperty(), newPinConfirm.textProperty());
okButton.disableProperty().bind(isInvalid);
@@ -70,7 +70,7 @@ class CoinCell extends TreeTableCell<Entry, Number> implements ConfirmationsList
setContextMenu(contextMenu);
if(entry instanceof TransactionEntry transactionEntry) {
tooltip.showConfirmations(transactionEntry.confirmationsProperty());
tooltip.showConfirmations(transactionEntry.confirmationsProperty(), transactionEntry.isCoinbase());
if(transactionEntry.isConfirming()) {
ConfirmationProgressIndicator arc = new ConfirmationProgressIndicator(transactionEntry.getConfirmations());
@@ -119,6 +119,7 @@ class CoinCell extends TreeTableCell<Entry, Number> implements ConfirmationsList
private static final class CoinTooltip extends Tooltip {
private final IntegerProperty confirmationsProperty = new SimpleIntegerProperty();
private boolean showConfirmations;
private boolean isCoinbase;
private String value;
public void setValue(String value) {
@@ -126,8 +127,9 @@ class CoinCell extends TreeTableCell<Entry, Number> implements ConfirmationsList
setTooltipText();
}
public void showConfirmations(IntegerProperty txEntryConfirmationsProperty) {
public void showConfirmations(IntegerProperty txEntryConfirmationsProperty, boolean coinbase) {
showConfirmations = true;
isCoinbase = coinbase;
int confirmations = txEntryConfirmationsProperty.get();
if(confirmations < BlockTransactionHash.BLOCKS_TO_FULLY_CONFIRM) {
@@ -155,7 +157,7 @@ class CoinCell extends TreeTableCell<Entry, Number> implements ConfirmationsList
if(confirmations == 0) {
return "Unconfirmed in mempool";
} else if(confirmations < BlockTransactionHash.BLOCKS_TO_FULLY_CONFIRM) {
return confirmations + " confirmation" + (confirmations == 1 ? "" : "s");
return confirmations + " confirmation" + (confirmations == 1 ? "" : "s") + (isCoinbase ? ", immature coinbase" : "");
} else {
return BlockTransactionHash.BLOCKS_TO_FULLY_CONFIRM + "+ confirmations";
}
@@ -2,6 +2,7 @@ package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.drongo.BitcoinUnit;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.CurrencyRate;
import com.sparrowwallet.sparrow.UnitFormat;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.EventManager;
@@ -17,6 +18,7 @@ import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.layout.StackPane;
@@ -28,6 +30,7 @@ import java.util.Optional;
public class CoinTreeTable extends TreeTableView<Entry> {
private BitcoinUnit bitcoinUnit;
private UnitFormat unitFormat;
private CurrencyRate currencyRate;
public BitcoinUnit getBitcoinUnit() {
return bitcoinUnit;
@@ -64,6 +67,18 @@ public class CoinTreeTable extends TreeTableView<Entry> {
}
}
public CurrencyRate getCurrencyRate() {
return currencyRate;
}
public void setCurrencyRate(CurrencyRate currencyRate) {
this.currencyRate = currencyRate;
if(!getChildren().isEmpty()) {
refresh();
}
}
public void updateHistoryStatus(WalletHistoryStatusEvent event) {
if(getRoot() != null) {
Entry entry = getRoot().getValue();
@@ -94,6 +109,7 @@ public class CoinTreeTable extends TreeTableView<Entry> {
hyperlink.setTranslateY(30);
hyperlink.setOnAction(event -> {
WalletBirthDateDialog dlg = new WalletBirthDateDialog(wallet.getBirthDate(), false);
dlg.initOwner(this.getScene().getWindow());
Optional<Date> optDate = dlg.showAndWait();
if(optDate.isPresent()) {
Storage storage = AppServices.get().getOpenWallets().get(wallet);
@@ -119,4 +135,12 @@ public class CoinTreeTable extends TreeTableView<Entry> {
stackPane.setAlignment(Pos.CENTER);
return stackPane;
}
public void setSortColumn(int columnIndex, TreeTableColumn.SortType sortType) {
if(columnIndex >= 0 && columnIndex < getColumns().size() && getSortOrder().isEmpty() && !getRoot().getChildren().isEmpty()) {
TreeTableColumn<Entry, ?> column = getColumns().get(columnIndex);
column.setSortType(sortType == null ? TreeTableColumn.SortType.DESCENDING : sortType);
getSortOrder().add(column);
}
}
}
@@ -10,12 +10,16 @@ import javafx.scene.control.MenuItem;
import javafx.scene.control.Tooltip;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
public class CopyableCoinLabel extends CopyableLabel {
private final LongProperty valueProperty = new SimpleLongProperty(-1);
private final Tooltip tooltip;
private final CoinContextMenu contextMenu;
private BitcoinUnit bitcoinUnit;
public CopyableCoinLabel() {
this("Unknown");
}
@@ -23,6 +27,21 @@ public class CopyableCoinLabel extends CopyableLabel {
public CopyableCoinLabel(String text) {
super(text);
valueProperty().addListener((observable, oldValue, newValue) -> setValueAsText((Long)newValue, Config.get().getUnitFormat(), Config.get().getBitcoinUnit()));
setOnMouseClicked(event -> {
if(bitcoinUnit == null) {
bitcoinUnit = Config.get().getBitcoinUnit();
}
if(bitcoinUnit == BitcoinUnit.SATOSHIS) {
bitcoinUnit = BitcoinUnit.BTC;
} else {
bitcoinUnit = BitcoinUnit.SATOSHIS;
}
refresh(Config.get().getUnitFormat(), bitcoinUnit);
});
tooltip = new Tooltip();
contextMenu = new CoinContextMenu();
}
@@ -63,6 +82,8 @@ public class CopyableCoinLabel extends CopyableLabel {
unit = (value >= BitcoinUnit.getAutoThreshold() ? BitcoinUnit.BTC : BitcoinUnit.SATOSHIS);
}
this.bitcoinUnit = unit;
if(unit.equals(BitcoinUnit.BTC)) {
tooltip.setText(satsValue);
setText(btcValue);
@@ -91,6 +91,7 @@ public abstract class DeviceDialog<R> extends Dialog<R> {
dialogPane.setPrefWidth(500);
dialogPane.setPrefHeight(360);
dialogPane.setMinHeight(dialogPane.getPrefHeight());
AppServices.moveToActiveWindowScreen(this);
setResultConverter(dialogButton -> dialogButton == cancelButtonType ? null : getResult());
@@ -673,8 +673,8 @@ public class DevicePane extends TitledDescriptionPane {
try {
CardApi cardApi = CardApi.getCardApi(device.getModel(), pin.get());
if(!cardApi.isInitialized()) {
if(pin.get().length() < 6) {
setDescription(pin.get().isEmpty() ? "Enter PIN code" : "PIN code too short");
if(pin.get().length() < device.getModel().getMinPinLength()) {
setDescription(pin.get().isEmpty() ? (device.getModel().hasDefaultPin() ? "Enter PIN code" : "Choose a PIN code") : "PIN code too short");
setContent(getCardPinEntry(importButton));
showHideLink.setVisible(false);
setExpanded(true);
@@ -795,7 +795,7 @@ public class DevicePane extends TitledDescriptionPane {
}
private void handleCardOperation(Service<?> service, ButtonBase operationButton, String operationDescription, boolean pinRequired, EventHandler<WorkerStateEvent> successHandler) {
if(pinRequired && pin.get().length() < 6) {
if(pinRequired && pin.get().length() < device.getModel().getMinPinLength()) {
setDescription(pin.get().isEmpty() ? "Enter PIN code" : "PIN code too short");
setContent(getCardPinEntry(operationButton));
showHideLink.setVisible(false);
@@ -940,7 +940,7 @@ public class DevicePane extends TitledDescriptionPane {
try {
CardApi cardApi = CardApi.getCardApi(device.getModel(), pin.get());
if(!cardApi.isInitialized()) {
if(pin.get().length() < 6) {
if(pin.get().length() < device.getModel().getMinPinLength()) {
setDescription(pin.get().isEmpty() ? "Enter PIN code" : "PIN code too short");
setContent(getCardPinEntry(getAddressButton));
showHideLink.setVisible(false);
@@ -1047,6 +1047,75 @@ public class DevicePane extends TitledDescriptionPane {
}
private Node getCardInitializationPanel(CardApi cardApi, ButtonBase operationButton, DeviceOperation deviceOperation) {
if(device.getModel().requiresSeedInitialization()) {
return getCardSeedInitializationPanel(cardApi, operationButton, deviceOperation);
}
return getCardEntropyInitializationPanel(cardApi, operationButton, deviceOperation);
}
private Node getCardSeedInitializationPanel(CardApi cardApi, ButtonBase operationButton, DeviceOperation deviceOperation) {
VBox confirmationBox = new VBox(5);
CustomPasswordField confirmationPin = new ViewPasswordField();
confirmationPin.setPromptText("Re-enter chosen PIN");
confirmationBox.getChildren().add(confirmationPin);
Button initializeButton = new Button("Initialize");
initializeButton.setDefaultButton(true);
initializeButton.setOnAction(event -> {
initializeButton.setDisable(true);
if(!pin.get().equals(confirmationPin.getText())) {
setError("PIN Error", "The confirmation PIN did not match");
return;
}
int pinSize = pin.get().length();
if(pinSize < device.getModel().getMinPinLength() || pinSize > device.getModel().getMaxPinLength()) {
setError("PIN Error", "PIN length must be between " + device.getModel().getMinPinLength() + " and " + device.getModel().getMaxPinLength() + " characters");
return;
}
SeedEntryDialog seedEntryDialog = new SeedEntryDialog(device.getModel().toDisplayString() + " Seed Words", 12);
seedEntryDialog.initOwner(this.getScene().getWindow());
Optional<List<String>> optWords = seedEntryDialog.showAndWait();
if(optWords.isPresent()) {
try {
List<String> mnemonicWords = optWords.get();
Bip39MnemonicCode.INSTANCE.check(mnemonicWords);
DeterministicSeed seed = new DeterministicSeed(mnemonicWords, "", System.currentTimeMillis(), DeterministicSeed.Type.BIP39);
byte[] seedBytes = seed.getSeedBytes();
Service<Void> cardInitializationService = cardApi.getInitializationService(seedBytes, messageProperty);
cardInitializationService.setOnSucceeded(successEvent -> {
AppServices.showSuccessDialog("Card Initialized", "The card was successfully initialized.\n\nYou can now import the keystore.");
operationButton.setDisable(false);
setDefaultStatus();
setExpanded(false);
});
cardInitializationService.setOnFailed(failEvent -> {
log.error("Error initializing card", failEvent.getSource().getException());
AppServices.showErrorDialog("Card Initialization Failed", "The card was not initialized.\n\n" + failEvent.getSource().getException().getMessage());
initializeButton.setDisable(false);
});
cardInitializationService.start();
} catch(MnemonicException e) {
log.error("Invalid seed entered", e);
AppServices.showErrorDialog("Invalid seed entered", "The seed was invalid.\n\n" + e.getMessage());
initializeButton.setDisable(false);
}
} else {
initializeButton.setDisable(false);
}
});
HBox contentBox = new HBox(20);
contentBox.getChildren().addAll(confirmationBox, initializeButton);
contentBox.setPadding(new Insets(10, 30, 10, 30));
HBox.setHgrow(confirmationBox, Priority.ALWAYS);
return contentBox;
}
private Node getCardEntropyInitializationPanel(CardApi cardApi, ButtonBase operationButton, DeviceOperation deviceOperation) {
VBox initTypeBox = new VBox(5);
RadioButton automatic = new RadioButton("Automatic (Recommended)");
RadioButton advanced = new RadioButton("Advanced");
@@ -100,7 +100,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
actionBox.getChildren().add(viewTransactionButton);
BlockTransaction blockTransaction = transactionEntry.getBlockTransaction();
if(blockTransaction.getHeight() <= 0 && blockTransaction.getTransaction().isReplaceByFee() &&
if(blockTransaction.getHeight() <= 0 && canRBF(blockTransaction) &&
Config.get().isIncludeMempoolOutputs() && transactionEntry.getWallet().allInputsFromWallet(blockTransaction.getHash())) {
Button increaseFeeButton = new Button("");
increaseFeeButton.setGraphic(getIncreaseFeeRBFGlyph());
@@ -124,7 +124,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
NodeEntry nodeEntry = (NodeEntry)entry;
Address address = nodeEntry.getAddress();
setText(address.toString());
setContextMenu(new AddressContextMenu(address, nodeEntry.getOutputDescriptor(), nodeEntry, true));
setContextMenu(new AddressContextMenu(address, nodeEntry.getOutputDescriptor(), nodeEntry, true, getTreeTableView()));
Tooltip tooltip = new Tooltip();
tooltip.setShowDelay(Duration.millis(250));
tooltip.setText(nodeEntry.getNode().toString());
@@ -149,6 +149,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
signMessageButton.setGraphic(getSignMessageGlyph());
signMessageButton.setOnAction(event -> {
MessageSignDialog messageSignDialog = new MessageSignDialog(nodeEntry.getWallet(), nodeEntry.getNode());
messageSignDialog.initOwner(getTreeTableView().getScene().getWindow());
messageSignDialog.showAndWait();
});
actionBox.getChildren().add(signMessageButton);
@@ -216,7 +217,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
.map(e -> (HashIndexEntry)e)
.filter(e -> e.getType().equals(HashIndexEntry.Type.INPUT) && e.isSpendable())
.map(e -> blockTransaction.getTransaction().getInputs().get((int)e.getHashIndex().getIndex()))
.filter(TransactionInput::isReplaceByFeeEnabled)
.filter(i -> Config.get().isMempoolFullRbf() || i.isReplaceByFeeEnabled())
.map(txInput -> walletTxos.keySet().stream().filter(txo -> txo.getHash().equals(txInput.getOutpoint().getHash()) && txo.getIndex() == txInput.getOutpoint().getIndex()).findFirst().get())
.collect(Collectors.toList());
@@ -230,16 +231,17 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
.filter(e -> e instanceof HashIndexEntry)
.map(e -> (HashIndexEntry)e)
.filter(e -> e.getType().equals(HashIndexEntry.Type.OUTPUT))
.map(e -> e.getBlockTransaction().getTransaction().getOutputs().get((int)e.getHashIndex().getIndex()))
.map(e -> blockTransaction.getTransaction().getOutputs().get((int)e.getHashIndex().getIndex()))
.collect(Collectors.toList());
List<TransactionOutput> consolidationOutputs = transactionEntry.getChildren().stream()
.filter(e -> e instanceof HashIndexEntry)
.map(e -> (HashIndexEntry)e)
.filter(e -> e.getType().equals(HashIndexEntry.Type.OUTPUT) && e.getKeyPurpose() == KeyPurpose.RECEIVE)
.map(e -> e.getBlockTransaction().getTransaction().getOutputs().get((int)e.getHashIndex().getIndex()))
.map(e -> blockTransaction.getTransaction().getOutputs().get((int)e.getHashIndex().getIndex()))
.collect(Collectors.toList());
boolean consolidationTransaction = consolidationOutputs.size() == blockTransaction.getTransaction().getOutputs().size() && consolidationOutputs.size() == 1;
long changeTotal = ourOutputs.stream().mapToLong(TransactionOutput::getValue).sum() - consolidationOutputs.stream().mapToLong(TransactionOutput::getValue).sum();
Transaction tx = blockTransaction.getTransaction();
double vSize = tx.getVirtualSize();
@@ -254,7 +256,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
List<OutputGroup> outputGroups = transactionEntry.getWallet().getGroupedUtxos(txoFilters, feeRate, AppServices.getMinimumRelayFeeRate(), Config.get().isGroupByAddress())
.stream().filter(outputGroup -> outputGroup.getEffectiveValue() >= 0).collect(Collectors.toList());
Collections.shuffle(outputGroups);
while((double)changeTotal / vSize < getMaxFeeRate() && !outputGroups.isEmpty() && !cancelTransaction) {
while((double)changeTotal / vSize < getMaxFeeRate() && !outputGroups.isEmpty() && !cancelTransaction && !consolidationTransaction) {
//If there is insufficient change output, include another random output group so the fee can be increased
OutputGroup outputGroup = outputGroups.remove(0);
for(BlockTransactionHashIndex utxo : outputGroup.getUtxos()) {
@@ -350,12 +352,14 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
List<BlockTransactionHashIndex> ourOutputs = transactionEntry.getChildren().stream()
.filter(e -> e instanceof HashIndexEntry)
.map(e -> (HashIndexEntry)e)
.filter(e -> e.getType().equals(HashIndexEntry.Type.OUTPUT))
.filter(e -> e.getType().equals(HashIndexEntry.Type.OUTPUT) && e.isSpendable())
.map(HashIndexEntry::getHashIndex)
.collect(Collectors.toList());
if(ourOutputs.isEmpty()) {
throw new IllegalStateException("Cannot create CPFP without any wallet outputs to spend");
AppServices.showErrorDialog("No spendable outputs", "None of the outputs on this transaction are spendable.\n\nEnsure that the outputs are not frozen" +
(transactionEntry.getConfirmations() <= 0 ? ", and spending unconfirmed UTXOs is allowed." : "."));
return;
}
BlockTransactionHashIndex cpfpUtxo = ourOutputs.get(0);
@@ -392,11 +396,13 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
Platform.runLater(() -> EventManager.get().post(new SpendUtxoEvent(transactionEntry.getWallet(), utxos, List.of(payment), null, blockTransaction.getFee(), true, null)));
}
private static boolean canRBF(BlockTransaction blockTransaction) {
return Config.get().isMempoolFullRbf() || blockTransaction.getTransaction().isReplaceByFee();
}
private static boolean canSignMessage(WalletNode walletNode) {
Wallet wallet = walletNode.getWallet();
return wallet.getKeystores().size() == 1 &&
(wallet.getKeystores().get(0).hasPrivateKey() || wallet.getKeystores().get(0).getSource() == KeystoreSource.HW_USB || wallet.getKeystores().get(0).getWalletModel().isCard()) &&
(!wallet.isBip47() || walletNode.getKeyPurpose() == KeyPurpose.RECEIVE);
return wallet.getKeystores().size() == 1 && (!wallet.isBip47() || walletNode.getKeyPurpose() == KeyPurpose.RECEIVE);
}
private static boolean containsWalletOutputs(TransactionEntry transactionEntry) {
@@ -469,7 +475,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
tooltip += "\nFee rate: " + String.format("%.2f", feeRate) + " sats/vB";
}
tooltip += "\nRBF: " + (transactionEntry.getBlockTransaction().getTransaction().isReplaceByFee() ? "Enabled" : "Disabled");
tooltip += "\nRBF: " + (canRBF(transactionEntry.getBlockTransaction()) ? "Enabled" : "Disabled");
}
return tooltip;
@@ -546,7 +552,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
});
getItems().add(viewTransaction);
if(blockTransaction.getTransaction().isReplaceByFee() && Config.get().isIncludeMempoolOutputs() && transactionEntry.getWallet().allInputsFromWallet(blockTransaction.getHash())) {
if(canRBF(blockTransaction) && Config.get().isIncludeMempoolOutputs() && transactionEntry.getWallet().allInputsFromWallet(blockTransaction.getHash())) {
MenuItem increaseFee = new MenuItem("Increase Fee (RBF)");
increaseFee.setGraphic(getIncreaseFeeRBFGlyph());
increaseFee.setOnAction(AE -> {
@@ -557,7 +563,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
getItems().add(increaseFee);
}
if(blockTransaction.getTransaction().isReplaceByFee() && Config.get().isIncludeMempoolOutputs() && transactionEntry.getWallet().allInputsFromWallet(blockTransaction.getHash())) {
if(canRBF(blockTransaction) && Config.get().isIncludeMempoolOutputs() && transactionEntry.getWallet().allInputsFromWallet(blockTransaction.getHash())) {
MenuItem cancelTx = new MenuItem("Cancel Transaction (RBF)");
cancelTx.setGraphic(getCancelTransactionRBFGlyph());
cancelTx.setOnAction(AE -> {
@@ -642,7 +648,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
}
public static class AddressContextMenu extends ContextMenu {
public AddressContextMenu(Address address, String outputDescriptor, NodeEntry nodeEntry, boolean addUtxoItems) {
public AddressContextMenu(Address address, String outputDescriptor, NodeEntry nodeEntry, boolean addUtxoItems, TreeTableView<Entry> treetable) {
if(nodeEntry == null || !nodeEntry.getWallet().isBip47()) {
MenuItem receiveToAddress = new MenuItem("Receive To");
receiveToAddress.setGraphic(getReceiveGlyph());
@@ -660,6 +666,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
signVerifyMessage.setOnAction(AE -> {
hide();
MessageSignDialog messageSignDialog = new MessageSignDialog(nodeEntry.getWallet(), nodeEntry.getNode());
messageSignDialog.initOwner(treetable.getScene().getWindow());
messageSignDialog.showAndWait();
});
getItems().add(signVerifyMessage);
@@ -789,6 +796,8 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
cell.getStyleClass().remove("transaction-row");
cell.getStyleClass().remove("node-row");
cell.getStyleClass().remove("utxo-row");
cell.getStyleClass().remove("unconfirmed-row");
cell.getStyleClass().remove("summary-row");
cell.getStyleClass().remove("address-cell");
cell.getStyleClass().remove("hashindex-row");
cell.getStyleClass().remove("confirming");
@@ -823,6 +832,10 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
if(hashIndexEntry.isSpent()) {
cell.getStyleClass().add("spent");
}
} else if(entry instanceof WalletSummaryDialog.UnconfirmedEntry) {
cell.getStyleClass().add("unconfirmed-row");
} else if(entry instanceof WalletSummaryDialog.SummaryEntry) {
cell.getStyleClass().add("summary-row");
}
}
}
@@ -0,0 +1,132 @@
package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.net.FeeRatesSource;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.Slider;
import javafx.util.StringConverter;
import java.util.*;
import java.util.stream.Collectors;
import static com.sparrowwallet.sparrow.AppServices.*;
public class FeeRangeSlider extends Slider {
public FeeRangeSlider() {
super(0, FEE_RATES_RANGE.size() - 1, 0);
setMajorTickUnit(1);
setMinorTickCount(0);
setSnapToTicks(false);
setShowTickLabels(true);
setShowTickMarks(true);
setBlockIncrement(Math.log(1.02) / Math.log(2));
setLabelFormatter(new StringConverter<>() {
@Override
public String toString(Double object) {
Long feeRate = LONG_FEE_RATES_RANGE.get(object.intValue());
if(isLongFeeRange() && feeRate >= 1000) {
return feeRate / 1000 + "k";
}
return Long.toString(feeRate);
}
@Override
public Double fromString(String string) {
return null;
}
});
updateTrackHighlight();
valueProperty().addListener((observable, oldValue, newValue) -> {
if(newValue != null) {
updateMaxFeeRange(newValue.doubleValue());
}
});
}
public double getFeeRate() {
return Math.pow(2.0, getValue());
}
public void setFeeRate(double feeRate) {
double value = Math.log(feeRate) / Math.log(2);
updateMaxFeeRange(value);
setValue(value);
}
private void updateMaxFeeRange(double value) {
if(value >= getMax() && !isLongFeeRange()) {
setMax(LONG_FEE_RATES_RANGE.size() - 1);
updateTrackHighlight();
} else if(value == getMin() && isLongFeeRange()) {
setMax(FEE_RATES_RANGE.size() - 1);
updateTrackHighlight();
}
}
private boolean isLongFeeRange() {
return getMax() > FEE_RATES_RANGE.size() - 1;
}
public void updateTrackHighlight() {
addFeeRangeTrackHighlight(0);
}
private void addFeeRangeTrackHighlight(int count) {
Platform.runLater(() -> {
Node track = lookup(".track");
if(track != null) {
Map<Integer, Double> targetBlocksFeeRates = getTargetBlocksFeeRates();
String highlight = "";
if(targetBlocksFeeRates.get(Integer.MAX_VALUE) != null) {
highlight += "#a0a1a766 " + getPercentageOfFeeRange(targetBlocksFeeRates.get(Integer.MAX_VALUE)) + "%, ";
}
highlight += "#41a9c966 " + getPercentageOfFeeRange(targetBlocksFeeRates, FeeRatesSource.BLOCKS_IN_TWO_HOURS - 1) + "%, ";
highlight += "#fba71b66 " + getPercentageOfFeeRange(targetBlocksFeeRates, FeeRatesSource.BLOCKS_IN_HOUR - 1) + "%, ";
highlight += "#c8416466 " + getPercentageOfFeeRange(targetBlocksFeeRates, FeeRatesSource.BLOCKS_IN_HALF_HOUR - 1) + "%";
track.setStyle("-fx-background-color: " +
"-fx-shadow-highlight-color, " +
"linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border), " +
"linear-gradient(to bottom, derive(-fx-control-inner-background, -9%), derive(-fx-control-inner-background, 0%), derive(-fx-control-inner-background, -5%), derive(-fx-control-inner-background, -12%)), " +
"linear-gradient(to right, " + highlight + ")");
} else if(count < 20) {
addFeeRangeTrackHighlight(count+1);
}
});
}
private Map<Integer, Double> getTargetBlocksFeeRates() {
Map<Integer, Double> retrievedFeeRates = AppServices.getTargetBlockFeeRates();
if(retrievedFeeRates == null) {
retrievedFeeRates = TARGET_BLOCKS_RANGE.stream().collect(Collectors.toMap(java.util.function.Function.identity(), v -> getFallbackFeeRate(),
(u, v) -> { throw new IllegalStateException("Duplicate target blocks"); },
LinkedHashMap::new));
}
return retrievedFeeRates;
}
private int getPercentageOfFeeRange(Map<Integer, Double> targetBlocksFeeRates, Integer minTargetBlocks) {
List<Integer> rates = new ArrayList<>(targetBlocksFeeRates.keySet());
Collections.reverse(rates);
for(Integer targetBlocks : rates) {
if(targetBlocks < minTargetBlocks) {
return getPercentageOfFeeRange(targetBlocksFeeRates.get(targetBlocks));
}
}
return 100;
}
private int getPercentageOfFeeRange(Double feeRate) {
double index = Math.log(feeRate) / Math.log(2);
if(isLongFeeRange()) {
index *= ((double)FEE_RATES_RANGE.size() / (LONG_FEE_RATES_RANGE.size())) * 0.99;
}
return (int)Math.round(index * 10.0);
}
}
@@ -0,0 +1,94 @@
package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.drongo.protocol.Transaction;
import com.sparrowwallet.sparrow.CurrencyRate;
import com.sparrowwallet.sparrow.UnitFormat;
import com.sparrowwallet.sparrow.wallet.Entry;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Tooltip;
import javafx.scene.control.TreeTableCell;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import org.controlsfx.tools.Platform;
import java.math.BigDecimal;
import java.util.Currency;
public class FiatCell extends TreeTableCell<Entry, Number> {
private final Tooltip tooltip;
private final FiatContextMenu contextMenu;
public FiatCell() {
super();
tooltip = new Tooltip();
contextMenu = new FiatContextMenu();
getStyleClass().add("coin-cell");
if(Platform.getCurrent() == Platform.OSX) {
getStyleClass().add("number-field");
}
}
@Override
protected void updateItem(Number amount, boolean empty) {
super.updateItem(amount, empty);
if(empty || amount == null) {
setText(null);
setGraphic(null);
setTooltip(null);
setContextMenu(null);
} else {
Entry entry = getTreeTableView().getTreeItem(getIndex()).getValue();
EntryCell.applyRowStyles(this, entry);
CoinTreeTable coinTreeTable = (CoinTreeTable) getTreeTableView();
UnitFormat format = coinTreeTable.getUnitFormat();
CurrencyRate currencyRate = coinTreeTable.getCurrencyRate();
if(currencyRate != null && currencyRate.isAvailable()) {
Currency currency = currencyRate.getCurrency();
double btcRate = currencyRate.getBtcRate();
BigDecimal satsBalance = BigDecimal.valueOf(amount.longValue());
BigDecimal btcBalance = satsBalance.divide(BigDecimal.valueOf(Transaction.SATOSHIS_PER_BITCOIN));
BigDecimal fiatBalance = btcBalance.multiply(BigDecimal.valueOf(btcRate));
String label = format.formatCurrencyValue(fiatBalance.doubleValue());
tooltip.setText("1 BTC = " + currency.getSymbol() + " " + format.formatCurrencyValue(btcRate));
setText(label);
setGraphic(null);
setTooltip(tooltip);
setContextMenu(contextMenu);
} else {
setText(null);
setGraphic(null);
setTooltip(null);
setContextMenu(null);
}
}
}
private class FiatContextMenu extends ContextMenu {
public FiatContextMenu() {
MenuItem copyValue = new MenuItem("Copy Value");
copyValue.setOnAction(AE -> {
hide();
ClipboardContent content = new ClipboardContent();
content.putString(getText());
Clipboard.getSystemClipboard().setContent(content);
});
MenuItem copyRate = new MenuItem("Copy Rate");
copyRate.setOnAction(AE -> {
hide();
ClipboardContent content = new ClipboardContent();
content.putString(getTooltip().getText());
Clipboard.getSystemClipboard().setContent(content);
});
getItems().addAll(copyValue, copyRate);
}
}
}
@@ -150,6 +150,7 @@ public abstract class FileImportPane extends TitledDescriptionPane {
private void importQR() {
QRScanDialog qrScanDialog = new QRScanDialog();
qrScanDialog.initOwner(this.getScene().getWindow());
Optional<QRScanDialog.Result> optionalResult = qrScanDialog.showAndWait();
if(optionalResult.isPresent()) {
QRScanDialog.Result result = optionalResult.get();
@@ -116,6 +116,7 @@ public class FileKeystoreExportPane extends TitledDescriptionPane {
if(keystore.getSource() == KeystoreSource.HW_USB || keystore.getWalletModel().isCard()) {
TextAreaDialog dialog = new TextAreaDialog(message, false);
dialog.initOwner(this.getScene().getWindow());
dialog.setTitle("Sign " + exporter.getName() + " Export");
dialog.getDialogPane().setHeaderText("The following text needs to be signed by the device.\nClick OK to continue.");
dialog.showAndWait();
@@ -126,6 +127,7 @@ public class FileKeystoreExportPane extends TitledDescriptionPane {
List<String> operationFingerprints = List.of(keystore.getKeyDerivation().getMasterFingerprint());
DeviceSignMessageDialog deviceSignMessageDialog = new DeviceSignMessageDialog(operationFingerprints, wallet, message, keystore.getKeyDerivation());
deviceSignMessageDialog.initOwner(this.getScene().getWindow());
Optional<String> optSignature = deviceSignMessageDialog.showAndWait();
if(optSignature.isPresent()) {
exporter.addSignature(keystore, optSignature.get(), baos);
@@ -155,6 +157,7 @@ public class FileKeystoreExportPane extends TitledDescriptionPane {
} else {
qrDisplayDialog = new QRDisplayDialog(baos.toString(StandardCharsets.UTF_8));
}
qrDisplayDialog.initOwner(buttonBox.getScene().getWindow());
qrDisplayDialog.showAndWait();
}
} catch(Exception e) {
@@ -1,7 +1,10 @@
package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.drongo.KeyPurpose;
import com.sparrowwallet.drongo.OutputDescriptor;
import com.sparrowwallet.drongo.SecureString;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.hummingbird.registry.CryptoOutput;
import com.sparrowwallet.hummingbird.registry.RegistryType;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.EventManager;
@@ -10,6 +13,8 @@ import com.sparrowwallet.sparrow.event.TimedEvent;
import com.sparrowwallet.sparrow.event.WalletExportEvent;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.io.*;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Control;
@@ -24,6 +29,8 @@ import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Optional;
import static com.sparrowwallet.sparrow.wallet.SettingsController.getCryptoOutput;
public class FileWalletExportPane extends TitledDescriptionPane {
private final Wallet wallet;
private final WalletExport exporter;
@@ -111,19 +118,16 @@ public class FileWalletExportPane extends TitledDescriptionPane {
if(wallet.isEncrypted() && exporter.walletExportRequiresDecryption()) {
Wallet copy = wallet.copy();
WalletPasswordDialog dlg = new WalletPasswordDialog(wallet.getMasterName(), WalletPasswordDialog.PasswordRequirement.LOAD);
dlg.initOwner(buttonBox.getScene().getWindow());
Optional<SecureString> password = dlg.showAndWait();
if(password.isPresent()) {
final String walletId = AppServices.get().getOpenWallets().get(wallet).getWalletId(wallet);
String walletPassword = password.get().asString();
Storage.DecryptWalletService decryptWalletService = new Storage.DecryptWalletService(copy, password.get());
decryptWalletService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(walletId, TimedEvent.Action.END, "Done"));
Wallet decryptedWallet = decryptWalletService.getValue();
try {
exportWallet(file, decryptedWallet);
} finally {
decryptedWallet.clearPrivate();
}
exportWallet(file, decryptedWallet, walletPassword);
});
decryptWalletService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(walletId, TimedEvent.Action.END, "Failed"));
@@ -133,28 +137,42 @@ public class FileWalletExportPane extends TitledDescriptionPane {
decryptWalletService.start();
}
} else {
exportWallet(file, wallet);
exportWallet(file, wallet, null);
}
}
private void exportWallet(File file, Wallet exportWallet) {
private void exportWallet(File file, Wallet exportWallet, String password) {
try {
if(file != null) {
try(OutputStream outputStream = new FileOutputStream(file)) {
exporter.exportWallet(exportWallet, outputStream);
FileWalletExportService fileWalletExportService = new FileWalletExportService(exporter, file, exportWallet, password);
fileWalletExportService.setOnSucceeded(event -> {
EventManager.get().post(new WalletExportEvent(exportWallet));
}
});
fileWalletExportService.setOnFailed(event -> {
Throwable e = event.getSource().getException();
String errorMessage = e.getMessage();
if(e.getCause() != null && e.getCause().getMessage() != null && !e.getCause().getMessage().isEmpty()) {
errorMessage = e.getCause().getMessage();
}
setError("Export Error", errorMessage);
});
fileWalletExportService.start();
} else {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
exporter.exportWallet(exportWallet, outputStream);
exporter.exportWallet(exportWallet, outputStream, password);
QRDisplayDialog qrDisplayDialog;
if(exporter instanceof CoboVaultMultisig) {
qrDisplayDialog = new QRDisplayDialog(RegistryType.BYTES.toString(), outputStream.toByteArray(), true);
} else if(exporter instanceof PassportMultisig || exporter instanceof KeystoneMultisig || exporter instanceof JadeMultisig || exporter instanceof Bip129) {
qrDisplayDialog = new QRDisplayDialog(RegistryType.BYTES.toString(), outputStream.toByteArray(), false);
} else if(exporter instanceof Descriptor) {
OutputDescriptor outputDescriptor = OutputDescriptor.getOutputDescriptor(exportWallet, KeyPurpose.DEFAULT_PURPOSES, null);
CryptoOutput cryptoOutput = getCryptoOutput(exportWallet);
qrDisplayDialog = new DescriptorQRDisplayDialog(exportWallet.getFullDisplayName(), outputDescriptor.toString(true), cryptoOutput.toUR());
} else {
qrDisplayDialog = new QRDisplayDialog(outputStream.toString(StandardCharsets.UTF_8));
}
qrDisplayDialog.initOwner(buttonBox.getScene().getWindow());
qrDisplayDialog.showAndWait();
}
} catch(Exception e) {
@@ -163,6 +181,42 @@ public class FileWalletExportPane extends TitledDescriptionPane {
errorMessage = e.getCause().getMessage();
}
setError("Export Error", errorMessage);
} finally {
if(file == null && password != null) {
exportWallet.clearPrivate();
}
}
}
public static class FileWalletExportService extends Service<Void> {
private final WalletExport exporter;
private final File file;
private final Wallet wallet;
private final String password;
public FileWalletExportService(WalletExport exporter, File file, Wallet wallet, String password) {
this.exporter = exporter;
this.file = file;
this.wallet = wallet;
this.password = password;
}
@Override
protected Task<Void> createTask() {
return new Task<>() {
@Override
protected Void call() throws Exception {
try(OutputStream outputStream = new FileOutputStream(file)) {
exporter.exportWallet(wallet, outputStream, password);
} finally {
if(password != null) {
wallet.clearPrivate();
}
}
return null;
}
};
}
}
}
@@ -12,7 +12,7 @@ public class FileWalletImportPane extends FileImportPane {
private final WalletImport importer;
public FileWalletImportPane(WalletImport importer) {
super(importer, importer.getName(), "Wallet import", importer.getWalletImportDescription(), "image/" + importer.getWalletModel().getType() + ".png", importer.isWalletImportScannable(), true);
super(importer, importer.getName(), "Wallet import", importer.getWalletImportDescription(), "image/" + importer.getWalletModel().getType() + ".png", importer.isWalletImportScannable(), importer.isWalletImportFileFormatAvailable());
this.importer = importer;
}
@@ -12,10 +12,9 @@ import com.sparrowwallet.drongo.protocol.ScriptType;
import com.sparrowwallet.drongo.wallet.*;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.event.OpenWalletsEvent;
import com.sparrowwallet.sparrow.event.RequestOpenWalletsEvent;
import com.sparrowwallet.sparrow.event.StorageEvent;
import com.sparrowwallet.sparrow.event.TimedEvent;
import com.sparrowwallet.sparrow.event.*;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5Brands;
import com.sparrowwallet.sparrow.io.Storage;
import javafx.application.Platform;
import javafx.scene.control.*;
@@ -23,6 +22,7 @@ import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import org.controlsfx.control.SegmentedButton;
import org.controlsfx.glyphfont.Glyph;
import org.controlsfx.validation.ValidationResult;
import org.controlsfx.validation.ValidationSupport;
import org.controlsfx.validation.decoration.StyleClassValidationDecoration;
@@ -38,6 +38,8 @@ import java.util.List;
import java.util.Locale;
import java.util.Optional;
import static com.sparrowwallet.sparrow.AppServices.showErrorDialog;
public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
private static final Logger log = LoggerFactory.getLogger(MessageSignDialog.class);
@@ -50,6 +52,7 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
private final ToggleButton formatBip322;
private final Wallet wallet;
private WalletNode walletNode;
private boolean canSign;
private boolean closed;
/**
@@ -90,10 +93,12 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
public MessageSignDialog(Wallet wallet, WalletNode walletNode, String title, String msg, ButtonType... buttons) {
if(walletNode != null) {
checkWalletSigning(walletNode.getWallet());
this.canSign = canSign(walletNode.getWallet());
}
if(wallet != null) {
checkWalletSigning(wallet);
this.canSign = canSign(wallet);
}
this.wallet = wallet;
@@ -148,6 +153,7 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
signature.setPrefRowCount(4);
signature.setStyle("-fx-pref-height: 80px");
signature.setWrapText(true);
signature.setOnMouseClicked(event -> signature.selectAll());
signatureField.getInputs().add(signature);
Field formatField = new Field();
@@ -172,6 +178,7 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
formatButtons.setDisable(true);
}
ButtonType showQrButtonType = new javafx.scene.control.ButtonType("Sign by QR", ButtonBar.ButtonData.LEFT);
ButtonType signButtonType = new javafx.scene.control.ButtonType("Sign", ButtonBar.ButtonData.BACK_PREVIOUS);
ButtonType verifyButtonType = new javafx.scene.control.ButtonType("Verify", ButtonBar.ButtonData.NEXT_FORWARD);
ButtonType doneButtonType = new javafx.scene.control.ButtonType("Done", ButtonBar.ButtonData.CANCEL_CLOSE);
@@ -190,10 +197,20 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
});
}
} else {
dialogPane.getButtonTypes().addAll(signButtonType, verifyButtonType, doneButtonType);
dialogPane.getButtonTypes().addAll(showQrButtonType, signButtonType, verifyButtonType, doneButtonType);
Button showQrButton = (Button) dialogPane.lookupButton(showQrButtonType);
showQrButton.setDisable(wallet == null);
showQrButton.setGraphic(getGlyph(new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.QRCODE)));
showQrButton.setGraphicTextGap(5);
showQrButton.setOnAction(event -> {
showQr();
});
Button signButton = (Button) dialogPane.lookupButton(signButtonType);
signButton.setDisable(wallet == null);
signButton.setDisable(!canSign);
signButton.setGraphic(getGlyph(getSignGlyph()));
signButton.setGraphicTextGap(5);
signButton.setOnAction(event -> {
signMessage();
});
@@ -205,7 +222,8 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
});
boolean validAddress = isValidAddress();
signButton.setDisable(!validAddress || (wallet == null));
showQrButton.setDisable(!validAddress || (wallet == null));
signButton.setDisable(!validAddress || !canSign);
verifyButton.setDisable(!validAddress);
ValidationSupport validationSupport = new ValidationSupport();
@@ -216,7 +234,8 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
address.textProperty().addListener((observable, oldValue, newValue) -> {
boolean valid = isValidAddress();
signButton.setDisable(!valid || (wallet == null));
showQrButton.setDisable(!valid || (wallet == null));
signButton.setDisable(!valid || !canSign);
verifyButton.setDisable(!valid);
if(valid) {
@@ -248,7 +267,7 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
AppServices.onEscapePressed(dialogPane.getScene(), () -> setResult(ButtonBar.ButtonData.CANCEL_CLOSE));
AppServices.moveToActiveWindowScreen(this);
setResultConverter(dialogButton -> dialogButton == signButtonType || dialogButton == verifyButtonType ? ButtonBar.ButtonData.APPLY : dialogButton.getButtonData());
setResultConverter(dialogButton -> dialogButton == showQrButtonType || dialogButton == signButtonType || dialogButton == verifyButtonType ? ButtonBar.ButtonData.APPLY : dialogButton.getButtonData());
Platform.runLater(() -> {
if(address.getText().isEmpty()) {
@@ -269,9 +288,12 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
if(wallet.getKeystores().size() != 1) {
throw new IllegalArgumentException("Cannot sign messages using a wallet with multiple keystores - a single key is required");
}
if(!wallet.getKeystores().get(0).hasPrivateKey() && wallet.getKeystores().get(0).getSource() != KeystoreSource.HW_USB && !wallet.getKeystores().get(0).getWalletModel().isCard()) {
throw new IllegalArgumentException("Cannot sign messages using a wallet without private keys or a connected keystore");
}
}
private boolean canSign(Wallet wallet) {
return wallet.getKeystores().get(0).hasPrivateKey()
|| wallet.getKeystores().get(0).getSource() == KeystoreSource.HW_USB
|| wallet.getKeystores().get(0).getWalletModel().isCard();
}
private Address getAddress()throws InvalidAddressException {
@@ -320,6 +342,11 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
return;
}
if(!canSign) {
AppServices.showErrorDialog("Wallet can't sign", "This wallet cannot sign a message.");
return;
}
//Note we can expect a single keystore due to the check in the constructor
Wallet signingWallet = walletNode.getWallet();
if(signingWallet.getKeystores().get(0).hasPrivateKey()) {
@@ -358,6 +385,7 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
List<String> fingerprints = List.of(deviceWallet.getKeystores().get(0).getKeyDerivation().getMasterFingerprint());
KeyDerivation fullDerivation = deviceWallet.getKeystores().get(0).getKeyDerivation().extend(walletNode.getDerivation());
DeviceSignMessageDialog deviceSignMessageDialog = new DeviceSignMessageDialog(fingerprints, deviceWallet, message.getText().trim(), fullDerivation);
deviceSignMessageDialog.initOwner(getDialogPane().getScene().getWindow());
Optional<String> optSignature = deviceSignMessageDialog.showAndWait();
if(optSignature.isPresent()) {
signature.clear();
@@ -430,6 +458,60 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
return providedAddress.equals(signedMessageAddress);
}
private void showQr() {
if(walletNode == null) {
AppServices.showErrorDialog("Address not in wallet", "The provided address is not present in the currently selected wallet.");
return;
}
//Note we can expect a single keystore due to the check in the constructor
KeyDerivation firstDerivation = walletNode.getWallet().getKeystores().get(0).getKeyDerivation();
String derivationPath = KeyDerivation.writePath(firstDerivation.extend(walletNode.getDerivation()).getDerivation(), false);
String qrText = "signmessage " + derivationPath + " ascii:" + message.getText().trim();
QRDisplayDialog qrDisplayDialog = new QRDisplayDialog(qrText, true);
qrDisplayDialog.initOwner(getDialogPane().getScene().getWindow());
Optional<ButtonType> optButtonType = qrDisplayDialog.showAndWait();
if(optButtonType.isPresent() && optButtonType.get().getButtonData() == ButtonBar.ButtonData.NEXT_FORWARD) {
scanQr();
}
}
private void scanQr() {
QRScanDialog qrScanDialog = new QRScanDialog();
qrScanDialog.initOwner(getDialogPane().getScene().getWindow());
Optional<QRScanDialog.Result> optionalResult = qrScanDialog.showAndWait();
if(optionalResult.isPresent()) {
QRScanDialog.Result result = optionalResult.get();
if(result.payload != null) {
signature.clear();
signature.appendText(result.payload);
} else if(result.exception != null) {
log.error("Error scanning QR", result.exception);
showErrorDialog("Error scanning QR", result.exception.getMessage());
} else {
AppServices.showErrorDialog("Invalid QR Code", "Cannot parse QR code into a signature.");
}
}
}
protected Glyph getSignGlyph() {
if(wallet != null) {
if(wallet.containsSource(KeystoreSource.HW_USB)) {
return new Glyph(FontAwesome5Brands.FONT_NAME, FontAwesome5Brands.Glyph.USB);
} else if(wallet.getKeystores().get(0).getWalletModel().isCard()) {
return new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.WIFI);
}
}
return new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.PEN_FANCY);
}
private static Glyph getGlyph(Glyph glyph) {
glyph.setFontSize(11);
return glyph;
}
@Subscribe
public void openWallets(OpenWalletsEvent event) {
Storage storage = event.getStorage(wallet);
@@ -439,6 +521,7 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
}
WalletPasswordDialog dlg = new WalletPasswordDialog(wallet.getMasterName(), WalletPasswordDialog.PasswordRequirement.LOAD);
dlg.initOwner(getDialogPane().getScene().getWindow());
Optional<SecureString> password = dlg.showAndWait();
if(password.isPresent()) {
Storage.DecryptWalletService decryptWalletService = new Storage.DecryptWalletService(walletNode.getWallet().copy(), password.get());
@@ -1,5 +1,6 @@
package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.drongo.wallet.Bip39MnemonicCode;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
@@ -138,6 +139,7 @@ public class MnemonicGridDialog extends Dialog<List<String>> {
dialogPane.setPrefWidth(952);
dialogPane.setPrefHeight(500);
dialogPane.setMinHeight(dialogPane.getPrefHeight());
AppServices.setStageIcon(dialogPane.getScene().getWindow());
AppServices.moveToActiveWindowScreen(this);
}
@@ -169,20 +171,31 @@ public class MnemonicGridDialog extends Dialog<List<String>> {
List<String> abbreviations = selectedCells.stream()
.map(position -> (String)spreadsheetView.getGrid().getRows().get(position.getRow()).get(position.getColumn()).getItem()).collect(Collectors.toList());
boolean isInteger = abbreviations.stream().allMatch(Utils::isNumber);
boolean isHex = abbreviations.stream().allMatch(Utils::isHex);
List<String> words = new ArrayList<>();
for(String abbreviation : abbreviations) {
for(String word : Bip39MnemonicCode.INSTANCE.getWordList()) {
if((abbreviation.length() == 3 && word.equals(abbreviation)) || (abbreviation.length() >= 4 && word.startsWith(abbreviation))) {
words.add(word);
break;
if(isInteger) {
try {
int index = Integer.parseInt(abbreviation);
words.add(Bip39MnemonicCode.INSTANCE.getWordList().get(index - 1));
} catch(NumberFormatException e) {
//ignore
}
} else if(isHex) {
try {
int index = Integer.parseInt(abbreviation, 16);
words.add(Bip39MnemonicCode.INSTANCE.getWordList().get(index - 1));
} catch(NumberFormatException e) {
//ignore
}
} else {
for(String word : Bip39MnemonicCode.INSTANCE.getWordList()) {
if((abbreviation.length() == 3 && word.equals(abbreviation)) || (abbreviation.length() >= 4 && word.startsWith(abbreviation))) {
words.add(word);
}
}
}
try {
int index = Integer.parseInt(abbreviation);
words.add(Bip39MnemonicCode.INSTANCE.getWordList().get(index - 1));
} catch(NumberFormatException e) {
//ignore
}
}
@@ -269,6 +282,7 @@ public class MnemonicGridDialog extends Dialog<List<String>> {
ButtonBar.setButtonData(generateButton, buttonData);
generateButton.setOnAction(event -> {
SeedEntryDialog seedEntryDialog = new SeedEntryDialog("Border Wallets Entropy Grid Recovery Seed", 12);
seedEntryDialog.initOwner(getDialogPane().getScene().getWindow());
Optional<List<String>> optWords = seedEntryDialog.showAndWait();
if(optWords.isPresent()) {
List<String> mnemonicWords = optWords.get();
@@ -254,6 +254,7 @@ public class MnemonicKeystoreImportPane extends MnemonicKeystorePane {
if(!dryrun) {
if(passphraseProperty.get() != null && !passphraseProperty.get().isEmpty()) {
KeystorePassphraseDialog keystorePassphraseDialog = new KeystorePassphraseDialog(null, keystore, true);
keystorePassphraseDialog.initOwner(this.getScene().getWindow());
Optional<String> optPassphrase = keystorePassphraseDialog.showAndWait();
if(optPassphrase.isEmpty() || !optPassphrase.get().equals(passphraseProperty.get())) {
throw new ImportException("Re-entered passphrase did not match");
@@ -97,6 +97,7 @@ public class MnemonicKeystorePane extends TitledDescriptionPane {
protected void showGrid() {
MnemonicGridDialog mnemonicGridDialog = new MnemonicGridDialog();
mnemonicGridDialog.initOwner(this.getScene().getWindow());
Optional<List<String>> optWords = mnemonicGridDialog.showAndWait();
if(optWords.isPresent()) {
List<String> words = optWords.get();
@@ -134,6 +135,7 @@ public class MnemonicKeystorePane extends TitledDescriptionPane {
protected void scanQR() {
QRScanDialog qrScanDialog = new QRScanDialog();
qrScanDialog.initOwner(this.getScene().getWindow());
Optional<QRScanDialog.Result> optionalResult = qrScanDialog.showAndWait();
if(optionalResult.isPresent()) {
QRScanDialog.Result result = optionalResult.get();
@@ -109,6 +109,7 @@ public class MnemonicWalletKeystoreImportPane extends MnemonicKeystorePane {
List<List<ChildNumber>> derivations = ScriptType.getScriptTypesForPolicyType(PolicyType.SINGLE).stream().map(ScriptType::getDefaultDerivation).collect(Collectors.toList());
derivations.add(List.of(new ChildNumber(0, true)));
derivations.add(ScriptType.P2PKH.getDefaultDerivation(1)); //Bisq segwit misderivation
for(ScriptType scriptType : ScriptType.getScriptTypesForPolicyType(PolicyType.SINGLE)) {
for(List<ChildNumber> derivation : derivations) {
@@ -110,6 +110,7 @@ public class PayNymCell extends ListCell<PayNym> {
MenuItem rename = new MenuItem("Rename Contact...");
rename.setOnAction(event -> {
WalletLabelDialog walletLabelDialog = new WalletLabelDialog(payNym.nymName(), "Contact");
walletLabelDialog.initOwner(PayNymCell.this.getScene().getWindow());
Optional<String> optLabel = walletLabelDialog.showAndWait();
if(optLabel.isPresent()) {
int index = getListView().getItems().indexOf(payNym);
@@ -1,6 +1,7 @@
package com.sparrowwallet.sparrow.control;
import com.google.common.base.Throwables;
import com.google.common.eventbus.Subscribe;
import com.google.common.io.Files;
import com.sparrowwallet.drongo.KeyPurpose;
import com.sparrowwallet.drongo.address.Address;
@@ -14,6 +15,9 @@ import com.sparrowwallet.drongo.psbt.PSBT;
import com.sparrowwallet.drongo.psbt.PSBTInput;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.UnitFormat;
import com.sparrowwallet.sparrow.event.FeeRatesUpdatedEvent;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.io.CardApi;
import com.sparrowwallet.sparrow.io.Config;
@@ -46,10 +50,7 @@ import tornadofx.control.Form;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.*;
import java.util.stream.Collectors;
import static com.sparrowwallet.drongo.protocol.ScriptType.P2TR;
@@ -62,6 +63,8 @@ public class PrivateKeySweepDialog extends Dialog<Transaction> {
private final CopyableLabel keyAddress;
private final ComboBoxTextField toAddress;
private final ComboBox<Wallet> toWallet;
private final FeeRangeSlider feeRange;
private final CopyableLabel feeRate;
public PrivateKeySweepDialog(Wallet wallet) {
final DialogPane dialogPane = getDialogPane();
@@ -146,7 +149,24 @@ public class PrivateKeySweepDialog extends Dialog<Transaction> {
stackPane.getChildren().addAll(toWallet, toAddress);
toAddressField.getInputs().add(stackPane);
fieldset.getChildren().addAll(keyField, keyScriptTypeField, addressField, toAddressField);
Field feeRangeField = new Field();
feeRangeField.setText("Fee range:");
feeRange = new FeeRangeSlider();
feeRange.setMaxWidth(320);
feeRangeField.getInputs().add(feeRange);
Field feeRateField = new Field();
feeRateField.setText("Fee rate:");
feeRate = new CopyableLabel();
feeRateField.getInputs().add(feeRate);
feeRange.valueProperty().addListener((observable, oldValue, newValue) -> {
updateFeeRate();
});
feeRange.setFeeRate(AppServices.getDefaultFeeRate());
updateFeeRate();
fieldset.getChildren().addAll(keyField, keyScriptTypeField, addressField, toAddressField, feeRangeField, feeRateField);
form.getChildren().add(fieldset);
dialogPane.setContent(form);
@@ -170,6 +190,7 @@ public class PrivateKeySweepDialog extends Dialog<Transaction> {
boolean isValidKey = isValidKey();
createButton.setDisable(!isValidKey || !isValidToAddress());
setScriptTypes(isValidKey);
if(isValidKey) {
setFromAddress();
}
@@ -201,6 +222,11 @@ public class PrivateKeySweepDialog extends Dialog<Transaction> {
setResultConverter(dialogButton -> null);
dialogPane.setPrefWidth(680);
EventManager.get().register(this);
setOnCloseRequest(event -> {
EventManager.get().unregister(this);
});
ValidationSupport validationSupport = new ValidationSupport();
Platform.runLater(() -> {
validationSupport.setValidationDecorator(new StyleClassValidationDecoration());
@@ -224,6 +250,7 @@ public class PrivateKeySweepDialog extends Dialog<Transaction> {
private void decryptKey() {
PassphraseDialog passphraseDialog = new PassphraseDialog();
passphraseDialog.initOwner(getDialogPane().getScene().getWindow());
Optional<String> optPassphrase = passphraseDialog.showAndWait();
if(optPassphrase.isPresent()) {
try {
@@ -263,8 +290,19 @@ public class PrivateKeySweepDialog extends Dialog<Transaction> {
keyAddress.setText(address.toString());
}
private void setScriptTypes(boolean isValidKey) {
boolean compressed = !isValidKey || getPrivateKey().getKey().isCompressed();
if(compressed && !keyScriptType.getItems().equals(ScriptType.getAddressableScriptTypes(PolicyType.SINGLE))) {
keyScriptType.getItems().addAll(ScriptType.getAddressableScriptTypes(PolicyType.SINGLE).stream().filter(s -> !keyScriptType.getItems().contains(s)).collect(Collectors.toList()));
} else if(!compressed && !keyScriptType.getItems().equals(List.of(ScriptType.P2PKH))) {
keyScriptType.getSelectionModel().select(0);
keyScriptType.getItems().removeIf(scriptType -> scriptType != ScriptType.P2PKH);
}
}
private void scanPrivateKey() {
QRScanDialog qrScanDialog = new QRScanDialog();
qrScanDialog.initOwner(getDialogPane().getScene().getWindow());
Optional<QRScanDialog.Result> result = qrScanDialog.showAndWait();
if(result.isPresent() && result.get().payload != null) {
key.setText(result.get().payload);
@@ -294,6 +332,7 @@ public class PrivateKeySweepDialog extends Dialog<Transaction> {
private void unsealPrivateKey() {
DeviceUnsealDialog deviceUnsealDialog = new DeviceUnsealDialog(Collections.emptyList());
deviceUnsealDialog.initOwner(getDialogPane().getScene().getWindow());
Optional<DeviceUnsealDialog.DevicePrivateKey> optPrivateKey = deviceUnsealDialog.showAndWait();
if(optPrivateKey.isPresent()) {
DeviceUnsealDialog.DevicePrivateKey devicePrivateKey = optPrivateKey.get();
@@ -312,6 +351,7 @@ public class PrivateKeySweepDialog extends Dialog<Transaction> {
Date since = null;
if(Config.get().getServerType() == ServerType.BITCOIN_CORE) {
WalletBirthDateDialog addressScanDateDialog = new WalletBirthDateDialog(null, true);
addressScanDateDialog.initOwner(getDialogPane().getScene().getWindow());
Optional<Date> optSince = addressScanDateDialog.showAndWait();
if(optSince.isPresent()) {
since = optSince.get();
@@ -330,6 +370,7 @@ public class PrivateKeySweepDialog extends Dialog<Transaction> {
if(Config.get().getServerType() == ServerType.BITCOIN_CORE) {
ServiceProgressDialog serviceProgressDialog = new ServiceProgressDialog("Address Scan", "Scanning address for transactions...", "/image/sparrow.png", addressUtxosService);
serviceProgressDialog.initOwner(getDialogPane().getScene().getWindow());
AppServices.moveToActiveWindowScreen(serviceProgressDialog);
}
@@ -352,7 +393,7 @@ public class PrivateKeySweepDialog extends Dialog<Transaction> {
TransactionOutput sweepOutput = new TransactionOutput(noFeeTransaction, total, destAddress.getOutputScript());
noFeeTransaction.addOutput(sweepOutput);
Double feeRate = AppServices.getDefaultFeeRate();
double feeRate = feeRange.getFeeRate();
long fee = (long)Math.ceil(noFeeTransaction.getVirtualSize() * feeRate);
if(feeRate == Transaction.DEFAULT_MIN_RELAY_FEE) {
fee++;
@@ -420,6 +461,16 @@ public class PrivateKeySweepDialog extends Dialog<Transaction> {
return glyph;
}
private void updateFeeRate() {
UnitFormat format = Config.get().getUnitFormat() == null ? UnitFormat.DOT : Config.get().getUnitFormat();
feeRate.setText(format.getCurrencyFormat().format(feeRange.getFeeRate()) + " sats/vB");
}
@Subscribe
public void feeRatesUpdated(FeeRatesUpdatedEvent event) {
feeRange.updateTrackHighlight();
}
public class PassphraseDialog extends Dialog<String> {
private final CustomPasswordField passphrase;
@@ -1,7 +1,7 @@
package com.sparrowwallet.sparrow.control;
public enum QRDensity {
NORMAL("Normal", 250),
NORMAL("Normal", 400),
LOW("Low", 80);
private final String name;
@@ -1,6 +1,7 @@
package com.sparrowwallet.sparrow.control;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
@@ -29,18 +30,21 @@ import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
@SuppressWarnings("deprecation")
public class QRDisplayDialog extends Dialog<UR> {
public class QRDisplayDialog extends Dialog<ButtonType> {
private static final Logger log = LoggerFactory.getLogger(QRDisplayDialog.class);
private static final int MIN_FRAGMENT_LENGTH = 10;
private static final int ANIMATION_PERIOD_MILLIS = 200;
private static final int QR_WIDTH = 480;
private static final int QR_HEIGHT = 480;
private static final int DEFAULT_QR_SIZE = 580;
private static final int REDUCED_QR_SIZE = 520;
private final int qrSize = getQRSize();
private final UR ur;
private UREncoder encoder;
@@ -58,14 +62,14 @@ public class QRDisplayDialog extends Dialog<UR> {
private static boolean initialDensityChange;
public QRDisplayDialog(String type, byte[] data, boolean addLegacyEncodingOption) throws UR.URException {
this(UR.fromBytes(type, data), addLegacyEncodingOption);
this(UR.fromBytes(type, data), addLegacyEncodingOption, false);
}
public QRDisplayDialog(UR ur) {
this(ur, false);
this(ur, false, false);
}
public QRDisplayDialog(UR ur, boolean addLegacyEncodingOption) {
public QRDisplayDialog(UR ur, boolean addLegacyEncodingOption, boolean addScanButton) {
this.ur = ur;
this.addLegacyEncodingOption = addLegacyEncodingOption;
this.encoder = new UREncoder(ur, Config.get().getQrDensity().getMaxFragmentLength(), MIN_FRAGMENT_LENGTH, 0);
@@ -98,18 +102,29 @@ public class QRDisplayDialog extends Dialog<UR> {
dialogPane.getButtonTypes().add(densityButtonType);
}
dialogPane.setPrefWidth(40 + QR_WIDTH + 40);
dialogPane.setPrefHeight(40 + QR_HEIGHT + 85);
if(addScanButton) {
final ButtonType scanButtonType = new javafx.scene.control.ButtonType("Scan QR", ButtonBar.ButtonData.NEXT_FORWARD);
dialogPane.getButtonTypes().add(scanButtonType);
}
dialogPane.setPrefWidth(40 + qrSize + 40);
dialogPane.setPrefHeight(40 + qrSize + 85);
dialogPane.setMinHeight(dialogPane.getPrefHeight());
AppServices.moveToActiveWindowScreen(this);
setResultConverter(dialogButton -> dialogButton != cancelButtonType ? ur : null);
setResultConverter(dialogButton -> dialogButton);
}
public QRDisplayDialog(String data) {
this(data, false);
}
public QRDisplayDialog(String data, boolean addScanButton) {
this.ur = null;
this.encoder = null;
final DialogPane dialogPane = getDialogPane();
final DialogPane dialogPane = new QRDisplayDialogPane();
setDialogPane(dialogPane);
AppServices.setStageIcon(dialogPane.getScene().getWindow());
StackPane stackPane = new StackPane();
@@ -121,11 +136,22 @@ public class QRDisplayDialog extends Dialog<UR> {
final ButtonType cancelButtonType = new javafx.scene.control.ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
dialogPane.getButtonTypes().addAll(cancelButtonType);
dialogPane.setPrefWidth(40 + QR_WIDTH + 40);
dialogPane.setPrefHeight(40 + QR_HEIGHT + 85);
if(addScanButton) {
final ButtonType scanButtonType = new javafx.scene.control.ButtonType("Scan QR", ButtonBar.ButtonData.NEXT_FORWARD);
dialogPane.getButtonTypes().add(scanButtonType);
}
dialogPane.setPrefWidth(40 + qrSize + 40);
dialogPane.setPrefHeight(40 + qrSize + 85);
dialogPane.setMinHeight(dialogPane.getPrefHeight());
AppServices.moveToActiveWindowScreen(this);
setResultConverter(dialogButton -> dialogButton != cancelButtonType ? ur : null);
setResultConverter(dialogButton -> dialogButton);
}
private int getQRSize() {
return AppServices.isReducedWindowHeight() ? REDUCED_QR_SIZE : DEFAULT_QR_SIZE;
}
private void createAnimateQRService() {
@@ -153,7 +179,7 @@ public class QRDisplayDialog extends Dialog<UR> {
protected Image getQrCode(String fragment) {
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix qrMatrix = qrCodeWriter.encode(fragment, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT);
BitMatrix qrMatrix = qrCodeWriter.encode(fragment, BarcodeFormat.QR_CODE, qrSize, qrSize, Map.of(EncodeHintType.MARGIN, "2"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(qrMatrix, "PNG", baos, new MatrixToImageConfig());
@@ -280,6 +306,12 @@ public class QRDisplayDialog extends Dialog<UR> {
return density;
}
} else if(buttonType.getButtonData() == ButtonBar.ButtonData.NEXT_FORWARD) {
Button scanButton = (Button)super.createButton(buttonType);
scanButton.setGraphicTextGap(5);
scanButton.setGraphic(getGlyph(FontAwesome5.Glyph.CAMERA));
return scanButton;
}
return super.createButton(buttonType);
@@ -173,6 +173,7 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
dialogPane.getButtonTypes().addAll(hdButtonType, camButtonType, cancelButtonType);
dialogPane.setPrefWidth(646);
dialogPane.setPrefHeight(webcamResolutionProperty.get() == WebcamResolution.HD ? 490 : 590);
dialogPane.setMinHeight(dialogPane.getPrefHeight());
AppServices.moveToActiveWindowScreen(this);
setResultConverter(dialogButton -> dialogButton != cancelButtonType ? result : null);
@@ -441,6 +442,39 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
CryptoBip39 cryptoBip39 = (CryptoBip39)ur.decodeFromRegistry();
DeterministicSeed seed = getSeed(cryptoBip39);
return new Result(seed);
} else if(urRegistryType.equals(RegistryType.PSBT)) {
URPSBT urPSBT = (URPSBT)ur.decodeFromRegistry();
try {
PSBT psbt = new PSBT(urPSBT.getPsbt(), false);
return new Result(psbt);
} catch(Exception e) {
log.error("Error parsing PSBT from UR type " + urRegistryType, e);
return new Result(new URException("Error parsing PSBT from UR type " + urRegistryType, e));
}
} else if(urRegistryType.equals(RegistryType.ADDRESS)) {
URAddress urAddress = (URAddress)ur.decodeFromRegistry();
Address address = getAddress(urAddress);
if(address != null) {
return new Result(BitcoinURI.fromAddress(address));
} else {
return new Result(new URException("Unknown " + urRegistryType + " type of " + urAddress.getType()));
}
} else if(urRegistryType.equals(RegistryType.HDKEY)) {
URHDKey urHDKey = (URHDKey)ur.decodeFromRegistry();
ExtendedKey extendedKey = getExtendedKey(urHDKey);
return new Result(extendedKey, urHDKey.getName());
} else if(urRegistryType.equals(RegistryType.OUTPUT_DESCRIPTOR)) {
UROutputDescriptor urOutputDescriptor = (UROutputDescriptor)ur.decodeFromRegistry();
OutputDescriptor outputDescriptor = getOutputDescriptor(urOutputDescriptor);
return new Result(outputDescriptor);
} else if(urRegistryType.equals(RegistryType.ACCOUNT_DESCRIPTOR)) {
URAccountDescriptor urAccountDescriptor = (URAccountDescriptor)ur.decodeFromRegistry();
List<Wallet> wallets = getWallets(urAccountDescriptor);
return new Result(wallets);
} else if(urRegistryType.equals(RegistryType.SEED)) {
URSeed urSeed = (URSeed)ur.decodeFromRegistry();
DeterministicSeed seed = getSeed(urSeed);
return new Result(seed);
} else {
log.error("Unsupported UR type " + urRegistryType);
return new Result(new URException("UR type " + urRegistryType + " is not supported"));
@@ -502,18 +536,22 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
if(cryptoOutput.getMultiKey() != null) {
MultiKey multiKey = cryptoOutput.getMultiKey();
Map<ExtendedKey, KeyDerivation> extendedPublicKeys = new LinkedHashMap<>();
Map<ExtendedKey, String> extendedPublicKeyLabels = new LinkedHashMap<>();
for(CryptoHDKey cryptoHDKey : multiKey.getHdKeys()) {
ExtendedKey extendedKey = getExtendedKey(cryptoHDKey);
KeyDerivation keyDerivation = getKeyDerivation(cryptoHDKey.getOrigin());
extendedPublicKeys.put(extendedKey, keyDerivation);
if(cryptoHDKey.getName() != null) {
extendedPublicKeyLabels.put(extendedKey, cryptoHDKey.getName());
}
}
return new OutputDescriptor(scriptType, multiKey.getThreshold(), extendedPublicKeys);
return new OutputDescriptor(scriptType, multiKey.getThreshold(), extendedPublicKeys, new LinkedHashMap<>(), extendedPublicKeyLabels);
} else if(cryptoOutput.getEcKey() != null) {
throw new IllegalArgumentException("EC keys are currently unsupported");
} else if(cryptoOutput.getHdKey() != null) {
ExtendedKey extendedKey = getExtendedKey(cryptoOutput.getHdKey());
KeyDerivation keyDerivation = getKeyDerivation(cryptoOutput.getHdKey().getOrigin());
return new OutputDescriptor(scriptType, extendedKey, keyDerivation);
return new OutputDescriptor(scriptType, extendedKey, keyDerivation, cryptoOutput.getHdKey().getName());
}
throw new IllegalStateException("CryptoOutput did not contain sufficient information");
@@ -579,6 +617,40 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
private DeterministicSeed getSeed(CryptoBip39 cryptoBip39) {
return new DeterministicSeed(cryptoBip39.getWords(), null, System.currentTimeMillis(), DeterministicSeed.Type.BIP39);
}
private OutputDescriptor getOutputDescriptor(UROutputDescriptor urOutputDescriptor) {
String source = urOutputDescriptor.getSource();
List<RegistryItem> keys = urOutputDescriptor.getKeys();
Map<ExtendedKey, String> mapExtendedPublicKeyLabels = new LinkedHashMap<>();
for(int i = 0; i < keys.size(); i++) {
RegistryItem key = keys.get(i);
if(key instanceof URHDKey urhdKey) {
ExtendedKey extendedKey = getExtendedKey(urhdKey);
KeyDerivation keyDerivation = getKeyDerivation(urhdKey.getOrigin());
source = source.replaceAll("@" + i, OutputDescriptor.writeKey(extendedKey, keyDerivation, null, true, true));
if(urhdKey.getName() != null) {
mapExtendedPublicKeyLabels.put(extendedKey, urhdKey.getName());
}
} else {
throw new IllegalArgumentException("Only extended HD keys are supported in output descriptors");
}
}
return OutputDescriptor.getOutputDescriptor(source, mapExtendedPublicKeyLabels);
}
private List<Wallet> getWallets(URAccountDescriptor urAccountDescriptor) {
List<Wallet> wallets = new ArrayList<>();
String masterFingerprint = Utils.bytesToHex(urAccountDescriptor.getMasterFingerprint());
for(UROutputDescriptor urOutputDescriptor : urAccountDescriptor.getOutputDescriptors()) {
OutputDescriptor outputDescriptor = getOutputDescriptor(urOutputDescriptor);
Wallet wallet = outputDescriptor.toKeystoreWallet(masterFingerprint);
wallets.add(wallet);
}
return wallets;
}
}
private class QRScanListener implements WebcamListener {
@@ -1,6 +1,8 @@
package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.drongo.KeyPurpose;
import com.sparrowwallet.drongo.address.Address;
import com.sparrowwallet.drongo.address.InvalidAddressException;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.wallet.*;
@@ -21,6 +23,7 @@ import tornadofx.control.Form;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
public class SearchWalletDialog extends Dialog<Entry> {
private static final Logger log = LoggerFactory.getLogger(SearchWalletDialog.class);
@@ -36,13 +39,16 @@ public class SearchWalletDialog extends Dialog<Entry> {
throw new IllegalArgumentException("No wallets selected to search");
}
boolean showWallet = walletForms.stream().map(WalletForm::getMasterWallet).distinct().limit(2).count() > 1;
boolean showAccount = walletForms.stream().anyMatch(walletForm -> !walletForm.getWallet().isMasterWallet() || !walletForm.getNestedWalletForms().isEmpty());
final DialogPane dialogPane = getDialogPane();
dialogPane.getStylesheets().add(AppServices.class.getResource("general.css").toExternalForm());
dialogPane.getStylesheets().add(AppServices.class.getResource("dialog.css").toExternalForm());
dialogPane.getStylesheets().add(AppServices.class.getResource("wallet/wallet.css").toExternalForm());
dialogPane.getStylesheets().add(AppServices.class.getResource("search.css").toExternalForm());
AppServices.setStageIcon(dialogPane.getScene().getWindow());
dialogPane.setHeaderText("Search Wallet");
dialogPane.setHeaderText(showWallet ? "Search All Wallets" : "Search Wallet");
Image image = new Image("image/sparrow-small.png", 50, 50, false, false);
if(!image.isError()) {
@@ -69,11 +75,9 @@ public class SearchWalletDialog extends Dialog<Entry> {
fieldset.getChildren().addAll(searchField);
form.getChildren().add(fieldset);
boolean showWallet = walletForms.size() > 1 || walletForms.stream().anyMatch(walletForm -> !walletForm.getNestedWalletForms().isEmpty());
results = new CoinTreeTable();
results.setShowRoot(false);
results.setPrefWidth(showWallet ? 950 : 850);
results.setPrefWidth(showWallet || showAccount ? 950 : 850);
results.setUnitFormat(walletForms.iterator().next().getWallet());
results.setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY);
results.setPlaceholder(new Label("No results"));
@@ -81,11 +85,19 @@ public class SearchWalletDialog extends Dialog<Entry> {
if(showWallet) {
TreeTableColumn<Entry, String> walletColumn = new TreeTableColumn<>("Wallet");
walletColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<Entry, String> param) -> {
return new ReadOnlyObjectWrapper<>(param.getValue().getValue().getWallet().getDisplayName());
return new ReadOnlyObjectWrapper<>(param.getValue().getValue().getWallet().getMasterName());
});
results.getColumns().add(walletColumn);
}
if(showAccount) {
TreeTableColumn<Entry, String> accountColumn = new TreeTableColumn<>("Account");
accountColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<Entry, String> param) -> {
return new ReadOnlyObjectWrapper<>(param.getValue().getValue().getWallet().getDisplayName());
});
results.getColumns().add(accountColumn);
}
TreeTableColumn<Entry, String> typeColumn = new TreeTableColumn<>("Type");
typeColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<Entry, String> param) -> {
return new ReadOnlyObjectWrapper<>(param.getValue().getValue().getEntryType());
@@ -135,25 +147,22 @@ public class SearchWalletDialog extends Dialog<Entry> {
});
search.textProperty().addListener((observable, oldValue, newValue) -> {
searchWallet(newValue.toLowerCase(Locale.ROOT));
searchWallets(newValue.toLowerCase(Locale.ROOT));
});
setResizable(true);
AppServices.moveToActiveWindowScreen(this);
Platform.runLater(search::requestFocus);
}
private void searchWallet(String searchText) {
private void searchWallets(String searchText) {
List<Entry> matchingEntries = new ArrayList<>();
if(!searchText.isEmpty()) {
Long searchValue = null;
try {
searchValue = Math.abs(Long.parseLong(searchText));
} catch(NumberFormatException e) {
//ignore
}
Long searchValue = getSearchValue(searchText);
Address searchAddress = getSearchAddress(searchText);
for(WalletForm walletForm : walletForms) {
WalletTransactionsEntry walletTransactionsEntry = walletForm.getWalletTransactionsEntry();
@@ -161,7 +170,8 @@ public class SearchWalletDialog extends Dialog<Entry> {
if(entry instanceof TransactionEntry transactionEntry) {
if(transactionEntry.getBlockTransaction().getHash().toString().equals(searchText) ||
(transactionEntry.getLabel() != null && transactionEntry.getLabel().toLowerCase(Locale.ROOT).contains(searchText)) ||
(transactionEntry.getValue() != null && searchValue != null && Math.abs(transactionEntry.getValue()) == searchValue)) {
(transactionEntry.getValue() != null && searchValue != null && Math.abs(transactionEntry.getValue()) == searchValue) ||
(searchAddress != null && transactionEntry.getBlockTransaction().getTransaction().getOutputs().stream().map(output -> output.getScript().getToAddress()).filter(Objects::nonNull).anyMatch(address -> address.equals(searchAddress)))) {
matchingEntries.add(entry);
}
}
@@ -213,6 +223,22 @@ public class SearchWalletDialog extends Dialog<Entry> {
results.setRoot(rootItem);
}
private Long getSearchValue(String searchText) {
try {
return Math.abs(Long.parseLong(searchText));
} catch(NumberFormatException e) {
return null;
}
}
private Address getSearchAddress(String searchText) {
try {
return Address.fromString(searchText);
} catch(InvalidAddressException e) {
return null;
}
}
private static class SearchWalletEntry extends Entry {
public SearchWalletEntry(Wallet wallet, List<Entry> entries) {
super(wallet, wallet.getName(), entries);
@@ -81,6 +81,7 @@ public class SendToManyDialog extends Dialog<List<Payment>> {
dialogPane.setPrefWidth(850);
dialogPane.setPrefHeight(500);
setResizable(true);
AppServices.setStageIcon(dialogPane.getScene().getWindow());
AppServices.moveToActiveWindowScreen(this);
}
@@ -85,6 +85,7 @@ public class TextAreaDialog extends Dialog<String> {
dialogPane.setPrefWidth(700);
dialogPane.setPrefHeight(400);
setResizable(true);
AppServices.moveToActiveWindowScreen(this);
}
@@ -109,6 +110,7 @@ public class TextAreaDialog extends Dialog<String> {
ButtonBar.setButtonData(scanButton, buttonData);
scanButton.setOnAction(event -> {
QRScanDialog qrScanDialog = new QRScanDialog();
qrScanDialog.initOwner(getDialogPane().getScene().getWindow());
Optional<QRScanDialog.Result> optionalResult = qrScanDialog.showAndWait();
if(optionalResult.isPresent()) {
QRScanDialog.Result result = optionalResult.get();
@@ -14,6 +14,7 @@ import com.sparrowwallet.sparrow.event.ExcludeUtxoEvent;
import com.sparrowwallet.sparrow.event.ReplaceChangeAddressEvent;
import com.sparrowwallet.sparrow.event.SorobanInitiatedEvent;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.glyphfont.GlyphUtils;
import com.sparrowwallet.sparrow.io.Config;
import com.sparrowwallet.sparrow.soroban.SorobanServices;
import com.sparrowwallet.sparrow.wallet.OptimizationStrategy;
@@ -44,7 +45,6 @@ import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import org.controlsfx.glyphfont.FontAwesome;
import org.controlsfx.glyphfont.Glyph;
import org.controlsfx.tools.Platform;
@@ -56,6 +56,8 @@ import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import static com.sparrowwallet.sparrow.glyphfont.GlyphUtils.*;
public class TransactionDiagram extends GridPane {
private static final int MAX_UTXOS = 8;
private static final int REDUCED_MAX_UTXOS = MAX_UTXOS - 2;
@@ -72,6 +74,7 @@ public class TransactionDiagram extends GridPane {
private WalletTransaction walletTx;
private final BooleanProperty finalProperty = new SimpleBooleanProperty(false);
private final ObjectProperty<TransactionDiagramLabel> labelProperty = new SimpleObjectProperty<>(null);
private final ObjectProperty<OptimizationStrategy> optimizationStrategyProperty = new SimpleObjectProperty<>(OptimizationStrategy.EFFICIENCY);
private boolean expanded;
private TransactionDiagram expandedDiagram;
@@ -154,6 +157,10 @@ public class TransactionDiagram extends GridPane {
updateDerivedDiagram(expandedDiagram);
}
}
if(getLabel() != null) {
getLabel().update(this);
}
}
public void update(String message) {
@@ -534,7 +541,7 @@ public class TransactionDiagram extends GridPane {
return input.getLabel() != null && !input.getLabel().isEmpty() ? input.getLabel() : input.getHashAsString().substring(0, 8) + "..:" + input.getIndex();
}
private String getSatsValue(long amount) {
String getSatsValue(long amount) {
UnitFormat format = Config.get().getUnitFormat() == null ? UnitFormat.DOT : Config.get().getUnitFormat();
return format.formatSatsValue(amount);
}
@@ -637,7 +644,7 @@ public class TransactionDiagram extends GridPane {
double width = 140.0;
long sum = walletTx.getTotal();
List<Long> values = walletTx.getTransaction().getOutputs().stream().map(TransactionOutput::getValue).collect(Collectors.toList());
List<Long> values = walletTx.getTransaction().getOutputs().stream().filter(txo -> txo.getScript().getToAddress() != null).map(TransactionOutput::getValue).collect(Collectors.toList());
values.add(walletTx.getFee());
int numOutputs = displayedPayments.size() + walletTx.getChangeMap().size() + 1;
for(int i = 1; i <= numOutputs; i++) {
@@ -681,18 +688,18 @@ public class TransactionDiagram extends GridPane {
List<OutputNode> outputNodes = new ArrayList<>();
for(Payment payment : displayedPayments) {
Glyph outputGlyph = getOutputGlyph(payment);
Glyph outputGlyph = GlyphUtils.getOutputGlyph(walletTx, payment);
boolean labelledPayment = outputGlyph.getStyleClass().stream().anyMatch(style -> List.of("premix-icon", "badbank-icon", "whirlpoolfee-icon").contains(style)) || payment instanceof AdditionalPayment;
payment.setLabel(getOutputLabel(payment));
Label recipientLabel = new Label(payment.getLabel() == null || payment.getType() == Payment.Type.FAKE_MIX || payment.getType() == Payment.Type.MIX ? payment.getAddress().toString().substring(0, 8) + "..." : payment.getLabel(), outputGlyph);
recipientLabel.getStyleClass().add("output-label");
recipientLabel.getStyleClass().add(labelledPayment ? "payment-label" : "recipient-label");
Wallet toWallet = getToWallet(payment);
Wallet toWallet = walletTx.getToWallet(AppServices.get().getOpenWallets().keySet(), payment);
WalletNode toNode = walletTx.getWallet() != null && !walletTx.getWallet().isBip47() ? walletTx.getAddressNodeMap().get(payment.getAddress()) : null;
Wallet toBip47Wallet = getBip47SendWallet(payment);
Tooltip recipientTooltip = new Tooltip((toWallet == null ? (toNode != null ? "Consolidate " : "Pay ") : "Receive ")
+ getSatsValue(payment.getAmount()) + " sats to "
+ (payment instanceof AdditionalPayment ? (isExpanded() ? "\n" : "(click to expand)\n") + payment : (toWallet == null ? (payment.getLabel() == null ? (toNode != null ? toNode : (toBip47Wallet == null ? "external address" : toBip47Wallet.getDisplayName())) : payment.getLabel()) : toWallet.getFullDisplayName()) + "\n" + payment.getAddress().toString()));
+ (payment instanceof AdditionalPayment ? (isExpanded() ? "\n" : "(click to expand)\n") + payment : (toWallet == null ? (payment.getLabel() == null ? (toNode != null ? toNode : (toBip47Wallet == null ? "external address" : toBip47Wallet.getDisplayName())) : payment.getLabel()) : toWallet.getFullDisplayName()) + "\n" + payment.getAddress().toString())
+ (walletTx.isDuplicateAddress(payment) ? " (Duplicate)" : ""));
recipientTooltip.getStyleClass().add("recipient-label");
recipientTooltip.setShowDelay(new Duration(TOOLTIP_SHOW_DELAY));
recipientTooltip.setShowDuration(Duration.INDEFINITE);
@@ -714,6 +721,7 @@ public class TransactionDiagram extends GridPane {
outputNodes.add(new OutputNode(paymentBox, payment.getAddress(), payment.getAmount()));
}
Set<Integer> seenIndexes = new HashSet<>();
for(Map.Entry<WalletNode, Long> changeEntry : walletTx.getChangeMap().entrySet()) {
WalletNode changeNode = changeEntry.getKey();
WalletNode defaultChangeNode = walletTx.getWallet().getFreshNode(KeyPurpose.CHANGE);
@@ -759,11 +767,15 @@ public class TransactionDiagram extends GridPane {
actionBox.getChildren().addAll(region, amountLabel);
}
outputNodes.add(new OutputNode(actionBox, changeAddress, changeEntry.getValue()));
}
if(isFinal()) {
Collections.sort(outputNodes);
int changeIndex = outputNodes.size();
if(isFinal()) {
changeIndex = getOutputIndex(changeAddress, changeEntry.getValue(), seenIndexes);
seenIndexes.add(changeIndex);
if(changeIndex > outputNodes.size()) {
changeIndex = outputNodes.size();
}
}
outputNodes.add(changeIndex, new OutputNode(actionBox, changeAddress, changeEntry.getValue()));
}
for(OutputNode outputNode : outputNodes) {
@@ -917,38 +929,10 @@ public class TransactionDiagram extends GridPane {
return spacer;
}
private String getOutputLabel(Payment payment) {
if(payment.getLabel() != null) {
return payment.getLabel();
}
if(payment.getType() == Payment.Type.WHIRLPOOL_FEE) {
return "Whirlpool Fee";
} else if(walletTx.isPremixSend(payment)) {
int premixIndex = getOutputIndex(payment.getAddress(), payment.getAmount()) - 2;
return "Premix #" + premixIndex;
} else if(walletTx.isBadbankSend(payment)) {
return "Badbank Change";
}
return null;
}
private int getOutputIndex(Address address, long amount) {
return walletTx.getTransaction().getOutputs().stream().filter(txOutput -> address.equals(txOutput.getScript().getToAddress()) && txOutput.getValue() == amount).mapToInt(TransactionOutput::getIndex).findFirst().orElseThrow();
}
private Wallet getToWallet(Payment payment) {
for(Wallet openWallet : AppServices.get().getOpenWallets().keySet()) {
if(openWallet != walletTx.getWallet() && openWallet.isValid()) {
WalletNode addressNode = openWallet.getWalletAddresses().get(payment.getAddress());
if(addressNode != null) {
return addressNode.getWallet();
}
}
}
return null;
private int getOutputIndex(Address address, long amount, Collection<Integer> seenIndexes) {
List<TransactionOutput> addressOutputs = walletTx.getTransaction().getOutputs().stream().filter(txOutput -> txOutput.getScript().getToAddress() != null).collect(Collectors.toList());
TransactionOutput output = addressOutputs.stream().filter(txOutput -> address.equals(txOutput.getScript().getToAddress()) && txOutput.getValue() == amount && !seenIndexes.contains(txOutput.getIndex())).findFirst().orElseThrow();
return addressOutputs.indexOf(output);
}
private Wallet getBip47SendWallet(Payment payment) {
@@ -968,151 +952,6 @@ public class TransactionDiagram extends GridPane {
return null;
}
public Glyph getOutputGlyph(Payment payment) {
if(payment.getType().equals(Payment.Type.MIX)) {
return getMixGlyph();
} else if(payment.getType().equals(Payment.Type.FAKE_MIX)) {
return getFakeMixGlyph();
} else if(walletTx.isConsolidationSend(payment)) {
return getConsolidationGlyph();
} else if(walletTx.isPremixSend(payment)) {
return getPremixGlyph();
} else if(walletTx.isBadbankSend(payment)) {
return getBadbankGlyph();
} else if(payment.getType().equals(Payment.Type.WHIRLPOOL_FEE)) {
return getWhirlpoolFeeGlyph();
} else if(payment instanceof AdditionalPayment) {
return ((AdditionalPayment)payment).getOutputGlyph(this);
} else if(getToWallet(payment) != null) {
return getDepositGlyph();
}
return getPaymentGlyph();
}
public static Glyph getExcludeGlyph() {
Glyph excludeGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.TIMES_CIRCLE);
excludeGlyph.getStyleClass().add("exclude-utxo");
excludeGlyph.setFontSize(12);
return excludeGlyph;
}
public static Glyph getPaymentGlyph() {
Glyph paymentGlyph = new Glyph("FontAwesome", FontAwesome.Glyph.SEND);
paymentGlyph.getStyleClass().add("payment-icon");
paymentGlyph.setFontSize(12);
return paymentGlyph;
}
public static Glyph getConsolidationGlyph() {
Glyph consolidationGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.REPLY_ALL);
consolidationGlyph.getStyleClass().add("consolidation-icon");
consolidationGlyph.setFontSize(12);
return consolidationGlyph;
}
public static Glyph getDepositGlyph() {
Glyph depositGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.ARROW_DOWN);
depositGlyph.getStyleClass().add("deposit-icon");
depositGlyph.setFontSize(12);
return depositGlyph;
}
public static Glyph getPremixGlyph() {
Glyph premixGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.RANDOM);
premixGlyph.getStyleClass().add("premix-icon");
premixGlyph.setFontSize(12);
return premixGlyph;
}
public static Glyph getBadbankGlyph() {
Glyph badbankGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.BIOHAZARD);
badbankGlyph.getStyleClass().add("badbank-icon");
badbankGlyph.setFontSize(12);
return badbankGlyph;
}
public static Glyph getWhirlpoolFeeGlyph() {
Glyph whirlpoolFeeGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.HAND_HOLDING_WATER);
whirlpoolFeeGlyph.getStyleClass().add("whirlpoolfee-icon");
whirlpoolFeeGlyph.setFontSize(12);
return whirlpoolFeeGlyph;
}
public static Glyph getFakeMixGlyph() {
Glyph fakeMixGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.THEATER_MASKS);
fakeMixGlyph.getStyleClass().add("fakemix-icon");
fakeMixGlyph.setFontSize(12);
return fakeMixGlyph;
}
public static Glyph getTxoGlyph() {
return getChangeGlyph();
}
public static Glyph getMixGlyph() {
Glyph payjoinGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.RANDOM);
payjoinGlyph.getStyleClass().add("mix-icon");
payjoinGlyph.setFontSize(12);
return payjoinGlyph;
}
public static Glyph getChangeGlyph() {
Glyph changeGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.COINS);
changeGlyph.getStyleClass().add("change-icon");
changeGlyph.setFontSize(12);
return changeGlyph;
}
public static Glyph getChangeWarningGlyph() {
Glyph changeWarningGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.EXCLAMATION_TRIANGLE);
changeWarningGlyph.getStyleClass().add("change-warning-icon");
changeWarningGlyph.setFontSize(12);
return changeWarningGlyph;
}
public static Glyph getChangeReplaceGlyph() {
Glyph changeReplaceGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.ARROW_DOWN);
changeReplaceGlyph.getStyleClass().add("change-replace-icon");
changeReplaceGlyph.setFontSize(12);
return changeReplaceGlyph;
}
private Glyph getFeeGlyph() {
Glyph feeGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.HAND_HOLDING);
feeGlyph.getStyleClass().add("fee-icon");
feeGlyph.setFontSize(12);
return feeGlyph;
}
private Glyph getWarningGlyph() {
Glyph feeWarningGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.EXCLAMATION_CIRCLE);
feeWarningGlyph.getStyleClass().add("fee-warning-icon");
feeWarningGlyph.setFontSize(12);
return feeWarningGlyph;
}
private Glyph getQuestionGlyph() {
Glyph feeWarningGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.QUESTION_CIRCLE);
feeWarningGlyph.getStyleClass().add("question-icon");
feeWarningGlyph.setFontSize(12);
return feeWarningGlyph;
}
private Glyph getLockGlyph() {
Glyph lockGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.LOCK);
lockGlyph.getStyleClass().add("lock-icon");
lockGlyph.setFontSize(12);
return lockGlyph;
}
private Glyph getUserGlyph() {
Glyph userGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.USER);
userGlyph.getStyleClass().add("user-icon");
userGlyph.setFontSize(12);
return userGlyph;
}
private Glyph getUserAddGlyph() {
Glyph userAddGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.USER_PLUS);
userAddGlyph.getStyleClass().add("useradd-icon");
@@ -1162,6 +1001,10 @@ public class TransactionDiagram extends GridPane {
}
}
public WalletTransaction getWalletTransaction() {
return walletTx;
}
public boolean isFinal() {
return finalProperty.get();
}
@@ -1174,6 +1017,18 @@ public class TransactionDiagram extends GridPane {
this.finalProperty.set(isFinal);
}
public TransactionDiagramLabel getLabel() {
return labelProperty.get();
}
public ObjectProperty<TransactionDiagramLabel> labelProperty() {
return labelProperty;
}
public void setLabelProperty(TransactionDiagramLabel label) {
this.labelProperty.set(label);
}
public OptimizationStrategy getOptimizationStrategy() {
return optimizationStrategyProperty.get();
}
@@ -1253,7 +1108,7 @@ public class TransactionDiagram extends GridPane {
}
}
private static class AdditionalPayment extends Payment {
public static class AdditionalPayment extends Payment {
private final List<Payment> additionalPayments;
public AdditionalPayment(List<Payment> additionalPayments) {
@@ -1261,10 +1116,10 @@ public class TransactionDiagram extends GridPane {
this.additionalPayments = additionalPayments;
}
public Glyph getOutputGlyph(TransactionDiagram transactionDiagram) {
public Glyph getOutputGlyph(WalletTransaction walletTx) {
Glyph glyph = null;
for(Payment payment : additionalPayments) {
Glyph paymentGlyph = transactionDiagram.getOutputGlyph(payment);
Glyph paymentGlyph = GlyphUtils.getOutputGlyph(walletTx, payment);
if(glyph != null && !paymentGlyph.getStyleClass().equals(glyph.getStyleClass())) {
return getPaymentGlyph();
}
@@ -1280,7 +1135,7 @@ public class TransactionDiagram extends GridPane {
}
}
private class OutputNode implements Comparable<OutputNode> {
private static class OutputNode {
public Pane outputLabel;
public Address address;
public long amount;
@@ -1290,18 +1145,9 @@ public class TransactionDiagram extends GridPane {
this.address = address;
this.amount = amount;
}
@Override
public int compareTo(TransactionDiagram.OutputNode o) {
try {
return getOutputIndex(address, amount) - getOutputIndex(o.address, o.amount);
} catch(Exception e) {
return 0;
}
}
}
private static class LabelContextMenu extends ContextMenu {
private class LabelContextMenu extends ContextMenu {
public LabelContextMenu(Address address, long value) {
if(address != null) {
MenuItem copyAddress = new MenuItem("Copy Address");
@@ -1317,6 +1163,7 @@ public class TransactionDiagram extends GridPane {
showAddress.setOnAction(event -> {
hide();
QRDisplayDialog qrDisplayDialog = new QRDisplayDialog(address.toString());
qrDisplayDialog.initOwner(TransactionDiagram.this.getScene().getWindow());
qrDisplayDialog.showAndWait();
});
getItems().add(showAddress);
@@ -0,0 +1,270 @@
package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.drongo.wallet.*;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.glyphfont.GlyphUtils;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
import org.controlsfx.glyphfont.Glyph;
import java.util.*;
import java.util.stream.Collectors;
public class TransactionDiagramLabel extends HBox {
private final List<HBox> outputs = new ArrayList<>();
private final Button left;
private final Button right;
private final IntegerProperty displayedIndex = new SimpleIntegerProperty(-1);
public TransactionDiagramLabel() {
setSpacing(5);
setAlignment(Pos.CENTER_RIGHT);
left = new Button("");
left.setGraphic(getLeftGlyph());
left.setOnAction(event -> {
int index = displayedIndex.get();
if(index > 0) {
index--;
}
displayedIndex.set(index);
});
right = new Button("");
right.setGraphic(getRightGlyph());
right.setOnAction(event -> {
int index = displayedIndex.get();
if(index < outputs.size() - 1) {
index++;
}
displayedIndex.set(index);
});
displayedIndex.addListener((observable, oldValue, newValue) -> {
left.setDisable(newValue.intValue() <= 0);
right.setDisable(newValue.intValue() < 0 || newValue.intValue() >= outputs.size() - 1);
if(oldValue.intValue() >= 0 && oldValue.intValue() < outputs.size()) {
outputs.get(oldValue.intValue()).setVisible(false);
}
if(newValue.intValue() >= 0 && newValue.intValue() < outputs.size()) {
outputs.get(newValue.intValue()).setVisible(true);
}
});
}
public void update(TransactionDiagram transactionDiagram) {
getChildren().clear();
outputs.clear();
displayedIndex.set(-1);
double maxWidth = getMaxWidth();
WalletTransaction walletTx = transactionDiagram.getWalletTransaction();
List<OutputLabel> outputLabels = new ArrayList<>();
List<Payment> premixOutputs = walletTx.getPayments().stream().filter(walletTx::isPremixSend).collect(Collectors.toList());
if(!premixOutputs.isEmpty()) {
OutputLabel premixOutputLabel = getPremixOutputLabel(transactionDiagram, premixOutputs);
if(premixOutputLabel != null) {
outputLabels.add(premixOutputLabel);
}
Optional<Payment> optWhirlpoolFee = walletTx.getPayments().stream().filter(payment -> payment.getType() == Payment.Type.WHIRLPOOL_FEE).findFirst();
if(optWhirlpoolFee.isPresent()) {
OutputLabel whirlpoolFeeOutputLabel = getWhirlpoolFeeOutputLabel(transactionDiagram, optWhirlpoolFee.get(), premixOutputs);
outputLabels.add(whirlpoolFeeOutputLabel);
}
List<Payment> badbankOutputs = walletTx.getPayments().stream().filter(walletTx::isBadbankSend).collect(Collectors.toList());
List<OutputLabel> badbankOutputLabels = badbankOutputs.stream().map(payment -> getBadbankOutputLabel(transactionDiagram, payment)).collect(Collectors.toList());
outputLabels.addAll(badbankOutputLabels);
} else if(walletTx.getPayments().size() >= 5 && walletTx.getPayments().stream().mapToLong(Payment::getAmount).distinct().count() <= 1 && walletTx.getWallet() != null
&& walletTx.getWallet().getStandardAccountType() == StandardAccount.WHIRLPOOL_PREMIX && walletTx.getPayments().stream().anyMatch(walletTx::isPostmixSend)) {
OutputLabel mixOutputLabel = getMixOutputLabel(transactionDiagram, walletTx.getPayments());
if(mixOutputLabel != null) {
outputLabels.add(mixOutputLabel);
}
} else if(walletTx.getPayments().size() >= 5 && walletTx.getPayments().stream().mapToLong(Payment::getAmount).distinct().count() <= 1 && walletTx.getWallet() != null
&& walletTx.getWallet().getStandardAccountType() == StandardAccount.WHIRLPOOL_POSTMIX && walletTx.getPayments().stream().anyMatch(walletTx::isConsolidationSend)) {
OutputLabel remixOutputLabel = getRemixOutputLabel(transactionDiagram, walletTx.getPayments());
if(remixOutputLabel != null) {
outputLabels.add(remixOutputLabel);
}
} else {
List<Payment> payments = walletTx.getPayments().stream().filter(payment -> payment.getType() == Payment.Type.DEFAULT && !walletTx.isConsolidationSend(payment)).collect(Collectors.toList());
List<OutputLabel> paymentLabels = payments.stream().map(payment -> getOutputLabel(transactionDiagram, payment)).collect(Collectors.toList());
if(walletTx.getSelectedUtxos().values().stream().allMatch(Objects::isNull)) {
paymentLabels.sort(Comparator.comparingInt(paymentLabel -> (paymentLabel.text.startsWith("Receive") ? 0 : 1)));
}
outputLabels.addAll(paymentLabels);
List<Payment> consolidations = walletTx.getPayments().stream().filter(payment -> payment.getType() == Payment.Type.DEFAULT && walletTx.isConsolidationSend(payment)).collect(Collectors.toList());
outputLabels.addAll(consolidations.stream().map(consolidation -> getOutputLabel(transactionDiagram, consolidation)).collect(Collectors.toList()));
List<Payment> mixes = walletTx.getPayments().stream().filter(payment -> payment.getType() == Payment.Type.MIX || payment.getType() == Payment.Type.FAKE_MIX).collect(Collectors.toList());
outputLabels.addAll(mixes.stream().map(payment -> getOutputLabel(transactionDiagram, payment)).collect(Collectors.toList()));
}
Map<WalletNode, Long> changeMap = walletTx.getChangeMap();
outputLabels.addAll(changeMap.entrySet().stream().map(changeEntry -> getOutputLabel(transactionDiagram, changeEntry)).collect(Collectors.toList()));
OutputLabel feeOutputLabel = getFeeOutputLabel(transactionDiagram);
if(feeOutputLabel != null) {
outputLabels.add(feeOutputLabel);
}
for(OutputLabel outputLabel : outputLabels) {
maxWidth = Math.max(maxWidth, outputLabel.width);
outputs.add(outputLabel.hBox);
getChildren().add(outputLabel.hBox);
}
HBox buttonBox = new HBox();
buttonBox.setAlignment(Pos.CENTER_RIGHT);
buttonBox.getChildren().addAll(left, right);
getChildren().add(buttonBox);
setMaxWidth(maxWidth);
setPrefWidth(maxWidth);
if(outputLabels.size() > 0) {
displayedIndex.set(0);
}
}
private OutputLabel getPremixOutputLabel(TransactionDiagram transactionDiagram, List<Payment> premixOutputs) {
if(premixOutputs.isEmpty()) {
return null;
}
Payment premixOutput = premixOutputs.get(0);
long total = premixOutputs.stream().mapToLong(Payment::getAmount).sum();
Glyph glyph = GlyphUtils.getOutputGlyph(transactionDiagram.getWalletTransaction(), premixOutput);
String text;
if(premixOutputs.size() == 1) {
text = "Premix transaction with 1 output of " + transactionDiagram.getSatsValue(premixOutput.getAmount()) + " sats";
} else {
text = "Premix transaction with " + premixOutputs.size() + " outputs of " + transactionDiagram.getSatsValue(premixOutput.getAmount()) + " sats each ("
+ transactionDiagram.getSatsValue(total) + " sats)";
}
return getOutputLabel(glyph, text);
}
private OutputLabel getBadbankOutputLabel(TransactionDiagram transactionDiagram, Payment payment) {
Glyph glyph = GlyphUtils.getOutputGlyph(transactionDiagram.getWalletTransaction(), payment);
String text = "Badbank change of " + transactionDiagram.getSatsValue(payment.getAmount()) + " sats to " + payment.getAddress().toString();
return getOutputLabel(glyph, text);
}
private OutputLabel getWhirlpoolFeeOutputLabel(TransactionDiagram transactionDiagram, Payment whirlpoolFee, List<Payment> premixOutputs) {
long total = premixOutputs.stream().mapToLong(Payment::getAmount).sum();
double feePercentage = (double)whirlpoolFee.getAmount() / (total - whirlpoolFee.getAmount());
Glyph glyph = GlyphUtils.getOutputGlyph(transactionDiagram.getWalletTransaction(), whirlpoolFee);
String text = "Whirlpool fee of " + transactionDiagram.getSatsValue(whirlpoolFee.getAmount()) + " sats (" + String.format("%.2f", feePercentage * 100.0) + "% of total premix value)";
return getOutputLabel(glyph, text);
}
private OutputLabel getMixOutputLabel(TransactionDiagram transactionDiagram, List<Payment> mixOutputs) {
if(mixOutputs.isEmpty()) {
return null;
}
Payment remixOutput = mixOutputs.get(0);
long total = mixOutputs.stream().mapToLong(Payment::getAmount).sum();
Glyph glyph = GlyphUtils.getPremixGlyph();
String text = "Mix transaction with " + mixOutputs.size() + " outputs of " + transactionDiagram.getSatsValue(remixOutput.getAmount()) + " sats each ("
+ transactionDiagram.getSatsValue(total) + " sats)";
return getOutputLabel(glyph, text);
}
private OutputLabel getRemixOutputLabel(TransactionDiagram transactionDiagram, List<Payment> remixOutputs) {
if(remixOutputs.isEmpty()) {
return null;
}
Payment remixOutput = remixOutputs.get(0);
long total = remixOutputs.stream().mapToLong(Payment::getAmount).sum();
Glyph glyph = GlyphUtils.getPremixGlyph();
String text = "Remix transaction with " + remixOutputs.size() + " outputs of " + transactionDiagram.getSatsValue(remixOutput.getAmount()) + " sats each ("
+ transactionDiagram.getSatsValue(total) + " sats)";
return getOutputLabel(glyph, text);
}
private OutputLabel getOutputLabel(TransactionDiagram transactionDiagram, Payment payment) {
WalletTransaction walletTx = transactionDiagram.getWalletTransaction();
Wallet toWallet = walletTx.getToWallet(AppServices.get().getOpenWallets().keySet(), payment);
WalletNode toNode = walletTx.getWallet() != null && !walletTx.getWallet().isBip47() ? walletTx.getAddressNodeMap().get(payment.getAddress()) : null;
Glyph glyph = GlyphUtils.getOutputGlyph(transactionDiagram.getWalletTransaction(), payment);
String text = (toWallet == null ? (toNode != null ? "Consolidate " : "Pay ") : "Receive ") + transactionDiagram.getSatsValue(payment.getAmount()) + " sats to " + payment.getAddress().toString();
return getOutputLabel(glyph, text);
}
private OutputLabel getOutputLabel(TransactionDiagram transactionDiagram, Map.Entry<WalletNode, Long> changeEntry) {
WalletTransaction walletTx = transactionDiagram.getWalletTransaction();
Glyph glyph = GlyphUtils.getChangeGlyph();
String text = "Change of " + transactionDiagram.getSatsValue(changeEntry.getValue()) + " sats to " + walletTx.getChangeAddress(changeEntry.getKey()).toString();
return getOutputLabel(glyph, text);
}
private OutputLabel getFeeOutputLabel(TransactionDiagram transactionDiagram) {
WalletTransaction walletTx = transactionDiagram.getWalletTransaction();
if(walletTx.getFee() < 0) {
return null;
}
Glyph glyph = GlyphUtils.getFeeGlyph();
String text = "Fee of " + transactionDiagram.getSatsValue(walletTx.getFee()) + " sats (" + String.format("%.2f", walletTx.getFeePercentage() * 100.0) + "%)";
return getOutputLabel(glyph, text);
}
private OutputLabel getOutputLabel(Glyph glyph, String text) {
Label icon = new Label();
icon.setMinWidth(15);
glyph.setFontSize(12);
icon.setGraphic(glyph);
CopyableLabel label = new CopyableLabel();
label.setFont(Font.font("Roboto Mono Italic", 13));
label.setText(text);
HBox output = new HBox(5);
output.setAlignment(Pos.CENTER);
output.managedProperty().bind(output.visibleProperty());
output.setVisible(false);
output.getChildren().addAll(icon, label);
double lineWidth = TextUtils.computeTextWidth(label.getFont(), label.getText(), 0.0D) + 2 + getSpacing() + icon.getMinWidth() + 60;
return new OutputLabel(output, lineWidth, text);
}
public static Glyph getLeftGlyph() {
Glyph caretLeftGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.CARET_LEFT);
caretLeftGlyph.getStyleClass().add("label-left-icon");
caretLeftGlyph.setFontSize(15);
return caretLeftGlyph;
}
public static Glyph getRightGlyph() {
Glyph caretRightGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.CARET_RIGHT);
caretRightGlyph.getStyleClass().add("label-right-icon");
caretRightGlyph.setFontSize(15);
return caretRightGlyph;
}
private record OutputLabel(HBox hBox, double width, String text) {}
}
@@ -50,8 +50,7 @@ public class TransactionsTreeTable extends CoinTreeTable {
setPlaceholder(getDefaultPlaceholder(rootEntry.getWallet()));
setEditable(true);
setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY);
dateCol.setSortType(TreeTableColumn.SortType.DESCENDING);
getSortOrder().add(dateCol);
setSortColumn(0, TreeTableColumn.SortType.DESCENDING);
}
public void updateAll(WalletTransactionsEntry rootEntry) {
@@ -61,16 +60,13 @@ public class TransactionsTreeTable extends CoinTreeTable {
setRoot(rootItem);
rootItem.setExpanded(true);
if(getColumns().size() > 0 && getSortOrder().isEmpty()) {
TreeTableColumn<Entry, ?> dateCol = getColumns().get(0);
getSortOrder().add(dateCol);
dateCol.setSortType(TreeTableColumn.SortType.DESCENDING);
}
setSortColumn(0, TreeTableColumn.SortType.DESCENDING);
}
public void updateHistory() {
//Transaction entries should have already been updated using WalletTransactionsEntry.updateHistory, so only a resort required
sort();
setSortColumn(0, TreeTableColumn.SortType.DESCENDING);
}
public void updateLabel(Entry entry) {
@@ -0,0 +1,46 @@
package com.sparrowwallet.sparrow.control;
import javafx.scene.control.TreeTableColumn;
public class TreeTableColumnConfig {
private final int index;
private final Integer width;
private final TreeTableColumn.SortType sortType;
public TreeTableColumnConfig(int index, Integer width, TreeTableColumn.SortType sortType) {
this.index = index;
this.width = width;
this.sortType = sortType;
}
public TreeTableColumnConfig(int index, String width, String sortType) {
this.index = index;
this.width = width.isEmpty() ? null : Integer.valueOf(width, 10);
this.sortType = sortType.isEmpty() ? null : TreeTableColumn.SortType.valueOf(sortType);
}
public int getIndex() {
return index;
}
public Integer getWidth() {
return width;
}
public TreeTableColumn.SortType getSortType() {
return sortType;
}
public String toString() {
return index + "-" + (width == null ? "" : width) + "-" + (sortType == null ? "" : sortType);
}
public static TreeTableColumnConfig fromString(String columnConfig) {
String[] parts = columnConfig.split("-", 3);
if(parts.length == 3) {
return new TreeTableColumnConfig(Integer.parseInt(parts[0]), parts[1], parts[2]);
}
return new TreeTableColumnConfig(Integer.parseInt(parts[0]), (Integer)null, null);
}
}
@@ -0,0 +1,42 @@
package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.sparrow.wallet.Entry;
import javafx.scene.control.TreeTableColumn;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
public class TreeTableConfig {
private final List<TreeTableColumnConfig> columnConfigs;
public TreeTableConfig(CoinTreeTable treeTable) {
columnConfigs = new ArrayList<>();
TreeTableColumn<Entry, ?> sortColumn = treeTable.getSortOrder().isEmpty() ? null : treeTable.getSortOrder().get(0);
for(int i = 0; i < treeTable.getColumns().size(); i++) {
TreeTableColumn<Entry, ?> column = treeTable.getColumns().get(i);
//TODO: Support column widths
columnConfigs.add(new TreeTableColumnConfig(i, null, sortColumn == column ? column.getSortType() : null));
}
}
public TreeTableConfig(List<TreeTableColumnConfig> columnConfigs) {
this.columnConfigs = columnConfigs;
}
public String toString() {
StringJoiner joiner = new StringJoiner("|");
columnConfigs.stream().forEach(col -> joiner.add(col.toString()));
return joiner.toString();
}
public static TreeTableConfig fromString(String tableConfig) {
List<TreeTableColumnConfig> columnConfigs = new ArrayList<>();
String[] parts = tableConfig.split("\\|");
for(String part : parts) {
columnConfigs.add(TreeTableColumnConfig.fromString(part));
}
return new TreeTableConfig(columnConfigs);
}
}
@@ -83,8 +83,7 @@ public class UtxosTreeTable extends CoinTreeTable {
setPlaceholder(getDefaultPlaceholder(rootEntry.getWallet()));
setEditable(true);
setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY);
amountCol.setSortType(TreeTableColumn.SortType.DESCENDING);
getSortOrder().add(amountCol);
setSortColumn(getColumns().size() - 1, TreeTableColumn.SortType.DESCENDING);
getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
}
@@ -96,17 +95,14 @@ public class UtxosTreeTable extends CoinTreeTable {
setRoot(rootItem);
rootItem.setExpanded(true);
if(getColumns().size() > 0 && getSortOrder().isEmpty()) {
TreeTableColumn<Entry, ?> amountCol = getColumns().get(getColumns().size() - 1);
getSortOrder().add(amountCol);
amountCol.setSortType(TreeTableColumn.SortType.DESCENDING);
}
setSortColumn(getColumns().size() - 1, TreeTableColumn.SortType.DESCENDING);
}
public void updateHistory() {
//Utxo entries should have already been updated, so only a resort required
if(!getRoot().getChildren().isEmpty()) {
sort();
setSortColumn(getColumns().size() - 1, TreeTableColumn.SortType.DESCENDING);
}
}
@@ -6,6 +6,7 @@ import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.event.WalletExportEvent;
import com.sparrowwallet.sparrow.wallet.WalletForm;
import com.sparrowwallet.sparrow.io.*;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
@@ -17,7 +18,9 @@ import java.util.List;
public class WalletExportDialog extends Dialog<Wallet> {
private Wallet wallet;
public WalletExportDialog(Wallet wallet) {
public WalletExportDialog(WalletForm walletForm) {
this.wallet = walletForm.getWallet();
EventManager.get().register(this);
setOnCloseRequest(event -> {
EventManager.get().unregister(this);
@@ -42,9 +45,10 @@ public class WalletExportDialog extends Dialog<Wallet> {
List<WalletExport> exporters;
if(wallet.getPolicyType() == PolicyType.SINGLE) {
exporters = List.of(new Electrum(), new ElectrumPersonalServer(), new Descriptor(), new SpecterDesktop(), new Sparrow(), new WalletLabels());
exporters = List.of(new Electrum(), new ElectrumPersonalServer(), new Descriptor(), new SpecterDesktop(), new Sparrow(), new WalletLabels(), new WalletTransactions(walletForm));
} else if(wallet.getPolicyType() == PolicyType.MULTI) {
exporters = List.of(new Bip129(), new CaravanMultisig(), new ColdcardMultisig(), new CoboVaultMultisig(), new Electrum(), new ElectrumPersonalServer(), new KeystoneMultisig(), new Descriptor(), new JadeMultisig(), new PassportMultisig(), new SpecterDesktop(), new BlueWalletMultisig(), new SpecterDIY(), new Sparrow(), new WalletLabels());
exporters = List.of(new Bip129(), new CaravanMultisig(), new ColdcardMultisig(), new CoboVaultMultisig(), new Electrum(), new ElectrumPersonalServer(), new KeystoneMultisig(),
new Descriptor(), new JadeMultisig(), new PassportMultisig(), new SpecterDesktop(), new BlueWalletMultisig(), new SpecterDIY(), new Sparrow(), new WalletLabels(), new WalletTransactions(walletForm));
} else {
throw new UnsupportedOperationException("Cannot export wallet with policy type " + wallet.getPolicyType());
}
@@ -64,6 +68,7 @@ public class WalletExportDialog extends Dialog<Wallet> {
dialogPane.getButtonTypes().addAll(cancelButtonType);
dialogPane.setPrefWidth(500);
dialogPane.setPrefHeight(480);
dialogPane.setMinHeight(dialogPane.getPrefHeight());
AppServices.moveToActiveWindowScreen(this);
setResultConverter(dialogButton -> dialogButton != cancelButtonType ? wallet : null);
@@ -51,7 +51,7 @@ public class WalletImportDialog extends Dialog<Wallet> {
AnchorPane.setRightAnchor(scrollPane, 0.0);
importAccordion = new Accordion();
List<KeystoreFileImport> keystoreImporters = List.of(new ColdcardSinglesig(), new CoboVaultSinglesig(), new Jade(), new KeystoneSinglesig(), new PassportSinglesig(), new GordianSeedTool(), new SeedSigner(), new SpecterDIY());
List<KeystoreFileImport> keystoreImporters = List.of(new ColdcardSinglesig(), new CoboVaultSinglesig(), new Jade(), new KeystoneSinglesig(), new PassportSinglesig(), new GordianSeedTool(), new SeedSigner(), new SpecterDIY(), new Krux(), new AirGapVault());
for(KeystoreFileImport importer : keystoreImporters) {
if(!importer.isDeprecated() || Config.get().isShowDeprecatedImportExport()) {
FileWalletKeystoreImportPane importPane = new FileWalletKeystoreImportPane(importer);
@@ -59,7 +59,7 @@ public class WalletImportDialog extends Dialog<Wallet> {
}
}
List<WalletImport> walletImporters = new ArrayList<>(List.of(new Bip129(), new CaravanMultisig(), new ColdcardMultisig(), new CoboVaultMultisig(), new Electrum(), new KeystoneMultisig(), new Descriptor(), new SpecterDesktop(), new BlueWalletMultisig(), new Sparrow()));
List<WalletImport> walletImporters = new ArrayList<>(List.of(new Bip129(), new CaravanMultisig(), new ColdcardMultisig(), new CoboVaultMultisig(), new Electrum(), new KeystoneMultisig(), new Descriptor(), new SpecterDesktop(), new BlueWalletMultisig(), new Sparrow(), new JadeMultisig()));
if(!selectedWalletForms.isEmpty()) {
walletImporters.add(new WalletLabels(selectedWalletForms));
}
@@ -90,6 +90,7 @@ public class WalletImportDialog extends Dialog<Wallet> {
dialogPane.setPrefWidth(500);
dialogPane.setPrefHeight(600);
dialogPane.setMinHeight(dialogPane.getPrefHeight());
AppServices.moveToActiveWindowScreen(this);
setResultConverter(dialogButton -> dialogButton != cancelButtonType ? wallet : null);
@@ -0,0 +1,172 @@
package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.CurrencyRate;
import com.sparrowwallet.sparrow.io.Config;
import com.sparrowwallet.sparrow.net.ExchangeSource;
import com.sparrowwallet.sparrow.wallet.Entry;
import com.sparrowwallet.sparrow.wallet.Function;
import com.sparrowwallet.sparrow.wallet.WalletForm;
import com.sparrowwallet.sparrow.wallet.WalletTransactionsEntry;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.geometry.Side;
import javafx.scene.chart.NumberAxis;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class WalletSummaryDialog extends Dialog<Void> {
public WalletSummaryDialog(List<WalletForm> walletForms) {
if(walletForms.isEmpty()) {
throw new IllegalArgumentException("No wallets selected to summarize");
}
Wallet masterWallet = walletForms.get(0).getMasterWallet();
final DialogPane dialogPane = getDialogPane();
dialogPane.getStylesheets().add(AppServices.class.getResource("general.css").toExternalForm());
dialogPane.getStylesheets().add(AppServices.class.getResource("dialog.css").toExternalForm());
dialogPane.getStylesheets().add(AppServices.class.getResource("wallet/wallet.css").toExternalForm());
dialogPane.getStylesheets().add(AppServices.class.getResource("wallet/transactions.css").toExternalForm());
AppServices.setStageIcon(dialogPane.getScene().getWindow());
dialogPane.setHeaderText("Wallet Summary for " + masterWallet.getName());
Image image = new Image("image/sparrow-small.png", 50, 50, false, false);
if(!image.isError()) {
ImageView imageView = new ImageView();
imageView.setSmooth(false);
imageView.setImage(image);
dialogPane.setGraphic(imageView);
}
HBox hBox = new HBox(40);
CoinTreeTable table = new CoinTreeTable();
TreeTableColumn<Entry, String> nameColumn = new TreeTableColumn<>("Wallet");
nameColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<Entry, String> param) -> {
return new ReadOnlyObjectWrapper<>(param.getValue().getValue().getLabel());
});
nameColumn.setCellFactory(p -> new LabelCell());
table.getColumns().add(nameColumn);
TreeTableColumn<Entry, Number> balanceColumn = new TreeTableColumn<>("Balance");
balanceColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<Entry, Number> param) -> {
return new ReadOnlyObjectWrapper<>(param.getValue().getValue().getValue());
});
balanceColumn.setCellFactory(p -> new CoinCell());
table.getColumns().add(balanceColumn);
table.setUnitFormat(masterWallet);
CurrencyRate currencyRate = AppServices.getFiatCurrencyExchangeRate();
if(currencyRate != null && currencyRate.isAvailable() && Config.get().getExchangeSource() != ExchangeSource.NONE) {
TreeTableColumn<Entry, Number> fiatColumn = new TreeTableColumn<>(currencyRate.getCurrency().getSymbol());
fiatColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<Entry, Number> param) -> {
return new ReadOnlyObjectWrapper<>(param.getValue().getValue().getValue());
});
fiatColumn.setCellFactory(p -> new FiatCell());
table.getColumns().add(fiatColumn);
table.setCurrencyRate(currencyRate);
}
SummaryEntry rootEntry = new SummaryEntry(walletForms);
TreeItem<Entry> rootItem = new TreeItem<>(rootEntry);
for(Entry childEntry : rootEntry.getChildren()) {
TreeItem<Entry> childItem = new TreeItem<>(childEntry);
rootItem.getChildren().add(childItem);
childItem.getChildren().add(new TreeItem<>(new UnconfirmedEntry((WalletTransactionsEntry)childEntry)));
}
table.setShowRoot(true);
table.setRoot(rootItem);
rootItem.setExpanded(true);
table.setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY);
table.setPrefWidth(450);
VBox vBox = new VBox();
vBox.getChildren().add(table);
hBox.getChildren().add(vBox);
NumberAxis xAxis = new NumberAxis();
xAxis.setSide(Side.BOTTOM);
xAxis.setForceZeroInRange(false);
xAxis.setMinorTickVisible(false);
NumberAxis yAxis = new NumberAxis();
yAxis.setSide(Side.LEFT);
BalanceChart balanceChart = new BalanceChart(xAxis, yAxis);
balanceChart.initialize(new WalletTransactionsEntry(masterWallet, true));
balanceChart.setAnimated(false);
balanceChart.setLegendVisible(false);
balanceChart.setVerticalGridLinesVisible(false);
hBox.getChildren().add(balanceChart);
getDialogPane().setContent(hBox);
ButtonType okButtonType = new javafx.scene.control.ButtonType("Done", ButtonBar.ButtonData.OK_DONE);
dialogPane.getButtonTypes().addAll(okButtonType);
setResizable(true);
AppServices.moveToActiveWindowScreen(this);
}
public static class SummaryEntry extends Entry {
private SummaryEntry(List<WalletForm> walletForms) {
super(walletForms.get(0).getWallet(), walletForms.get(0).getWallet().getName(), walletForms.stream().map(WalletForm::getWalletTransactionsEntry).collect(Collectors.toList()));
}
@Override
public Long getValue() {
long value = 0;
for(Entry entry : getChildren()) {
value += entry.getValue();
}
return value;
}
@Override
public String getEntryType() {
return null;
}
@Override
public Function getWalletFunction() {
return Function.TRANSACTIONS;
}
}
public static class UnconfirmedEntry extends Entry {
private final WalletTransactionsEntry walletTransactionsEntry;
private UnconfirmedEntry(WalletTransactionsEntry walletTransactionsEntry) {
super(walletTransactionsEntry.getWallet(), "Unconfirmed", Collections.emptyList());
this.walletTransactionsEntry = walletTransactionsEntry;
}
@Override
public Long getValue() {
return walletTransactionsEntry.getMempoolBalance();
}
@Override
public String getEntryType() {
return null;
}
@Override
public Function getWalletFunction() {
return Function.TRANSACTIONS;
}
}
}
@@ -0,0 +1,15 @@
package com.sparrowwallet.sparrow.event;
import com.sparrowwallet.drongo.psbt.PSBT;
public class PSBTReorderedEvent {
private final PSBT psbt;
public PSBTReorderedEvent(PSBT psbt) {
this.psbt = psbt;
}
public PSBT getPsbt() {
return psbt;
}
}
@@ -0,0 +1,15 @@
package com.sparrowwallet.sparrow.event;
import com.sparrowwallet.drongo.wallet.Wallet;
public class WhirlpoolIndexHighFrequencyEvent {
private final Wallet wallet;
public WhirlpoolIndexHighFrequencyEvent(Wallet wallet) {
this.wallet = wallet;
}
public Wallet getWallet() {
return wallet;
}
}
@@ -25,6 +25,8 @@ public class FontAwesome5 extends GlyphFont {
BTC('\uf15a'),
BULLSEYE('\uf140'),
CAMERA('\uf030'),
CARET_LEFT('\uf0d9'),
CARET_RIGHT('\uf0da'),
CHECK_CIRCLE('\uf058'),
CIRCLE('\uf111'),
COINS('\uf51e'),
@@ -49,8 +51,10 @@ public class FontAwesome5 extends GlyphFont {
LINK('\uf0c1'),
LOCK('\uf023'),
LOCK_OPEN('\uf3c1'),
LONG_ARROW_ALT_RIGHT('\uf30b'),
MAGNIFYING_GLASS_PLUS('\uf00e'),
MAGNIFYING_GLASS_MINUS('\uf010'),
MICROCHIP('\uf2db'),
MINUS_CIRCLE('\uf056'),
PEN_FANCY('\uf5ac'),
PLUS('\uf067'),
@@ -0,0 +1,178 @@
package com.sparrowwallet.sparrow.glyphfont;
import com.sparrowwallet.drongo.wallet.Payment;
import com.sparrowwallet.drongo.wallet.WalletTransaction;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.control.TransactionDiagram;
import org.controlsfx.glyphfont.FontAwesome;
import org.controlsfx.glyphfont.Glyph;
public class GlyphUtils {
public static Glyph getOutputGlyph(WalletTransaction walletTx, Payment payment) {
if(payment.getType().equals(Payment.Type.MIX)) {
return getMixGlyph();
} else if(payment.getType().equals(Payment.Type.FAKE_MIX)) {
return getFakeMixGlyph();
} else if(walletTx.isConsolidationSend(payment)) {
return getConsolidationGlyph();
} else if(walletTx.isPremixSend(payment)) {
return getPremixGlyph();
} else if(walletTx.isBadbankSend(payment)) {
return getBadbankGlyph();
} else if(payment.getType().equals(Payment.Type.WHIRLPOOL_FEE)) {
return getWhirlpoolFeeGlyph();
} else if(payment instanceof TransactionDiagram.AdditionalPayment) {
return ((TransactionDiagram.AdditionalPayment)payment).getOutputGlyph(walletTx);
} else if(walletTx.getToWallet(AppServices.get().getOpenWallets().keySet(), payment) != null) {
return getDepositGlyph();
} else if(walletTx.isDuplicateAddress(payment)) {
return getPaymentWarningGlyph();
}
return getPaymentGlyph();
}
public static Glyph getPaymentGlyph() {
Glyph paymentGlyph = new Glyph("FontAwesome", FontAwesome.Glyph.SEND);
paymentGlyph.getStyleClass().add("payment-icon");
paymentGlyph.setFontSize(12);
return paymentGlyph;
}
public static Glyph getPaymentWarningGlyph() {
Glyph paymentWarningGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.EXCLAMATION_TRIANGLE);
paymentWarningGlyph.getStyleClass().add("payment-warning-icon");
paymentWarningGlyph.setFontSize(12);
return paymentWarningGlyph;
}
public static Glyph getConsolidationGlyph() {
Glyph consolidationGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.REPLY_ALL);
consolidationGlyph.getStyleClass().add("consolidation-icon");
consolidationGlyph.setFontSize(12);
return consolidationGlyph;
}
public static Glyph getDepositGlyph() {
Glyph depositGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.ARROW_DOWN);
depositGlyph.getStyleClass().add("deposit-icon");
depositGlyph.setFontSize(12);
return depositGlyph;
}
public static Glyph getPremixGlyph() {
Glyph premixGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.RANDOM);
premixGlyph.getStyleClass().add("premix-icon");
premixGlyph.setFontSize(12);
return premixGlyph;
}
public static Glyph getBadbankGlyph() {
Glyph badbankGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.BIOHAZARD);
badbankGlyph.getStyleClass().add("badbank-icon");
badbankGlyph.setFontSize(12);
return badbankGlyph;
}
public static Glyph getWhirlpoolFeeGlyph() {
Glyph whirlpoolFeeGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.HAND_HOLDING_WATER);
whirlpoolFeeGlyph.getStyleClass().add("whirlpoolfee-icon");
whirlpoolFeeGlyph.setFontSize(12);
return whirlpoolFeeGlyph;
}
public static Glyph getFakeMixGlyph() {
Glyph fakeMixGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.THEATER_MASKS);
fakeMixGlyph.getStyleClass().add("fakemix-icon");
fakeMixGlyph.setFontSize(12);
return fakeMixGlyph;
}
public static Glyph getTxoGlyph() {
return getChangeGlyph();
}
public static Glyph getMixGlyph() {
Glyph payjoinGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.RANDOM);
payjoinGlyph.getStyleClass().add("mix-icon");
payjoinGlyph.setFontSize(12);
return payjoinGlyph;
}
public static Glyph getExternalInputGlyph() {
Glyph externalGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.LONG_ARROW_ALT_RIGHT);
externalGlyph.getStyleClass().add("external-input-icon");
externalGlyph.setFontSize(12);
return externalGlyph;
}
public static Glyph getExcludeGlyph() {
Glyph excludeGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.TIMES_CIRCLE);
excludeGlyph.getStyleClass().add("exclude-utxo");
excludeGlyph.setFontSize(12);
return excludeGlyph;
}
public static Glyph getChangeGlyph() {
Glyph changeGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.COINS);
changeGlyph.getStyleClass().add("change-icon");
changeGlyph.setFontSize(12);
return changeGlyph;
}
public static Glyph getChangeWarningGlyph() {
Glyph changeWarningGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.EXCLAMATION_TRIANGLE);
changeWarningGlyph.getStyleClass().add("change-warning-icon");
changeWarningGlyph.setFontSize(12);
return changeWarningGlyph;
}
public static Glyph getChangeReplaceGlyph() {
Glyph changeReplaceGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.ARROW_DOWN);
changeReplaceGlyph.getStyleClass().add("change-replace-icon");
changeReplaceGlyph.setFontSize(12);
return changeReplaceGlyph;
}
public static Glyph getFeeGlyph() {
Glyph feeGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.HAND_HOLDING);
feeGlyph.getStyleClass().add("fee-icon");
feeGlyph.setFontSize(12);
return feeGlyph;
}
public static Glyph getWarningGlyph() {
Glyph feeWarningGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.EXCLAMATION_CIRCLE);
feeWarningGlyph.getStyleClass().add("fee-warning-icon");
feeWarningGlyph.setFontSize(12);
return feeWarningGlyph;
}
public static Glyph getQuestionGlyph() {
Glyph feeWarningGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.QUESTION_CIRCLE);
feeWarningGlyph.getStyleClass().add("question-icon");
feeWarningGlyph.setFontSize(12);
return feeWarningGlyph;
}
public static Glyph getLockGlyph() {
Glyph lockGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.LOCK);
lockGlyph.getStyleClass().add("lock-icon");
lockGlyph.setFontSize(12);
return lockGlyph;
}
public static Glyph getUserGlyph() {
Glyph userGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.USER);
userGlyph.getStyleClass().add("user-icon");
userGlyph.setFontSize(12);
return userGlyph;
}
public static Glyph getOpcodeGlyph() {
Glyph userGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.MICROCHIP);
userGlyph.getStyleClass().add("opcode-icon");
userGlyph.setFontSize(12);
return userGlyph;
}
}
@@ -0,0 +1,35 @@
package com.sparrowwallet.sparrow.io;
import com.sparrowwallet.drongo.wallet.WalletModel;
public class AirGapVault extends KeystoneSinglesig {
@Override
public String getName() {
return "AirGap Vault";
}
@Override
public String getKeystoreImportDescription(int account) {
return "Import QR created on your AirGap Vault, by selecting the Secret > Account > Sparrow Wallet";
}
@Override
public WalletModel getWalletModel() {
return WalletModel.AIRGAP_VAULT;
}
@Override
public boolean isFileFormatAvailable() {
return false;
}
@Override
public boolean isWalletImportFileFormatAvailable() {
return false;
}
@Override
public boolean isDeprecated() {
return true;
}
}
@@ -189,7 +189,7 @@ public class Bip129 implements KeystoreFileExport, KeystoreFileImport, WalletExp
}
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
public void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException {
try {
String record = "BSMS 1.0\n" +
OutputDescriptor.getOutputDescriptor(wallet) +
@@ -28,7 +28,7 @@ public class CaravanMultisig implements WalletImport, WalletExport {
@Override
public String getName() {
return "Caravan Multisig";
return "Unchained or Caravan Multisig";
}
@Override
@@ -94,7 +94,7 @@ public class CaravanMultisig implements WalletImport, WalletExport {
}
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
public void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException {
if(!wallet.isValid()) {
throw new ExportException("Cannot export an incomplete wallet");
}
@@ -10,6 +10,7 @@ import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletModel;
import com.sparrowwallet.sparrow.io.ckcard.CkCardApi;
import com.sparrowwallet.sparrow.io.satochip.SatoCardApi;
import javafx.beans.property.StringProperty;
import javafx.concurrent.Service;
import org.controlsfx.tools.Platform;
@@ -23,6 +24,7 @@ import javax.smartcardio.TerminalFactory;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -33,19 +35,30 @@ public abstract class CardApi {
new File("/usr/lib/libpcsclite.so.1"),
new File("/usr/local/lib/libpcsclite.so.1"),
new File("/lib/x86_64-linux-gnu/libpcsclite.so.1"),
new File("/lib/aarch64-linux-gnu/libpcsclite.so.1")};
new File("/lib/aarch64-linux-gnu/libpcsclite.so.1"),
new File("/usr/lib64/libpcsclite.so.1"),
new File("/usr/lib/x86_64-linux-gnu/libpcsclite.so.1")};
private static boolean initialized;
public static List<WalletModel> getConnectedCards() throws CardException {
List<WalletModel> cards = new ArrayList<>();
try {
CkCardApi ckCardApi = new CkCardApi(null, null);
return List.of(ckCardApi.getCardType());
cards.add(ckCardApi.getCardType());
} catch(Exception e) {
//ignore
}
return Collections.emptyList();
try {
SatoCardApi satoCardApi = new SatoCardApi(null, null);
cards.add(satoCardApi.getCardType());
} catch(Exception e) {
//ignore
}
return cards;
}
public static CardApi getCardApi(WalletModel walletModel, String pin) throws CardException {
@@ -53,6 +66,10 @@ public abstract class CardApi {
return new CkCardApi(walletModel, pin);
}
if(walletModel == WalletModel.SATOCHIP) {
return new SatoCardApi(walletModel, pin);
}
throw new IllegalArgumentException("Cannot create card API for " + walletModel.toDisplayString());
}
@@ -6,5 +6,5 @@ import javax.smartcardio.CardException;
public interface CardImport extends ImportExport {
boolean isInitialized() throws CardException;
void initialize(String pin, byte[] chainCode, StringProperty messageProperty) throws CardException;
void initialize(String pin, byte[] entropy, StringProperty messageProperty) throws CardException;
}
@@ -165,7 +165,7 @@ public class ColdcardMultisig implements WalletImport, KeystoreFileImport, Walle
}
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
public void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException {
if(!wallet.isValid()) {
throw new ExportException("Cannot export an incomplete wallet");
}
@@ -78,6 +78,7 @@ public class Config {
private int maxPageSize = DEFAULT_PAGE_SIZE;
private boolean usePayNym;
private boolean sameAppMixing;
private boolean mempoolFullRbf;
private Double appWidth;
private Double appHeight;
@@ -670,6 +671,15 @@ public class Config {
flush();
}
public boolean isMempoolFullRbf() {
return mempoolFullRbf;
}
public void setMempoolFullRbf(boolean mempoolFullRbf) {
this.mempoolFullRbf = mempoolFullRbf;
flush();
}
public Double getAppWidth() {
return appWidth;
}
@@ -23,7 +23,7 @@ public class Descriptor implements WalletImport, WalletExport {
}
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
public void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write("# Receive and change descriptor (BIP389):");
@@ -65,7 +65,7 @@ public class Descriptor implements WalletImport, WalletExport {
@Override
public boolean isWalletExportScannable() {
return false;
return true;
}
@Override
@@ -2,10 +2,7 @@ package com.sparrowwallet.sparrow.io;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.sparrowwallet.drongo.ExtendedKey;
import com.sparrowwallet.drongo.KeyDerivation;
import com.sparrowwallet.drongo.KeyPurpose;
import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.drongo.*;
import com.sparrowwallet.drongo.address.Address;
import com.sparrowwallet.drongo.crypto.*;
import com.sparrowwallet.drongo.policy.Policy;
@@ -18,7 +15,10 @@ import org.slf4j.LoggerFactory;
import java.io.*;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
public class Electrum implements KeystoreFileImport, WalletImport, WalletExport {
@@ -301,11 +301,11 @@ public class Electrum implements KeystoreFileImport, WalletImport, WalletExport
@Override
public String getExportFileExtension(Wallet wallet) {
return "json";
return wallet.isEncrypted() ? "" : "json";
}
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
public void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException {
try {
ElectrumJsonWallet ew = new ElectrumJsonWallet();
if(wallet.getPolicyType().equals(PolicyType.SINGLE)) {
@@ -342,7 +342,18 @@ public class Electrum implements KeystoreFileImport, WalletImport, WalletExport
ek.seed = keystore.getSeed().getMnemonicString().asString();
ek.passphrase = keystore.getSeed().getPassphrase() == null ? null : keystore.getSeed().getPassphrase().asString();
}
ew.use_encryption = false;
if(password != null) {
ek.xprv = encrypt(ek.xprv, password);
if(ek.seed != null) {
ek.seed = encrypt(ek.seed, password);
}
if(ek.passphrase != null) {
ek.passphrase = encrypt(ek.passphrase, password);
}
ew.use_encryption = true;
} else {
ew.use_encryption = false;
}
} else if(keystore.getSource() == KeystoreSource.SW_WATCH) {
ek.type = "bip32";
ek.xpub = keystore.getExtendedPublicKey().toString(xpubHeader);
@@ -373,14 +384,41 @@ public class Electrum implements KeystoreFileImport, WalletImport, WalletExport
gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
String json = gson.toJson(eJson);
if(password != null) {
ECKey encryptionKey = Pbkdf2KeyDeriver.DEFAULT_INSTANCE.deriveECKey(password);
outputStream = new DeflaterOutputStream(new ECIESOutputStream(outputStream, encryptionKey));
}
outputStream.write(json.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
outputStream.close();
} catch (Exception e) {
log.error("Error exporting Electrum Wallet", e);
throw new ExportException("Error exporting Electrum Wallet", e);
}
}
private String encrypt(String plain, String password) throws NoSuchAlgorithmException {
if(plain == null) {
return null;
}
byte[] plainBytes = plain.getBytes(StandardCharsets.UTF_8);
KeyDeriver keyDeriver = new DoubleSha256KeyDeriver();
Key key = keyDeriver.deriveKey(password);
KeyCrypter keyCrypter = new AESKeyCrypter();
byte[] initializationVector = new byte[16];
SecureRandom.getInstanceStrong().nextBytes(initializationVector);
EncryptedData encryptedData = keyCrypter.encrypt(plainBytes, initializationVector, key);
byte[] encrypted = new byte[initializationVector.length + encryptedData.getEncryptedBytes().length];
System.arraycopy(initializationVector, 0, encrypted, 0, 16);
System.arraycopy(encryptedData.getEncryptedBytes(), 0, encrypted, 16, encryptedData.getEncryptedBytes().length);
byte[] encryptedBase64 = Base64.getEncoder().encode(encrypted);
return new String(encryptedBase64, StandardCharsets.UTF_8);
}
@Override
public boolean isEncrypted(File file) {
return (FileType.BINARY.equals(IOUtils.getFileType(file)));
@@ -29,7 +29,7 @@ public class ElectrumPersonalServer implements WalletExport {
}
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
public void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException {
if(wallet.getScriptType() == ScriptType.P2TR) {
throw new ExportException(getName() + " does not support Taproot wallets.");
}
@@ -36,7 +36,7 @@ public class Hwi {
private static final Logger log = LoggerFactory.getLogger(Hwi.class);
private static final String HWI_HOME_DIR = "hwi";
private static final String HWI_VERSION_PREFIX = "hwi-";
private static final String HWI_VERSION = "2.2.1";
private static final String HWI_VERSION = "2.3.1";
private static final String HWI_VERSION_DIR = HWI_VERSION_PREFIX + HWI_VERSION;
private static boolean isPromptActive = false;
@@ -1,8 +1,11 @@
package com.sparrowwallet.sparrow.io;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletModel;
import java.io.InputStream;
public class JadeMultisig extends ColdcardMultisig {
@Override
public String getName() {
@@ -38,4 +41,30 @@ public class JadeMultisig extends ColdcardMultisig {
public boolean walletExportRequiresDecryption() {
return false;
}
@Override
public String getWalletImportDescription() {
return "Import the QR created using Options > Wallet > Registered Wallets on your Jade.";
}
@Override
public boolean isWalletImportScannable() {
return true;
}
@Override
public boolean isWalletImportFileFormatAvailable() {
return false;
}
@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", "Jade"));
keystore.setWalletModel(WalletModel.JADE);
}
return wallet;
}
}
@@ -0,0 +1,25 @@
package com.sparrowwallet.sparrow.io;
import com.sparrowwallet.drongo.wallet.WalletModel;
public class Krux extends SpecterDIY {
@Override
public String getName() {
return "Krux";
}
@Override
public String getKeystoreImportDescription(int account) {
return "Import file or QR created on your Krux by selecting Extended Public Key from the main menu once you have loaded your mnemonic.";
}
@Override
public WalletModel getWalletModel() {
return WalletModel.KRUX;
}
@Override
public boolean isFileFormatAvailable() {
return false;
}
}
@@ -1,6 +1,7 @@
package com.sparrowwallet.sparrow.io;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
@@ -104,7 +105,7 @@ public class PdfUtils {
private static javafx.scene.image.Image getQrCode(String fragment) throws IOException, WriterException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix qrMatrix = qrCodeWriter.encode(fragment.toUpperCase(Locale.ROOT), BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT);
BitMatrix qrMatrix = qrCodeWriter.encode(fragment.toUpperCase(Locale.ROOT), BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, Map.of(EncodeHintType.MARGIN, "2"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(qrMatrix, "PNG", baos, new MatrixToImageConfig());
@@ -28,7 +28,7 @@ public class Sparrow implements WalletImport, WalletExport {
}
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
public void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException {
try {
Wallet exportedWallet = !wallet.isMasterWallet() ? wallet.getMasterWallet() : wallet;
PersistenceType persistenceType = PersistenceType.DB;
@@ -65,7 +65,7 @@ public class SpecterDIY implements KeystoreFileImport, WalletExport {
}
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
public void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException {
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
writer.append("addwallet ").append(wallet.getFullName()).append("&").append(OutputDescriptor.getOutputDescriptor(wallet).toString().replace('\'', 'h')).append("\n");
@@ -18,7 +18,7 @@ public class SpecterDesktop implements WalletImport, WalletExport {
private static final Logger log = LoggerFactory.getLogger(SpecterDesktop.class);
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
public void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException {
try {
SpecterWallet specterWallet = new SpecterWallet();
specterWallet.label = wallet.getFullName();
@@ -8,7 +8,6 @@ import com.sparrowwallet.drongo.wallet.StandardAccount;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.SparrowWallet;
import com.sparrowwallet.sparrow.control.WalletPasswordDialog;
import com.sparrowwallet.sparrow.soroban.Soroban;
import com.sparrowwallet.sparrow.whirlpool.Whirlpool;
import javafx.concurrent.ScheduledService;
@@ -753,7 +752,7 @@ public class Storage {
protected Void call() throws IOException, ExportException {
Sparrow export = new Sparrow();
try(BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newWalletFile))) {
export.exportWallet(wallet, outputStream);
export.exportWallet(wallet, outputStream, null);
}
return null;
@@ -5,7 +5,7 @@ import com.sparrowwallet.drongo.wallet.Wallet;
import java.io.OutputStream;
public interface WalletExport extends ImportExport {
void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException;
void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException;
String getWalletExportDescription();
String getExportFileExtension(Wallet wallet);
boolean isWalletExportScannable();
@@ -8,4 +8,7 @@ public interface WalletImport extends FileImport {
String getWalletImportDescription();
Wallet importWallet(InputStream inputStream, String password) throws ImportException;
boolean isWalletImportScannable();
default boolean isWalletImportFileFormatAvailable() {
return true;
}
}
@@ -37,7 +37,7 @@ public class WalletLabels implements WalletImport, WalletExport {
@Override
public String getName() {
return "Wallet Labels";
return "Labels";
}
@Override
@@ -46,7 +46,7 @@ public class WalletLabels implements WalletImport, WalletExport {
}
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream) throws ExportException {
public void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException {
List<Label> labels = new ArrayList<>();
List<Wallet> allWallets = wallet.isMasterWallet() ? wallet.getAllWallets() : wallet.getMasterWallet().getAllWallets();
for(Wallet exportWallet : allWallets) {
@@ -0,0 +1,179 @@
package com.sparrowwallet.sparrow.io;
import com.csvreader.CsvWriter;
import com.sparrowwallet.drongo.BitcoinUnit;
import com.sparrowwallet.drongo.protocol.Transaction;
import com.sparrowwallet.drongo.protocol.TransactionInput;
import com.sparrowwallet.drongo.protocol.TransactionOutput;
import com.sparrowwallet.drongo.wallet.BlockTransaction;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletModel;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.UnitFormat;
import com.sparrowwallet.sparrow.control.EntryCell;
import com.sparrowwallet.sparrow.net.ExchangeSource;
import com.sparrowwallet.sparrow.wallet.Entry;
import com.sparrowwallet.sparrow.wallet.TransactionEntry;
import com.sparrowwallet.sparrow.wallet.WalletForm;
import com.sparrowwallet.sparrow.wallet.WalletTransactionsEntry;
import org.apache.commons.lang3.time.DateUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
public class WalletTransactions implements WalletExport {
private static final long ONE_DAY = 24*60*60*1000L;
private final WalletForm walletForm;
public WalletTransactions(WalletForm walletForm) {
this.walletForm = walletForm;
}
@Override
public String getName() {
return "Transactions";
}
@Override
public WalletModel getWalletModel() {
return WalletModel.TRANSACTIONS;
}
@Override
public void exportWallet(Wallet wallet, OutputStream outputStream, String password) throws ExportException {
WalletTransactionsEntry walletTransactionsEntry = walletForm.getWalletTransactionsEntry();
ExchangeSource exchangeSource = Config.get().getExchangeSource();
if(Config.get().getExchangeSource() == null) {
exchangeSource = ExchangeSource.COINGECKO;
}
Currency fiatCurrency = (exchangeSource == ExchangeSource.NONE || !AppServices.onlineProperty().get() ? null : Config.get().getFiatCurrency());
Map<Date, Double> fiatRates = new HashMap<>();
if(fiatCurrency != null && !walletTransactionsEntry.getChildren().isEmpty()) {
LongSummaryStatistics stats = walletTransactionsEntry.getChildren().stream()
.map(entry -> ((TransactionEntry)entry).getBlockTransaction().getDate())
.filter(Objects::nonNull)
.collect(Collectors.summarizingLong(Date::getTime));
fiatRates = exchangeSource.getHistoricalExchangeRates(fiatCurrency, new Date(stats.getMin() - ONE_DAY), new Date(stats.getMax()));
}
BitcoinUnit bitcoinUnit = Config.get().getBitcoinUnit();
if(bitcoinUnit == null || bitcoinUnit.equals(BitcoinUnit.AUTO)) {
bitcoinUnit = walletForm.getWallet().getAutoUnit();
}
try {
CsvWriter writer = new CsvWriter(outputStream, ',', StandardCharsets.UTF_8);
writer.write("Date");
writer.write("Label");
writer.write("Value");
writer.write("Balance");
writer.write("Fee");
if(fiatCurrency != null) {
writer.write("Value (" + fiatCurrency.getCurrencyCode() + ")");
}
writer.write("Txid");
writer.endRecord();
for(Entry entry : walletTransactionsEntry.getChildren()) {
TransactionEntry txEntry = (TransactionEntry)entry;
writer.write(txEntry.getBlockTransaction().getDate() == null ? "Unconfirmed" : EntryCell.DATE_FORMAT.format(txEntry.getBlockTransaction().getDate()));
writer.write(txEntry.getLabel());
writer.write(getCoinValue(bitcoinUnit, txEntry.getValue()));
writer.write(getCoinValue(bitcoinUnit, txEntry.getBalance()));
Long fee = txEntry.getValue() < 0 ? getFee(wallet, txEntry.getBlockTransaction()) : null;
writer.write(fee == null ? "" : getCoinValue(bitcoinUnit, fee));
if(fiatCurrency != null) {
Double fiatValue = getFiatValue(txEntry, fiatRates);
writer.write(fiatValue == null ? "" : getFiatValue(fiatValue));
}
writer.write(txEntry.getBlockTransaction().getHash().toString());
writer.endRecord();
}
if(fiatCurrency != null) {
writer.endRecord();
writer.writeComment(" Historical " + fiatCurrency.getCurrencyCode() + " values are taken from daily rates and should only be considered as approximate.");
}
writer.close();
} catch(IOException e) {
throw new ExportException("Error writing transactions CSV", e);
}
}
private Long getFee(Wallet wallet, BlockTransaction blockTransaction) {
long fee = 0L;
for(TransactionInput txInput : blockTransaction.getTransaction().getInputs()) {
if(txInput.isCoinBase()) {
return 0L;
}
BlockTransaction inputTx = wallet.getWalletTransaction(txInput.getOutpoint().getHash());
if(inputTx == null || inputTx.getTransaction().getOutputs().size() <= txInput.getOutpoint().getIndex()) {
return null;
}
TransactionOutput spentOutput = inputTx.getTransaction().getOutputs().get((int)txInput.getOutpoint().getIndex());
fee += spentOutput.getValue();
}
for(TransactionOutput txOutput : blockTransaction.getTransaction().getOutputs()) {
fee -= txOutput.getValue();
}
return fee;
}
private String getCoinValue(BitcoinUnit bitcoinUnit, Long value) {
UnitFormat format = Config.get().getUnitFormat() == null ? UnitFormat.DOT : Config.get().getUnitFormat();
return BitcoinUnit.BTC.equals(bitcoinUnit) ? format.tableFormatBtcValue(value) : String.format(Locale.ENGLISH, "%d", value);
}
private String getFiatValue(Double value) {
UnitFormat format = Config.get().getUnitFormat() == null ? UnitFormat.DOT : Config.get().getUnitFormat();
return format.tableFormatCurrencyValue(value);
}
private Double getFiatValue(TransactionEntry txEntry, Map<Date, Double> fiatRates) {
Double dayRate = null;
if(txEntry.getBlockTransaction().getDate() == null) {
if(AppServices.getFiatCurrencyExchangeRate() != null) {
dayRate = AppServices.getFiatCurrencyExchangeRate().getBtcRate();
}
} else {
dayRate = fiatRates.get(DateUtils.truncate(txEntry.getBlockTransaction().getDate(), Calendar.DAY_OF_MONTH));
}
if(dayRate != null) {
return dayRate * txEntry.getValue() / Transaction.SATOSHIS_PER_BITCOIN;
}
return null;
}
@Override
public String getWalletExportDescription() {
return "Exports a CSV file containing dates and values of the transactions in this wallet. Additionally, if a fiat currency has been configured, the fiat value on the day they were first included in the blockchain.";
}
@Override
public String getExportFileExtension(Wallet wallet) {
return "csv";
}
@Override
public boolean isWalletExportScannable() {
return false;
}
@Override
public boolean walletExportRequiresDecryption() {
return false;
}
}
@@ -47,7 +47,7 @@ public class CardTransport {
break;
} catch(CardException e) {
if(!iter.hasNext()) {
log.error(e.getMessage());
log.debug(e.getMessage());
throw e;
}
}
@@ -62,7 +62,7 @@ public class CardTransport {
CardChannel cardChannel = connection.getBasicChannel();
ResponseAPDU resp = cardChannel.transmit(new CommandAPDU(0, 0xA4, 4, 0, Utils.hexToBytes(APPID.toUpperCase())));
if(resp.getSW() != SW_OKAY) {
throw new CardException("Card initialization error, response was 0x" + Integer.toHexString(resp.getSW()) + ". Note that only the Tapsigner is currently supported.");
throw new CardException("Card initialization error, response was 0x" + Integer.toHexString(resp.getSW()));
}
return connection;
@@ -26,7 +26,7 @@ public class Tapsigner implements KeystoreCardImport {
}
@Override
public void initialize(String pin, byte[] chainCode, StringProperty messageProperty) throws CardException {
public void initialize(String pin, byte[] entropy, StringProperty messageProperty) throws CardException {
if(pin.length() < 6) {
throw new CardException("PIN too short.");
}
@@ -43,7 +43,7 @@ public class Tapsigner implements KeystoreCardImport {
throw new IllegalStateException("Card is already initialized.");
}
cardApi.checkWait(cardStatus, new SimpleIntegerProperty(), messageProperty);
cardApi.initialize(0, chainCode);
cardApi.initialize(0, entropy);
} finally {
if(cardApi != null) {
cardApi.disconnect();
@@ -0,0 +1,139 @@
package com.sparrowwallet.sparrow.io.satochip;
import com.sparrowwallet.drongo.Utils;
import java.io.ByteArrayOutputStream;
/**
* ISO7816-4 APDU.
*/
public class APDUCommand {
protected int cla;
protected int ins;
protected int p1;
protected int p2;
protected byte[] data;
protected boolean needsLE;
/**
* Constructs an APDU with no response data length field. The data field cannot be null, but can be a zero-length array.
*
* @param cla class byte
* @param ins instruction code
* @param p1 P1 parameter
* @param p2 P2 parameter
* @param data the APDU data
*/
public APDUCommand(int cla, int ins, int p1, int p2, byte[] data) {
this(cla, ins, p1, p2, data, false);
}
/**
* Constructs an APDU with an optional data length field. The data field cannot be null, but can be a zero-length array.
* The LE byte, if sent, is set to 0.
*
* @param cla class byte
* @param ins instruction code
* @param p1 P1 parameter
* @param p2 P2 parameter
* @param data the APDU data
* @param needsLE whether the LE byte should be sent or not
*/
public APDUCommand(int cla, int ins, int p1, int p2, byte[] data, boolean needsLE) {
this.cla = cla & 0xff;
this.ins = ins & 0xff;
this.p1 = p1 & 0xff;
this.p2 = p2 & 0xff;
this.data = data;
this.needsLE = needsLE;
}
/**
* Serializes the APDU in order to send it to the card.
*
* @return the byte array representation of the APDU
*/
public byte[] serialize() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(this.cla);
out.write(this.ins);
out.write(this.p1);
out.write(this.p2);
out.write(this.data.length);
out.write(this.data, 0, this.data.length);
if(this.needsLE) {
out.write(0); // Response length
}
return out.toByteArray();
}
/**
* Serializes the APDU to human readable hex string format
*
* @return the hex string representation of the APDU
*/
public String toHexString() {
byte[] raw = this.serialize();
if(raw == null) {
return "";
}
return Utils.bytesToHex(raw);
}
/**
* Returns the CLA of the APDU
*
* @return the CLA of the APDU
*/
public int getCla() {
return cla;
}
/**
* Returns the INS of the APDU
*
* @return the INS of the APDU
*/
public int getIns() {
return ins;
}
/**
* Returns the P1 of the APDU
*
* @return the P1 of the APDU
*/
public int getP1() {
return p1;
}
/**
* Returns the P2 of the APDU
*
* @return the P2 of the APDU
*/
public int getP2() {
return p2;
}
/**
* Returns the data field of the APDU
*
* @return the data field of the APDU
*/
public byte[] getData() {
return data;
}
/**
* Returns whether LE is sent or not.
*
* @return whether LE is sent or not
*/
public boolean getNeedsLE() {
return this.needsLE;
}
}
@@ -0,0 +1,119 @@
package com.sparrowwallet.sparrow.io.satochip;
import com.sparrowwallet.drongo.Utils;
/**
* ISO7816-4 APDU response.
*/
public class APDUResponse {
public static final int SW_OK = 0x9000;
public static final int SW_SECURITY_CONDITION_NOT_SATISFIED = 0x6982;
public static final int SW_AUTHENTICATION_METHOD_BLOCKED = 0x6983;
public static final int SW_CARD_LOCKED = 0x6283;
public static final int SW_REFERENCED_DATA_NOT_FOUND = 0x6A88;
public static final int SW_CONDITIONS_OF_USE_NOT_SATISFIED = 0x6985; // applet may be already installed
public static final int SW_WRONG_PIN_MASK = 0x63C0;
public static final String HEXES = "0123456789ABCDEF";
private final byte[] apdu;
private byte[] data;
private int sw;
private int sw1;
private int sw2;
/**
* Creates an APDU object by parsing the raw response from the card.
*
* @param apdu the raw response from the card.
*/
public APDUResponse(byte[] apdu) {
if(apdu.length < 2) {
throw new IllegalArgumentException("APDU response must be at least 2 bytes");
}
this.apdu = apdu;
this.parse();
}
public APDUResponse(byte[] data, byte sw1, byte sw2) {
byte[] apdu = new byte[data.length + 2];
System.arraycopy(data, 0, apdu, 0, data.length);
apdu[data.length] = sw1;
apdu[data.length + 1] = sw2;
this.apdu = apdu;
this.parse();
}
/**
* Parses the APDU response, separating the response data from SW.
*/
private void parse() {
int length = this.apdu.length;
this.sw1 = this.apdu[length - 2] & 0xff;
this.sw2 = this.apdu[length - 1] & 0xff;
this.sw = (this.sw1 << 8) | this.sw2;
this.data = new byte[length - 2];
System.arraycopy(this.apdu, 0, this.data, 0, length - 2);
}
/**
* Returns the data field of this APDU.
*
* @return the data field of this APDU
*/
public byte[] getData() {
return this.data;
}
/**
* Returns the Status Word.
*
* @return the status word
*/
public int getSw() {
return this.sw;
}
/**
* Returns the SW1 byte
*
* @return SW1
*/
public int getSw1() {
return this.sw1;
}
/**
* Returns the SW2 byte
*
* @return SW2
*/
public int getSw2() {
return this.sw2;
}
/**
* Returns the raw unparsed response.
*
* @return raw APDU data
*/
public byte[] getBytes() {
return this.apdu;
}
/**
* Serializes the APDU to human readable hex string format
*
* @return the hex string representation of the APDU
*/
public String toHexString() {
byte[] raw = this.apdu;
if(raw == null) {
return "";
}
return Utils.bytesToHex(raw);
}
}
@@ -0,0 +1,214 @@
package com.sparrowwallet.sparrow.io.satochip;
public final class Constants {
// Prevents instantiation of class
private Constants() {
}
/****************************************
* Instruction codes *
****************************************/
public static final byte CLA = (byte) 0xB0;
// Applet initialization
public static final byte INS_SETUP = (byte) 0x2A;
// Keys' use and management
public static final byte INS_IMPORT_KEY = (byte) 0x32;
public static final byte INS_RESET_KEY = (byte) 0x33;
public static final byte INS_GET_PUBLIC_FROM_PRIVATE = (byte) 0x35;
// External authentication
public static final byte INS_CREATE_PIN = (byte) 0x40; //TODO: remove?
public static final byte INS_VERIFY_PIN = (byte) 0x42;
public static final byte INS_CHANGE_PIN = (byte) 0x44;
public static final byte INS_UNBLOCK_PIN = (byte) 0x46;
public static final byte INS_LOGOUT_ALL = (byte) 0x60;
// Status information
public static final byte INS_LIST_PINS = (byte) 0x48;
public static final byte INS_GET_STATUS = (byte) 0x3C;
public static final byte INS_CARD_LABEL = (byte) 0x3D;
// HD wallet
public static final byte INS_BIP32_IMPORT_SEED = (byte) 0x6C;
public static final byte INS_BIP32_RESET_SEED = (byte) 0x77;
public static final byte INS_BIP32_GET_AUTHENTIKEY = (byte) 0x73;
public static final byte INS_BIP32_SET_AUTHENTIKEY_PUBKEY = (byte) 0x75;
public static final byte INS_BIP32_GET_EXTENDED_KEY = (byte) 0x6D;
public static final byte INS_BIP32_SET_EXTENDED_PUBKEY = (byte) 0x74;
public static final byte INS_SIGN_MESSAGE = (byte) 0x6E;
public static final byte INS_SIGN_SHORT_MESSAGE = (byte) 0x72;
public static final byte INS_SIGN_TRANSACTION = (byte) 0x6F;
public static final byte INS_PARSE_TRANSACTION = (byte) 0x71;
public static final byte INS_CRYPT_TRANSACTION_2FA = (byte) 0x76;
public static final byte INS_SET_2FA_KEY = (byte) 0x79;
public static final byte INS_RESET_2FA_KEY = (byte) 0x78;
public static final byte INS_SIGN_TRANSACTION_HASH = (byte) 0x7A;
// secure channel
public static final byte INS_INIT_SECURE_CHANNEL = (byte) 0x81;
public static final byte INS_PROCESS_SECURE_CHANNEL = (byte) 0x82;
// secure import from SeedKeeper
public static final byte INS_IMPORT_ENCRYPTED_SECRET = (byte) 0xAC;
public static final byte INS_IMPORT_TRUSTED_PUBKEY = (byte) 0xAA;
public static final byte INS_EXPORT_TRUSTED_PUBKEY = (byte) 0xAB;
public static final byte INS_EXPORT_AUTHENTIKEY = (byte) 0xAD;
// Personalization PKI support
public static final byte INS_IMPORT_PKI_CERTIFICATE = (byte) 0x92;
public static final byte INS_EXPORT_PKI_CERTIFICATE = (byte) 0x93;
public static final byte INS_SIGN_PKI_CSR = (byte) 0x94;
public static final byte INS_EXPORT_PKI_PUBKEY = (byte) 0x98;
public static final byte INS_LOCK_PKI = (byte) 0x99;
public static final byte INS_CHALLENGE_RESPONSE_PKI = (byte) 0x9A;
// reset to factory settings
public static final byte INS_RESET_TO_FACTORY = (byte) 0xFF;
/****************************************
* Error codes *
****************************************/
/**
* Entered PIN is not correct
*/
public static final short SW_PIN_FAILED = (short) 0x63C0;// includes number of tries remaining
///** DEPRECATED - Entered PIN is not correct */
//public static final short SW_AUTH_FAILED = (short) 0x9C02;
/**
* Required operation is not allowed in actual circumstances
*/
public static final short SW_OPERATION_NOT_ALLOWED = (short) 0x9C03;
/**
* Required setup is not not done
*/
public static final short SW_SETUP_NOT_DONE = (short) 0x9C04;
/**
* Required setup is already done
*/
public static final short SW_SETUP_ALREADY_DONE = (short) 0x9C07;
/**
* Required feature is not (yet) supported
*/
public static final short SW_UNSUPPORTED_FEATURE = (short) 0x9C05;
/**
* Required operation was not authorized because of a lack of privileges
*/
public static final short SW_UNAUTHORIZED = (short) 0x9C06;
/**
* Algorithm specified is not correct
*/
public static final short SW_INCORRECT_ALG = (short) 0x9C09;
/**
* There have been memory problems on the card
*/
public static final short SW_NO_MEMORY_LEFT = (short) 0x9C01;
///** DEPRECATED - Required object is missing */
//public static final short SW_OBJECT_NOT_FOUND= (short) 0x9C07;
/**
* Incorrect P1 parameter
*/
public static final short SW_INCORRECT_P1 = (short) 0x9C10;
/**
* Incorrect P2 parameter
*/
public static final short SW_INCORRECT_P2 = (short) 0x9C11;
/**
* Invalid input parameter to command
*/
public static final short SW_INVALID_PARAMETER = (short) 0x9C0F;
/**
* Eckeys initialized
*/
public static final short SW_ECKEYS_INITIALIZED_KEY = (short) 0x9C1A;
/**
* Verify operation detected an invalid signature
*/
public static final short SW_SIGNATURE_INVALID = (short) 0x9C0B;
/**
* Operation has been blocked for security reason
*/
public static final short SW_IDENTITY_BLOCKED = (short) 0x9C0C;
/**
* For debugging purposes
*/
public static final short SW_INTERNAL_ERROR = (short) 0x9CFF;
/**
* Very low probability error
*/
public static final short SW_BIP32_DERIVATION_ERROR = (short) 0x9C0E;
/**
* Incorrect initialization of method
*/
public static final short SW_INCORRECT_INITIALIZATION = (short) 0x9C13;
/**
* Bip32 seed is not initialized
*/
public static final short SW_BIP32_UNINITIALIZED_SEED = (short) 0x9C14;
/**
* Bip32 seed is already initialized (must be reset before change)
*/
public static final short SW_BIP32_INITIALIZED_SEED = (short) 0x9C17;
//** DEPRECATED - Bip32 authentikey pubkey is not initialized*/
//public static final short SW_BIP32_UNINITIALIZED_AUTHENTIKEY_PUBKEY= (short) 0x9C16;
/**
* Incorrect transaction hash
*/
public static final short SW_INCORRECT_TXHASH = (short) 0x9C15;
/**
* 2FA already initialized
*/
public static final short SW_2FA_INITIALIZED_KEY = (short) 0x9C18;
/**
* 2FA uninitialized
*/
public static final short SW_2FA_UNINITIALIZED_KEY = (short) 0x9C19;
/**
* HMAC errors
*/
public static final short SW_HMAC_UNSUPPORTED_KEYSIZE = (short) 0x9c1E;
public static final short SW_HMAC_UNSUPPORTED_MSGSIZE = (short) 0x9c1F;
/**
* Secure channel
*/
public static final short SW_SECURE_CHANNEL_REQUIRED = (short) 0x9C20;
public static final short SW_SECURE_CHANNEL_UNINITIALIZED = (short) 0x9C21;
public static final short SW_SECURE_CHANNEL_WRONG_IV = (short) 0x9C22;
public static final short SW_SECURE_CHANNEL_WRONG_MAC = (short) 0x9C23;
/**
* Secret data is too long for import
**/
public static final short SW_IMPORTED_DATA_TOO_LONG = (short) 0x9C32;
/**
* Wrong HMAC when importing Secret through Secure import
**/
public static final short SW_SECURE_IMPORT_WRONG_MAC = (short) 0x9C33;
/**
* Wrong Fingerprint when importing Secret through Secure import
**/
public static final short SW_SECURE_IMPORT_WRONG_FINGERPRINT = (short) 0x9C34;
/**
* No Trusted Pubkey when importing Secret through Secure import
**/
public static final short SW_SECURE_IMPORT_NO_TRUSTEDPUBKEY = (short) 0x9C35;
/**
* PKI perso error
*/
public static final short SW_PKI_ALREADY_LOCKED = (short) 0x9C40;
/**
* CARD HAS BEEN RESET TO FACTORY
*/
public static final short SW_RESET_TO_FACTORY = (short) 0xFF00;
/**
* For instructions that have been deprecated
*/
public static final short SW_INS_DEPRECATED = (short) 0x9C26;
/**
* For debugging purposes 2
*/
public static final short SW_DEBUG_FLAG = (short) 0x9FFF;
}
@@ -0,0 +1,101 @@
package com.sparrowwallet.sparrow.io.satochip;
import java.util.StringTokenizer;
/**
* Keypath object to be used with the SatochipCommandSet
*/
public class KeyPath {
private final byte[] data;
/**
* Parses a keypath into a byte array to be used with the SatochipCommandSet object.
* <p>
* A valid string is composed of a minimum of one and a maximum of 11 components separated by "/".
* <p>
* The first component should be "m", indicating the master key.
* <p>
* All other components are positive integers fitting in 31 bit, eventually suffixed by an apostrophe (') sign,
* which indicates an hardened key.
* <p>
* An example of a valid path is "m/44'/0'/0'/0/0"
*
* @param keypath the keypath as a string
*/
public KeyPath(String keypath) {
StringTokenizer tokenizer = new StringTokenizer(keypath, "/");
String sourceOrFirstElement = tokenizer.nextToken(); // m
int componentCount = tokenizer.countTokens();
if(componentCount > 10) {
throw new IllegalArgumentException("Too many components");
}
data = new byte[4 * componentCount];
for(int i = 0; i < componentCount; i++) {
long component = parseComponent(tokenizer.nextToken());
writeComponent(component, i);
}
}
public KeyPath(byte[] data) {
this.data = data;
}
private long parseComponent(String num) {
long sign;
if(num.endsWith("'")) {
sign = 0x80000000L;
num = num.substring(0, (num.length() - 1));
} else {
sign = 0L;
}
if(num.startsWith("+") || num.startsWith("-")) {
throw new NumberFormatException("No sign allowed");
}
return (sign | Long.parseLong(num));
}
private void writeComponent(long component, int i) {
int off = (i * 4);
data[off] = (byte) ((component >> 24) & 0xff);
data[off + 1] = (byte) ((component >> 16) & 0xff);
data[off + 2] = (byte) ((component >> 8) & 0xff);
data[off + 3] = (byte) (component & 0xff);
}
/**
* The byte encoded key path.
*
* @return byte encoded key path
*/
public byte[] getData() {
return data;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append('m');
for(int i = 0; i < this.data.length; i += 4) {
sb.append('/');
appendComponent(sb, i);
}
return sb.toString();
}
private void appendComponent(StringBuffer sb, int i) {
int num = ((this.data[i] & 0x7f) << 24) | ((this.data[i + 1] & 0xff) << 16) | ((this.data[i + 2] & 0xff) << 8) | (this.data[i + 3] & 0xff);
sb.append(num);
if((this.data[i] & 0x80) == 0x80) {
sb.append('\'');
}
}
}
@@ -0,0 +1,390 @@
package com.sparrowwallet.sparrow.io.satochip;
import com.sparrowwallet.drongo.ExtendedKey;
import com.sparrowwallet.drongo.KeyDerivation;
import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.drongo.Network;
import com.sparrowwallet.drongo.address.Address;
import com.sparrowwallet.drongo.crypto.ChildNumber;
import com.sparrowwallet.drongo.crypto.ECKey;
import com.sparrowwallet.drongo.crypto.ECDSASignature;
import com.sparrowwallet.drongo.crypto.SchnorrSignature;
import com.sparrowwallet.drongo.protocol.*;
import com.sparrowwallet.drongo.psbt.PSBT;
import com.sparrowwallet.drongo.psbt.PSBTInput;
import com.sparrowwallet.drongo.psbt.PSBTInputSigner;
import com.sparrowwallet.drongo.wallet.*;
import com.sparrowwallet.sparrow.control.CardImportPane;
import com.sparrowwallet.sparrow.io.CardApi;
import javafx.beans.property.StringProperty;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.smartcardio.*;
import java.util.*;
import java.nio.charset.StandardCharsets;
public class SatoCardApi extends CardApi {
private static final Logger log = LoggerFactory.getLogger(SatoCardApi.class);
private final WalletModel cardType;
private final SatochipCommandSet cardProtocol;
private final String pin;
private String basePath = null;
public SatoCardApi(WalletModel cardType, String pin) throws CardException {
this.cardType = cardType;
this.cardProtocol = new SatochipCommandSet();
this.pin = pin;
}
@Override
public boolean isInitialized() throws CardException {
SatoCardStatus cardStatus = this.getStatus();
return cardStatus.isInitialized(); // setupDone && isSeeded
}
//TODO
@Override
public void initialize(int slot, byte[] seedBytes) throws CardException {
// TODO check device certificate
SatoCardStatus cardStatus = this.getStatus();
APDUResponse rapdu;
if(!cardStatus.isSetupDone()) {
byte maxPinTries = 5;
rapdu = this.cardProtocol.cardSetup(maxPinTries, pin.getBytes(StandardCharsets.UTF_8));
// check ok
}
if(!cardStatus.isSeeded()) {
// check pin
rapdu = this.cardProtocol.cardVerifyPIN(0, pin);
// todo: check PIN response
rapdu = this.cardProtocol.cardBip32ImportSeed(seedBytes);
// check ok
}
}
@Override
public WalletModel getCardType() throws CardException {
return WalletModel.SATOCHIP;
}
//TODO
@Override
public int getCurrentSlot() throws CardException {
throw new CardException("Satochip does not support slots");
}
//TODO
@Override
public ScriptType getDefaultScriptType() {
return ScriptType.P2WPKH;
}
SatoCardStatus getStatus() throws CardException {
return this.cardProtocol.getApplicationStatus();
}
@Override
public Service<Void> getAuthDelayService() throws CardException {
return null;
}
@Override
public boolean requiresBackup() throws CardException {
return false;
}
@Override
public Service<String> getBackupService() {
return null;
}
@Override
public boolean changePin(String newPin) throws CardException {
this.cardProtocol.cardChangePIN((byte) 0, this.pin, newPin);
return true;
}
void setDerivation(List<ChildNumber> derivation) throws CardException {
this.basePath = KeyDerivation.writePath(derivation);
}
@Override
public Service<Void> getInitializationService(byte[] seedBytes, StringProperty messageProperty) {
return new CardInitializationService(seedBytes, messageProperty);
}
@Override
public Service<Keystore> getImportService(List<ChildNumber> derivation, StringProperty messageProperty) {
return new CardImportPane.CardImportService(new Satochip(), pin, derivation, messageProperty);
}
/*
* Satochip derives BIP32 keys based on the fullPath (from masterseed to leaf), not the partial path from a given xpub.
* the basePath (from masterseed to xpub) is only provided in Satochip.java:getKeystore(String pin, List<ChildNumber> derivation, StringProperty messageProperty)
* In SatoCardApi:getKeystore(), no derivation path (i.e. basePath from masterSeed to xpub or relative path) is given and no derivation is reliably available as a object field.
* currently, we try to get the path from this.basePath if available (or use a default value) but it's not reliable enough
*/
@Override
public Keystore getKeystore() throws CardException {
this.cardProtocol.cardVerifyPIN(0, pin);
String keyDerivationString = (this.basePath != null ? this.basePath : getDefaultScriptType().getDefaultDerivationPath());
ExtendedKey.Header xtype = Network.get().getXpubHeader();
String xpub = this.cardProtocol.cardBip32GetXpub(keyDerivationString, xtype);
ExtendedKey extendedKey = ExtendedKey.fromDescriptor(xpub);
String masterXpub = this.cardProtocol.cardBip32GetXpub("m", xtype);
ExtendedKey masterExtendedKey = ExtendedKey.fromDescriptor(masterXpub);
String masterFingerprint = Utils.bytesToHex(masterExtendedKey.getKey().getFingerprint());
KeyDerivation keyDerivation = new KeyDerivation(masterFingerprint, keyDerivationString);
Keystore keystore = new Keystore();
keystore.setLabel(WalletModel.SATOCHIP.toDisplayString());
keystore.setKeyDerivation(keyDerivation);
keystore.setSource(KeystoreSource.HW_USB);
keystore.setExtendedPublicKey(extendedKey);
keystore.setWalletModel(WalletModel.SATOCHIP);
return keystore;
}
@Override
public Service<PSBT> getSignService(Wallet wallet, PSBT psbt, StringProperty messageProperty) {
return new SignService(wallet, psbt, messageProperty);
}
void sign(Wallet wallet, PSBT psbt) throws CardException {
Map<PSBTInput, WalletNode> signingNodes = wallet.getSigningNodes(psbt);
for(PSBTInput psbtInput : psbt.getPsbtInputs()) {
if(!psbtInput.isSigned()) {
WalletNode signingNode = signingNodes.get(psbtInput);
String fullPath = null;
List<Keystore> keystores = wallet.getKeystores();
for(int i = 0; i < keystores.size(); i++) {
Keystore keystore = keystores.get(i);
WalletModel walletModel = keystore.getWalletModel();
if(walletModel == WalletModel.SATOCHIP) {
String basePath = keystore.getKeyDerivation().getDerivationPath();
String extendedPath = signingNode.getDerivationPath().substring(1);
fullPath = basePath + extendedPath;
keystore.getPubKey(signingNode);
break;
}
}
psbtInput.sign(new CardPSBTInputSigner(signingNode, fullPath));
}
}
}
@Override
public Service<String> getSignMessageService(String message, ScriptType scriptType, List<ChildNumber> derivation, StringProperty messageProperty) {
return new SignMessageService(message, scriptType, derivation, messageProperty);
}
String signMessage(String message, ScriptType scriptType, List<ChildNumber> derivation) throws CardException {
String fullpath = KeyDerivation.writePath(derivation);
cardProtocol.cardVerifyPIN(0, pin);
// 2FA is optionnal, currently not supported in sparrow as it requires to send 2FA to a mobile app through a server.
SatoCardStatus cardStatus = this.getStatus();
if(cardStatus.needs2FA()) {
throw new CardException("Satochip 2FA is not (yet) supported within Sparrow");
}
// derive the correct key in satochip
APDUResponse rapdu = cardProtocol.cardBip32GetExtendedKey(fullpath);
// recover pubkey
SatochipParser parser = new SatochipParser();
byte[][] extendeKeyBytes = parser.parseBip32GetExtendedKey(rapdu);
ECKey pubkey = ECKey.fromPublicOnly(extendeKeyBytes[0]);
// sign msg
return pubkey.signMessage(message, scriptType, hash -> {
try {
// do the signature with satochip
byte keynbr = (byte) 0xFF;
byte[] chalresponse = null;
APDUResponse rapdu2 = cardProtocol.cardSignTransactionHash(keynbr, hash.getBytes(), chalresponse);
byte[] sigBytes = rapdu2.getData();
return ECDSASignature.decodeFromDER(sigBytes);
} catch(Exception e) {
throw new RuntimeException(e);
}
});
}
@Override
public Service<ECKey> getPrivateKeyService(Integer slot, StringProperty messageProperty) {
throw new UnsupportedOperationException("Satochip does not support private key export");
}
@Override
public Service<Address> getAddressService(StringProperty messageProperty) {
return null;
}
@Override
public void disconnect() {
cardProtocol.cardDisconnect();
}
public class CardInitializationService extends Service<Void> {
private final byte[] seedBytes;
private final StringProperty messageProperty;
public CardInitializationService(byte[] seedBytes, StringProperty messageProperty) {
this.seedBytes = seedBytes;
this.messageProperty = messageProperty;
}
@Override
protected Task<Void> createTask() {
return new Task<>() {
@Override
protected Void call() throws Exception {
if(seedBytes == null) {
throw new CardException("Failed to initialize Satochip - no seed provided");
}
initialize(0, seedBytes);
return null;
}
};
}
}
public class SignService extends Service<PSBT> {
private final Wallet wallet;
private final PSBT psbt;
private final StringProperty messageProperty;
public SignService(Wallet wallet, PSBT psbt, StringProperty messageProperty) {
this.wallet = wallet;
this.psbt = psbt;
this.messageProperty = messageProperty;
}
@Override
protected Task<PSBT> createTask() {
return new Task<>() {
@Override
protected PSBT call() throws Exception {
sign(wallet, psbt);
return psbt;
}
};
}
}
private class CardPSBTInputSigner implements PSBTInputSigner {
private final WalletNode signingNode;
private final String fullPath;
private ECKey pubkey;
// todo: provide derivationpath instead of WalletNode??
public CardPSBTInputSigner(WalletNode signingNode, String fullPath) {
this.signingNode = signingNode;
this.fullPath = fullPath;
}
@Override
public TransactionSignature sign(Sha256Hash hash, SigHash sigHash, TransactionSignature.Type signatureType) {
try {
// 2FA is optional, currently not supported in sparrow as it requires to send 2FA to a mobile app through a server.
SatoCardStatus cardStatus = getStatus();
if(cardStatus.needs2FA()) {
throw new CardException("Satochip 2FA is not (yet) supported within Sparrow");
}
// verify PIN
APDUResponse rapdu0 = cardProtocol.cardVerifyPIN(0, pin);
// derive the correct key in satochip and recover pubkey
APDUResponse rapdu = cardProtocol.cardBip32GetExtendedKey(fullPath);
SatochipParser parser = new SatochipParser();
byte[][] extendeKeyBytes = parser.parseBip32GetExtendedKey(rapdu);
ECKey internalPubkey = ECKey.fromPublicOnly(extendeKeyBytes[0]);
if(signatureType == TransactionSignature.Type.ECDSA) {
// for ECDSA, pubkey is the same as internalPubkey
pubkey = internalPubkey;
// do the signature with satochip
byte keynbr = (byte) 0xFF;
byte[] chalresponse = null;
APDUResponse rapdu2 = cardProtocol.cardSignTransactionHash(keynbr, hash.getBytes(), chalresponse);
byte[] sigBytes = rapdu2.getData();
ECDSASignature ecdsaSig = ECDSASignature.decodeFromDER(sigBytes).toCanonicalised();
TransactionSignature txSig = new TransactionSignature(ecdsaSig, sigHash);
// verify
boolean isCorrect = pubkey.verify(hash, txSig);
return txSig;
} else {
// Satochip supports schnorr signature only for version >= 0.14 !
byte[] versionBytes = cardStatus.getCardVersion();
int protocolVersion = versionBytes[0] * 256 + versionBytes[1];
if(protocolVersion < (256 * 0 + 14)) {
throw new CardException(WalletModel.SATOCHIP.toDisplayString() + " (with version below v0.14) cannot sign Taproot transactions");
}
// tweak the bip32 key according to bip341
byte keynbr = (byte) 0xFF;
byte[] tweak = null;
APDUResponse rapduTweak = cardProtocol.cardTaprootTweakPrivkey(keynbr, tweak);
byte[] tweakedPubkeyBytes = new byte[65];
System.arraycopy(rapduTweak.getData(), 2, tweakedPubkeyBytes, 0, 65);
pubkey = ECKey.fromPublicOnly(tweakedPubkeyBytes);
byte[] chalresponse = null;
APDUResponse rapdu2 = cardProtocol.cardSignSchnorrHash(keynbr, hash.getBytes(), chalresponse);
byte[] sigBytes = rapdu2.getData();
SchnorrSignature schnorrSig = SchnorrSignature.decode(sigBytes);
TransactionSignature txSig = new TransactionSignature(schnorrSig, sigHash);
// verify sig with outputPubkey...
boolean isCorrect2 = pubkey.verify(hash, txSig);
return txSig; //new TransactionSignature(schnorrSig, sigHash);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
}
@Override
public ECKey getPubKey() {
return pubkey;
}
}
public class SignMessageService extends Service<String> {
private final String message;
private final ScriptType scriptType;
private final List<ChildNumber> derivation;
private final StringProperty messageProperty;
public SignMessageService(String message, ScriptType scriptType, List<ChildNumber> derivation, StringProperty messageProperty) {
this.message = message;
this.scriptType = scriptType;
this.derivation = derivation;
this.messageProperty = messageProperty;
}
@Override
protected Task<String> createTask() {
return new Task<>() {
@Override
protected String call() throws Exception {
return signMessage(message, scriptType, derivation);
}
};
}
}
}
@@ -0,0 +1,119 @@
package com.sparrowwallet.sparrow.io.satochip;
/**
* Parses the result of a GET STATUS command retrieving application status.
*/
public class SatoCardStatus {
private boolean setup_done = false;
private boolean is_seeded = false;
private boolean needs_secure_channel = false;
private boolean needs_2FA = false;
private byte protocol_major_version = (byte) 0;
private byte protocol_minor_version = (byte) 0;
private byte applet_major_version = (byte) 0;
private byte applet_minor_version = (byte) 0;
private byte PIN0_remaining_tries = (byte) 0;
private byte PUK0_remaining_tries = (byte) 0;
private byte PIN1_remaining_tries = (byte) 0;
private byte PUK1_remaining_tries = (byte) 0;
private int protocol_version = 0; //(d["protocol_major_version"]<<8)+d["protocol_minor_version"]
/**
* Constructor from TLV data
*
* @param rapdu the TLV data
* @throws IllegalArgumentException if the TLV does not follow the expected format
*/
public SatoCardStatus(APDUResponse rapdu) {
int sw = rapdu.getSw();
if(sw == 0x9000) {
byte[] data = rapdu.getData();
protocol_major_version = data[0];
protocol_minor_version = data[1];
applet_major_version = data[2];
applet_minor_version = data[3];
protocol_version = (protocol_major_version << 8) + protocol_minor_version;
if(data.length >= 8) {
PIN0_remaining_tries = data[4];
PUK0_remaining_tries = data[5];
PIN1_remaining_tries = data[6];
PUK1_remaining_tries = data[7];
needs_2FA = false; //default value
}
if(data.length >= 9) {
needs_2FA = data[8] != 0X00;
}
if(data.length >= 10) {
is_seeded = data[9] != 0X00;
}
if(data.length >= 11) {
setup_done = data[10] != 0X00;
} else {
setup_done = true;
}
if(data.length >= 12) {
needs_secure_channel = data[11] != 0X00;
} else {
needs_secure_channel = false;
needs_2FA = false; //default value
}
} else if(sw == 0x9c04) {
setup_done = false;
is_seeded = false;
needs_secure_channel = false;
} else {
throw new IllegalArgumentException("Invalid getStatus data");
}
}
// getters
public boolean isSeeded() {
return is_seeded;
}
public boolean isSetupDone() {
return setup_done;
}
public boolean isInitialized() {
return (setup_done && is_seeded);
}
public boolean needsSecureChannel() {
return needs_secure_channel;
}
public boolean needs2FA() {
return needs_2FA;
}
public byte getPin0RemainingCounter() {
return PIN0_remaining_tries;
}
public byte[] getCardVersion() {
byte[] versionBytes = new byte[4];
versionBytes[0] = protocol_major_version;
versionBytes[1] = protocol_minor_version;
versionBytes[2] = applet_major_version;
versionBytes[3] = applet_minor_version;
return versionBytes;
}
@Override
public String toString() {
return "setup_done: " + setup_done + "\n" +
"is_seeded: " + is_seeded + "\n" +
"needs_2FA: " + needs_2FA + "\n" +
"needs_secure_channel: " + needs_secure_channel + "\n" +
"protocol_major_version: " + protocol_major_version + "\n" +
"protocol_minor_version: " + protocol_minor_version + "\n" +
"applet_major_version: " + applet_major_version + "\n" +
"applet_minor_version: " + applet_minor_version;
}
}
@@ -0,0 +1,63 @@
package com.sparrowwallet.sparrow.io.satochip;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.smartcardio.*;
import javax.smartcardio.CardChannel;
import java.util.List;
import java.util.*;
public class SatoCardTransport {
private static final Logger log = LoggerFactory.getLogger(SatoCardTransport.class);
private final Card connection;
SatoCardTransport(byte[] appletAid) throws CardException {
TerminalFactory tf = TerminalFactory.getDefault();
List<CardTerminal> terminals = tf.terminals().list();
if(terminals.isEmpty()) {
throw new IllegalStateException("No reader connected");
}
Card connection = null;
for(Iterator<CardTerminal> iter = terminals.iterator(); iter.hasNext(); ) {
try {
connection = getConnection(iter.next(), appletAid);
break;
} catch(CardException e) {
if(!iter.hasNext()) {
log.info(e.getMessage());
throw e;
}
}
}
this.connection = connection;
}
private Card getConnection(CardTerminal cardTerminal, byte[] appletAid) throws CardException {
Card connection = cardTerminal.connect("*");
CardChannel cardChannel = connection.getBasicChannel();
ResponseAPDU resp = cardChannel.transmit(new CommandAPDU(0, 0xA4, 4, 0, appletAid));
if(resp.getSW() != APDUResponse.SW_OK) {
throw new CardException("Card initialization error, response was 0x" + Integer.toHexString(resp.getSW()));
}
return connection;
}
APDUResponse send(APDUCommand capdu) throws CardException {
javax.smartcardio.CardChannel cardChannel = this.connection.getBasicChannel();
CommandAPDU cmd = new CommandAPDU(capdu.getCla(), capdu.getIns(), capdu.getP1(), capdu.getP2(), capdu.getData());
ResponseAPDU resp = cardChannel.transmit(cmd);
return new APDUResponse(resp.getBytes());
}
void disconnect() throws CardException {
connection.disconnect(true);
}
}
@@ -0,0 +1,95 @@
package com.sparrowwallet.sparrow.io.satochip;
import com.sparrowwallet.drongo.crypto.ChildNumber;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.WalletModel;
import com.sparrowwallet.sparrow.io.KeystoreCardImport;
import com.sparrowwallet.sparrow.io.ImportException;
import javafx.beans.property.StringProperty;
import javax.smartcardio.CardException;
import java.util.List;
public class Satochip implements KeystoreCardImport {
@Override
public boolean isInitialized() throws CardException {
SatoCardApi cardApi = null;
try {
cardApi = new SatoCardApi(WalletModel.SATOCHIP, null);
return cardApi.isInitialized();
} finally {
if(cardApi != null) {
cardApi.disconnect();
}
}
}
@Override
public void initialize(String pin, byte[] entropy, StringProperty messageProperty) throws CardException {
if(pin.length() < 4) {
throw new CardException("PIN too short.");
}
if(pin.length() > 16) {
throw new CardException("PIN too long.");
}
SatoCardApi cardApi = null;
try {
cardApi = new SatoCardApi(WalletModel.SATOCHIP, pin);
SatoCardStatus cardStatus = cardApi.getStatus();
if(cardStatus.isInitialized()) {
throw new IllegalStateException("Card is already initialized.");
}
cardApi.initialize(0, entropy);
} finally {
if(cardApi != null) {
cardApi.disconnect();
}
}
}
@Override
public Keystore getKeystore(String pin, List<ChildNumber> derivation, StringProperty messageProperty) throws ImportException {
if(pin.length() < 4) {
throw new ImportException("PIN too short.");
}
if(pin.length() > 16) {
throw new ImportException("PIN too long.");
}
SatoCardApi cardApi = null;
try {
cardApi = new SatoCardApi(WalletModel.SATOCHIP, pin);
SatoCardStatus cardStatus = cardApi.getStatus();
if(!cardStatus.isInitialized()) {
throw new IllegalStateException("Card is not initialized.");
}
cardApi.setDerivation(derivation);
return cardApi.getKeystore();
} catch(Exception e) {
throw new ImportException(e);
} finally {
if(cardApi != null) {
cardApi.disconnect();
}
}
}
@Override
public String getKeystoreImportDescription(int account) {
return "Import the keystore from your Satochip by inserting or placing it on the card reader.";
}
@Override
public String getName() {
return "Satochip";
}
@Override
public WalletModel getWalletModel() {
return WalletModel.SATOCHIP;
}
}
@@ -0,0 +1,494 @@
package com.sparrowwallet.sparrow.io.satochip;
import com.sparrowwallet.drongo.ExtendedKey;
import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.drongo.protocol.Base58;
import com.sparrowwallet.sparrow.io.CardAuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import static com.sparrowwallet.sparrow.io.satochip.Constants.*;
import javax.smartcardio.*;
/**
* This class is used to send APDU to the applet. Each method corresponds to an APDU as defined in the APPLICATION.md
* file. Some APDUs map to multiple methods for the sake of convenience since their payload or response require some
* pre/post processing.
*/
public class SatochipCommandSet {
private static final Logger log = LoggerFactory.getLogger(SatochipCommandSet.class);
private final SatoCardTransport cardTransport;
private final SecureChannelSession secureChannel;
private SatoCardStatus status;
private SatochipParser parser = null;
private String pinCached = null;
public static final byte[] SATOCHIP_AID = Utils.hexToBytes("5361746f43686970"); //SatoChip
/**
* Creates a SatochipCommandSet using the given APDU Channel
*/
public SatochipCommandSet() throws CardException {
this.cardTransport = new SatoCardTransport(SATOCHIP_AID);
this.secureChannel = new SecureChannelSession();
this.parser = new SatochipParser();
}
/**
* Returns the application info as stored from the last sent SELECT command. Returns null if no succesful SELECT
* command has been sent using this command set.
*
* @return the application info object
*/
public SatoCardStatus getApplicationStatus() {
if(this.status == null) {
this.cardGetStatus();
}
return this.status;
}
/****************************************
* AUTHENTIKEY *
****************************************/
public APDUResponse cardTransmit(APDUCommand plainApdu) {
// we try to transmit the APDU until we receive the answer or we receive an unrecoverable error
boolean isApduTransmitted = false;
do {
try {
byte[] apduBytes = plainApdu.serialize();
byte ins = apduBytes[1];
boolean isEncrypted = false;
// check if status available
if(status == null) {
APDUCommand statusCapdu = new APDUCommand(0xB0, INS_GET_STATUS, 0x00, 0x00, new byte[0]);
APDUResponse statusRapdu = this.cardTransport.send(statusCapdu);
status = new SatoCardStatus(statusRapdu);
}
APDUCommand capdu = plainApdu;
if(status.needsSecureChannel() && (ins != 0xA4) && (ins != 0x81) && (ins != 0x82) && (ins != INS_GET_STATUS)) {
if(!secureChannel.initializedSecureChannel()) {
// get card's public key
APDUResponse secChannelRapdu = this.cardInitiateSecureChannel();
byte[] pubkey = this.parser.parseInitiateSecureChannel(secChannelRapdu);
// setup secure channel
this.secureChannel.initiateSecureChannel(pubkey);
}
// encrypt apdu
capdu = secureChannel.encryptSecureChannel(plainApdu);
isEncrypted = true;
}
APDUResponse rapdu = this.cardTransport.send(capdu);
int sw12 = rapdu.getSw();
// check answer
if(sw12 == 0x9000) { // ok!
if(isEncrypted) {
// decrypt
rapdu = secureChannel.decryptSecureChannel(rapdu);
}
isApduTransmitted = true; // leave loop
return rapdu;
}
// PIN authentication is required
else if(sw12 == 0x9C06) {
//cardVerifyPIN();
log.error("Error, Satochip PIN required");
throw new CardAuthorizationException("PIN is required");
}
// SecureChannel is not initialized
else if(sw12 == 0x9C21) {
log.error("Error, Satochip secure channel required");
secureChannel.resetSecureChannel();
} else {
// cannot resolve issue at this point
isApduTransmitted = true; // leave loop
return rapdu;
}
} catch(Exception e) {
log.warn("Error transmitting Satochip command set" + e);
return new APDUResponse(new byte[0], (byte) 0x00, (byte) 0x00); // return empty APDUResponse
}
} while(!isApduTransmitted);
return new APDUResponse(new byte[0], (byte) 0x00, (byte) 0x00); // should not happen
}
public void cardDisconnect() {
secureChannel.resetSecureChannel();
status = null;
pinCached = null;
try {
cardTransport.disconnect();
} catch(CardException e) {
log.error("Error disconnecting Satochip" + e);
}
}
public void cardGetStatus() {
APDUCommand plainApdu = new APDUCommand(0xB0, INS_GET_STATUS, 0x00, 0x00, new byte[0]);
APDUResponse respApdu = this.cardTransmit(plainApdu);
this.status = new SatoCardStatus(respApdu);
}
public APDUResponse cardInitiateSecureChannel() throws CardException {
byte[] pubkey = secureChannel.getPublicKey();
APDUCommand plainApdu = new APDUCommand(0xB0, INS_INIT_SECURE_CHANNEL, 0x00, 0x00, pubkey);
return this.cardTransport.send(plainApdu);
}
/****************************************
* CARD MGMT *
****************************************/
public APDUResponse cardSetup(byte pin_tries0, byte[] pin0) {
// use random values for pin1, ublk0, ublk1
SecureRandom random = new SecureRandom();
byte[] ublk0 = new byte[8];
byte[] ublk1 = new byte[8];
byte[] pin1 = new byte[8];
random.nextBytes(ublk0);
random.nextBytes(ublk1);
random.nextBytes(pin1);
byte ublk_tries0 = (byte) 0x01;
byte ublk_tries1 = (byte) 0x01;
byte pin_tries1 = (byte) 0x01;
return cardSetup(pin_tries0, ublk_tries0, pin0, ublk0, pin_tries1, ublk_tries1, pin1, ublk1);
}
public APDUResponse cardSetup(byte pin_tries0, byte ublk_tries0, byte[] pin0, byte[] ublk0,
byte pin_tries1, byte ublk_tries1, byte[] pin1, byte[] ublk1) {
byte[] pin = {0x4D, 0x75, 0x73, 0x63, 0x6C, 0x65, 0x30, 0x30}; //default pin
byte cla = (byte) 0xB0;
byte ins = INS_SETUP;
byte p1 = 0;
byte p2 = 0;
// data=[pin_length(1) | pin |
// pin_tries0(1) | ublk_tries0(1) | pin0_length(1) | pin0 | ublk0_length(1) | ublk0 |
// pin_tries1(1) | ublk_tries1(1) | pin1_length(1) | pin1 | ublk1_length(1) | ublk1 |
// memsize(2) | memsize2(2) | ACL(3) |
// option_flags(2) | hmacsha160_key(20) | amount_limit(8)]
int optionsize = 0;
int option_flags = 0; // do not use option (mostly deprecated)
int offset = 0;
int datasize = 16 + pin.length + pin0.length + pin1.length + ublk0.length + ublk1.length + optionsize;
byte[] data = new byte[datasize];
data[offset++] = (byte) pin.length;
System.arraycopy(pin, 0, data, offset, pin.length);
offset += pin.length;
// pin0 & ublk0
data[offset++] = pin_tries0;
data[offset++] = ublk_tries0;
data[offset++] = (byte) pin0.length;
System.arraycopy(pin0, 0, data, offset, pin0.length);
offset += pin0.length;
data[offset++] = (byte) ublk0.length;
System.arraycopy(ublk0, 0, data, offset, ublk0.length);
offset += ublk0.length;
// pin1 & ublk1
data[offset++] = pin_tries1;
data[offset++] = ublk_tries1;
data[offset++] = (byte) pin1.length;
System.arraycopy(pin1, 0, data, offset, pin1.length);
offset += pin1.length;
data[offset++] = (byte) ublk1.length;
System.arraycopy(ublk1, 0, data, offset, ublk1.length);
offset += ublk1.length;
// memsize default (deprecated)
data[offset++] = (byte) 00;
data[offset++] = (byte) 32;
data[offset++] = (byte) 00;
data[offset++] = (byte) 32;
// ACL (deprecated)
data[offset++] = (byte) 0x01;
data[offset++] = (byte) 0x01;
data[offset++] = (byte) 0x01;
APDUCommand plainApdu = new APDUCommand(cla, ins, p1, p2, data);
APDUResponse respApdu = this.cardTransmit(plainApdu);
if(respApdu.getSw() == 0x9000) {
//setPin0(pin0); // todo: cache value...
} else {
log.error("Error " + respApdu.toHexString());
}
return respApdu;
}
/****************************************
* PIN MGMT *
****************************************/
public APDUResponse cardVerifyPIN() throws CardException {
return this.cardVerifyPIN((byte) 0, pinCached);
}
public APDUResponse cardVerifyPIN(int pinNbr, String pin) throws CardException {
if(pin == null) {
if(pinCached == null) {
throw new CardException("PIN required!");
}
pin = this.pinCached;
}
byte[] pinBytes = pin.getBytes(StandardCharsets.UTF_8);
if(pinBytes.length > 16) {
throw new CardException("PIN should be maximum 16 characters!");
}
APDUCommand capdu = new APDUCommand(0xB0, INS_VERIFY_PIN, (byte) pinNbr, 0x00, pinBytes);
APDUResponse rapdu = this.cardTransmit(capdu);
// correct PIN: cache PIN value
int sw = rapdu.getSw();
if(sw == 0x9000) {
this.pinCached = pin; //set cached PIN value
}
// wrong PIN, get remaining tries available (since v0.11)
else if((sw & 0xffc0) == 0x63c0) {
this.pinCached = null; //reset cached PIN value
int pinLeft = (sw & ~0xffc0);
throw new CardAuthorizationException("Wrong PIN, remaining tries: " + pinLeft);
}
// wrong PIN (legacy before v0.11)
else if(sw == 0x9c02) {
this.pinCached = null; //reset cached PIN value
SatoCardStatus cardStatus = this.getApplicationStatus();
int pinLeft = cardStatus.getPin0RemainingCounter();
throw new CardAuthorizationException("Wrong PIN, remaining tries: " + pinLeft);
}
// blocked PIN
else if(sw == 0x9c0c) {
throw new CardException("Card is blocked!");
}
return rapdu;
}
public void cardChangePIN(int pinNbr, String oldPin, String newPin) throws CardException {
byte[] oldPinBytes = oldPin.getBytes(StandardCharsets.UTF_8);
byte[] newPinBytes = newPin.getBytes(StandardCharsets.UTF_8);
int lc = 1 + oldPinBytes.length + 1 + newPinBytes.length;
byte[] data = new byte[lc];
data[0] = (byte) oldPinBytes.length;
int offset = 1;
System.arraycopy(oldPinBytes, 0, data, offset, oldPinBytes.length);
offset += oldPinBytes.length;
data[offset] = (byte) newPinBytes.length;
offset += 1;
System.arraycopy(newPinBytes, 0, data, offset, newPinBytes.length);
APDUCommand capdu = new APDUCommand(0xB0, INS_CHANGE_PIN, (byte) pinNbr, 0x00, data);
APDUResponse rapdu = this.cardTransmit(capdu);
// correct PIN: cache PIN value
int sw = rapdu.getSw();
if(sw == 0x9000) {
this.pinCached = newPin;
}
// wrong PIN, get remaining tries available (since v0.11)
else if((sw & 0xffc0) == 0x63c0) {
int pinLeft = (sw & ~0xffc0);
throw new CardAuthorizationException("Wrong PIN, remaining tries: " + pinLeft);
}
// wrong PIN (legacy before v0.11)
else if(sw == 0x9c02) {
SatoCardStatus cardStatus = this.getApplicationStatus();
int pinLeft = cardStatus.getPin0RemainingCounter();
throw new CardAuthorizationException("Wrong PIN, remaining tries: " + pinLeft);
}
// blocked PIN
else if(sw == 0x9c0c) {
throw new CardException("Card is blocked!");
}
}
/****************************************
* BIP32 *
****************************************/
public APDUResponse cardBip32ImportSeed(byte[] masterseed) {
APDUCommand plainApdu = new APDUCommand(0xB0, INS_BIP32_IMPORT_SEED, masterseed.length, 0x00, masterseed);
return this.cardTransmit(plainApdu);
}
public APDUResponse cardBip32GetExtendedKey(String stringPath) {
KeyPath keyPath = new KeyPath(stringPath);
byte[] bytePath = keyPath.getData();
return cardBip32GetExtendedKey(bytePath);
}
public APDUResponse cardBip32GetExtendedKey(byte[] bytePath) {
byte p1 = (byte) (bytePath.length / 4);
APDUCommand capdu = new APDUCommand(0xB0, INS_BIP32_GET_EXTENDED_KEY, p1, 0x40, bytePath);
APDUResponse rapdu = this.cardTransmit(capdu);
if(rapdu.getSw() == 0x9C01) {
// error 0X9C01: no memory available for key derivation => flush memory cache in card
capdu = new APDUCommand(0xB0, INS_BIP32_GET_EXTENDED_KEY, p1, 0x80, bytePath);
rapdu = this.cardTransmit(capdu);
}
return rapdu;
}
/*
* Get the BIP32 xpub for given path.
*
* Parameters:
* path (str): the path; if given as a string, it will be converted to bytes (4 bytes for each path index)
* xtype (str): the type of transaction such as 'standard', 'p2wpkh-p2sh', 'p2wpkh', 'p2wsh-p2sh', 'p2wsh'
* is_mainnet (bool): is mainnet or testnet
*
* Return:
* xpub (str): the corresponding xpub value
*/
public String cardBip32GetXpub(String stringPath, ExtendedKey.Header xtype) throws CardException {
// path is of the form 44'/0'/1'
KeyPath keyPath = new KeyPath(stringPath);
byte[] bytePath = keyPath.getData();
int depth = bytePath.length / 4;
APDUResponse rapdu = this.cardBip32GetExtendedKey(bytePath);
byte[][] extendedkey = this.parser.parseBip32GetExtendedKey(rapdu);
byte[] fingerprint = new byte[4];
byte[] childNumber = new byte[4];
if(depth == 0) { //masterkey
// fingerprint and childnumber set to all-zero bytes by default
//fingerprint= bytes([0,0,0,0])
//childNumber= bytes([0,0,0,0])
} else { //get parent info
byte[] bytePathParent = Arrays.copyOfRange(bytePath, 0, bytePath.length - 4);
APDUResponse rapdu2 = this.cardBip32GetExtendedKey(bytePathParent);
byte[][] extendedkeyParent = this.parser.parseBip32GetExtendedKey(rapdu2);
byte[] identifier = Utils.sha256hash160(extendedkeyParent[0]);
fingerprint = Arrays.copyOfRange(identifier, 0, 4);
childNumber = Arrays.copyOfRange(bytePath, bytePath.length - 4, bytePath.length);
}
ByteBuffer buffer = ByteBuffer.allocate(78);
buffer.putInt(xtype.getHeader());
buffer.put((byte) depth);
buffer.put(fingerprint);
buffer.put(childNumber);
buffer.put(extendedkey[1]); // chaincode
buffer.put(extendedkey[0]); // pubkey (compressed)
byte[] xpubByte = buffer.array();
return Base58.encodeChecked(xpubByte);
}
/****************************************
* SIGNATURES *
****************************************/
public APDUResponse cardSignTransactionHash(byte keynbr, byte[] txhash, byte[] chalresponse) throws CardException {
byte[] data;
if(txhash.length != 32) {
throw new CardException("Wrong txhash length (should be 32)");
}
if(chalresponse == null) {
data = new byte[32];
System.arraycopy(txhash, 0, data, 0, txhash.length);
} else if(chalresponse.length == 20) {
data = new byte[32 + 2 + 20];
int offset = 0;
System.arraycopy(txhash, 0, data, offset, txhash.length);
offset += 32;
data[offset++] = (byte) 0x80; // 2 middle bytes for 2FA flag
data[offset++] = (byte) 0x00;
System.arraycopy(chalresponse, 0, data, offset, chalresponse.length);
} else {
throw new CardException("Wrong challenge-response length (should be 20)");
}
APDUCommand plainApdu = new APDUCommand(0xB0, INS_SIGN_TRANSACTION_HASH, keynbr, 0x00, data);
return this.cardTransmit(plainApdu);
}
/**
* This function signs a given hash with a std or the last extended key
* If 2FA is enabled, a HMAC must be provided as an additional security layer. *
* ins: 0x7B
* p1: key number or 0xFF for the last derived Bip32 extended key
* p2: 0x00
* data: [hash(32b) | option: 2FA-flag(2b)|hmac(20b)]
* return: [sig]
*/
public APDUResponse cardSignSchnorrHash(byte keynbr, byte[] txhash, byte[] chalresponse) throws CardException {
byte[] data;
if(txhash.length != 32) {
throw new CardException("Wrong txhash length (should be 32)");
}
if(chalresponse == null) {
data = new byte[32];
System.arraycopy(txhash, 0, data, 0, txhash.length);
} else if(chalresponse.length == 20) {
data = new byte[32 + 2 + 20];
int offset = 0;
System.arraycopy(txhash, 0, data, offset, txhash.length);
offset += 32;
data[offset++] = (byte) 0x80; // 2 middle bytes for 2FA flag
data[offset++] = (byte) 0x00;
System.arraycopy(chalresponse, 0, data, offset, chalresponse.length);
} else {
throw new CardException("Wrong challenge-response length (should be 20)");
}
APDUCommand plainApdu = new APDUCommand(0xB0, 0x7B, keynbr, 0x00, data);
return this.cardTransmit(plainApdu);
}
/**
* This function tweak the currently available private stored in the Satochip.
* Tweaking is based on the 'taproot_tweak_seckey(seckey0, h)' algorithm specification defined here:
* https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#constructing-and-spending-taproot-outputs
* <p>
* ins: 0x7C
* p1: key number or 0xFF for the last derived Bip32 extended key
* p2: 0x00
* data: [hash(32b) | option: 2FA-flag(2b)|hmac(20b)]
* return: [sig]
*/
public APDUResponse cardTaprootTweakPrivkey(byte keynbr, byte[] tweak) throws CardException {
byte[] data;
if(tweak == null) {
tweak = new byte[32]; // by default use a 32-byte vector filled with '0x00'
}
if(tweak.length != 32) {
throw new CardException("Wrong tweak length (should be 32)");
}
data = new byte[33];
data[0] = (byte) 32;
System.arraycopy(tweak, 0, data, 1, tweak.length);
APDUCommand plainApdu = new APDUCommand(0xB0, 0x7C, keynbr, 0x00, data);
return this.cardTransmit(plainApdu);
}
}
@@ -0,0 +1,130 @@
package com.sparrowwallet.sparrow.io.satochip;
import com.sparrowwallet.drongo.protocol.Sha256Hash;
import com.sparrowwallet.drongo.crypto.ECKey;
import com.sparrowwallet.drongo.crypto.ECDSASignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.smartcardio.CardException;
import java.util.Arrays;
public class SatochipParser {
private static final Logger log = LoggerFactory.getLogger(SatochipParser.class);
public SatochipParser() {
}
/****************************************
* PARSER *
****************************************/
public byte[] parseInitiateSecureChannel(APDUResponse rapdu) throws CardException {
try {
byte[] data = rapdu.getData();
// data= [coordxSize | coordx | sig1Size | sig1 | sig2Size | sig2]
int offset = 0;
int coordxSize = 256 * data[offset++] + data[offset++];
byte[] coordx = new byte[coordxSize];
System.arraycopy(data, offset, coordx, 0, coordxSize);
offset += coordxSize;
// msg1 is [coordx_size | coordx]
byte[] msg1 = new byte[2 + coordxSize];
System.arraycopy(data, 0, msg1, 0, msg1.length);
int sig1Size = 256 * data[offset++] + data[offset++];
byte[] sig1 = new byte[sig1Size];
System.arraycopy(data, offset, sig1, 0, sig1Size);
offset += sig1Size;
// msg2 is [coordxSize | coordx | sig1Size | sig1]
byte[] msg2 = new byte[2 + coordxSize + 2 + sig1Size];
System.arraycopy(data, 0, msg2, 0, msg2.length);
int sig2Size = 256 * data[offset++] + data[offset++];
byte[] sig2 = new byte[sig2Size];
System.arraycopy(data, offset, sig2, 0, sig2Size);
offset += sig2Size;
return recoverPubkey(msg1, sig1, coordx, false);
} catch(Exception e) {
throw new CardException("Error parsing Satochip response", e);
}
}
public byte[][] parseBip32GetExtendedKey(APDUResponse rapdu) throws CardException {
try {
byte[][] extendedkey = new byte[2][];
extendedkey[0] = new byte[33]; // pubkey
extendedkey[1] = new byte[32]; // chaincode
byte[] data = rapdu.getData();
//data: [chaincode(32b) | coordx_size(2b) | coordx | sig_size(2b) | sig | sig_size(2b) | sig2]
int offset = 0;
byte[] chaincode = new byte[32];
System.arraycopy(data, offset, chaincode, 0, chaincode.length);
offset += 32;
int coordxSize = 256 * (data[offset++] & 0x7f) + data[offset++]; // (data[32] & 0x80) is ignored (optimization flag)
byte[] coordx = new byte[coordxSize];
System.arraycopy(data, offset, coordx, 0, coordxSize);
offset += coordxSize;
// msg1 is [chaincode | coordx_size | coordx]
byte[] msg1 = new byte[32 + 2 + coordxSize];
System.arraycopy(data, 0, msg1, 0, msg1.length);
int sig1Size = 256 * data[offset++] + data[offset++];
byte[] sig1 = new byte[sig1Size];
System.arraycopy(data, offset, sig1, 0, sig1Size);
offset += sig1Size;
// msg2 is [chaincode | coordxSize | coordx | sig1Size | sig1]
byte[] msg2 = new byte[32 + 2 + coordxSize + 2 + sig1Size];
System.arraycopy(data, 0, msg2, 0, msg2.length);
int sig2Size = 256 * data[offset++] + data[offset++];
byte[] sig2 = new byte[sig2Size];
System.arraycopy(data, offset, sig2, 0, sig2Size);
offset += sig2Size;
byte[] pubkey = recoverPubkey(msg1, sig1, coordx, true); // true: compressed (33 bytes)
// todo: recover from si2
System.arraycopy(pubkey, 0, extendedkey[0], 0, pubkey.length);
System.arraycopy(chaincode, 0, extendedkey[1], 0, chaincode.length);
return extendedkey;
} catch(Exception e) {
throw new CardException("Error parsing Satochip extended key", e);
}
}
/****************************************
* recovery methods *
****************************************/
public byte[] recoverPubkey(byte[] msg, byte[] dersig, byte[] coordx, Boolean compressed) throws CardException {
// convert msg to hash
//byte[] hash = Sha256Hash.hash(msg);
ECDSASignature ecdsaSig = ECDSASignature.decodeFromDER(dersig);
byte recId = -1;
ECKey k = null;
for(byte i = 0; i < 4; i++) {
k = ECKey.recoverFromSignature(i, ecdsaSig, Sha256Hash.of(msg), compressed);
if(k != null && Arrays.equals(k.getPubKeyXCoord(), coordx)) {
recId = i;
break;
}
}
if(recId == -1) {
throw new CardException("Could not construct a recoverable key. This should never happen.");
}
return k.getPubKey();
}
}
@@ -0,0 +1,199 @@
package com.sparrowwallet.sparrow.io.satochip;
import com.sparrowwallet.drongo.crypto.AESKeyCrypter;
import com.sparrowwallet.drongo.bip47.SecretPoint;
import com.sparrowwallet.drongo.crypto.ECKey;
import com.sparrowwallet.drongo.crypto.Key;
import com.sparrowwallet.drongo.crypto.EncryptedData;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.smartcardio.CardException;
import java.security.SecureRandom;
import java.nio.ByteBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handles a SecureChannel session with the card.
*/
public class SecureChannelSession {
private static final Logger log = LoggerFactory.getLogger(SecureChannelSession.class);
public static final int SC_SECRET_LENGTH = 16;
public static final int SC_BLOCK_SIZE = 16;
public static final int IV_SIZE = 16;
public static final int MAC_SIZE = 20;
// secure channel constants
private final static byte INS_INIT_SECURE_CHANNEL = (byte) 0x81;
private final static byte INS_PROCESS_SECURE_CHANNEL = (byte) 0x82;
private final static short SW_SECURE_CHANNEL_REQUIRED = (short) 0x9C20;
private final static short SW_SECURE_CHANNEL_UNINITIALIZED = (short) 0x9C21;
private final static short SW_SECURE_CHANNEL_WRONG_IV = (short) 0x9C22;
private final static short SW_SECURE_CHANNEL_WRONG_MAC = (short) 0x9C23;
private boolean initialized_secure_channel = false;
// secure channel keys
private byte[] secret;
private byte[] iv;
private int ivCounter;
byte[] derived_key;
byte[] mac_key;
// for ECDH
private SecretPoint secretPoint;
private final ECKey eckey;
// for session encryption
private final SecureRandom random;
private final AESKeyCrypter aesCipher;
/**
* Constructs a SecureChannel session on the client.
*/
public SecureChannelSession() {
random = new SecureRandom();
// generate keypair
eckey = new ECKey();
aesCipher = new AESKeyCrypter();
}
/**
* Generates a pairing secret. This should be called before each session. The public key of the card is used as input
* for the EC-DH algorithm. The output is stored as the secret.
*
* @param pubkeyData the public key returned by the applet as response to the SELECT command
*/
public void initiateSecureChannel(byte[] pubkeyData) { //TODO: check keyData format
try {
byte[] privkeyData = this.eckey.getPrivKeyBytes();
secretPoint = new SecretPoint(privkeyData, pubkeyData);
secret = secretPoint.ECDHSecretAsBytes();
//log.trace("SATOCHIP SecureChannelSession initiateSecureChannel() secret: " + Utils.bytesToHex(secret));
// derive session encryption key
byte[] msg_key = "sc_key".getBytes();
byte[] derived_key_2Ob = getHmacSha1Hash(secret, msg_key);
derived_key = new byte[16];
System.arraycopy(derived_key_2Ob, 0, derived_key, 0, 16);
//log.trace("SATOCHIP SecureChannelSession initiateSecureChannel() derived_key: " + Utils.bytesToHex(derived_key));
// derive session mac key
byte[] msg_mac = "sc_mac".getBytes();
mac_key = getHmacSha1Hash(secret, msg_mac);
//log.trace("SATOCHIP SecureChannelSession initiateSecureChannel() mac_key: " + Utils.bytesToHex(mac_key));
ivCounter = 1;
initialized_secure_channel = true;
} catch(Exception e) {
log.error("Error initiating secure channel", e);
}
}
public APDUCommand encryptSecureChannel(APDUCommand plainApdu) throws CardException {
try {
byte[] plainBytes = plainApdu.serialize();
// set iv
iv = new byte[SC_BLOCK_SIZE];
random.nextBytes(iv);
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(ivCounter); // big endian
byte[] ivCounterBytes = bb.array();
System.arraycopy(ivCounterBytes, 0, iv, 12, 4);
ivCounter += 2;
// encrypt data
Key aesKey = new Key(derived_key, null, null);
byte[] encrypted = aesCipher.encrypt(plainBytes, iv, aesKey).getEncryptedBytes();
// mac
int offset = 0;
byte[] data_to_mac = new byte[IV_SIZE + 2 + encrypted.length];
System.arraycopy(iv, offset, data_to_mac, offset, IV_SIZE);
offset += IV_SIZE;
data_to_mac[offset++] = (byte) (encrypted.length >> 8);
data_to_mac[offset++] = (byte) (encrypted.length % 256);
System.arraycopy(encrypted, 0, data_to_mac, offset, encrypted.length);
// log.trace("SATOCHIP data_to_mac: "+ SatochipParser.toHexString(data_to_mac));
byte[] mac = getHmacSha1Hash(mac_key, data_to_mac);
// copy all data to new data buffer
offset = 0;
byte[] data = new byte[IV_SIZE + 2 + encrypted.length + 2 + MAC_SIZE];
System.arraycopy(iv, offset, data, offset, IV_SIZE);
offset += IV_SIZE;
data[offset++] = (byte) (encrypted.length >> 8);
data[offset++] = (byte) (encrypted.length % 256);
System.arraycopy(encrypted, 0, data, offset, encrypted.length);
offset += encrypted.length;
data[offset++] = (byte) (mac.length >> 8);
data[offset++] = (byte) (mac.length % 256);
System.arraycopy(mac, 0, data, offset, mac.length);
// convert to C-APDU
return new APDUCommand(0xB0, INS_PROCESS_SECURE_CHANNEL, 0x00, 0x00, data);
} catch(Exception e) {
throw new CardException("Error encrypting secure channel", e);
}
}
public APDUResponse decryptSecureChannel(APDUResponse encryptedApdu) throws CardException {
try {
byte[] encryptedBytes = encryptedApdu.getData();
if(encryptedBytes.length == 0) {
return encryptedApdu; // no decryption needed
} else if(encryptedBytes.length < 40) {
// has at least (IV_SIZE + 2 + 2 + 20)
throw new RuntimeException("Encrypted response has wrong length: " + encryptedBytes.length);
}
int offset = 0;
byte[] iv = new byte[IV_SIZE];
System.arraycopy(encryptedBytes, offset, iv, 0, IV_SIZE);
offset += IV_SIZE;
int ciphertext_size = ((encryptedBytes[offset++] & 0xff) << 8) + (encryptedBytes[offset++] & 0xff);
if((encryptedBytes.length - offset) != ciphertext_size) {
throw new RuntimeException("Encrypted response has wrong length ciphertext_size: " + ciphertext_size);
}
byte[] ciphertext = new byte[ciphertext_size];
System.arraycopy(encryptedBytes, offset, ciphertext, 0, ciphertext.length);
// decrypt data
Key aesKey = new Key(derived_key, null, null);
EncryptedData encryptedData = new EncryptedData(iv, ciphertext, null, null);
byte[] decrypted = aesCipher.decrypt(encryptedData, aesKey);
return new APDUResponse(decrypted, (byte) 0x90, (byte) 0x00);
} catch(Exception e) {
throw new CardException("Error decrypting secure channel", e);
}
}
public boolean initializedSecureChannel() {
return initialized_secure_channel;
}
public byte[] getPublicKey() {
return eckey.getPubKey(false);
}
public void resetSecureChannel() {
initialized_secure_channel = false;
}
public static byte[] getHmacSha1Hash(byte[] key, byte[] data) {
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKeySpec);
return mac.doFinal(data);
} catch(Exception e) {
throw new RuntimeException("Error computing HmacSHA1", e);
}
}
}
@@ -6,6 +6,7 @@ import com.sparrowwallet.sparrow.control.FileKeystoreImportPane;
import com.sparrowwallet.sparrow.control.TitledDescriptionPane;
import com.sparrowwallet.sparrow.io.*;
import com.sparrowwallet.sparrow.io.ckcard.Tapsigner;
import com.sparrowwallet.sparrow.io.satochip.Satochip;
import javafx.fxml.FXML;
import javafx.scene.control.Accordion;
import org.slf4j.Logger;
@@ -24,9 +25,9 @@ public class HwAirgappedController extends KeystoreImportDetailController {
public void initializeView() {
List<KeystoreFileImport> fileImporters = Collections.emptyList();
if(getMasterController().getWallet().getPolicyType().equals(PolicyType.SINGLE)) {
fileImporters = List.of(new ColdcardSinglesig(), new CoboVaultSinglesig(), new Jade(), new KeystoneSinglesig(), new PassportSinglesig(), new SeedSigner(), new GordianSeedTool(), new SpecterDIY());
fileImporters = List.of(new ColdcardSinglesig(), new CoboVaultSinglesig(), new Jade(), new KeystoneSinglesig(), new PassportSinglesig(), new SeedSigner(), new GordianSeedTool(), new SpecterDIY(), new Krux(), new AirGapVault());
} else if(getMasterController().getWallet().getPolicyType().equals(PolicyType.MULTI)) {
fileImporters = List.of(new Bip129(), new ColdcardMultisig(), new CoboVaultMultisig(), new Jade(), new KeystoneMultisig(), new PassportMultisig(), new SeedSigner(), new GordianSeedTool(), new SpecterDIY());
fileImporters = List.of(new Bip129(), new ColdcardMultisig(), new CoboVaultMultisig(), new Jade(), new KeystoneMultisig(), new PassportMultisig(), new SeedSigner(), new GordianSeedTool(), new SpecterDIY(), new Krux());
}
for(KeystoreFileImport importer : fileImporters) {
@@ -38,7 +39,7 @@ public class HwAirgappedController extends KeystoreImportDetailController {
}
}
List<KeystoreCardImport> cardImporters = List.of(new Tapsigner());
List<KeystoreCardImport> cardImporters = List.of(new Tapsigner(), new Satochip());
for(KeystoreCardImport importer : cardImporters) {
if(!importer.isDeprecated() || Config.get().isShowDeprecatedImportExport()) {
CardImportPane importPane = new CardImportPane(getMasterController().getWallet(), importer, getMasterController().getRequiredDerivation());
@@ -55,6 +55,7 @@ public class KeystoreImportDialog extends Dialog<Keystore> {
dialogPane.getButtonTypes().add(cancelButtonType);
dialogPane.setPrefWidth(650);
dialogPane.setPrefHeight(690);
dialogPane.setMinHeight(dialogPane.getPrefHeight());
AppServices.moveToActiveWindowScreen(this);
setResultConverter(dialogButton -> dialogButton != cancelButtonType ? getWatchOnlyKeystore() : null);
@@ -228,7 +228,7 @@ public class BatchedElectrumServerRpc implements ElectrumServerRpc {
try {
return batchRequest.execute();
} catch(JsonRpcBatchException e) {
throw new ElectrumServerRpcException("Error getting fee estimates: " + e.getErrors(), e);
throw new ElectrumServerRpcException("Error getting fee estimates from connected server: " + e.getErrors(), e);
} catch(Exception e) {
throw new ElectrumServerRpcException("Error getting fee estimates for target blocks: " + targetBlocks, e);
}
@@ -1,19 +1,17 @@
package com.sparrowwallet.sparrow.net;
import com.google.common.net.HostAndPort;
import com.sparrowwallet.drongo.Network;
import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.drongo.protocol.Sha256Hash;
import com.sparrowwallet.drongo.protocol.Transaction;
import com.sparrowwallet.nightjar.http.JavaHttpException;
import com.sparrowwallet.sparrow.AppServices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.List;
@@ -30,7 +28,7 @@ public enum BroadcastSource {
return List.of(Network.MAINNET, Network.TESTNET);
}
protected URL getURL(Proxy proxy) throws MalformedURLException {
protected URL getURL(HostAndPort proxy) throws MalformedURLException {
if(Network.get() == Network.MAINNET) {
return new URL(getBaseUrl(proxy) + "/api/tx");
} else if(Network.get() == Network.TESTNET) {
@@ -51,7 +49,7 @@ public enum BroadcastSource {
return List.of(Network.MAINNET, Network.TESTNET, Network.SIGNET);
}
protected URL getURL(Proxy proxy) throws MalformedURLException {
protected URL getURL(HostAndPort proxy) throws MalformedURLException {
if(Network.get() == Network.MAINNET) {
return new URL(getBaseUrl(proxy) + "/api/tx");
} else if(Network.get() == Network.TESTNET) {
@@ -74,7 +72,7 @@ public enum BroadcastSource {
return List.of(Network.MAINNET);
}
protected URL getURL(Proxy proxy) throws MalformedURLException {
protected URL getURL(HostAndPort proxy) throws MalformedURLException {
if(Network.get() == Network.MAINNET) {
return new URL(getBaseUrl(proxy) + "/api/tx");
} else if(Network.get() == Network.TESTNET) {
@@ -95,7 +93,7 @@ public enum BroadcastSource {
return List.of(Network.MAINNET);
}
protected URL getURL(Proxy proxy) throws MalformedURLException {
protected URL getURL(HostAndPort proxy) throws MalformedURLException {
if(Network.get() == Network.MAINNET) {
return new URL(getBaseUrl(proxy) + "/api/tx");
} else if(Network.get() == Network.TESTNET) {
@@ -131,7 +129,7 @@ public enum BroadcastSource {
return onionUrl;
}
public String getBaseUrl(Proxy proxy) {
public String getBaseUrl(HostAndPort proxy) {
return (proxy == null ? getTlsUrl() : getOnionUrl());
}
@@ -139,48 +137,30 @@ public enum BroadcastSource {
public abstract List<Network> getSupportedNetworks();
protected abstract URL getURL(Proxy proxy) throws MalformedURLException;
protected abstract URL getURL(HostAndPort proxy) throws MalformedURLException;
public Sha256Hash postTransactionData(String data) throws BroadcastException {
//If a Tor proxy is configured, ensure we use a new circuit by configuring a random proxy password
Proxy proxy = AppServices.getProxy(Integer.toString(secureRandom.nextInt()));
HttpClientService httpClientService = AppServices.getHttpClientService();
httpClientService.changeIdentity();
try {
URL url = getURL(proxy);
URL url = getURL(httpClientService.getTorProxy());
if(log.isInfoEnabled()) {
log.info("Broadcasting transaction to " + url);
}
HttpURLConnection connection = proxy == null ? (HttpURLConnection)url.openConnection() : (HttpURLConnection)url.openConnection(proxy);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setDoOutput(true);
try(OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream())) {
writer.write(data);
writer.flush();
}
StringBuilder response = new StringBuilder();
try(BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
String responseLine;
while((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
}
int statusCode = connection.getResponseCode();
if(statusCode < 200 || statusCode >= 300) {
throw new BroadcastException("Could not broadcast transaction, server returned " + statusCode + ": " + response);
}
String response = httpClientService.postString(url.toString(), null, "text/plain", data);
try {
return Sha256Hash.wrap(response.toString().trim());
return Sha256Hash.wrap(response.trim());
} catch(Exception e) {
throw new BroadcastException("Could not retrieve txid from broadcast, server returned " + statusCode + ": " + response);
throw new BroadcastException("Could not retrieve txid from broadcast, server returned: " + response);
}
} catch(IOException e) {
} catch(JavaHttpException e) {
throw new BroadcastException("Could not broadcast transaction, server returned " + e.getStatusCode() + ": " + e.getResponseBody());
} catch(Exception e) {
log.error("Could not post transaction via " + getName(), e);
throw new BroadcastException("Could not broadcast transaction via " + getName(), e);
}
@@ -18,6 +18,7 @@ import com.sparrowwallet.sparrow.io.Server;
import com.sparrowwallet.sparrow.net.cormorant.Cormorant;
import com.sparrowwallet.sparrow.net.cormorant.bitcoind.CormorantBitcoindException;
import com.sparrowwallet.sparrow.paynym.PayNym;
import com.sparrowwallet.sparrow.paynym.PayNymService;
import javafx.application.Platform;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
@@ -355,14 +356,14 @@ public class ElectrumServer {
//Because node children are added sequentially in WalletNode.fillToIndex, we can simply look at the number of children to determine the highest filled index
int historySize = purposeNode.getChildren().size();
//The gap limit size takes the highest used index in the retrieved history and adds the gap limit (plus one to be comparable to the number of children since index is zero based)
int gapLimitSize = getGapLimitSize(wallet, nodeTransactionMap);
int gapLimitSize = getGapLimitSize(wallet, nodeTransactionMap, purposeNode);
while(historySize < gapLimitSize) {
purposeNode.fillToIndex(wallet, gapLimitSize - 1);
subscribeWalletNodes(wallet, getAddressNodes(wallet, purposeNode), nodeTransactionMap, historySize);
getReferences(wallet, nodeTransactionMap.keySet(), nodeTransactionMap, historySize);
getReferencedTransactions(wallet, nodeTransactionMap);
historySize = purposeNode.getChildren().size();
gapLimitSize = getGapLimitSize(wallet, nodeTransactionMap);
gapLimitSize = getGapLimitSize(wallet, nodeTransactionMap, purposeNode);
}
}
@@ -377,8 +378,9 @@ public class ElectrumServer {
return purposeNode.getChildren().stream().filter(walletNode -> walletNode.getIndex() >= startFromIndex).collect(Collectors.toCollection(TreeSet::new));
}
private int getGapLimitSize(Wallet wallet, Map<WalletNode, Set<BlockTransactionHash>> nodeTransactionMap) {
int highestIndex = nodeTransactionMap.keySet().stream().filter(node -> node.getDerivation().size() > 1).map(WalletNode::getIndex).max(Comparator.comparing(Integer::valueOf)).orElse(-1);
private int getGapLimitSize(Wallet wallet, Map<WalletNode, Set<BlockTransactionHash>> nodeTransactionMap, WalletNode purposeNode) {
int highestIndex = nodeTransactionMap.keySet().stream().filter(node -> node.getDerivation().size() > 1 && purposeNode.getKeyPurpose() == node.getKeyPurpose())
.map(WalletNode::getIndex).max(Comparator.comparing(Integer::valueOf)).orElse(-1);
return highestIndex + wallet.getGapLimit() + 1;
}
@@ -502,19 +504,19 @@ public class ElectrumServer {
}
}
public List<Set<BlockTransactionHash>> getOutputTransactionReferences(Transaction transaction, int indexStart, int indexEnd) throws ServerException {
public List<Set<BlockTransactionHash>> getOutputTransactionReferences(Transaction transaction, int indexStart, int indexEnd, List<Set<BlockTransactionHash>> blockTransactionHashes) throws ServerException {
try {
Map<String, String> pathScriptHashes = new LinkedHashMap<>();
for(int i = indexStart; i < transaction.getOutputs().size() && i < indexEnd; i++) {
TransactionOutput output = transaction.getOutputs().get(i);
pathScriptHashes.put(Integer.toString(i), getScriptHash(output));
if(blockTransactionHashes.get(i) == null) {
TransactionOutput output = transaction.getOutputs().get(i);
pathScriptHashes.put(Integer.toString(i), getScriptHash(output));
}
}
Map<String, ScriptHashTx[]> result = electrumServerRpc.getScriptHashHistory(getTransport(), null, pathScriptHashes, false);
List<Set<BlockTransactionHash>> blockTransactionHashes = new ArrayList<>(transaction.getOutputs().size());
for(int i = 0; i < transaction.getOutputs().size(); i++) {
blockTransactionHashes.add(null);
Map<String, ScriptHashTx[]> result = new HashMap<>();
if(!pathScriptHashes.isEmpty()) {
result = electrumServerRpc.getScriptHashHistory(getTransport(), null, pathScriptHashes, false);
}
for(String index : result.keySet()) {
@@ -811,6 +813,18 @@ public class ElectrumServer {
}
public Map<Integer, Double> getFeeEstimates(List<Integer> targetBlocks) throws ServerException {
Map<Integer, Double> targetBlocksFeeRatesSats = getDefaultFeeEstimates(targetBlocks);
FeeRatesSource feeRatesSource = Config.get().getFeeRatesSource();
feeRatesSource = (feeRatesSource == null ? FeeRatesSource.MEMPOOL_SPACE : feeRatesSource);
if(Network.get().equals(Network.MAINNET)) {
targetBlocksFeeRatesSats.putAll(feeRatesSource.getBlockTargetFeeRates(targetBlocksFeeRatesSats));
}
return targetBlocksFeeRatesSats;
}
public Map<Integer, Double> getDefaultFeeEstimates(List<Integer> targetBlocks) throws ServerException {
try {
Map<Integer, Double> targetBlocksFeeRatesBtcKb = electrumServerRpc.getFeeEstimates(getTransport(), targetBlocks);
@@ -823,15 +837,12 @@ public class ElectrumServer {
targetBlocksFeeRatesSats.put(target, minFeeRateSatsKb / 1000d);
}
FeeRatesSource feeRatesSource = Config.get().getFeeRatesSource();
feeRatesSource = (feeRatesSource == null ? FeeRatesSource.MEMPOOL_SPACE : feeRatesSource);
if(Network.get().equals(Network.MAINNET)) {
targetBlocksFeeRatesSats.putAll(feeRatesSource.getBlockTargetFeeRates(targetBlocksFeeRatesSats));
}
return targetBlocksFeeRatesSats;
} catch(ElectrumServerRpcException e) {
throw new ServerException(e.getMessage(), e);
log.warn(e.getMessage());
return targetBlocks.stream().collect(Collectors.toMap(java.util.function.Function.identity(), v -> AppServices.getFallbackFeeRate(),
(u, v) -> { throw new IllegalStateException("Duplicate target blocks"); },
LinkedHashMap::new));
}
}
@@ -1560,17 +1571,26 @@ public class ElectrumServer {
private final Transaction transaction;
private final int indexStart;
private final int indexEnd;
public TransactionOutputsReferenceService(Transaction transaction) {
this.transaction = transaction;
this.indexStart = 0;
this.indexEnd = transaction.getOutputs().size();
}
private final List<Set<BlockTransactionHash>> blockTransactionHashes;
private final Map<Sha256Hash, BlockTransaction> transactionMap;
public TransactionOutputsReferenceService(Transaction transaction, int indexStart, int indexEnd) {
this.transaction = transaction;
this.indexStart = Math.min(transaction.getOutputs().size(), indexStart);
this.indexEnd = Math.min(transaction.getOutputs().size(), indexEnd);
this.blockTransactionHashes = new ArrayList<>(transaction.getOutputs().size());
for(int i = 0; i < transaction.getOutputs().size(); i++) {
blockTransactionHashes.add(null);
}
this.transactionMap = new HashMap<>();
}
public TransactionOutputsReferenceService(Transaction transaction, int indexStart, int indexEnd, List<Set<BlockTransactionHash>> blockTransactionHashes, Map<Sha256Hash, BlockTransaction> transactionMap) {
this.transaction = transaction;
this.indexStart = Math.min(transaction.getOutputs().size(), indexStart);
this.indexEnd = Math.min(transaction.getOutputs().size(), indexEnd);
this.blockTransactionHashes = blockTransactionHashes;
this.transactionMap = transactionMap;
}
@Override
@@ -1578,7 +1598,7 @@ public class ElectrumServer {
return new Task<>() {
protected List<BlockTransaction> call() throws ServerException {
ElectrumServer electrumServer = new ElectrumServer();
List<Set<BlockTransactionHash>> outputTransactionReferences = electrumServer.getOutputTransactionReferences(transaction, indexStart, indexEnd);
List<Set<BlockTransactionHash>> outputTransactionReferences = electrumServer.getOutputTransactionReferences(transaction, indexStart, indexEnd, blockTransactionHashes);
Set<BlockTransactionHash> setReferences = new HashSet<>();
for(Set<BlockTransactionHash> outputReferences : outputTransactionReferences) {
@@ -1588,16 +1608,16 @@ public class ElectrumServer {
}
setReferences.remove(null);
setReferences.remove(UNFETCHABLE_BLOCK_TRANSACTION);
setReferences.removeIf(ref -> transactionMap.get(ref.getHash()) != null);
List<BlockTransaction> blockTransactions = new ArrayList<>(transaction.getOutputs().size());
for(int i = 0; i < transaction.getOutputs().size(); i++) {
blockTransactions.add(null);
}
Map<Sha256Hash, BlockTransaction> transactionMap = new HashMap<>();
if(!setReferences.isEmpty()) {
Map<Integer, BlockHeader> blockHeaderMap = electrumServer.getBlockHeaders(null, setReferences);
transactionMap = electrumServer.getTransactions(null, setReferences, blockHeaderMap);
transactionMap.putAll(electrumServer.getTransactions(null, setReferences, blockHeaderMap));
}
for(int i = 0; i < outputTransactionReferences.size(); i++) {
@@ -1695,7 +1715,7 @@ public class ElectrumServer {
Map<WalletNode, Set<BlockTransactionHash>> childTransactionMap = new TreeMap<>();
electrumServer.getReferences(childWallet, childWallet.getNode(KeyPurpose.RECEIVE).getChildren(), childTransactionMap, 0);
if(childTransactionMap.values().stream().anyMatch(blockTransactionHashes -> !blockTransactionHashes.isEmpty())) {
if(StandardAccount.WHIRLPOOL_ACCOUNTS.contains(standardAccount)) {
if(StandardAccount.isWhirlpoolAccount(standardAccount)) {
foundAccounts.addAll(StandardAccount.WHIRLPOOL_ACCOUNTS);
} else {
foundAccounts.add(standardAccount);
@@ -1724,7 +1744,7 @@ public class ElectrumServer {
List<StandardAccount> accounts = new ArrayList<>();
for(StandardAccount account : StandardAccount.values()) {
if(account != StandardAccount.ACCOUNT_0 && (!StandardAccount.WHIRLPOOL_ACCOUNTS.contains(account) || wallet.getScriptType() == ScriptType.P2WPKH)) {
if(account != StandardAccount.ACCOUNT_0 && (!StandardAccount.isWhirlpoolAccount(account) || wallet.getScriptType() == ScriptType.P2WPKH)) {
accounts.add(account);
}
}
@@ -1881,7 +1901,7 @@ public class ElectrumServer {
private PayNym getPayNym(PaymentCode paymentCode) {
try {
return AppServices.getPayNymService().getPayNym(paymentCode.toString()).blockingFirst();
return PayNymService.getPayNym(paymentCode.toString()).blockingFirst();
} catch(Exception e) {
//ignore
}
@@ -1,20 +1,20 @@
package com.sparrowwallet.sparrow.net;
import com.google.gson.Gson;
import com.sparrowwallet.nightjar.http.JavaHttpException;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.event.ExchangeRatesUpdatedEvent;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
@@ -29,6 +29,11 @@ public enum ExchangeSource {
public Double getExchangeRate(Currency currency) {
return null;
}
@Override
public Map<Date, Double> getHistoricalExchangeRates(Currency currency, Date start, Date end) {
return Collections.emptyMap();
}
},
COINBASE("Coinbase") {
@Override
@@ -50,15 +55,14 @@ public enum ExchangeSource {
private CoinbaseRates getRates() {
String url = "https://api.coinbase.com/v2/exchange-rates?currency=BTC";
Proxy proxy = AppServices.getProxy();
if(log.isInfoEnabled()) {
log.info("Requesting exchange rates from " + url);
}
try(InputStream is = (proxy == null ? new URL(url).openStream() : new URL(url).openConnection(proxy).getInputStream()); Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
Gson gson = new Gson();
return gson.fromJson(reader, CoinbaseRates.class);
HttpClientService httpClientService = AppServices.getHttpClientService();
try {
return httpClientService.requestJson(url, CoinbaseRates.class, null);
} catch (Exception e) {
if(log.isDebugEnabled()) {
log.warn("Error retrieving currency rates", e);
@@ -68,6 +72,52 @@ public enum ExchangeSource {
return new CoinbaseRates();
}
}
@Override
public Map<Date, Double> getHistoricalExchangeRates(Currency currency, Date start, Date end) {
Map<Date, Double> historicalRates = new TreeMap<>();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Instant currentInstant = start.toInstant();
Instant endInstant = end.toInstant();
while(currentInstant.isBefore(endInstant) || currentInstant.equals(endInstant)) {
Date fromDate = Date.from(currentInstant.atZone(ZoneId.systemDefault()).toInstant());
currentInstant = currentInstant.plus(300, ChronoUnit.DAYS);
Date toDate = Date.from(currentInstant.atZone(ZoneId.systemDefault()).toInstant());
toDate = toDate.after(end) ? end : toDate;
String startTime = dateFormat.format(fromDate);
String endTime = dateFormat.format(toDate);
String url = "https://api.pro.coinbase.com/products/BTC-" + currency.getCurrencyCode() + "/candles?start=" + startTime + "T12:00:00&end=" + endTime + "T12:00:00&granularity=86400";
if(log.isInfoEnabled()) {
log.info("Requesting historical exchange rates from " + url);
}
HttpClientService httpClientService = AppServices.getHttpClientService();
try {
Number[][] coinbaseData = httpClientService.requestJson(url, Number[][].class, Map.of("User-Agent", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1)", "Accept", "*/*"));
for(Number[] price : coinbaseData) {
Date date = new Date(price[0].longValue() * 1000);
historicalRates.put(DateUtils.truncate(date, Calendar.DAY_OF_MONTH), price[4].doubleValue());
}
} catch(Exception e) {
if(log.isDebugEnabled()) {
log.warn("Error retrieving historical currency rates", e);
} else {
if(e instanceof JavaHttpException javaHttpException && javaHttpException.getStatusCode() == 404) {
log.warn("Error retrieving historical currency rates (" + e.getMessage() + "). BTC-" + currency.getCurrencyCode() + " may not be supported by " + this);
} else {
log.warn("Error retrieving historical currency rates (" + e.getMessage() + ")");
}
}
}
}
return historicalRates;
}
},
COINGECKO("Coingecko") {
@Override
@@ -89,15 +139,14 @@ public enum ExchangeSource {
private CoinGeckoRates getRates() {
String url = "https://api.coingecko.com/api/v3/exchange_rates";
Proxy proxy = AppServices.getProxy();
if(log.isInfoEnabled()) {
log.info("Requesting exchange rates from " + url);
}
try(InputStream is = (proxy == null ? new URL(url).openStream() : new URL(url).openConnection(proxy).getInputStream()); Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
Gson gson = new Gson();
return gson.fromJson(reader, CoinGeckoRates.class);
HttpClientService httpClientService = AppServices.getHttpClientService();
try {
return httpClientService.requestJson(url, CoinGeckoRates.class, null);
} catch(Exception e) {
if(log.isDebugEnabled()) {
log.warn("Error retrieving currency rates", e);
@@ -107,6 +156,36 @@ public enum ExchangeSource {
return new CoinGeckoRates();
}
}
@Override
public Map<Date, Double> getHistoricalExchangeRates(Currency currency, Date start, Date end) {
long startDate = start.getTime() / 1000;
long endDate = end.getTime() / 1000;
String url = "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart/range?vs_currency=" + currency.getCurrencyCode() + "&from=" + startDate + "&to=" + endDate;
if(log.isInfoEnabled()) {
log.info("Requesting historical exchange rates from " + url);
}
Map<Date, Double> historicalRates = new TreeMap<>();
HttpClientService httpClientService = AppServices.getHttpClientService();
try {
CoinGeckoHistoricalRates coinGeckoHistoricalRates = httpClientService.requestJson(url, CoinGeckoHistoricalRates.class, null);
for(List<Number> historicalRate : coinGeckoHistoricalRates.prices) {
Date date = new Date(historicalRate.get(0).longValue());
historicalRates.put(DateUtils.truncate(date, Calendar.DAY_OF_MONTH), historicalRate.get(1).doubleValue());
}
} catch(Exception e) {
if(log.isDebugEnabled()) {
log.warn("Error retrieving historical currency rates", e);
} else {
log.warn("Error retrieving historical currency rates (" + e.getMessage() + ")");
}
}
return historicalRates;
}
};
private static final Logger log = LoggerFactory.getLogger(ExchangeSource.class);
@@ -121,6 +200,8 @@ public enum ExchangeSource {
public abstract Double getExchangeRate(Currency currency);
public abstract Map<Date, Double> getHistoricalExchangeRates(Currency currency, Date start, Date end);
private static boolean isValidISO4217Code(String code) {
try {
Currency currency = Currency.getInstance(code);
@@ -176,22 +257,26 @@ public enum ExchangeSource {
}
private static class CoinbaseRates {
CoinbaseData data;
public CoinbaseData data = new CoinbaseData();
}
private static class CoinbaseData {
String currency;
Map<String, Double> rates;
public String currency;
public Map<String, Double> rates = new LinkedHashMap<>();
}
private static class CoinGeckoRates {
Map<String, CoinGeckoRate> rates = new LinkedHashMap<>();
public Map<String, CoinGeckoRate> rates = new LinkedHashMap<>();
}
private static class CoinGeckoRate {
String name;
String unit;
Double value;
String type;
public String name;
public String unit;
public Double value;
public String type;
}
private static class CoinGeckoHistoricalRates {
public List<List<Number>> prices = new ArrayList<>();
}
}
@@ -1,16 +1,9 @@
package com.sparrowwallet.sparrow.net;
import com.google.gson.Gson;
import com.sparrowwallet.sparrow.AppServices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -26,14 +19,14 @@ public enum FeeRatesSource {
@Override
public Map<Integer, Double> getBlockTargetFeeRates(Map<Integer, Double> defaultblockTargetFeeRates) {
String url = AppServices.isUsingProxy() ? "http://mempoolhqx4isw62xs7abwphsq7ldayuidyx2v2oethdhhj6mlo2r6ad.onion/api/v1/fees/recommended" : "https://mempool.space/api/v1/fees/recommended";
return getThreeTierFeeRates(defaultblockTargetFeeRates, url);
return getThreeTierFeeRates(this, defaultblockTargetFeeRates, url);
}
},
BITCOINFEES_EARN_COM("bitcoinfees.earn.com") {
@Override
public Map<Integer, Double> getBlockTargetFeeRates(Map<Integer, Double> defaultblockTargetFeeRates) {
String url = "https://bitcoinfees.earn.com/api/v1/fees/recommended";
return getThreeTierFeeRates(defaultblockTargetFeeRates, url);
return getThreeTierFeeRates(this, defaultblockTargetFeeRates, url);
}
},
MINIMUM("Minimum (1 sat/vB)") {
@@ -46,6 +39,22 @@ public enum FeeRatesSource {
return blockTargetFeeRates;
}
},
OXT_ME("oxt.me") {
@Override
public Map<Integer, Double> getBlockTargetFeeRates(Map<Integer, Double> defaultblockTargetFeeRates) {
String url = AppServices.isUsingProxy() ? "http://oxtwshnfyktikbflierkwcxxksbonl6v73l5so5zky7ur72w52tktkid.onion/stats/global/mempool" : "https://api.oxt.me/stats/global/mempool";
return getThreeTierFeeRates(this, defaultblockTargetFeeRates, url);
}
@Override
protected ThreeTierRates getThreeTierRates(String url, HttpClientService httpClientService) throws Exception {
OxtRates oxtRates = httpClientService.requestJson(url, OxtRates.class, null);
if(oxtRates.data == null || oxtRates.data.length < 1) {
throw new Exception("Invalid response from " + url);
}
return oxtRates.data[0].getThreeTierRates();
}
};
private static final Logger log = LoggerFactory.getLogger(FeeRatesSource.class);
@@ -65,17 +74,15 @@ public enum FeeRatesSource {
return name;
}
private static Map<Integer, Double> getThreeTierFeeRates(Map<Integer, Double> defaultblockTargetFeeRates, String url) {
Proxy proxy = AppServices.getProxy();
private static Map<Integer, Double> getThreeTierFeeRates(FeeRatesSource feeRatesSource, Map<Integer, Double> defaultblockTargetFeeRates, String url) {
if(log.isInfoEnabled()) {
log.info("Requesting fee rates from " + url);
}
Map<Integer, Double> blockTargetFeeRates = new LinkedHashMap<>();
try(InputStream is = (proxy == null ? new URL(url).openStream() : new URL(url).openConnection(proxy).getInputStream()); Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
Gson gson = new Gson();
ThreeTierRates threeTierRates = gson.fromJson(reader, ThreeTierRates.class);
HttpClientService httpClientService = AppServices.getHttpClientService();
try {
ThreeTierRates threeTierRates = feeRatesSource.getThreeTierRates(url, httpClientService);
Double lastRate = null;
for(Integer blockTarget : defaultblockTargetFeeRates.keySet()) {
if(blockTarget < BLOCKS_IN_HALF_HOUR) {
@@ -110,15 +117,22 @@ public enum FeeRatesSource {
return blockTargetFeeRates;
}
protected ThreeTierRates getThreeTierRates(String url, HttpClientService httpClientService) throws Exception {
return httpClientService.requestJson(url, ThreeTierRates.class, null);
}
@Override
public String toString() {
return name;
}
private static class ThreeTierRates {
Double fastestFee;
Double halfHourFee;
Double hourFee;
Double minimumFee;
private record ThreeTierRates(Double fastestFee, Double halfHourFee, Double hourFee, Double minimumFee) {}
private record OxtRates(OxtRatesData[] data) {}
private record OxtRatesData(Double recommended_fee_099, Double recommended_fee_090, Double recommended_fee_050) {
public ThreeTierRates getThreeTierRates() {
return new ThreeTierRates(recommended_fee_099/1000, recommended_fee_090/1000, recommended_fee_050/1000, null);
}
}
}
@@ -0,0 +1,74 @@
package com.sparrowwallet.sparrow.net;
import com.google.common.net.HostAndPort;
import com.samourai.http.client.HttpUsage;
import com.samourai.http.client.IHttpClient;
import com.sparrowwallet.nightjar.http.JavaHttpClientService;
import io.reactivex.Observable;
import java8.util.Optional;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import java.util.Map;
public class HttpClientService {
private final JavaHttpClientService httpClientService;
public HttpClientService(HostAndPort torProxy) {
this.httpClientService = new JavaHttpClientService(torProxy, 120000);
}
public <T> T requestJson(String url, Class<T> responseType, Map<String, String> headers) throws Exception {
IHttpClient httpClient = httpClientService.getHttpClient(HttpUsage.COORDINATOR_REST);
return httpClient.getJson(url, responseType, headers);
}
public <T> Observable<Optional<T>> postJson(String url, Class<T> responseType, Map<String, String> headers, Object body) {
IHttpClient httpClient = httpClientService.getHttpClient(HttpUsage.COORDINATOR_REST);
return httpClient.postJson(url, responseType, headers, body);
}
public String postString(String url, Map<String, String> headers, String contentType, String content) throws Exception {
IHttpClient httpClient = httpClientService.getHttpClient(HttpUsage.COORDINATOR_REST);
return httpClient.postString(url, headers, contentType, content);
}
public void changeIdentity() {
HostAndPort torProxy = getTorProxy();
if(torProxy != null) {
TorUtils.changeIdentity(torProxy);
}
}
public HostAndPort getTorProxy() {
return httpClientService.getTorProxy();
}
public void setTorProxy(HostAndPort torProxy) {
//Ensure all http clients are shutdown first
httpClientService.shutdown();
httpClientService.setTorProxy(torProxy);
}
public void shutdown() {
httpClientService.shutdown();
}
public static class ShutdownService extends Service<Boolean> {
private final HttpClientService httpClientService;
public ShutdownService(HttpClientService httpClientService) {
this.httpClientService = httpClientService;
}
@Override
protected Task<Boolean> createTask() {
return new Task<>() {
protected Boolean call() throws Exception {
httpClientService.shutdown();
return true;
}
};
}
}
}
@@ -96,9 +96,8 @@ public final class IpAddressMatcher {
private InetAddress parseAddress(String address) {
try {
return InetAddress.getByName(address);
}
catch (UnknownHostException e) {
throw new IllegalArgumentException("Failed to parse address: " + address, e);
} catch(UnknownHostException e) {
throw new IllegalArgumentException("Failed to resolve address: " + address, e);
}
}
@@ -14,7 +14,9 @@ public enum PublicElectrumServer {
EMZY_DE("electrum.emzy.de", "ssl://electrum.emzy.de:50002", Network.MAINNET),
BITAROO_NET("electrum.bitaroo.net", "ssl://electrum.bitaroo.net:50002", Network.MAINNET),
DIYNODES_COM("electrum.diynodes.com", "ssl://electrum.diynodes.com:50022", Network.MAINNET),
TESTNET_ARANGUREN_ORG("testnet.aranguren.org", "ssl://testnet.aranguren.org:51002", Network.TESTNET);
SETHFORPRIVACY_COM("fulcrum.sethforprivacy.com", "ssl://fulcrum.sethforprivacy.com:50002", Network.MAINNET),
TESTNET_ARANGUREN_ORG("testnet.aranguren.org", "ssl://testnet.aranguren.org:51002", Network.TESTNET),
TESTNET_QTORNADO_COM("testnet.qtornado.com", "ssl://testnet.qtornado.com:51002", Network.TESTNET);
PublicElectrumServer(String name, String url, Network network) {
this.server = new Server(url, name);
@@ -1,6 +1,5 @@
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;
@@ -19,6 +18,7 @@ import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
@@ -40,6 +40,8 @@ public class TcpTransport implements CloseableTransport, TimeoutCounter {
private String response;
private final CountDownLatch readReadySignal = new CountDownLatch(1);
private final ReentrantLock readLock = new ReentrantLock();
private final Condition readingCondition = readLock.newCondition();
@@ -110,6 +112,17 @@ public class TcpTransport implements CloseableTransport, TimeoutCounter {
}
private String readResponse() throws IOException {
if(firstRead) {
try {
//Ensure read thread has started
if(!readReadySignal.await(2, TimeUnit.SECONDS)) {
throw new IOException("Read thread did not start");
}
} catch(InterruptedException e) {
throw new IOException("Read ready await interrupted");
}
}
try {
if(!readLock.tryLock((readTimeouts[readTimeoutIndex] * 1000L) + (requestIdCount * PER_REQUEST_READ_TIMEOUT_MILLIS), TimeUnit.MILLISECONDS)) {
readTimeoutIndex = Math.min(readTimeoutIndex + 1, readTimeouts.length - 1);
@@ -155,6 +168,7 @@ public class TcpTransport implements CloseableTransport, TimeoutCounter {
public void readInputLoop() throws ServerException {
readLock.lock();
readReadySignal.countDown();
try {
try {
@@ -86,6 +86,10 @@ public class Tor {
dormantCanceledByStartup.set(TorConfig.Option.AorTorF.getTrue());
builder.put(dormantCanceledByStartup);
TorConfig.Setting.Ports.Control controlPort = new TorConfig.Setting.Ports.Control();
controlPort.set(TorConfig.Option.AorDorPort.Auto.INSTANCE);
builder.put(controlPort);
return builder.build();
}
};

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