Compare commits

...
102 Commits
Author SHA1 Message Date
Craig Raw 0d16c87b40 minor caravan name update 2024-05-13 11:36:04 +02:00
Craig Raw b59a65dcfe export electrum wallets with only usb capable hardware wallets as hardware keystore types 2024-05-10 09:54:33 +02:00
Craig Raw 87cc28e0a4 improve error message when importing invalid coldcard multisig config 2024-05-09 15:44:47 +02:00
Craig Raw 1187925543 fix wallet loading failure icon color in tab label when using dark theme 2024-05-09 14:42:13 +02:00
Craig Raw cd4edab4ae add testnet4 public server and tx broadcast from mempool.space 2024-05-09 13:00:11 +02:00
Craig Raw daf320f36b optionally show output descriptor qr export as bbqr, update coldcard import and export instructions 2024-05-09 12:20:54 +02:00
Craig Raw f6ff92865b avoid adding testnet symlink in windows as admin privileges are required 2024-05-08 16:15:31 +02:00
Craig Raw d420c71673 add testnet4 network support 2024-05-08 15:50:15 +02:00
Craig Raw 07101b3ca0 add additional fingerprint check when finding signing nodes from provided psbt input derivation paths 2024-05-06 09:51:34 +02:00
Craig Raw 00f7f3f5b3 update default derivation path for unknown unchained signer 2024-05-06 08:17:04 +02:00
Craig Raw 5d2c133401 fix single character multisig output descriptor threshold parsing issue 2024-05-03 12:16:25 +02:00
Craig Raw 7b0dfd66a7 fix premature decompression of bbqr zlib parts 2024-05-03 11:46:33 +02:00
Craig Raw 83719e7df2 fix signing regression on psbts with external inputs 2024-04-30 11:55:28 +02:00
Craig Raw f1b246f0b0 bump to v1.9.1 2024-04-26 09:07:37 +02:00
Craig Raw 599880ea5c improve samourai backup import error message 2024-04-25 15:21:13 +02:00
Craig Raw d625bab02e bump to v1.9.0 2024-04-25 15:13:10 +02:00
Craig Raw 1676676e06 remove whirlpool and soroban features and dependencies 2024-04-25 15:11:22 +02:00
Craig Raw f7e603118f bump to v1.8.7 2024-04-24 11:27:58 +02:00
Craig Raw f6fd889712 ignore scroll events with zero scroll movement 2024-04-24 09:00:36 +02:00
Craig Raw 21d91d3d10 add additional check against existing child wallet names when suggesting new accounts to add 2024-04-23 08:32:58 +02:00
Craig Raw f1cddc28e7 copy context menu changes on receive tab 2024-04-22 16:57:44 +02:00
Craig Raw 1887e1c7b0 allow editing of the output descriptor of a new account on a watch only wallet 2024-04-22 13:29:41 +02:00
Craig Raw 3e870f362d fall back to sparrow logo for faulty wallet icon loads 2024-04-22 12:18:28 +02:00
Craig Raw 665d70b845 fix freeze on account settings tab loading wallet type icon 2024-04-22 12:05:24 +02:00
Craig Raw c2cbe62a5a fix showing multiple password dialogs on bip47 paynym wallet linking 2024-04-22 10:02:02 +02:00
Craig Raw c6b6e74515 maintain strong reference to key derivation service until action completion 2024-04-19 10:49:42 +02:00
Craig Raw 8ddc494b53 parse output descriptors with missing fingerprints in key origin information 2024-04-19 09:59:48 +02:00
Craig Raw 33f439f49a minor text changes 2024-04-19 09:43:18 +02:00
Craig Raw d68ab40c94 add wallet import for samourai backup export 2024-04-18 16:04:06 +02:00
Craig Raw 31346e2afa add mix selected button to the postmix account in desktop and terminal 2024-04-18 13:22:50 +02:00
Craig Raw c407a41475 add fine adjustment control for fee rate slider using mouse scroll 2024-04-18 12:12:40 +02:00
Craig Raw 8baa8e2e96 support changing the frame rate of animated qrs with mouse scroll on the qr image 2024-04-18 11:45:10 +02:00
Craig Raw 72adbe44a7 cleanup 2024-04-18 10:06:35 +02:00
Craig Raw dd64c18c21 followup 2024-04-18 09:45:58 +02:00
Craig Raw 2354b061a9 add user write permissions to jvm legal files 2024-04-18 09:29:11 +02:00
Craig Raw a5050117a3 handle null proxy configuration when fetching proxy 2024-04-17 14:11:41 +02:00
Craig Raw f245b57022 add export search results as csv functionality 2024-04-17 14:01:55 +02:00
Craig Raw d3752a856b make search wallet dialog non-modal, close any non-modal dialogs on application closing 2024-04-17 12:33:13 +02:00
Craig Raw fe7dba6d83 support searching on multiple addresses, txids and utxos in a search phrase separated by spaces 2024-04-17 09:22:31 +02:00
Craig Raw 2d0a94d024 add copy context menu to date/address/output column in search wallet dialog 2024-04-16 14:34:27 +02:00
Craig Raw 41146310d6 allow label editing in the search wallet dialog 2024-04-16 13:26:58 +02:00
Craig Raw a167f6aedb add show all wallets summary 2024-04-16 12:31:56 +02:00
Craig Raw 0fed7c45ee change transactions and utxos csv export to use utc timezone for dates 2024-04-16 10:35:42 +02:00
Craig Raw 5a0df265bc unminimize existing app window when second instance is launched 2024-04-15 12:40:17 +02:00
Craig Raw 646b8b0e65 show discover button when adding accounts on a bitcoin core connection, but warn user account discovery is not generally supported if no accounts are found 2024-04-15 09:55:24 +02:00
Craig Raw c9b40b1973 fall back to coldcard singlesig import if multisig format import fails 2024-04-15 08:32:38 +02:00
Craig Raw 9ec5b6ce26 fix network enum error on startup in signet 2024-04-14 08:13:30 +02:00
Craig Raw 93893111c6 fix issue where gap limit was not increased when wallet could partially sign transaction 2024-04-12 09:12:33 +02:00
Craig Raw 3600d32ffd bump to v1.8.6 2024-04-11 13:48:12 +02:00
Craig Raw 1e0855c11d use hwi 3.0.0 built on ubuntu 20.04 amd64 2024-04-11 10:46:44 +02:00
Craig Raw 15cb028951 merge whirlpool 1.x client using decentralized soroban 2024-04-11 08:37:28 +02:00
Craig Raw e178168bec fix npe on soroban counterparty timeout 2024-04-11 08:09:08 +02:00
Craig Raw 5696e00cb5 fix stonewallx2 transaction address selection 2024-04-10 12:42:11 +02:00
craigrawandGitHub 594a873f20 Merge pull request #1369 from zeroleak/whirlpool-1.0.6
upgrade to whirlpool 1.0.6 to support simpler onion switching
2024-04-10 10:34:47 +02:00
zeroleak da30d4223a upgrade whirlpool-client 1.0.6 2024-04-10 09:52:41 +02:00
Craig Raw 2441b4d7c3 handle coldcard singlesig file imports containing p2sh-p2wsh 2024-04-10 07:44:24 +02:00
Craig Raw cc739a71e9 followup 2024-04-09 11:03:20 +02:00
Craig Raw 5f98eb9eb9 followup 2024-04-08 13:45:52 +02:00
Craig Raw 5aa25b98c3 supporting importing labels from electrum history csv using wallet labels import 2024-04-08 13:38:36 +02:00
Craig Raw 5058cd283d use hwi 3.0.0 built on ubuntu 20.04 aarch64 2024-04-08 11:36:27 +02:00
Craig Raw af6171692b upgrade to hwi 3.0.0 2024-04-08 11:19:34 +02:00
Craig Raw 3c631fa653 add button to display seedqr on seed display dialog after warning 2024-04-05 13:50:05 +02:00
Craig Raw 10a796098b keep any existing seeds with matching fingerprints when changing a wallets output descriptor, rederiving the xpub if necessary 2024-04-05 12:11:46 +02:00
Craig Raw 8ac642b09c set default derivation for mnemonic and xprv imports to current keystore derivation 2024-04-04 14:05:41 +02:00
Craig Raw 33d9f260c4 close qr display dialog for current fresh address when it updates 2024-04-04 12:50:03 +02:00
Craig Raw 86247c6440 dynamically retrieve currently selected pool when tx0 preview is fetched 2024-04-04 12:15:33 +02:00
Craig Raw c39425ed3b improve logging on tor cookie read errors 2024-04-04 10:41:32 +02:00
Craig Raw e5e94c3ea6 compute latest block on open 2024-04-03 12:40:51 +02:00
Craig Raw 9ba4458f48 fix tor proxy switching for whirlpool client and mixing bip47 utxos 2024-04-02 17:14:19 +02:00
craigrawandGitHub a9fd7c263f Merge pull request #1349 from zeroleak/whirlpool-1.0.5
whirlpool 1.0.5
2024-04-02 11:05:38 +02:00
zeroleak 6ef1313137 upgrade whirlpool-client 1.0.5 2024-04-01 16:32:56 +02:00
Craig Raw 8e66db0237 Merge branch 'master' into whirlpool-1.0.0 2024-03-29 10:12:11 +02:00
Craig Raw 6da98befe1 update drongo to latest 2024-03-29 10:10:51 +02:00
Craig Raw 6b4c301458 always bring first instance to foreground when second instance is closed 2024-03-29 09:36:11 +02:00
Craig Raw 86ff7b8cf9 optimize initial fee rates fetching by avoiding double server fee estimate and histogram calls where possible 2024-03-28 15:36:47 +02:00
Craig Raw a805d9e036 use cached fee rate estimates on initial server connection if available, and retrieve updates from fee rate source immediately afterwards 2024-03-28 14:14:32 +02:00
Craig Raw f0bfc44e72 avoid saving lock file link for default instance if environment variable is set 2024-03-28 12:01:48 +02:00
Craig Raw 0fad93524e delete existing instance lock file and recreate if client connection fails 2024-03-28 10:56:37 +02:00
Craig Raw c1fc8712d5 use default sparrow home location in user dir for instance lock file pointer 2024-03-28 09:12:44 +02:00
Craig Raw 5d674b7e91 followup to handle situations where creating symlinks fails 2024-03-27 13:08:01 +02:00
Craig Raw d1a353ae53 use unix sockets in sparrow home for instance checks and message passing, with system symlink to find existing instances for files and uris 2024-03-27 12:45:05 +02:00
Craig Raw 08ec158d19 support cookie authentication for tor control port 2024-03-26 13:26:32 +02:00
Craig Raw 2e8112cba0 add restart in different home folder to tools menu 2024-03-26 11:37:46 +02:00
Craig Raw c108741b6f upgrade to pgpainless 1.6.7 with basic modules support 2024-03-26 10:04:05 +02:00
Craig Raw 4450d625dd external destination now checks for custom postmix handler 2024-03-25 17:01:31 +02:00
Craig Raw 2e1ee0c5b2 ensure whirlpool wallets use nfkd encoding for passphrases 2024-03-25 16:57:36 +02:00
Craig Raw 1c3c2d8089 cache tx0info and clear after tx0 broadcast 2024-03-25 16:23:24 +02:00
craigrawandGitHub a4991064af Merge pull request #1333 from zeroleak/whirlpool-1.0.0-beta23
upgrade to whirlpool 1.0.1
2024-03-25 14:54:48 +02:00
Craig Raw 6ea6f4b5d2 add new wallet, open wallet and import wallet hyperlinks to background text shown when no tabs are open 2024-03-25 14:25:31 +02:00
Craig Raw 210d52c001 change unselected tabs to be lighter colored than selected tabs in dark theme 2024-03-25 13:05:16 +02:00
zeroleak fcbed8795f upgrade whirlpool-client 1.0.1 2024-03-20 15:24:42 +01:00
zeroleak 0d9e798bb7 upgrade whirlpool-client 1.0.0-beta23 2024-03-19 15:01:15 +01:00
Craig Raw 9d0c35bc75 handle import of ur crypto-hdkey without source fingerprint 2024-03-18 07:48:55 +02:00
Craig Raw f3c44e6f3e fix script display of uncompressed pubkeys 2024-03-16 08:08:18 +02:00
Craig Raw 14d0437424 indicate if disconnected on startup, and display status with instruction on how to connect for longer 2024-03-14 09:36:02 +02:00
Craig Raw d2934c94c5 disable manifest field in download verify dialog if signature signs release file directly 2024-03-14 09:05:14 +02:00
Craig Raw 2e847199f5 fix message signing by qr with no action on scan qr 2024-03-14 08:49:52 +02:00
Craig Raw c9d1650ed4 various updates and fixes 2024-03-13 15:58:43 +02:00
zeroleak da74089969 upgrade to whirlpool 1.0.0-beta10 2024-03-11 02:12:56 +01:00
Craig Raw d1ac5b076e avoid adding block explorer to transaction context menu when configured to none 2024-03-09 10:24:42 +02:00
Craig Raw e1564217ed bump to v1.8.5 2024-03-07 20:16:35 +02:00
zeroleak 249a01c208 upgrade to whirlpool 1.0.0-beta4 2024-03-05 18:32:20 +01:00
165 changed files with 3281 additions and 8379 deletions
+5 -3
View File
@@ -64,10 +64,12 @@ Usage: sparrow [options]
Possible Values: [ERROR, WARN, INFO, DEBUG, TRACE]
--network, -n
Network to use
Possible Values: [mainnet, testnet, regtest, signet]
Possible Values: [mainnet, testnet, regtest, signet, testnet4]
```
As a fallback, the network (mainnet, testnet, regtest or signet) can also be set using an environment variable `SPARROW_NETWORK`. For example:
Note that testnet currently refers to testnet3.
As a fallback, the network (mainnet, testnet, testnet4, regtest or signet) can also be set using an environment variable `SPARROW_NETWORK`. For example:
`export SPARROW_NETWORK=testnet`
@@ -83,7 +85,7 @@ When not explicitly configured using the command line argument above, Sparrow st
| Linux | ~/.sparrow |
| Windows | %APPDATA%/Sparrow |
Testnet, regtest and signet configurations (along with their wallets) are stored in subfolders to allow easy switching between networks.
Testnet3, testnet4, regtest and signet configurations (along with their wallets) are stored in subfolders to allow easy switching between networks.
## Reporting Issues
+27 -83
View File
@@ -7,7 +7,7 @@ plugins {
id 'org.beryx.jlink' version '3.0.1'
}
def sparrowVersion = '1.8.4'
def sparrowVersion = '1.9.1'
def os = org.gradle.internal.os.OperatingSystem.current()
def osName = os.getFamilyName()
if(os.macOsX) {
@@ -123,8 +123,8 @@ dependencies {
implementation('org.slf4j:jul-to-slf4j:2.0.12') {
exclude group: 'org.slf4j'
}
implementation('com.sparrowwallet.nightjar:nightjar:0.2.40')
implementation('com.sparrowwallet.bokmakierie:bokmakierie:1.0')
implementation('org.eclipse.jetty:jetty-client:9.4.54.v20240208')
implementation('io.reactivex.rxjava2:rxjava:2.2.15')
implementation('io.reactivex.rxjava2:rxjavafx:2.2.2')
implementation('org.apache.commons:commons-lang3:3.7')
@@ -212,8 +212,6 @@ jlink {
uses 'org.flywaydb.core.extensibility.FlywayExtension'
uses 'org.flywaydb.core.internal.database.DatabaseType'
uses 'org.eclipse.jetty.http.HttpFieldPreEncoder'
uses 'org.eclipse.jetty.websocket.api.extensions.Extension'
uses 'org.eclipse.jetty.websocket.common.RemoteEndpointFactory'
}
options = ['--strip-native-commands', '--strip-java-debug-attributes', '--compress', '2', '--no-header-files', '--no-man-pages', '--ignore-signing-information', '--exclude-files', '**.png', '--exclude-resources', 'glob:/com.sparrowwallet.merged.module/META-INF/*']
@@ -248,6 +246,8 @@ jlink {
"--add-reads=com.sparrowwallet.merged.module=com.fasterxml.jackson.annotation",
"--add-reads=com.sparrowwallet.merged.module=com.fasterxml.jackson.core",
"--add-reads=com.sparrowwallet.merged.module=co.nstant.in.cbor",
"--add-reads=com.sparrowwallet.merged.module=org.bouncycastle.pg",
"--add-reads=com.sparrowwallet.merged.module=org.bouncycastle.provider",
"--add-reads=kotlin.stdlib=kotlinx.coroutines.core"]
if(os.windows) {
@@ -290,6 +290,16 @@ jlink {
}
}
tasks.jlink.finalizedBy "addUserWritePermission"
task addUserWritePermission(type: Exec) {
if(os.windows) {
commandLine 'icacls', "$buildDir\\image\\legal", '/grant', 'Users:(OI)(CI)F', '/T'
} else {
commandLine 'chmod', '-R', 'u+w', "$buildDir/image/legal"
}
}
task removeGroupWritePermission(type: Exec) {
commandLine 'chmod', '-R', 'g-w', "$buildDir/jpackage/Sparrow"
}
@@ -491,65 +501,21 @@ extraJavaModuleInfo {
exports('co.nstant.in.cbor.model')
exports('co.nstant.in.cbor.builder')
}
module('nightjar-0.2.40.jar', 'com.sparrowwallet.nightjar', '0.2.40') {
requires('com.google.common')
requires('net.sourceforge.streamsupport')
requires('org.slf4j')
requires('org.bouncycastle.provider')
requires('com.fasterxml.jackson.databind')
requires('com.fasterxml.jackson.annotation')
requires('com.fasterxml.jackson.core')
requires('ch.qos.logback.classic')
requires('org.json')
requires('io.reactivex.rxjava2')
exports('com.samourai.http.client')
exports('com.samourai.tor.client')
exports('com.samourai.wallet.api.backend')
exports('com.samourai.wallet.api.backend.beans')
exports('com.samourai.wallet.client.indexHandler')
exports('com.samourai.wallet.hd')
exports('com.samourai.wallet.util')
exports('com.samourai.wallet.bip47.rpc')
exports('com.samourai.wallet.bip47.rpc.java')
exports('com.samourai.wallet.cahoots')
exports('com.samourai.wallet.cahoots.psbt')
exports('com.samourai.wallet.cahoots.stonewallx2')
exports('com.samourai.soroban.cahoots')
exports('com.samourai.soroban.client')
exports('com.samourai.soroban.client.cahoots')
exports('com.samourai.soroban.client.meeting')
exports('com.samourai.soroban.client.rpc')
exports('com.samourai.wallet.send')
exports('com.samourai.whirlpool.client.event')
exports('com.samourai.whirlpool.client.wallet')
exports('com.samourai.whirlpool.client.wallet.beans')
exports('com.samourai.whirlpool.client.wallet.data.dataSource')
exports('com.samourai.whirlpool.client.wallet.data.dataPersister')
exports('com.samourai.whirlpool.client.whirlpool')
exports('com.samourai.whirlpool.client.whirlpool.beans')
exports('com.samourai.whirlpool.client.wallet.data.pool')
exports('com.samourai.whirlpool.client.wallet.data.utxo')
exports('com.samourai.whirlpool.client.wallet.data.utxoConfig')
exports('com.samourai.whirlpool.client.wallet.data.supplier')
exports('com.samourai.whirlpool.client.mix.handler')
exports('com.samourai.whirlpool.client.mix.listener')
exports('com.samourai.whirlpool.protocol.beans')
exports('com.samourai.whirlpool.protocol.rest')
exports('com.samourai.whirlpool.client.tx0')
exports('com.samourai.wallet.segwit.bech32')
exports('com.samourai.whirlpool.client.wallet.data.chain')
exports('com.samourai.whirlpool.client.wallet.data.wallet')
exports('com.samourai.whirlpool.client.wallet.data.minerFee')
exports('com.samourai.whirlpool.client.wallet.data.walletState')
exports('com.sparrowwallet.nightjar.http')
exports('com.sparrowwallet.nightjar.stomp')
exports('com.sparrowwallet.nightjar.tor')
module('commons-codec-1.10.jar', 'commons.codec', '1.10') {
exports('org.apache.commons.codec')
}
module('throwing-supplier-1.0.3.jar', 'zeroleak.throwingsupplier', '1.0.3') {
exports('com.zeroleak.throwingsupplier')
module('logback-core-1.2.13.jar', 'ch.qos.logback.core', '1.2.13') {
exports('ch.qos.logback.core')
}
module('okhttp-2.7.5.jar', 'com.squareup.okhttp', '2.7.5') {
exports('com.squareup.okhttp')
module('jackson-datatype-jsr310-2.13.2.jar', 'jackson-datatype-jsr310', '2.13.2') {
exports('com.fasterxml.jackson.datatype.jsr310')
}
module('json-20240205.jar', 'org.json', '20240205') {
exports('org.json')
}
module('scrypt-1.4.0.jar', 'scrypt', '1.4.0') {
exports('com.lambdaworks.codec')
exports('com.lambdaworks.crypto')
}
module('okio-1.6.0.jar', 'com.squareup.okio', '1.6.0') {
exports('okio')
@@ -557,22 +523,12 @@ extraJavaModuleInfo {
module('java-jwt-3.8.1.jar', 'com.auth0.jwt', '3.8.1') {
exports('com.auth0.jwt')
}
module('json-20180130.jar', 'org.json', '1.0') {
exports('org.json')
}
module('scrypt-1.4.0.jar', 'com.lambdaworks.scrypt', '1.4.0') {
exports('com.lambdaworks.codec')
exports('com.lambdaworks.crypto')
}
module('streamsupport-1.7.0.jar', 'net.sourceforge.streamsupport', '1.7.0') {
requires('jdk.unsupported')
exports('java8.util')
exports('java8.util.function')
exports('java8.util.stream')
}
module('protobuf-java-2.6.1.jar', 'com.google.protobuf', '2.6.1') {
exports('com.google.protobuf')
}
module('commons-text-1.2.jar', 'org.apache.commons.text', '1.2') {
exports('org.apache.commons.text')
}
@@ -705,18 +661,6 @@ extraJavaModuleInfo {
module('jcommander-1.81.jar', 'com.beust.jcommander', '1.81') {
exports('com.beust.jcommander')
}
module('pgpainless-core-1.6.6.jar', 'org.pgpainless.core', '1.6.6') {
exports('org.pgpainless')
exports('org.pgpainless.key')
exports('org.pgpainless.key.parsing')
exports('org.pgpainless.decryption_verification')
exports('org.pgpainless.exception')
exports('org.pgpainless.signature')
exports('org.pgpainless.util')
requires('org.bouncycastle.provider')
requires('org.bouncycastle.pg')
requires('org.slf4j')
}
module('jzlib-1.1.3.jar', 'com.jcraft.jzlib', '1.1.3') {
exports('com.jcraft.jzlib')
}
@@ -143,7 +143,7 @@ abstract public class ExtraModuleInfoTransform implements TransformAction<ExtraM
private static void copyEntries(JarInputStream inputStream, JarOutputStream outputStream) throws IOException {
JarEntry jarEntry = inputStream.getNextJarEntry();
while (jarEntry != null) {
if(!jarEntry.getName().equals("module-info.class") && !jarEntry.getName().equals("org/bouncycastle/CachingBcPublicKeyDataDecryptorFactory.class")) {
if(!jarEntry.getName().equals("module-info.class")) {
outputStream.putNextEntry(jarEntry);
outputStream.write(inputStream.readAllBytes());
outputStream.closeEntry();
+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.8.3"
GIT_TAG="1.9.0"
```
The project can then be initially cloned as follows:
+1 -1
Submodule drongo updated: 3b8435ca37...571db32574
+1 -1
View File
@@ -21,7 +21,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.8.4</string>
<string>1.9.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<!-- See https://developer.apple.com/app-store/categories/ for list of AppStore categories -->
@@ -27,10 +27,7 @@ import com.sparrowwallet.sparrow.net.ElectrumServer;
import com.sparrowwallet.sparrow.net.ServerType;
import com.sparrowwallet.sparrow.preferences.PreferenceGroup;
import com.sparrowwallet.sparrow.preferences.PreferencesDialog;
import com.sparrowwallet.sparrow.soroban.CounterpartyDialog;
import com.sparrowwallet.sparrow.paynym.PayNymDialog;
import com.sparrowwallet.sparrow.soroban.Soroban;
import com.sparrowwallet.sparrow.soroban.SorobanServices;
import com.sparrowwallet.sparrow.transaction.TransactionController;
import com.sparrowwallet.sparrow.transaction.TransactionData;
import com.sparrowwallet.sparrow.transaction.TransactionView;
@@ -187,9 +184,6 @@ public class AppController implements Initializable {
@FXML
private MenuItem sweepPrivateKey;
@FXML
private MenuItem findMixingPartner;
@FXML
private MenuItem showPayNym;
@@ -215,10 +209,14 @@ public class AppController implements Initializable {
@FXML
private UnlabeledToggleSwitch serverToggle;
private Storage.KeyDerivationService keyDerivationService;
private PauseTransition wait;
private Timeline statusTimeline;
private SearchWalletDialog searchWalletDialog;
private SendToManyDialog sendToManyDialog;
private DownloadVerifierDialog downloadVerifierDialog;
@@ -280,6 +278,15 @@ public class AppController implements Initializable {
void initializeView() {
setPlatformApplicationMenu();
rootStack.getScene().getWindow().setOnHiding(windowEvent -> {
if(searchWalletDialog != null && searchWalletDialog.isShowing()) {
searchWalletDialog.close();
}
if(sendToManyDialog != null && sendToManyDialog.isShowing()) {
sendToManyDialog.close();
}
});
rootStack.setOnDragOver(event -> {
if(event.getGestureSource() != rootStack && event.getDragboard().hasFiles()) {
event.acceptTransferModes(TransferMode.LINK);
@@ -333,6 +340,8 @@ public class AppController implements Initializable {
EventManager.get().post(new OpenWalletsEvent(tabs.getScene().getWindow(), Collections.emptyList()));
});
tabs.setPickOnBounds(false);
registerShortcuts();
BitcoinUnit unit = Config.get().getBitcoinUnit();
@@ -379,7 +388,10 @@ public class AppController implements Initializable {
preventSleepProperty.set(Config.get().isPreventSleep());
preventSleep.selectedProperty().bindBidirectional(preventSleepProperty);
List<Network> networks = new ArrayList<>(List.of(Network.MAINNET, Network.TESTNET, Network.SIGNET));
MenuItem homeItem = new MenuItem("Home Folder...");
homeItem.setOnAction(this::restartInHome);
restart.getItems().add(homeItem);
List<Network> networks = new ArrayList<>(List.of(Network.MAINNET, Network.TESTNET, Network.TESTNET4, Network.SIGNET));
networks.remove(Network.get());
for(Network network : networks) {
MenuItem networkItem = new MenuItem(network.toDisplayString());
@@ -405,10 +417,6 @@ public class AppController implements Initializable {
sendToMany.disableProperty().bind(exportWallet.disableProperty());
sweepPrivateKey.disableProperty().bind(Bindings.or(serverToggle.disableProperty(), AppServices.onlineProperty().not()));
showPayNym.setDisable(true);
findMixingPartner.setDisable(true);
AppServices.onlineProperty().addListener((observable, oldValue, newValue) -> {
findMixingPartner.setDisable(exportWallet.isDisable() || getSelectedWalletForm() == null || !SorobanServices.canWalletMix(getSelectedWalletForm().getWallet()) || !newValue);
});
configureSwitchServer();
setServerType(Config.get().getServerType());
@@ -971,19 +979,46 @@ public class AppController implements Initializable {
AppServices.get().setPreventSleep(item.isSelected());
}
public void restartInHome(ActionEvent event) {
Args args = getRestartArgs();
File initialDir = null;
if(args.dir != null) {
initialDir = new File(args.dir);
}
Stage window = new Stage();
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setTitle("Choose Sparrow Home Folder");
directoryChooser.setInitialDirectory(initialDir == null || !initialDir.exists() ? Storage.getSparrowHome() : initialDir);
File newHome = directoryChooser.showDialog(window);
if(newHome != null) {
args.dir = newHome.getAbsolutePath();
restart(event, args);
}
}
public void restart(ActionEvent event, Network network) {
if(System.getProperty(JPACKAGE_APP_PATH) == null) {
throw new IllegalStateException("Property " + JPACKAGE_APP_PATH + " is not present");
}
Args args = getRestartArgs();
args.network = network;
restart(event, args);
}
private static Args getRestartArgs() {
Args args = new Args();
ProcessHandle.current().info().arguments().ifPresent(argv -> {
JCommander jCommander = JCommander.newBuilder().addObject(args).acceptUnknownOptions(true).build();
jCommander.parse(argv);
});
args.network = network;
return args;
}
private void restart(ActionEvent event, Args args) {
try {
List<String> cmd = new ArrayList<>();
cmd.add(System.getProperty(JPACKAGE_APP_PATH));
@@ -1279,7 +1314,7 @@ public class AppController implements Initializable {
log.error("Error saving imported wallet", e);
}
} else {
Storage.KeyDerivationService keyDerivationService = new Storage.KeyDerivationService(storage, password.get());
keyDerivationService = new Storage.KeyDerivationService(storage, password.get());
keyDerivationService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(Storage.getWalletFile(wallet.getName()).getAbsolutePath(), TimedEvent.Action.END, "Done"));
ECKey encryptionFullKey = keyDerivationService.getValue();
@@ -1310,11 +1345,13 @@ public class AppController implements Initializable {
if(key != null) {
key.clear();
}
keyDerivationService = null;
}
});
keyDerivationService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(Storage.getWalletFile(wallet.getName()).getAbsolutePath(), TimedEvent.Action.END, "Failed"));
showErrorDialog("Error encrypting wallet", keyDerivationService.getException().getMessage());
keyDerivationService = null;
});
EventManager.get().post(new StorageEvent(Storage.getWalletFile(wallet.getName()).getAbsolutePath(), TimedEvent.Action.START, "Encrypting wallet..."));
keyDerivationService.start();
@@ -1387,7 +1424,6 @@ 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;
@@ -1413,74 +1449,6 @@ public class AppController implements Initializable {
optTransaction.ifPresent(transaction -> addTransactionTab(null, null, transaction));
}
public void findMixingPartner(ActionEvent event) {
WalletForm selectedWalletForm = getSelectedWalletForm();
if(selectedWalletForm != null) {
Wallet wallet = selectedWalletForm.getWallet();
Soroban soroban = AppServices.getSorobanServices().getSoroban(selectedWalletForm.getWalletId());
if(soroban.getHdWallet() == null) {
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();
Storage.KeyDerivationService keyDerivationService = new Storage.KeyDerivationService(storage, password.get(), true);
keyDerivationService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(selectedWalletForm.getWalletId(), TimedEvent.Action.END, "Done"));
ECKey encryptionFullKey = keyDerivationService.getValue();
Key key = new Key(encryptionFullKey.getPrivKeyBytes(), storage.getKeyDeriver().getSalt(), EncryptionType.Deriver.ARGON2);
copy.decrypt(key);
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);
}
counterpartyDialog.showAndWait();
} finally {
key.clear();
encryptionFullKey.clear();
password.get().clear();
}
});
keyDerivationService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(selectedWalletForm.getWalletId(), TimedEvent.Action.END, "Failed"));
if(keyDerivationService.getException() instanceof InvalidPasswordException) {
Optional<ButtonType> optResponse = showErrorDialog("Invalid Password", "The wallet password was invalid. Try again?", ButtonType.CANCEL, ButtonType.OK);
if(optResponse.isPresent() && optResponse.get().equals(ButtonType.OK)) {
Platform.runLater(() -> findMixingPartner(null));
}
} else {
log.error("Error deriving wallet key", keyDerivationService.getException());
}
});
EventManager.get().post(new StorageEvent(selectedWalletForm.getWalletId(), TimedEvent.Action.START, "Decrypting wallet..."));
keyDerivationService.start();
}
} 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);
}
counterpartyDialog.showAndWait();
}
} else {
CounterpartyDialog counterpartyDialog = new CounterpartyDialog(selectedWalletForm.getWalletId(), selectedWalletForm.getWallet());
counterpartyDialog.initOwner(rootStack.getScene().getWindow());
if(Config.get().isSameAppMixing()) {
counterpartyDialog.initModality(Modality.NONE);
}
counterpartyDialog.showAndWait();
}
}
}
public void showPayNym(ActionEvent event) {
WalletForm selectedWalletForm = getSelectedWalletForm();
if(selectedWalletForm != null) {
@@ -1573,13 +1541,46 @@ public class AppController implements Initializable {
}
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)));
if(searchWalletDialog != null) {
if(!searchWalletDialog.getWalletForms().equals(walletForms)) {
searchWalletDialog.close();
} else {
Stage stage = (Stage)searchWalletDialog.getDialogPane().getScene().getWindow();
stage.setAlwaysOnTop(true);
stage.setAlwaysOnTop(false);
return;
}
}
Platform.runLater(() -> {
searchWalletDialog = new SearchWalletDialog(walletForms);
searchWalletDialog.initModality(Modality.NONE);
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)));
}
searchWalletDialog = null;
});
}
public void showAllWalletsSummary(ActionEvent event) {
List<List<WalletForm>> allWalletForms = new ArrayList<>();
for(Tab tab : tabs.getTabs()) {
if(tab.getUserData() instanceof WalletTabData) {
TabPane subTabs = (TabPane)tab.getContent();
allWalletForms.add(subTabs.getTabs().stream().map(subTab -> ((WalletTabData)subTab.getUserData()).getWalletForm())
.filter(walletForm -> walletForm.getWallet().isValid() && !walletForm.isLocked()).collect(Collectors.toList()));
}
}
if(allWalletForms.isEmpty() || allWalletForms.stream().allMatch(List::isEmpty)) {
showErrorDialog("No wallets", "There are no open and unlocked wallets to summarize.");
} else {
WalletSummaryDialog walletSummaryDialog = new WalletSummaryDialog(allWalletForms);
walletSummaryDialog.initOwner(rootStack.getScene().getWindow());
walletSummaryDialog.showAndWait();
}
}
@@ -1591,7 +1592,7 @@ 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()) {
WalletSummaryDialog walletSummaryDialog = new WalletSummaryDialog(walletForms);
WalletSummaryDialog walletSummaryDialog = new WalletSummaryDialog(List.of(walletForms));
walletSummaryDialog.initOwner(rootStack.getScene().getWindow());
walletSummaryDialog.showAndWait();
}
@@ -1647,14 +1648,6 @@ public class AppController implements Initializable {
tabLabel.setGraphicTextGap(5.0);
tab.setGraphic(tabLabel);
tab.setClosable(true);
tab.setOnCloseRequest(event -> {
if(AppServices.getWhirlpoolServices().getWhirlpoolForMixToWallet(((WalletTabData)tab.getUserData()).getWalletForm().getWalletId()) != null) {
Optional<ButtonType> optType = AppServices.showWarningDialog("Close mix to wallet?", "This wallet has been configured as the final destination for mixes, and needs to be open for this to occur.\n\nAre you sure you want to close?", ButtonType.NO, ButtonType.YES);
if(optType.isPresent() && optType.get() == ButtonType.NO) {
event.consume();
}
}
});
TabPane subTabs = new TabPane();
subTabs.setSide(Side.LEFT);
@@ -2148,7 +2141,7 @@ public class AppController implements Initializable {
dlg.initOwner(rootStack.getScene().getWindow());
Optional<SecureString> password = dlg.showAndWait();
if(password.isPresent()) {
Storage.KeyDerivationService keyDerivationService = new Storage.KeyDerivationService(storage, password.get(), true);
keyDerivationService = new Storage.KeyDerivationService(storage, password.get(), true);
keyDerivationService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(selectedWalletForm.getWalletId(), TimedEvent.Action.END, "Done"));
ECKey encryptionFullKey = keyDerivationService.getValue();
@@ -2158,7 +2151,7 @@ public class AppController implements Initializable {
deleteStorage(storage, true);
} finally {
encryptionFullKey.clear();
password.get().clear();
keyDerivationService = null;
}
});
keyDerivationService.setOnFailed(workerStateEvent -> {
@@ -2171,6 +2164,7 @@ public class AppController implements Initializable {
} else {
log.error("Error deriving wallet key", keyDerivationService.getException());
}
keyDerivationService = null;
});
EventManager.get().post(new StorageEvent(selectedWalletForm.getWalletId(), TimedEvent.Action.START, "Decrypting wallet..."));
keyDerivationService.start();
@@ -2473,7 +2467,6 @@ public class AppController implements Initializable {
showLoadingLog.setDisable(true);
showTxHex.setDisable(false);
showPayNym.setDisable(true);
findMixingPartner.setDisable(true);
} else if(event instanceof WalletTabSelectedEvent) {
WalletTabSelectedEvent walletTabEvent = (WalletTabSelectedEvent)event;
WalletTabData walletTabData = walletTabEvent.getWalletTabData();
@@ -2485,7 +2478,6 @@ public class AppController implements Initializable {
showLoadingLog.setDisable(false);
showTxHex.setDisable(true);
showPayNym.setDisable(exportWallet.isDisable() || !walletTabData.getWallet().hasPaymentCode());
findMixingPartner.setDisable(exportWallet.isDisable() || !SorobanServices.canWalletMix(walletTabData.getWallet()) || !AppServices.onlineProperty().get());
}
}
}
@@ -2511,7 +2503,6 @@ public class AppController implements Initializable {
if(selectedWalletForm.getWalletId().equals(event.getWalletId())) {
exportWallet.setDisable(!event.getWallet().isValid() || selectedWalletForm.isLocked());
showPayNym.setDisable(exportWallet.isDisable() || !event.getWallet().hasPaymentCode());
findMixingPartner.setDisable(exportWallet.isDisable() || !SorobanServices.canWalletMix(event.getWallet()) || !AppServices.onlineProperty().get());
}
}
@@ -2753,7 +2744,7 @@ public class AppController implements Initializable {
public void disconnection(DisconnectionEvent event) {
serverToggle.setDisable(false);
if(!AppServices.isConnecting() && !AppServices.isConnected() && !statusBar.getText().startsWith(CONNECTION_FAILED_PREFIX) && !statusBar.getText().contains(TRYING_ANOTHER_SERVER_MESSAGE)) {
statusUpdated(new StatusEvent("Disconnected"));
statusUpdated(new StatusEvent("Disconnected (click toggle on the right to connect)", 240));
}
if(statusTimeline == null || statusTimeline.getStatus() != Animation.Status.RUNNING) {
statusBar.setProgress(0);
@@ -24,8 +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.soroban.SorobanServices;
import com.sparrowwallet.sparrow.whirlpool.WhirlpoolServices;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
@@ -95,11 +93,7 @@ public class AppServices {
private static AppServices INSTANCE;
private final WhirlpoolServices whirlpoolServices = new WhirlpoolServices();
private final SorobanServices sorobanServices = new SorobanServices();
private InteractionServices interactionServices;
private final InteractionServices interactionServices;
private static HttpClientService httpClientService;
@@ -117,6 +111,8 @@ public class AppServices {
private ElectrumServer.ConnectionService connectionService;
private ElectrumServer.FeeRatesService feeRatesService;
private Hwi.ScheduledEnumerateService deviceEnumerateService;
private VersionCheckService versionCheckService;
@@ -165,6 +161,11 @@ public class AppServices {
connectionService.cancel();
ratesService.cancel();
versionCheckService.cancel();
if(httpClientService != null) {
HttpClientService.ShutdownService shutdownService = new HttpClientService.ShutdownService(httpClientService);
shutdownService.start();
}
}
}
};
@@ -181,13 +182,12 @@ public class AppServices {
this.application = application;
this.interactionServices = interactionServices;
EventManager.get().register(this);
EventManager.get().register(whirlpoolServices);
EventManager.get().register(sorobanServices);
}
public void start() {
Config config = Config.get();
connectionService = createConnectionService();
feeRatesService = createFeeRatesService();
ratesService = createRatesService(config.getExchangeSource(), config.getFiatCurrency());
versionCheckService = createVersionCheckService();
torService = createTorService();
@@ -201,6 +201,8 @@ public class AppServices {
} else {
restartServices();
}
} else {
EventManager.get().post(new DisconnectionEvent());
}
addURIHandlers();
@@ -284,8 +286,15 @@ public class AppServices {
onlineProperty.setValue(true);
onlineProperty.addListener(onlineServicesListener);
if(connectionService.getValue() != null) {
EventManager.get().post(connectionService.getValue());
FeeRatesUpdatedEvent event = connectionService.getValue();
if(event != null) {
EventManager.get().post(event);
}
FeeRatesSource feeRatesSource = Config.get().getFeeRatesSource();
feeRatesSource = (feeRatesSource == null ? FeeRatesSource.MEMPOOL_SPACE : feeRatesSource);
if(event instanceof ConnectionEvent && Network.get().equals(Network.MAINNET) && feeRatesSource.isExternal()) {
EventManager.get().post(new FeeRatesSourceChangedEvent(feeRatesSource));
}
});
connectionService.setOnFailed(failEvent -> {
@@ -356,6 +365,15 @@ public class AppServices {
return connectionService;
}
private ElectrumServer.FeeRatesService createFeeRatesService() {
ElectrumServer.FeeRatesService feeRatesService = new ElectrumServer.FeeRatesService();
feeRatesService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(feeRatesService.getValue());
});
return feeRatesService;
}
private ExchangeSource.RatesService createRatesService(ExchangeSource exchangeSource, Currency currency) {
ExchangeSource.RatesService ratesService = new ExchangeSource.RatesService(
exchangeSource == null ? DEFAULT_EXCHANGE_SOURCE : exchangeSource,
@@ -476,7 +494,7 @@ public class AppServices {
public static Proxy getProxy(String proxyCircuitId) {
Config config = Config.get();
Proxy proxy = null;
if(config.isUseProxy()) {
if(config.isUseProxy() && config.getProxyServer() != null) {
HostAndPort proxyHostAndPort = HostAndPort.fromString(config.getProxyServer());
InetSocketAddress proxyAddress = new InetSocketAddress(proxyHostAndPort.getHost(), proxyHostAndPort.getPortOrDefault(ProxyTcpOverTlsTransport.DEFAULT_PROXY_PORT));
proxy = new Proxy(Proxy.Type.SOCKS, proxyAddress);
@@ -508,24 +526,15 @@ public class AppServices {
return INSTANCE;
}
public static WhirlpoolServices getWhirlpoolServices() {
return get().whirlpoolServices;
}
public static SorobanServices getSorobanServices() {
return get().sorobanServices;
}
public static InteractionServices getInteractionServices() {
return get().interactionServices;
}
public static HttpClientService getHttpClientService() {
HostAndPort torProxy = getTorProxy();
if(httpClientService == null) {
HostAndPort torProxy = getTorProxy();
httpClientService = new HttpClientService(torProxy);
} else {
HostAndPort torProxy = getTorProxy();
if(!Objects.equals(httpClientService.getTorProxy(), torProxy)) {
httpClientService.setTorProxy(getTorProxy());
}
@@ -898,6 +907,7 @@ public class AppServices {
}
if(openWindow instanceof Stage) {
((Stage)openWindow).setIconified(false);
((Stage)openWindow).setAlwaysOnTop(true);
((Stage)openWindow).setAlwaysOnTop(false);
}
@@ -1069,6 +1079,37 @@ public class AppServices {
return wallet;
}
public static final List<Network> WHIRLPOOL_NETWORKS = List.of(Network.MAINNET, Network.TESTNET);
public static boolean isWhirlpoolCompatible(Wallet wallet) {
return WHIRLPOOL_NETWORKS.contains(Network.get())
&& wallet.getScriptType() != ScriptType.P2TR //Taproot not yet supported
&& wallet.getKeystores().size() == 1
&& wallet.getKeystores().get(0).hasSeed()
&& wallet.getKeystores().get(0).getSeed().getType() == DeterministicSeed.Type.BIP39
&& wallet.getStandardAccountType() != null
&& StandardAccount.isMixableAccount(wallet.getStandardAccountType());
}
public static boolean isWhirlpoolPostmixCompatible(Wallet wallet) {
return WHIRLPOOL_NETWORKS.contains(Network.get())
&& wallet.getScriptType() != ScriptType.P2TR //Taproot not yet supported
&& wallet.getKeystores().size() == 1;
}
public static List<Wallet> addWhirlpoolWallets(Wallet decryptedWallet, String walletId, Storage storage) {
List<Wallet> childWallets = new ArrayList<>();
for(StandardAccount whirlpoolAccount : StandardAccount.WHIRLPOOL_ACCOUNTS) {
if(decryptedWallet.getChildWallet(whirlpoolAccount) == null) {
Wallet childWallet = decryptedWallet.addChildWallet(whirlpoolAccount);
childWallets.add(childWallet);
EventManager.get().post(new ChildWalletsAddedEvent(storage, decryptedWallet, childWallet));
}
}
return childWallets;
}
public static Font getMonospaceFont() {
return Font.font("Roboto Mono", 13);
}
@@ -1103,17 +1144,18 @@ public class AppServices {
@Subscribe
public void mempoolRateSizes(MempoolRateSizesUpdatedEvent event) {
addMempoolRateSizes(event.getMempoolRateSizes());
if(event.getMempoolRateSizes() != null) {
addMempoolRateSizes(event.getMempoolRateSizes());
}
}
@Subscribe
public void feeRateSourceChanged(FeeRatesSourceChangedEvent event) {
ElectrumServer.FeeRatesService feeRatesService = new ElectrumServer.FeeRatesService();
feeRatesService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(feeRatesService.getValue());
});
//Perform once-off fee rates retrieval to immediately change displayed rates
feeRatesService.start();
if(feeRatesService != null && !feeRatesService.isRunning() && Config.get().getMode() != Mode.OFFLINE) {
feeRatesService = createFeeRatesService();
feeRatesService.start();
}
}
@Subscribe
@@ -16,9 +16,9 @@ import java.io.File;
import java.util.*;
public class SparrowWallet {
public static final String APP_ID = "com.sparrowwallet.sparrow";
public static final String APP_ID = "sparrow";
public static final String APP_NAME = "Sparrow";
public static final String APP_VERSION = "1.8.4";
public static final String APP_VERSION = "1.9.1";
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";
@@ -66,6 +66,11 @@ public class SparrowWallet {
Network.set(Network.TESTNET);
}
File testnet4Flag = new File(Storage.getSparrowHome(), "network-" + Network.TESTNET4.getName());
if(testnet4Flag.exists()) {
Network.set(Network.TESTNET4);
}
File signetFlag = new File(Storage.getSparrowHome(), "network-" + Network.SIGNET.getName());
if(signetFlag.exists()) {
Network.set(Network.SIGNET);
@@ -79,7 +84,7 @@ public class SparrowWallet {
try {
instance = new Instance(fileUriArguments);
instance.acquireLock(); //If fileUriArguments is not empty, will exit app after sending fileUriArguments if lock cannot be acquired
instance.acquireLock(!fileUriArguments.isEmpty()); //If fileUriArguments is not empty, will exit app after sending fileUriArguments if lock cannot be acquired
} catch(InstanceException e) {
getLogger().error("Could not access application lock", e);
}
@@ -130,13 +135,13 @@ public class SparrowWallet {
private final List<String> fileUriArguments;
public Instance(List<String> fileUriArguments) {
super(SparrowWallet.APP_ID + "." + Network.get(), !fileUriArguments.isEmpty());
super(SparrowWallet.APP_ID, true);
this.fileUriArguments = fileUriArguments;
}
@Override
protected void receiveMessageList(List<String> messageList) {
if(messageList != null && !messageList.isEmpty()) {
if(messageList != null) {
AppServices.parseFileUriArguments(messageList);
AppServices.openFileUriArguments(null);
}
@@ -5,17 +5,13 @@ import com.sparrowwallet.drongo.wallet.StandardAccount;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.io.Config;
import com.sparrowwallet.sparrow.net.ServerType;
import com.sparrowwallet.sparrow.whirlpool.WhirlpoolServices;
import javafx.collections.FXCollections;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.util.StringConverter;
import org.controlsfx.glyphfont.Glyph;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
import static com.sparrowwallet.drongo.wallet.StandardAccount.*;
@@ -46,12 +42,14 @@ public class AddAccountDialog extends Dialog<List<StandardAccount>> {
standardAccountCombo = new ComboBox<>();
standardAccountCombo.setMaxWidth(Double.MAX_VALUE);
List<Integer> existingIndexes = new ArrayList<>();
Set<Integer> existingIndexes = new LinkedHashSet<>();
Wallet masterWallet = wallet.isMasterWallet() ? wallet : wallet.getMasterWallet();
existingIndexes.add(masterWallet.getAccountIndex());
for(Wallet childWallet : masterWallet.getChildWallets()) {
if(!childWallet.isNested()) {
existingIndexes.add(childWallet.getAccountIndex());
Optional<StandardAccount> optStdAcc = Arrays.stream(StandardAccount.values()).filter(stdacc -> stdacc.getName().equals(childWallet.getName())).findFirst();
optStdAcc.ifPresent(standardAccount -> existingIndexes.add(standardAccount.getAccountNumber()));
}
}
@@ -62,15 +60,14 @@ public class AddAccountDialog extends Dialog<List<StandardAccount>> {
}
}
if(WhirlpoolServices.canWalletMix(masterWallet) && !masterWallet.isWhirlpoolMasterWallet()) {
if(AppServices.isWhirlpoolCompatible(masterWallet) && !masterWallet.isWhirlpoolMasterWallet()) {
availableAccounts.add(WHIRLPOOL_PREMIX);
} else if(WhirlpoolServices.canWatchPostmix(masterWallet) && !existingIndexes.contains(WHIRLPOOL_POSTMIX.getAccountNumber())) {
} else if(AppServices.isWhirlpoolPostmixCompatible(masterWallet) && !existingIndexes.contains(WHIRLPOOL_POSTMIX.getAccountNumber())) {
availableAccounts.add(WHIRLPOOL_POSTMIX);
}
final ButtonType discoverButtonType = new javafx.scene.control.ButtonType("Discover", ButtonBar.ButtonData.LEFT);
if(!availableAccounts.isEmpty() && Config.get().getServerType() != ServerType.BITCOIN_CORE &&
(masterWallet.getKeystores().stream().allMatch(ks -> ks.getSource() == KeystoreSource.SW_SEED)
if(!availableAccounts.isEmpty() && (masterWallet.getKeystores().stream().allMatch(ks -> ks.getSource() == KeystoreSource.SW_SEED)
|| (masterWallet.getKeystores().size() == 1 && masterWallet.getKeystores().stream().allMatch(ks -> ks.getSource() == KeystoreSource.HW_USB)))) {
dialogPane.getButtonTypes().add(discoverButtonType);
Button discoverButton = (Button)dialogPane.lookupButton(discoverButtonType);
@@ -10,6 +10,7 @@ import javafx.beans.value.ChangeListener;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Tooltip;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
@@ -52,6 +53,7 @@ public class CopyableTextField extends CustomTextField {
selectedTextProperty().removeListener(selectionListener);
}
});
setContextMenu(new ContextMenu());
}
private void setupCopyButtonField(ObjectProperty<Node> rightProperty) {
@@ -3,13 +3,14 @@ package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.hummingbird.UR;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.io.PdfUtils;
import com.sparrowwallet.sparrow.io.bbqr.BBQR;
import javafx.event.ActionEvent;
import javafx.scene.control.*;
import javafx.scene.control.Button;
public class DescriptorQRDisplayDialog extends QRDisplayDialog {
public DescriptorQRDisplayDialog(String walletName, String outputDescriptor, UR ur) {
super(ur);
public DescriptorQRDisplayDialog(String walletName, String outputDescriptor, UR ur, BBQR bbqr, boolean selectBbqrButton) {
super(ur, bbqr, false, false, selectBbqrButton);
DialogPane dialogPane = getDialogPane();
final ButtonType pdfButtonType = new javafx.scene.control.ButtonType("Save PDF...", ButtonBar.ButtonData.HELP_2);
@@ -19,7 +20,7 @@ public class DescriptorQRDisplayDialog extends QRDisplayDialog {
pdfButton.setGraphicTextGap(5);
pdfButton.setGraphic(getGlyph(FontAwesome5.Glyph.FILE_PDF));
pdfButton.addEventFilter(ActionEvent.ACTION, event -> {
PdfUtils.saveOutputDescriptor(walletName, outputDescriptor, ur);
PdfUtils.saveOutputDescriptor(walletName, outputDescriptor, ur, isUseBbqrEncoding() ? bbqr : null);
event.consume();
});
}
@@ -71,6 +71,7 @@ public class DownloadVerifierDialog extends Dialog<ButtonBar.ButtonData> {
private final ObjectProperty<File> publicKey = new SimpleObjectProperty<>();
private final ObjectProperty<File> release = new SimpleObjectProperty<>();
private final BooleanProperty manifestDisabled = new SimpleBooleanProperty();
private final BooleanProperty publicKeyDisabled = new SimpleBooleanProperty();
private final Label signedBy;
@@ -100,7 +101,7 @@ public class DownloadVerifierDialog extends Dialog<ButtonBar.ButtonData> {
String version = VersionCheckService.getVersion() != null ? VersionCheckService.getVersion() : "x.x.x";
Field signatureField = setupField(signature, "Signature", SIGNATURE_EXTENSIONS, false, "sparrow-" + version + "-manifest.txt", null);
Field manifestField = setupField(manifest, "Manifest", MANIFEST_EXTENSIONS, false, "sparrow-" + version + "-manifest", null);
Field manifestField = setupField(manifest, "Manifest", MANIFEST_EXTENSIONS, false, "sparrow-" + version + "-manifest", manifestDisabled);
Field publicKeyField = setupField(publicKey, "Public Key", PUBLIC_KEY_EXTENSIONS, true, "pgp_keys", publicKeyDisabled);
Field releaseFileField = setupField(release, "Release File", getReleaseFileExtensions(), false, getReleaseFileExample(version), null);
@@ -264,6 +265,7 @@ public class DownloadVerifierDialog extends Dialog<ButtonBar.ButtonData> {
}
private void verify() {
manifestDisabled.set(false);
publicKeyDisabled.set(false);
if(signature.get() == null || manifest.get() == null) {
@@ -291,6 +293,7 @@ public class DownloadVerifierDialog extends Dialog<ButtonBar.ButtonData> {
}
if(manifest.get().equals(release.get())) {
manifestDisabled.set(true);
releaseHash.setText("No hash required, signature signs release file directly");
releaseHash.setGraphic(GlyphUtils.getSuccessGlyph());
releaseHash.setTooltip(null);
@@ -585,12 +585,14 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
getItems().add(createCpfp);
}
MenuItem openBlockExplorer = new MenuItem("Open in Block Explorer");
openBlockExplorer.setOnAction(AE -> {
hide();
AppServices.openBlockExplorer(blockTransaction.getHashAsString());
});
getItems().add(openBlockExplorer);
if(!Config.get().isBlockExplorerDisabled()) {
MenuItem openBlockExplorer = new MenuItem("Open in Block Explorer");
openBlockExplorer.setOnAction(AE -> {
hide();
AppServices.openBlockExplorer(blockTransaction.getHashAsString());
});
getItems().add(openBlockExplorer);
}
MenuItem copyTxid = new MenuItem("Copy Transaction ID");
copyTxid.setOnAction(AE -> {
@@ -604,7 +606,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
}
}
private static class TransactionContextMenu extends ContextMenu {
protected static class TransactionContextMenu extends ContextMenu {
public TransactionContextMenu(String date, BlockTransaction blockTransaction) {
MenuItem viewTransaction = new MenuItem("View Transaction");
viewTransaction.setGraphic(getViewTransactionGlyph());
@@ -612,12 +614,16 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
hide();
EventManager.get().post(new ViewTransactionEvent(this.getOwnerWindow(), blockTransaction));
});
getItems().add(viewTransaction);
MenuItem openBlockExplorer = new MenuItem("Open in Block Explorer");
openBlockExplorer.setOnAction(AE -> {
hide();
AppServices.openBlockExplorer(blockTransaction.getHashAsString());
});
if(!Config.get().isBlockExplorerDisabled()) {
MenuItem openBlockExplorer = new MenuItem("Open in Block Explorer");
openBlockExplorer.setOnAction(AE -> {
hide();
AppServices.openBlockExplorer(blockTransaction.getHashAsString());
});
getItems().add(openBlockExplorer);
}
MenuItem copyDate = new MenuItem("Copy Date");
copyDate.setOnAction(AE -> {
@@ -626,6 +632,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
content.putString(date);
Clipboard.getSystemClipboard().setContent(content);
});
getItems().add(copyDate);
MenuItem copyTxid = new MenuItem("Copy Transaction ID");
copyTxid.setOnAction(AE -> {
@@ -634,6 +641,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
content.putString(blockTransaction.getHashAsString());
Clipboard.getSystemClipboard().setContent(content);
});
getItems().add(copyTxid);
MenuItem copyHeight = new MenuItem("Copy Block Height");
copyHeight.setOnAction(AE -> {
@@ -642,8 +650,7 @@ public class EntryCell extends TreeTableCell<Entry, Entry> implements Confirmati
content.putString(blockTransaction.getHeight() > 0 ? Integer.toString(blockTransaction.getHeight()) : "Mempool");
Clipboard.getSystemClipboard().setContent(content);
});
getItems().addAll(viewTransaction, openBlockExplorer, copyDate, copyTxid, copyHeight);
getItems().add(copyHeight);
}
}
@@ -13,6 +13,8 @@ import java.util.stream.Collectors;
import static com.sparrowwallet.sparrow.AppServices.*;
public class FeeRangeSlider extends Slider {
private static final double FEE_RATE_SCROLL_INCREMENT = 0.01;
public FeeRangeSlider() {
super(0, FEE_RATES_RANGE.size() - 1, 0);
setMajorTickUnit(1);
@@ -45,6 +47,18 @@ public class FeeRangeSlider extends Slider {
updateMaxFeeRange(newValue.doubleValue());
}
});
setOnScroll(event -> {
if(event.getDeltaY() != 0) {
double newFeeRate = getFeeRate() + (event.getDeltaY() > 0 ? FEE_RATE_SCROLL_INCREMENT : -FEE_RATE_SCROLL_INCREMENT);
if(newFeeRate < LONG_FEE_RATES_RANGE.get(0)) {
newFeeRate = LONG_FEE_RATES_RANGE.get(0);
} else if(newFeeRate > LONG_FEE_RATES_RANGE.get(LONG_FEE_RATES_RANGE.size() - 1)) {
newFeeRate = LONG_FEE_RATES_RANGE.get(LONG_FEE_RATES_RANGE.size() - 1);
}
setFeeRate(newFeeRate);
}
});
}
public double getFeeRate() {
@@ -240,6 +240,8 @@ public abstract class FileImportPane extends TitledDescriptionPane {
contentBox.setPadding(new Insets(10, 30, 10, 30));
contentBox.setPrefHeight(60);
javafx.application.Platform.runLater(passwordField::requestFocus);
return contentBox;
}
}
@@ -29,7 +29,7 @@ public class FileKeystoreImportPane extends FileImportPane {
}
if(requiredDerivation != null && !requiredDerivation.getDerivation().equals(keystore.getKeyDerivation().getDerivation())) {
setError("Incorrect derivation", "This account requires a derivation of " + requiredDerivation.getDerivationPath() + ", but the imported keystore has a derivation of " + keystore.getKeyDerivation().getDerivationPath() + ".");
setError("Incorrect derivation", "This account requires a derivation of " + requiredDerivation.getDerivationPath() + ", but the imported keystore has a derivation of " + KeyDerivation.writePath(keystore.getKeyDerivation().getDerivation()) + ".");
} else {
EventManager.get().post(new KeystoreImportEvent(keystore));
}
@@ -171,11 +171,18 @@ public class FileWalletExportPane extends TitledDescriptionPane {
} else if(exporter instanceof Bip129) {
UR ur = UR.fromBytes(outputStream.toByteArray());
BBQR bbqr = new BBQR(BBQRType.UNICODE, outputStream.toByteArray());
qrDisplayDialog = new QRDisplayDialog(ur, bbqr, false, true, false);
qrDisplayDialog = new QRDisplayDialog(ur, bbqr, false, false, false);
} else if(exporter instanceof Descriptor) {
boolean addBbqrOption = exportWallet.getKeystores().stream().anyMatch(keystore -> keystore.getWalletModel().showBbqr());
boolean selectBbqrOption = exportWallet.getKeystores().stream().allMatch(keystore -> keystore.getWalletModel().selectBbqr());
OutputDescriptor outputDescriptor = OutputDescriptor.getOutputDescriptor(exportWallet, KeyPurpose.DEFAULT_PURPOSES, null);
CryptoOutput cryptoOutput = getCryptoOutput(exportWallet);
qrDisplayDialog = new DescriptorQRDisplayDialog(exportWallet.getFullDisplayName(), outputDescriptor.toString(true), cryptoOutput.toUR());
BBQR bbqr = addBbqrOption ? new BBQR(BBQRType.UNICODE, outputDescriptor.toString(true).getBytes(StandardCharsets.UTF_8)) : null;
qrDisplayDialog = new DescriptorQRDisplayDialog(exportWallet.getFullDisplayName(), outputDescriptor.toString(true), cryptoOutput.toUR(), bbqr, selectBbqrOption);
} else if(exporter.getClass().equals(ColdcardMultisig.class)) {
UR ur = UR.fromBytes(outputStream.toByteArray());
BBQR bbqr = new BBQR(BBQRType.UNICODE, outputStream.toByteArray());
qrDisplayDialog = new QRDisplayDialog(ur, bbqr, false, false, true);
} else {
qrDisplayDialog = new QRDisplayDialog(outputStream.toString(StandardCharsets.UTF_8));
}
@@ -12,6 +12,7 @@ import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.event.WalletImportEvent;
import com.sparrowwallet.sparrow.io.ImportException;
import com.sparrowwallet.sparrow.io.KeystoreFileImport;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
@@ -38,6 +39,7 @@ public class FileWalletKeystoreImportPane extends FileImportPane {
private final KeystoreFileImport importer;
private String fileName;
private byte[] fileBytes;
private String password;
public FileWalletKeystoreImportPane(KeystoreFileImport importer) {
super(importer, importer.getName(), "Wallet import", importer.getKeystoreImportDescription(), "image/" + importer.getWalletModel().getType() + ".png", importer.isKeystoreImportScannable(), importer.isFileFormatAvailable());
@@ -46,6 +48,7 @@ public class FileWalletKeystoreImportPane extends FileImportPane {
protected void importFile(String fileName, InputStream inputStream, String password) throws ImportException {
this.fileName = fileName;
this.password = password;
List<ScriptType> scriptTypes = ScriptType.getAddressableScriptTypes(PolicyType.SINGLE);
if(wallets != null && !wallets.isEmpty()) {
@@ -83,7 +86,7 @@ public class FileWalletKeystoreImportPane extends FileImportPane {
EventManager.get().post(new WalletImportEvent(wallet));
} else {
ByteArrayInputStream bais = new ByteArrayInputStream(fileBytes);
Keystore keystore = importer.getKeystore(scriptType, bais, "");
Keystore keystore = importer.getKeystore(scriptType, bais, password);
Wallet wallet = new Wallet();
wallet.setName(Files.getNameWithoutExtension(fileName));
@@ -151,6 +154,8 @@ public class FileWalletKeystoreImportPane extends FileImportPane {
contentBox.setPadding(new Insets(10, 30, 10, 30));
contentBox.setPrefHeight(60);
Platform.runLater(scriptTypeComboBox::requestFocus);
return contentBox;
}
}
@@ -472,7 +472,7 @@ public class MessageSignDialog extends Dialog<ButtonBar.ButtonData> {
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) {
if(optButtonType.isPresent() && optButtonType.get().getButtonData() == ButtonBar.ButtonData.OK_DONE) {
scanQr();
}
}
@@ -1,27 +1,11 @@
package com.sparrowwallet.sparrow.control;
import com.samourai.whirlpool.client.mix.listener.MixFailReason;
import com.samourai.whirlpool.client.mix.listener.MixStep;
import com.samourai.whirlpool.client.wallet.beans.MixProgress;
import com.samourai.whirlpool.protocol.beans.Utxo;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.wallet.Entry;
import com.sparrowwallet.sparrow.wallet.UtxoEntry;
import com.sparrowwallet.sparrow.whirlpool.Whirlpool;
import com.sparrowwallet.sparrow.whirlpool.WhirlpoolException;
import javafx.animation.Timeline;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.util.Duration;
import org.controlsfx.glyphfont.Glyph;
import org.controlsfx.tools.Platform;
import java.util.Locale;
public class MixStatusCell extends TreeTableCell<Entry, UtxoEntry.MixStatus> {
private static final int ERROR_DISPLAY_MILLIS = 5 * 60 * 1000;
public MixStatusCell() {
super();
setAlignment(Pos.CENTER_RIGHT);
@@ -41,174 +25,9 @@ public class MixStatusCell extends TreeTableCell<Entry, UtxoEntry.MixStatus> {
setGraphic(null);
} else {
setText(Integer.toString(mixStatus.getMixesDone()));
if(mixStatus.getNextMixUtxo() == null) {
setContextMenu(new MixStatusContextMenu(mixStatus.getUtxoEntry(), mixStatus.getMixProgress() != null && mixStatus.getMixProgress().getMixStep() != MixStep.FAIL));
} else {
setContextMenu(null);
}
if(mixStatus.getNextMixUtxo() != null) {
setMixSuccess(mixStatus.getNextMixUtxo());
} else if(mixStatus.getMixFailReason() != null) {
setMixFail(mixStatus.getMixFailReason(), mixStatus.getMixError(), mixStatus.getMixErrorTimestamp());
} else if(mixStatus.getMixProgress() != null) {
setMixProgress(mixStatus.getUtxoEntry(), mixStatus.getMixProgress());
} else {
setGraphic(null);
setTooltip(null);
}
}
}
private void setMixSuccess(Utxo nextMixUtxo) {
ProgressIndicator progressIndicator = getProgressIndicator();
progressIndicator.setProgress(-1);
setGraphic(progressIndicator);
Tooltip tt = new Tooltip();
tt.setText("Waiting for broadcast of " + nextMixUtxo.getHash().substring(0, 8) + "..." + ":" + nextMixUtxo.getIndex() );
setTooltip(tt);
}
private void setMixFail(MixFailReason mixFailReason, String mixError, Long mixErrorTimestamp) {
if(mixFailReason != MixFailReason.CANCEL) {
long elapsed = mixErrorTimestamp == null ? 0L : System.currentTimeMillis() - mixErrorTimestamp;
if(elapsed >= ERROR_DISPLAY_MILLIS) {
//Old error, don't set again.
return;
}
Glyph failGlyph = getFailGlyph();
setGraphic(failGlyph);
Tooltip tt = new Tooltip();
tt.setText(mixFailReason.getMessage() + (mixError == null ? "" : ": " + mixError) +
"\nMix failures are generally caused by peers disconnecting during a mix." +
"\nMake sure your internet connection is stable and the computer is configured to prevent sleeping." +
"\nTo prevent sleeping, use the " + getPlatformSleepConfig() + " or enable the function in the Tools menu.");
setTooltip(tt);
Duration fadeDuration = Duration.millis(ERROR_DISPLAY_MILLIS - elapsed);
double fadeFromValue = 1.0 - ((double)elapsed / ERROR_DISPLAY_MILLIS);
Timeline timeline = AnimationUtil.getSlowFadeOut(failGlyph, fadeDuration, fadeFromValue, 10);
timeline.setOnFinished(event -> {
setTooltip(null);
});
timeline.play();
} else {
setContextMenu(null);
setGraphic(null);
setTooltip(null);
}
}
private String getPlatformSleepConfig() {
Platform platform = Platform.getCurrent();
if(platform == Platform.OSX) {
return "OSX System Preferences";
} else if(platform == Platform.WINDOWS) {
return "Windows Control Panel";
}
return "system power settings";
}
private void setMixProgress(UtxoEntry utxoEntry, MixProgress mixProgress) {
if(mixProgress.getMixStep() != MixStep.FAIL) {
ProgressIndicator progressIndicator = getProgressIndicator();
progressIndicator.setProgress(mixProgress.getMixStep().getProgressPercent() == 100 ? -1 : mixProgress.getMixStep().getProgressPercent() / 100.0);
setGraphic(progressIndicator);
Tooltip tt = new Tooltip();
String status = mixProgress.getMixStep().getMessage().substring(0, 1).toUpperCase(Locale.ROOT) + mixProgress.getMixStep().getMessage().substring(1);
tt.setText(status);
setTooltip(tt);
if(mixProgress.getMixStep() == MixStep.REGISTERED_INPUT) {
tt.setOnShowing(event -> {
Whirlpool whirlpool = AppServices.getWhirlpoolServices().getWhirlpool(utxoEntry.getWallet());
Whirlpool.RegisteredInputsService registeredInputsService = new Whirlpool.RegisteredInputsService(whirlpool, mixProgress.getPoolId());
registeredInputsService.setOnSucceeded(eventStateHandler -> {
if(registeredInputsService.getValue() != null) {
tt.setText(status + " (1 of " + registeredInputsService.getValue() + ")");
}
});
registeredInputsService.start();
});
}
} else {
setGraphic(null);
setTooltip(null);
}
}
private ProgressIndicator getProgressIndicator() {
ProgressIndicator progressIndicator;
if(getGraphic() instanceof ProgressIndicator) {
progressIndicator = (ProgressIndicator)getGraphic();
} else {
progressIndicator = new ProgressBar();
}
return progressIndicator;
}
private static Glyph getMixGlyph() {
Glyph copyGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.RANDOM);
copyGlyph.setFontSize(12);
return copyGlyph;
}
private static Glyph getStopGlyph() {
Glyph copyGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.STOP_CIRCLE);
copyGlyph.setFontSize(12);
return copyGlyph;
}
public static Glyph getFailGlyph() {
Glyph failGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.EXCLAMATION_CIRCLE);
failGlyph.getStyleClass().add("fail-warning");
failGlyph.setFontSize(12);
return failGlyph;
}
private static class MixStatusContextMenu extends ContextMenu {
public MixStatusContextMenu(UtxoEntry utxoEntry, boolean isMixing) {
Whirlpool pool = AppServices.getWhirlpoolServices().getWhirlpool(utxoEntry.getWallet());
if(isMixing) {
MenuItem mixStop = new MenuItem("Stop Mixing");
if(pool != null) {
mixStop.disableProperty().bind(pool.mixingProperty().not());
}
mixStop.setGraphic(getStopGlyph());
mixStop.setOnAction(event -> {
hide();
Whirlpool whirlpool = AppServices.getWhirlpoolServices().getWhirlpool(utxoEntry.getWallet());
if(whirlpool != null) {
try {
whirlpool.mixStop(utxoEntry.getHashIndex());
} catch(WhirlpoolException e) {
AppServices.showErrorDialog("Error stopping mixing UTXO", e.getMessage());
}
}
});
getItems().add(mixStop);
} else {
MenuItem mixNow = new MenuItem("Mix Now");
if(pool != null) {
mixNow.disableProperty().bind(pool.mixingProperty().not());
}
mixNow.setGraphic(getMixGlyph());
mixNow.setOnAction(event -> {
hide();
Whirlpool whirlpool = AppServices.getWhirlpoolServices().getWhirlpool(utxoEntry.getWallet());
if(whirlpool != null) {
try {
whirlpool.mix(utxoEntry.getHashIndex());
} catch(WhirlpoolException e) {
AppServices.showErrorDialog("Error mixing UTXO", e.getMessage());
}
}
});
getItems().add(mixNow);
}
}
}
}
@@ -33,6 +33,7 @@ import java.util.Optional;
public class MnemonicKeystoreImportPane extends MnemonicKeystorePane {
protected final Wallet wallet;
private final KeystoreMnemonicImport importer;
private final KeyDerivation defaultDerivation;
private SplitMenuButton importButton;
@@ -43,10 +44,11 @@ public class MnemonicKeystoreImportPane extends MnemonicKeystorePane {
private Button confirmButton;
private List<String> generatedMnemonicCode;
public MnemonicKeystoreImportPane(Wallet wallet, KeystoreMnemonicImport importer) {
public MnemonicKeystoreImportPane(Wallet wallet, KeystoreMnemonicImport importer, KeyDerivation defaultDerivation) {
super(importer.getName(), "Create or enter seed", importer.getKeystoreImportDescription(), "image/" + importer.getWalletModel().getType() + ".png");
this.wallet = wallet;
this.importer = importer;
this.defaultDerivation = defaultDerivation;
createImportButton();
buttonBox.getChildren().add(importButton);
@@ -59,7 +61,7 @@ public class MnemonicKeystoreImportPane extends MnemonicKeystorePane {
importButton.getStyleClass().add("default-button");
importButton.setOnAction(event -> {
importButton.setDisable(true);
importKeystore(wallet.getScriptType().getDefaultDerivation(), false);
importKeystore(getDefaultDerivation(), false);
});
String[] accounts = new String[] {"Import Default Account #0", "Import Account #1", "Import Account #2", "Import Account #3", "Import Account #4", "Import Account #5", "Import Account #6", "Import Account #7", "Import Account #8", "Import Account #9"};
int scriptAccountsLength = ScriptType.P2SH.equals(wallet.getScriptType()) ? 1 : accounts.length;
@@ -77,6 +79,10 @@ public class MnemonicKeystoreImportPane extends MnemonicKeystorePane {
importButton.setVisible(false);
}
private List<ChildNumber> getDefaultDerivation() {
return defaultDerivation == null || defaultDerivation.getDerivation().isEmpty() ? wallet.getScriptType().getDefaultDerivation() : defaultDerivation.getDerivation();
}
protected void enterMnemonic(int numWords) {
generatedMnemonicCode = null;
super.enterMnemonic(numWords);
@@ -243,7 +249,7 @@ public class MnemonicKeystoreImportPane extends MnemonicKeystorePane {
setDescription("Ready to import");
showHideLink.setText("Show Derivation...");
showHideLink.setVisible(false);
setContent(getDerivationEntry(wallet.getScriptType().getDefaultDerivation()));
setContent(getDerivationEntry(getDefaultDerivation()));
}
}
@@ -79,10 +79,6 @@ public class PayNymAvatar extends StackPane {
this.paymentCodeProperty.set(paymentCode);
}
public void setPaymentCode(com.samourai.wallet.bip47.rpc.PaymentCode paymentCode) {
setPaymentCode(PaymentCode.fromString(paymentCode.toString()));
}
public void clearPaymentCode() {
this.paymentCodeProperty.set(null);
}
@@ -81,10 +81,7 @@ public class PayNymCell extends ListCell<PayNym> {
linkButton.setDisable(true);
payNymController.linkPayNym(payNym);
});
if(payNymController.isSelectLinkedOnly()) {
getStyleClass().add("unlinked");
}
getStyleClass().add("unlinked");
}
}
@@ -10,11 +10,6 @@ public class PaymentCodeTextField extends CopyableTextField {
setPaymentCodeString();
}
public void setPaymentCode(com.samourai.wallet.bip47.rpc.PaymentCode paymentCode) {
this.paymentCodeStr = paymentCode.toString();
setPaymentCodeString();
}
private void setPaymentCodeString() {
String abbrevPcode = paymentCodeStr.substring(0, 12) + "..." + paymentCodeStr.substring(paymentCodeStr.length() - 5);
setText(abbrevPcode);
@@ -42,7 +42,7 @@ public class QRDisplayDialog extends Dialog<ButtonType> {
private static final int MIN_FRAGMENT_LENGTH = 10;
private static final int ANIMATION_PERIOD_MILLIS = 200;
private static final double ANIMATION_PERIOD_MILLIS = 200d;
private static final int DEFAULT_QR_SIZE = 580;
private static final int REDUCED_QR_SIZE = 520;
@@ -100,6 +100,16 @@ public class QRDisplayDialog extends Dialog<ButtonType> {
qrImageView = new ImageView();
stackPane.getChildren().add(qrImageView);
qrImageView.setOnScroll(scrollEvent -> {
if(animateQRService != null && animateQRService.isRunning() && scrollEvent.getDeltaY() != 0) {
Duration duration = animateQRService.getPeriod();
Duration newDuration = scrollEvent.getDeltaY() > 0 ? duration.multiply(1.1) : duration.multiply(0.9);
if(newDuration.lessThan(Duration.millis(ANIMATION_PERIOD_MILLIS*10)) && newDuration.greaterThan(Duration.millis(ANIMATION_PERIOD_MILLIS/2))) {
animateQRService.setPeriod(newDuration);
}
}
});
dialogPane.setContent(Borders.wrap(stackPane).lineBorder().buildAll());
nextPart();
@@ -249,6 +259,10 @@ public class QRDisplayDialog extends Dialog<ButtonType> {
}
}
public boolean isUseBbqrEncoding() {
return useBbqrEncoding;
}
private void setUseBbqrEncoding(boolean useBbqrEncoding) {
if(useBbqrEncoding) {
this.useBbqrEncoding = true;
@@ -32,6 +32,7 @@ import com.sparrowwallet.sparrow.glyphfont.FontAwesome5;
import com.sparrowwallet.sparrow.io.Config;
import com.sparrowwallet.sparrow.io.bbqr.BBQRDecoder;
import com.sparrowwallet.sparrow.io.bbqr.BBQRException;
import com.sparrowwallet.sparrow.wallet.KeystoreController;
import javafx.application.Platform;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
@@ -621,7 +622,8 @@ public class QRScanDialog extends Dialog<QRScanDialog.Result> {
List<ChildNumber> path = cryptoKeypath.getComponents().stream().map(comp -> (IndexPathComponent)comp)
.map(comp -> new ChildNumber(comp.getIndex(), comp.isHardened())).collect(Collectors.toList());
return new KeyDerivation(Utils.bytesToHex(cryptoKeypath.getSourceFingerprint()), KeyDerivation.writePath(path));
String fingerprint = cryptoKeypath.getSourceFingerprint() == null ? KeystoreController.DEFAULT_WATCH_ONLY_FINGERPRINT : Utils.bytesToHex(cryptoKeypath.getSourceFingerprint());
return new KeyDerivation(fingerprint, KeyDerivation.writePath(path));
}
return null;
@@ -54,10 +54,10 @@ public class ScriptArea extends CodeArea {
ScriptChunk chunk = script.getChunks().get(i);
if(chunk.isOpCode()) {
append(chunk.toString(), "script-opcode");
} else if(chunk.isSignature()) {
append("<signature" + signatureCount++ + ">", "script-signature");
} else if(chunk.isPubKey()) {
append("<pubkey" + pubKeyCount++ + ">", "script-pubkey");
} else if(chunk.isSignature()) {
append("<signature" + signatureCount++ + ">", "script-signature");
} else if(chunk.isTaprootControlBlock()) {
append("<controlblock>", "script-controlblock");
} else if(chunk.isString()) {
@@ -1,18 +1,27 @@
package com.sparrowwallet.sparrow.control;
import com.csvreader.CsvWriter;
import com.sparrowwallet.drongo.BitcoinUnit;
import com.sparrowwallet.drongo.KeyPurpose;
import com.sparrowwallet.drongo.Utils;
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.UnitFormat;
import com.sparrowwallet.sparrow.glyphfont.GlyphUtils;
import com.sparrowwallet.sparrow.io.Config;
import com.sparrowwallet.sparrow.wallet.*;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.ListChangeListener;
import javafx.event.ActionEvent;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.controlsfx.control.textfield.TextFields;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -20,10 +29,11 @@ import tornadofx.control.Field;
import tornadofx.control.Fieldset;
import tornadofx.control.Form;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class SearchWalletDialog extends Dialog<Entry> {
private static final Logger log = LoggerFactory.getLogger(SearchWalletDialog.class);
@@ -48,7 +58,7 @@ public class SearchWalletDialog extends Dialog<Entry> {
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(showWallet ? "Search All Wallets" : "Search Wallet");
dialogPane.setHeaderText(showWallet ? "Search All Wallets" : "Search Wallet " + walletForms.get(0).getMasterWallet().getName());
Image image = new Image("image/sparrow-small.png", 50, 50, false, false);
if(!image.isError()) {
@@ -81,6 +91,7 @@ public class SearchWalletDialog extends Dialog<Entry> {
results.setUnitFormat(walletForms.iterator().next().getWallet());
results.setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY);
results.setPlaceholder(new Label("No results"));
results.setEditable(true);
if(showWallet) {
TreeTableColumn<Entry, String> walletColumn = new TreeTableColumn<>("Wallet");
@@ -117,7 +128,7 @@ public class SearchWalletDialog extends Dialog<Entry> {
labelCol.setCellValueFactory((TreeTableColumn.CellDataFeatures<Entry, String> param) -> {
return param.getValue().getValue().labelProperty();
});
labelCol.setCellFactory(p -> new SearchLabelCell());
labelCol.setCellFactory(p -> new LabelCell());
results.getColumns().add(labelCol);
TreeTableColumn<Entry, Number> amountCol = new TreeTableColumn<>("Value");
@@ -130,12 +141,20 @@ public class SearchWalletDialog extends Dialog<Entry> {
vBox.getChildren().addAll(form, results);
dialogPane.setContent(vBox);
ButtonType exportButtonType = new ButtonType("Export CSV", ButtonBar.ButtonData.LEFT);
ButtonType showButtonType = new javafx.scene.control.ButtonType("Show", ButtonBar.ButtonData.APPLY);
ButtonType cancelButtonType = new javafx.scene.control.ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
dialogPane.getButtonTypes().addAll(cancelButtonType, showButtonType);
dialogPane.getButtonTypes().addAll(exportButtonType, cancelButtonType, showButtonType);
Button showButton = (Button) dialogPane.lookupButton(showButtonType);
Button exportButton = (Button)dialogPane.lookupButton(exportButtonType);
exportButton.setGraphic(GlyphUtils.getDownArrowGlyph());
exportButton.addEventFilter(ActionEvent.ACTION, event -> {
event.consume();
exportResults(showWallet);
});
Button showButton = (Button)dialogPane.lookupButton(showButtonType);
showButton.setDefaultButton(true);
showButton.setDisable(true);
@@ -147,7 +166,7 @@ public class SearchWalletDialog extends Dialog<Entry> {
});
search.textProperty().addListener((observable, oldValue, newValue) -> {
searchWallets(newValue.toLowerCase(Locale.ROOT));
searchWallets(newValue);
});
setResizable(true);
@@ -157,42 +176,41 @@ public class SearchWalletDialog extends Dialog<Entry> {
Platform.runLater(search::requestFocus);
}
private void searchWallets(String searchText) {
List<Entry> matchingEntries = new ArrayList<>();
public List<WalletForm> getWalletForms() {
return walletForms;
}
if(!searchText.isEmpty()) {
Long searchValue = getSearchValue(searchText);
Address searchAddress = getSearchAddress(searchText);
private void searchWallets(String searchPhrase) {
Set<Entry> matchingEntries = new LinkedHashSet<>();
for(WalletForm walletForm : walletForms) {
WalletTransactionsEntry walletTransactionsEntry = walletForm.getWalletTransactionsEntry();
for(Entry entry : walletTransactionsEntry.getChildren()) {
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) ||
(searchAddress != null && transactionEntry.getBlockTransaction().getTransaction().getOutputs().stream().map(output -> output.getScript().getToAddress()).filter(Objects::nonNull).anyMatch(address -> address.equals(searchAddress)))) {
matchingEntries.add(entry);
}
}
}
if(!searchPhrase.isEmpty()) {
Set<String> searchWords = new LinkedHashSet<>(Arrays.stream(searchPhrase.split("\\s+"))
.filter(text -> isAddress(text) || isHash(text) || isHashIndex(text)).toList());
String freeText = removeOccurrences(searchPhrase, searchWords).trim();
if(!freeText.isEmpty()) {
searchWords.add(freeText);
}
for(KeyPurpose keyPurpose : KeyPurpose.DEFAULT_PURPOSES) {
NodeEntry purposeEntry = walletForm.getNodeEntry(keyPurpose);
for(Entry entry : purposeEntry.getChildren()) {
if(entry instanceof NodeEntry nodeEntry) {
if(nodeEntry.getAddress().toString().toLowerCase(Locale.ROOT).contains(searchText) ||
(nodeEntry.getLabel() != null && nodeEntry.getLabel().toLowerCase(Locale.ROOT).contains(searchText)) ||
(nodeEntry.getValue() != null && searchValue != null && Math.abs(nodeEntry.getValue()) == searchValue)) {
for(String searchText : searchWords) {
Long searchValue = getSearchValue(searchText);
Address searchAddress = getSearchAddress(searchText);
searchText = searchText.toLowerCase(Locale.ROOT);
for(WalletForm walletForm : walletForms) {
WalletTransactionsEntry walletTransactionsEntry = walletForm.getWalletTransactionsEntry();
for(Entry entry : walletTransactionsEntry.getChildren()) {
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) ||
(searchAddress != null && transactionEntry.getBlockTransaction().getTransaction().getOutputs().stream().map(output -> output.getScript().getToAddress()).filter(Objects::nonNull).anyMatch(address -> address.equals(searchAddress)))) {
matchingEntries.add(entry);
}
}
}
}
for(WalletForm nestedWalletForm : walletForm.getNestedWalletForms()) {
for(KeyPurpose keyPurpose : nestedWalletForm.getWallet().getWalletKeyPurposes()) {
NodeEntry purposeEntry = nestedWalletForm.getNodeEntry(keyPurpose);
for(KeyPurpose keyPurpose : KeyPurpose.DEFAULT_PURPOSES) {
NodeEntry purposeEntry = walletForm.getNodeEntry(keyPurpose);
for(Entry entry : purposeEntry.getChildren()) {
if(entry instanceof NodeEntry nodeEntry) {
if(nodeEntry.getAddress().toString().toLowerCase(Locale.ROOT).contains(searchText) ||
@@ -203,22 +221,38 @@ public class SearchWalletDialog extends Dialog<Entry> {
}
}
}
}
WalletUtxosEntry walletUtxosEntry = walletForm.getWalletUtxosEntry();
for(Entry entry : walletUtxosEntry.getChildren()) {
if(entry instanceof HashIndexEntry hashIndexEntry) {
if(hashIndexEntry.getBlockTransaction().getHash().toString().toLowerCase(Locale.ROOT).equals(searchText) ||
(hashIndexEntry.getLabel() != null && hashIndexEntry.getLabel().toLowerCase(Locale.ROOT).contains(searchText)) ||
(hashIndexEntry.getValue() != null && searchValue != null && Math.abs(hashIndexEntry.getValue()) == searchValue)) {
matchingEntries.add(entry);
for(WalletForm nestedWalletForm : walletForm.getNestedWalletForms()) {
for(KeyPurpose keyPurpose : nestedWalletForm.getWallet().getWalletKeyPurposes()) {
NodeEntry purposeEntry = nestedWalletForm.getNodeEntry(keyPurpose);
for(Entry entry : purposeEntry.getChildren()) {
if(entry instanceof NodeEntry nodeEntry) {
if(nodeEntry.getAddress().toString().toLowerCase(Locale.ROOT).contains(searchText) ||
(nodeEntry.getLabel() != null && nodeEntry.getLabel().toLowerCase(Locale.ROOT).contains(searchText)) ||
(nodeEntry.getValue() != null && searchValue != null && Math.abs(nodeEntry.getValue()) == searchValue)) {
matchingEntries.add(entry);
}
}
}
}
}
WalletUtxosEntry walletUtxosEntry = walletForm.getWalletUtxosEntry();
for(Entry entry : walletUtxosEntry.getChildren()) {
if(entry instanceof HashIndexEntry hashIndexEntry) {
if(hashIndexEntry.getBlockTransaction().getHash().toString().toLowerCase(Locale.ROOT).equals(searchText) ||
hashIndexEntry.getHashIndex().toString().toLowerCase(Locale.ROOT).equals(searchText) ||
(hashIndexEntry.getLabel() != null && hashIndexEntry.getLabel().toLowerCase(Locale.ROOT).contains(searchText)) ||
(hashIndexEntry.getValue() != null && searchValue != null && Math.abs(hashIndexEntry.getValue()) == searchValue)) {
matchingEntries.add(entry);
}
}
}
}
}
}
SearchWalletEntry rootEntry = new SearchWalletEntry(walletForms.iterator().next().getWallet(), matchingEntries);
SearchWalletEntry rootEntry = new SearchWalletEntry(walletForms.iterator().next().getWallet(), new ArrayList<>(matchingEntries));
RecursiveTreeItem<Entry> rootItem = new RecursiveTreeItem<>(rootEntry, Entry::getChildren);
results.setRoot(rootItem);
}
@@ -239,6 +273,95 @@ public class SearchWalletDialog extends Dialog<Entry> {
}
}
private boolean isAddress(String text) {
try {
Address.fromString(text);
return true;
} catch(InvalidAddressException e) {
return false;
}
}
private boolean isHash(String text) {
return text.length() == 64 && Utils.isHex(text);
}
private boolean isHashIndex(String text) {
String[] parts = text.split(":");
if(parts.length == 2 && isHash(parts[0])) {
try {
Integer.parseInt(parts[1]);
return true;
} catch(NumberFormatException e) {
//ignore
}
}
return false;
}
private String removeOccurrences(String inputString, Collection<String> stringsToRemove) {
for(String str : stringsToRemove) {
inputString = inputString.replaceAll("(?i)" + str, "");
}
return inputString;
}
public void exportResults(boolean showWallet) {
Stage window = new Stage();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Export search results to CSV");
fileChooser.setInitialFileName(getDialogPane().getHeaderText() + ".csv");
AppServices.moveToActiveWindowScreen(window, 800, 450);
File file = fileChooser.showSaveDialog(window);
if(file != null) {
try(FileOutputStream outputStream = new FileOutputStream(file)) {
CsvWriter writer = new CsvWriter(outputStream, ',', StandardCharsets.UTF_8);
List<String> headers = new ArrayList<>(List.of("Wallet", "Account", "Type", "Date", "Txid / Address / Output", "Label", "Value"));
if(!showWallet) {
headers.remove(0);
}
writer.writeRecord(headers.toArray(new String[0]));
for(TreeItem<Entry> item : results.getRoot().getChildren()) {
Entry entry = item.getValue();
if(showWallet) {
writer.write(entry.getWallet().getMasterName());
}
writer.write(entry.getWallet().getDisplayName());
writer.write(entry.getEntryType());
if(entry instanceof TransactionEntry transactionEntry) {
writer.write(transactionEntry.getBlockTransaction().getDate() == null ? "Unconfirmed" : EntryCell.DATE_FORMAT.format(transactionEntry.getBlockTransaction().getDate()));
writer.write(transactionEntry.getBlockTransaction().getHash().toString());
} else if(entry instanceof NodeEntry nodeEntry) {
writer.write("");
writer.write(nodeEntry.getAddress().toString());
} else if(entry instanceof HashIndexEntry hashIndexEntry) {
writer.write(hashIndexEntry.getBlockTransaction().getDate() == null ? "Unconfirmed" : EntryCell.DATE_FORMAT.format(hashIndexEntry.getBlockTransaction().getDate()));
writer.write(hashIndexEntry.getHashIndex().toString());
} else {
writer.write("");
writer.write("");
}
writer.write(entry.getLabel());
writer.write(getCoinValue(entry.getValue() == null ? 0 : entry.getValue()));
writer.endRecord();
}
writer.close();
} catch(IOException e) {
log.error("Error exporting search results as CSV", e);
AppServices.showErrorDialog("Error exporting search results as CSV", e.getMessage());
}
}
}
private String getCoinValue(Long value) {
UnitFormat format = Config.get().getUnitFormat() == null ? UnitFormat.DOT : Config.get().getUnitFormat();
return BitcoinUnit.BTC.equals(results.getBitcoinUnit()) ? format.tableFormatBtcValue(value) : String.format(Locale.ENGLISH, "%d", value);
}
private static class SearchWalletEntry extends Entry {
public SearchWalletEntry(Wallet wallet, List<Entry> entries) {
super(wallet, wallet.getName(), entries);
@@ -264,15 +387,19 @@ public class SearchWalletDialog extends Dialog<Entry> {
@Override
protected void updateItem(Entry entry, boolean empty) {
super.updateItem(entry, empty);
setContextMenu(null);
}
}
private static class SearchLabelCell extends LabelCell {
@Override
public void updateItem(String label, boolean empty) {
super.updateItem(label, empty);
setContextMenu(null);
ContextMenu copyMenu;
if(entry instanceof TransactionEntry transactionEntry) {
copyMenu = new TransactionContextMenu(getText(), transactionEntry.getBlockTransaction());
} else if(entry instanceof NodeEntry nodeEntry) {
copyMenu = new AddressContextMenu(nodeEntry.getAddress(), nodeEntry.getOutputDescriptor(), null, false, null);
} else if(entry instanceof UtxoEntry utxoEntry) {
copyMenu = new HashIndexEntryContextMenu(null, utxoEntry);
} else {
copyMenu = new ContextMenu();
}
copyMenu.getItems().removeIf(menuItem -> !menuItem.getText().startsWith("Copy"));
setContextMenu(copyMenu);
}
}
}
@@ -1,12 +1,16 @@
package com.sparrowwallet.sparrow.control;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.SeedQR;
import com.sparrowwallet.sparrow.AppServices;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import java.util.Optional;
public class SeedDisplayDialog extends Dialog<Void> {
public SeedDisplayDialog(Keystore decryptedKeystore) {
final DialogPane dialogPane = getDialogPane();
@@ -39,8 +43,15 @@ public class SeedDisplayDialog extends Dialog<Void> {
stackPane.getChildren().addAll(anchorPane);
final ButtonType seedQRButtonType = new javafx.scene.control.ButtonType("Show SeedQR", ButtonBar.ButtonData.LEFT);
final ButtonType cancelButtonType = new javafx.scene.control.ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
dialogPane.getButtonTypes().addAll(cancelButtonType);
dialogPane.getButtonTypes().addAll(seedQRButtonType, cancelButtonType);
Button seedQRButton = (Button)dialogPane.lookupButton(seedQRButtonType);
seedQRButton.addEventFilter(ActionEvent.ACTION, event -> {
event.consume();
showSeedQR(decryptedKeystore);
});
dialogPane.setPrefWidth(500);
dialogPane.setPrefHeight(150 + height);
@@ -48,4 +59,15 @@ public class SeedDisplayDialog extends Dialog<Void> {
Platform.runLater(() -> keystoreAccordion.setExpandedPane(keystorePane));
}
private void showSeedQR(Keystore decryptedKeystore) {
Optional<ButtonType> optButtonType = AppServices.showWarningDialog("Sensitive QR", "The following QR contains these seed words. " +
"Be careful before displaying or digitally recording it.\n\nAre you sure you want to continue?", ButtonType.YES, ButtonType.NO);
if(optButtonType.isPresent() && optButtonType.get() == ButtonType.YES) {
String seedQR = SeedQR.getSeedQR(decryptedKeystore.getSeed());
QRDisplayDialog qrDisplayDialog = new QRDisplayDialog(seedQR);
qrDisplayDialog.initOwner(getDialogPane().getScene().getWindow());
qrDisplayDialog.showAndWait();
}
}
}
@@ -0,0 +1,34 @@
package com.sparrowwallet.sparrow.control;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import org.fxmisc.richtext.CodeArea;
public class SelectableCodeArea extends CodeArea {
public SelectableCodeArea() {
super();
ContextMenu contextMenu = new ContextMenu();
MenuItem copy = new MenuItem("Copy");
copy.setDisable(true);
copy.setOnAction(event -> {
ClipboardContent content = new ClipboardContent();
content.putString(getSelectedText());
Clipboard.getSystemClipboard().setContent(content);
});
MenuItem copyAll = new MenuItem("Copy All");
copyAll.setOnAction(event -> {
ClipboardContent content = new ClipboardContent();
content.putString(getText());
Clipboard.getSystemClipboard().setContent(content);
});
contextMenu.getItems().addAll(copy, copyAll);
setContextMenu(contextMenu);
selectedTextProperty().addListener((observable, oldValue, newValue) -> {
copy.setDisable(newValue.isEmpty());
});
}
}
@@ -12,11 +12,9 @@ import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.Theme;
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;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
@@ -246,19 +244,9 @@ public class TransactionDiagram extends GridPane {
}
private List<Map<BlockTransactionHashIndex, WalletNode>> getDisplayedUtxoSets() {
boolean addUserSet = getOptimizationStrategy() == OptimizationStrategy.PRIVACY && SorobanServices.canWalletMix(walletTx.getWallet())
&& walletTx.getPayments().size() == 1
&& (walletTx.getPayments().get(0).getAddress().getScriptType() == walletTx.getWallet().getFreshNode(KeyPurpose.RECEIVE).getAddress().getScriptType());
List<Map<BlockTransactionHashIndex, WalletNode>> displayedUtxoSets = new ArrayList<>();
for(Map<BlockTransactionHashIndex, WalletNode> selectedUtxoSet : walletTx.getSelectedUtxoSets()) {
displayedUtxoSets.add(getDisplayedUtxos(selectedUtxoSet, addUserSet ? 2 : walletTx.getSelectedUtxoSets().size()));
}
if(addUserSet && displayedUtxoSets.size() == 1) {
Map<BlockTransactionHashIndex, WalletNode> addUserUtxoSet = new HashMap<>();
addUserUtxoSet.put(new AddUserBlockTransactionHashIndex(!walletTx.isTwoPersonCoinjoin()), null);
displayedUtxoSets.add(addUserUtxoSet);
displayedUtxoSets.add(getDisplayedUtxos(selectedUtxoSet, walletTx.getSelectedUtxoSets().size()));
}
List<Map<BlockTransactionHashIndex, WalletNode>> paddedUtxoSets = new ArrayList<>();
@@ -339,11 +327,9 @@ public class TransactionDiagram extends GridPane {
double setHeight = (height / numSets) - 5;
for(int set = 0; set < numSets; set++) {
boolean externalUserSet = displayedUtxoSets.get(set).values().stream().anyMatch(Objects::nonNull);
boolean addUserSet = displayedUtxoSets.get(set).keySet().stream().anyMatch(ref -> ref instanceof AddUserBlockTransactionHashIndex);
if(externalUserSet || addUserSet) {
boolean replace = !isFinal() && set > 0 && SorobanServices.canWalletMix(walletTx.getWallet());
Glyph bracketGlyph = !replace && walletTx.isCoinControlUsed() ? getLockGlyph() : (addUserSet ? getUserAddGlyph() : getCoinsGlyph(replace));
String tooltipText = addUserSet ? "Click to add a mix partner" : (walletTx.getWallet().getFullDisplayName() + (replace ? "\nClick to replace with a mix partner" : ""));
if(externalUserSet) {
Glyph bracketGlyph = walletTx.isCoinControlUsed() ? getLockGlyph() : getCoinsGlyph();
String tooltipText = walletTx.getWallet().getFullDisplayName();
StackPane stackPane = getBracket(width, setHeight, bracketGlyph, tooltipText);
allBrackets.getChildren().add(stackPane);
} else {
@@ -474,14 +460,6 @@ public class TransactionDiagram extends GridPane {
tooltip.setText(joiner.toString());
} else if(input instanceof InvisibleBlockTransactionHashIndex) {
tooltip.setText("");
} else if(input instanceof AddUserBlockTransactionHashIndex) {
tooltip.setText("");
label.setGraphic(walletTx.isTwoPersonCoinjoin() ? getQuestionGlyph() : getFeeWarningGlyph());
label.setOnMouseClicked(event -> {
EventManager.get().post(new SorobanInitiatedEvent(walletTx.getWallet()));
closeExpanded();
event.consume();
});
} else {
if(walletTx.getInputTransactions() != null && walletTx.getInputTransactions().get(input.getHash()) != null) {
BlockTransaction blockTransaction = walletTx.getInputTransactions().get(input.getHash());
@@ -570,7 +548,7 @@ public class TransactionDiagram extends GridPane {
CubicCurve curve = new CubicCurve();
curve.getStyleClass().add("input-line");
if(inputs.get(numUtxos-i) instanceof PayjoinBlockTransactionHashIndex || inputs.get(numUtxos-i) instanceof AddUserBlockTransactionHashIndex) {
if(inputs.get(numUtxos-i) instanceof PayjoinBlockTransactionHashIndex) {
curve.getStyleClass().add("input-dashed-line");
} else if(inputs.get(numUtxos-i) instanceof InvisibleBlockTransactionHashIndex) {
continue;
@@ -952,46 +930,10 @@ public class TransactionDiagram extends GridPane {
return null;
}
private Glyph getUserAddGlyph() {
Glyph userAddGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.USER_PLUS);
userAddGlyph.getStyleClass().add("useradd-icon");
userAddGlyph.setFontSize(12);
userAddGlyph.setOnMouseEntered(event -> {
userAddGlyph.setFontSize(18);
});
userAddGlyph.setOnMouseExited(event -> {
userAddGlyph.setFontSize(12);
});
userAddGlyph.setOnMouseClicked(event -> {
EventManager.get().post(new SorobanInitiatedEvent(walletTx.getWallet()));
closeExpanded();
event.consume();
});
return userAddGlyph;
}
private Glyph getCoinsGlyph(boolean allowReplacement) {
private Glyph getCoinsGlyph() {
Glyph coinsGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.COINS);
coinsGlyph.setFontSize(12);
if(allowReplacement) {
coinsGlyph.getStyleClass().add("coins-replace-icon");
coinsGlyph.setOnMouseEntered(event -> {
coinsGlyph.setIcon(FontAwesome5.Glyph.USER_PLUS);
coinsGlyph.setFontSize(18);
});
coinsGlyph.setOnMouseExited(event -> {
coinsGlyph.setIcon(FontAwesome5.Glyph.COINS);
coinsGlyph.setFontSize(12);
});
coinsGlyph.setOnMouseClicked(event -> {
EventManager.get().post(new SorobanInitiatedEvent(walletTx.getWallet()));
closeExpanded();
event.consume();
});
} else {
coinsGlyph.getStyleClass().add("coins-icon");
}
coinsGlyph.getStyleClass().add("coins-icon");
return coinsGlyph;
}
@@ -1094,20 +1036,6 @@ public class TransactionDiagram extends GridPane {
}
}
private static class AddUserBlockTransactionHashIndex extends BlockTransactionHashIndex {
private final boolean required;
public AddUserBlockTransactionHashIndex(boolean required) {
super(Sha256Hash.ZERO_HASH, 0, new Date(), 0L, 0, 0);
this.required = required;
}
@Override
public String getLabel() {
return "Add Mix Partner" + (required ? "" : "?");
}
}
public static class AdditionalPayment extends Payment {
private final List<Payment> additionalPayments;
@@ -19,9 +19,10 @@ import javafx.scene.shape.Circle;
import org.controlsfx.glyphfont.Glyph;
import org.girod.javafx.svgimage.SVGImage;
import org.girod.javafx.svgimage.SVGLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
@@ -137,7 +138,7 @@ public class WalletIcon extends StackPane {
}
private void addWalletIcon(String walletId) {
Image image = new Image(PROTOCOL + ":" + walletId + "?" + QUERY, WIDTH, HEIGHT, true, false);
Image image = new Image(PROTOCOL + ":" + walletId.replaceAll(" ", "%20").replaceAll("#", "%23") + "?" + QUERY, WIDTH, HEIGHT, true, false);
getChildren().clear();
Circle circle = new Circle(getPrefWidth() / 2,getPrefHeight() / 2,getPrefWidth() / 2);
circle.setFill(new ImagePattern(image));
@@ -176,6 +177,8 @@ public class WalletIcon extends StackPane {
}
public static class WalletIconStreamHandler extends URLStreamHandler {
private static final Logger log = LoggerFactory.getLogger(WalletIconStreamHandler.class);
@Override
protected URLConnection openConnection(URL url) throws IOException {
return new URLConnection(url) {
@@ -186,17 +189,19 @@ public class WalletIcon extends StackPane {
@Override
public InputStream getInputStream() throws IOException {
String walletId = url.getPath();
String walletId = url.getPath().replaceAll("%20", " ").replaceAll("%23", "#");
String query = url.getQuery();
Wallet wallet = AppServices.get().getWallet(walletId);
if(wallet == null) {
throw new IOException("Cannot find wallet for wallet id " + walletId);
log.warn("Cannot find wallet for wallet id " + walletId);
return getFallbackIconStream();
}
if(query.startsWith(QUERY)) {
if(wallet.getWalletConfig() == null || wallet.getWalletConfig().getIconData() == null) {
throw new IOException("No icon data for " + walletId);
log.warn("No icon data for " + walletId);
return getFallbackIconStream();
}
ByteArrayInputStream bais = new ByteArrayInputStream(wallet.getWalletConfig().getIconData());
@@ -207,7 +212,12 @@ public class WalletIcon extends StackPane {
}
}
throw new MalformedURLException("Cannot load url " + url);
log.warn("Cannot load url " + url);
return getFallbackIconStream();
}
private static InputStream getFallbackIconStream() {
return WalletIconStreamHandler.class.getResourceAsStream("/image/sparrow.png");
}
};
}
@@ -51,7 +51,8 @@ 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(), new Krux(), new AirGapVault());
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(), new Samourai());
for(KeystoreFileImport importer : keystoreImporters) {
if(!importer.isDeprecated() || Config.get().isShowDeprecatedImportExport()) {
FileWalletKeystoreImportPane importPane = new FileWalletKeystoreImportPane(importer);
@@ -59,7 +60,8 @@ 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(), new JadeMultisig()));
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));
}
@@ -18,17 +18,21 @@ import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import java.util.ArrayList;
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()) {
public WalletSummaryDialog(List<List<WalletForm>> summaryWalletFormsList) {
List<List<WalletForm>> walletFormsList = new ArrayList<>(summaryWalletFormsList);
walletFormsList.removeIf(List::isEmpty);
if(walletFormsList.isEmpty()) {
throw new IllegalArgumentException("No wallets selected to summarize");
}
Wallet masterWallet = walletForms.get(0).getMasterWallet();
boolean allOpenWallets = walletFormsList.size() > 1;
List<Wallet> masterWallets = walletFormsList.stream().map(walletForms -> walletForms.get(0).getMasterWallet()).toList();
final DialogPane dialogPane = getDialogPane();
dialogPane.getStylesheets().add(AppServices.class.getResource("general.css").toExternalForm());
@@ -37,7 +41,7 @@ public class WalletSummaryDialog extends Dialog<Void> {
dialogPane.getStylesheets().add(AppServices.class.getResource("wallet/transactions.css").toExternalForm());
AppServices.setStageIcon(dialogPane.getScene().getWindow());
dialogPane.setHeaderText("Wallet Summary for " + masterWallet.getName());
dialogPane.setHeaderText("Wallet Summary for " + (allOpenWallets ? "All Open Wallets" : masterWallets.get(0).getName()));
Image image = new Image("image/sparrow-small.png", 50, 50, false, false);
if(!image.isError()) {
@@ -64,7 +68,7 @@ public class WalletSummaryDialog extends Dialog<Void> {
});
balanceColumn.setCellFactory(p -> new CoinCell());
table.getColumns().add(balanceColumn);
table.setUnitFormat(masterWallet);
table.setUnitFormat(masterWallets.get(0));
CurrencyRate currencyRate = AppServices.getFiatCurrencyExchangeRate();
if(currencyRate != null && currencyRate.isAvailable() && Config.get().getExchangeSource() != ExchangeSource.NONE) {
@@ -77,12 +81,20 @@ public class WalletSummaryDialog extends Dialog<Void> {
table.setCurrencyRate(currencyRate);
}
SummaryEntry rootEntry = new SummaryEntry(walletForms);
Entry rootEntry = allOpenWallets ? new AllSummaryEntry(walletFormsList) : new SummaryEntry(walletFormsList.get(0));
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)));
if(allOpenWallets) {
for(Entry walletEntry : childEntry.getChildren()) {
TreeItem<Entry> walletItem = new TreeItem<>(walletEntry);
childItem.getChildren().add(walletItem);
walletItem.getChildren().add(new TreeItem<>(new UnconfirmedEntry((WalletTransactionsEntry)walletEntry)));
}
} else {
childItem.getChildren().add(new TreeItem<>(new UnconfirmedEntry((WalletTransactionsEntry)childEntry)));
}
}
table.setShowRoot(true);
@@ -97,6 +109,14 @@ public class WalletSummaryDialog extends Dialog<Void> {
hBox.getChildren().add(vBox);
Wallet balanceWallet;
if(allOpenWallets) {
balanceWallet = new Wallet();
balanceWallet.getChildWallets().addAll(masterWallets.stream().flatMap(mws -> mws.getAllWallets().stream()).toList());
} else {
balanceWallet = masterWallets.get(0);
}
NumberAxis xAxis = new NumberAxis();
xAxis.setSide(Side.BOTTOM);
xAxis.setForceZeroInRange(false);
@@ -104,7 +124,7 @@ public class WalletSummaryDialog extends Dialog<Void> {
NumberAxis yAxis = new NumberAxis();
yAxis.setSide(Side.LEFT);
BalanceChart balanceChart = new BalanceChart(xAxis, yAxis);
balanceChart.initialize(new WalletTransactionsEntry(masterWallet, true));
balanceChart.initialize(new WalletTransactionsEntry(balanceWallet, true));
balanceChart.setAnimated(false);
balanceChart.setLegendVisible(false);
balanceChart.setVerticalGridLinesVisible(false);
@@ -120,6 +140,32 @@ public class WalletSummaryDialog extends Dialog<Void> {
AppServices.moveToActiveWindowScreen(this);
}
public static class AllSummaryEntry extends Entry {
private AllSummaryEntry(List<List<WalletForm>> walletFormsList) {
super(null, "All Wallets", walletFormsList.stream().map(SummaryEntry::new).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 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()));
@@ -28,16 +28,18 @@ import java.util.List;
public class XprvKeystoreImportPane extends TitledDescriptionPane {
protected final Wallet wallet;
protected final KeystoreXprvImport importer;
protected final KeyDerivation defaultDerivation;
private Button enterXprvButton;
private SplitMenuButton importButton;
private ExtendedKey xprv;
public XprvKeystoreImportPane(Wallet wallet, KeystoreXprvImport importer) {
public XprvKeystoreImportPane(Wallet wallet, KeystoreXprvImport importer, KeyDerivation defaultDerivation) {
super(importer.getName(), "Extended key import", importer.getKeystoreImportDescription(), "image/" + importer.getWalletModel().getType() + ".png");
this.wallet = wallet;
this.importer = importer;
this.defaultDerivation = defaultDerivation;
createImportButton();
buttonBox.getChildren().add(importButton);
@@ -47,6 +49,7 @@ public class XprvKeystoreImportPane extends TitledDescriptionPane {
super("Master Private Key", "BIP32 key", "", "image/" + WalletModel.SEED.getType() + ".png");
this.wallet = null;
this.importer = null;
this.defaultDerivation = keystore.getKeyDerivation();
try {
this.xprv = keystore.getExtendedMasterPrivateKey();
@@ -79,7 +82,7 @@ public class XprvKeystoreImportPane extends TitledDescriptionPane {
importButton.getStyleClass().add("default-button");
importButton.setOnAction(event -> {
importButton.setDisable(true);
importKeystore(wallet.getScriptType().getDefaultDerivation());
importKeystore(getDefaultDerivation());
});
String[] accounts = new String[] {"Import Default Account #0", "Import Account #1", "Import Account #2", "Import Account #3", "Import Account #4", "Import Account #5", "Import Account #6", "Import Account #7", "Import Account #8", "Import Account #9"};
int scriptAccountsLength = ScriptType.P2SH.equals(wallet.getScriptType()) ? 1 : accounts.length;
@@ -97,6 +100,10 @@ public class XprvKeystoreImportPane extends TitledDescriptionPane {
importButton.setVisible(false);
}
private List<ChildNumber> getDefaultDerivation() {
return defaultDerivation == null || defaultDerivation.getDerivation().isEmpty() ? wallet.getScriptType().getDefaultDerivation() : defaultDerivation.getDerivation();
}
private void enterXprv() {
setDescription("Enter master private key");
showHideLink.setVisible(false);
@@ -149,7 +156,7 @@ public class XprvKeystoreImportPane extends TitledDescriptionPane {
importButton.setVisible(true);
setDescription("Ready to import");
xprv = ExtendedKey.fromDescriptor(xprvField.getText());
setContent(getDerivationEntry(wallet.getScriptType().getDefaultDerivation()));
setContent(getDerivationEntry(getDefaultDerivation()));
});
xprvField.textProperty().addListener((observable, oldValue, newValue) -> {
@@ -1,15 +0,0 @@
package com.sparrowwallet.sparrow.event;
import com.sparrowwallet.drongo.wallet.Wallet;
public class SorobanInitiatedEvent {
private Wallet wallet;
public SorobanInitiatedEvent(Wallet wallet) {
this.wallet = wallet;
}
public Wallet getWallet() {
return wallet;
}
}
@@ -1,6 +1,5 @@
package com.sparrowwallet.sparrow.event;
import com.samourai.whirlpool.client.whirlpool.beans.Pool;
import com.sparrowwallet.drongo.bip47.PaymentCode;
import com.sparrowwallet.drongo.wallet.BlockTransaction;
import com.sparrowwallet.drongo.wallet.BlockTransactionHashIndex;
@@ -17,7 +16,6 @@ public class SpendUtxoEvent {
private final Long fee;
private final boolean requireAllUtxos;
private final BlockTransaction replacedTransaction;
private final Pool pool;
private final PaymentCode paymentCode;
public SpendUtxoEvent(Wallet wallet, List<BlockTransactionHashIndex> utxos) {
@@ -32,19 +30,6 @@ public class SpendUtxoEvent {
this.fee = fee;
this.requireAllUtxos = requireAllUtxos;
this.replacedTransaction = replacedTransaction;
this.pool = null;
this.paymentCode = null;
}
public SpendUtxoEvent(Wallet wallet, List<BlockTransactionHashIndex> utxos, List<Payment> payments, List<byte[]> opReturns, Long fee, Pool pool) {
this.wallet = wallet;
this.utxos = utxos;
this.payments = payments;
this.opReturns = opReturns;
this.fee = fee;
this.requireAllUtxos = false;
this.replacedTransaction = null;
this.pool = pool;
this.paymentCode = null;
}
@@ -56,7 +41,6 @@ public class SpendUtxoEvent {
this.fee = null;
this.requireAllUtxos = false;
this.replacedTransaction = null;
this.pool = null;
this.paymentCode = paymentCode;
}
@@ -88,10 +72,6 @@ public class SpendUtxoEvent {
return replacedTransaction;
}
public Pool getPool() {
return pool;
}
public PaymentCode getPaymentCode() {
return paymentCode;
}
@@ -1,15 +0,0 @@
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;
}
}
@@ -1,67 +0,0 @@
package com.sparrowwallet.sparrow.event;
import com.samourai.whirlpool.client.mix.listener.MixFailReason;
import com.samourai.whirlpool.client.wallet.beans.MixProgress;
import com.samourai.whirlpool.protocol.beans.Utxo;
import com.sparrowwallet.drongo.wallet.BlockTransactionHashIndex;
import com.sparrowwallet.drongo.wallet.Wallet;
public class WhirlpoolMixEvent {
private final Wallet wallet;
private final BlockTransactionHashIndex utxo;
private final MixProgress mixProgress;
private final Utxo nextUtxo;
private final MixFailReason mixFailReason;
private final String mixError;
public WhirlpoolMixEvent(Wallet wallet, BlockTransactionHashIndex utxo, MixProgress mixProgress) {
this.wallet = wallet;
this.utxo = utxo;
this.mixProgress = mixProgress;
this.nextUtxo = null;
this.mixFailReason = null;
this.mixError = null;
}
public WhirlpoolMixEvent(Wallet wallet, BlockTransactionHashIndex utxo, Utxo nextUtxo) {
this.wallet = wallet;
this.utxo = utxo;
this.mixProgress = null;
this.nextUtxo = nextUtxo;
this.mixFailReason = null;
this.mixError = null;
}
public WhirlpoolMixEvent(Wallet wallet, BlockTransactionHashIndex utxo, MixFailReason mixFailReason, String mixError) {
this.wallet = wallet;
this.utxo = utxo;
this.mixProgress = null;
this.nextUtxo = null;
this.mixFailReason = mixFailReason;
this.mixError = mixError;
}
public Wallet getWallet() {
return wallet;
}
public BlockTransactionHashIndex getUtxo() {
return utxo;
}
public MixProgress getMixProgress() {
return mixProgress;
}
public Utxo getNextUtxo() {
return nextUtxo;
}
public MixFailReason getMixFailReason() {
return mixFailReason;
}
public String getMixError() {
return mixError;
}
}
@@ -1,19 +0,0 @@
package com.sparrowwallet.sparrow.event;
import com.samourai.whirlpool.protocol.beans.Utxo;
import com.sparrowwallet.drongo.wallet.BlockTransactionHashIndex;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletNode;
public class WhirlpoolMixSuccessEvent extends WhirlpoolMixEvent {
private final WalletNode walletNode;
public WhirlpoolMixSuccessEvent(Wallet wallet, BlockTransactionHashIndex utxo, Utxo nextUtxo, WalletNode walletNode) {
super(wallet, utxo, nextUtxo);
this.walletNode = walletNode;
}
public WalletNode getWalletNode() {
return walletNode;
}
}
@@ -203,4 +203,11 @@ public class GlyphUtils {
busyGlyph.setFontSize(12);
return busyGlyph;
}
public static Glyph getDownArrowGlyph() {
Glyph downGlyph = new Glyph(FontAwesome5.FONT_NAME, FontAwesome5.Glyph.ARROW_DOWN);
downGlyph.getStyleClass().add("arrow-down");
downGlyph.setFontSize(12);
return downGlyph;
}
}
@@ -1,535 +1,270 @@
/**
* Copyright 2019 Pratanu Mandal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.sparrowwallet.sparrow.instance;
import com.sparrowwallet.sparrow.io.Storage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.Set;
/**
* The <code>Instance</code> class is the primary logical entry point to the library.<br>
* It allows to create an application lock or free it and send and receive messages between first and subsequent instances.<br><br>
*
* <pre>
* // unique application ID
* String APP_ID = "tk.pratanumandal.unique4j-mlsdvo-20191511-#j.6";
*
* // create Instance instance
* Instance unique = new Instance(APP_ID) {
* &nbsp;&nbsp;&nbsp;&nbsp;&#64;Override
* &nbsp;&nbsp;&nbsp;&nbsp;protected void receiveMessage(String message) {
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// print received message (timestamp)
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(message);
* &nbsp;&nbsp;&nbsp;&nbsp;}
* &nbsp;&nbsp;&nbsp;&nbsp;
* &nbsp;&nbsp;&nbsp;&nbsp;&#64;Override
* &nbsp;&nbsp;&nbsp;&nbsp;protected String sendMessage() {
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// send timestamp as message
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Timestamp ts = new Timestamp(new Date().getTime());
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return "Another instance launch attempted: " + ts.toString();
* &nbsp;&nbsp;&nbsp;&nbsp;}
* };
*
* // try to obtain lock
* try {
* &nbsp;&nbsp;&nbsp;&nbsp;unique.acquireLock();
* } catch (InstanceException e) {
* &nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();
* }
*
* ...
*
* // try to free the lock before exiting program
* try {
* &nbsp;&nbsp;&nbsp;&nbsp;unique.freeLock();
* } catch (InstanceException e) {
* &nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();
* }
* </pre>
*
* @author Pratanu Mandal
* @since 1.3
*
*/
public abstract class Instance {
private static final Logger log = LoggerFactory.getLogger(Instance.class);
// starting position of port check
private static final int PORT_START = 7221;
// system temporary directory path
private static final String TEMP_DIR = System.getProperty("java.io.tmpdir");
/**
* Unique string representing the application ID.<br><br>
*
* The APP_ID must be as unique as possible.
* Avoid generic names like "my_app_id" or "hello_world".<br>
* A good strategy is to use the entire package name (group ID + artifact ID) along with some random characters.
*/
public final String APP_ID;
// auto exit from application or not
private final boolean AUTO_EXIT;
// lock server port
private int port;
// lock server socket
private ServerSocket server;
// lock file RAF object
private RandomAccessFile lockRAF;
// file lock for the lock file RAF object
private FileLock fileLock;
private static final String LINK_ENV_PROPERTY = "SPARROW_NO_LOCK_FILE_LINK";
/**
* Parameterized constructor.<br>
* This constructor configures to automatically exit the application for subsequent instances.<br><br>
*
* The APP_ID must be as unique as possible.
* Avoid generic names like "my_app_id" or "hello_world".<br>
* A good strategy is to use the entire package name (group ID + artifact ID) along with some random characters.
*
* @param APP_ID Unique string representing the application ID
*/
public Instance(final String APP_ID) {
this(APP_ID, true);
}
/**
* Parameterized constructor.<br>
* This constructor allows to explicitly specify the exit strategy for subsequent instances.<br><br>
*
* The APP_ID must be as unique as possible.
* Avoid generic names like "my_app_id" or "hello_world".<br>
* A good strategy is to use the entire package name (group ID + artifact ID) along with some random characters.
*
* @since 1.2
*
* @param APP_ID Unique string representing the application ID
* @param AUTO_EXIT If true, automatically exit the application for subsequent instances
*/
public Instance(final String APP_ID, final boolean AUTO_EXIT) {
this.APP_ID = APP_ID;
this.AUTO_EXIT = AUTO_EXIT;
}
/**
* Try to obtain lock. If not possible, send data to first instance.
*
* @deprecated Use <code>acquireLock()</code> instead.
* @throws InstanceException throws InstanceException if it is unable to start a server or connect to server
*/
@Deprecated
public void lock() throws InstanceException {
acquireLock();
}
/**
* Try to obtain lock. If not possible, send data to first instance.
*
* @since 1.2
*
* @return true if able to acquire lock, false otherwise
* @throws InstanceException throws InstanceException if it is unable to start a server or connect to server
*/
public boolean acquireLock() throws InstanceException {
// try to obtain port number from lock file
port = lockFile();
if (port == -1) {
// failed to fetch port number
// try to start server
startServer();
}
else {
// port number fetched from lock file
// try to start client
doClient();
}
return (server != null);
}
// start the server
private void startServer() throws InstanceException {
// try to create server
port = PORT_START;
while (true) {
try {
server = new ServerSocket(port, 50, InetAddress.getByName(null));
break;
} catch (IOException e) {
port++;
}
}
// try to lock file
lockFile(port);
// server created successfully; this is the first instance
// keep listening for data from other instances
Thread thread = new Thread() {
@Override
public void run() {
while (!server.isClosed()) {
try {
// establish connection
final Socket socket = server.accept();
// handle socket on a different thread to allow parallel connections
Thread thread = new Thread() {
@Override
public void run() {
try {
// open writer
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
// open reader
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
// read message length from client
int length = dis.readInt();
// read message string from client
String message = null;
if (length > -1) {
byte[] messageBytes = new byte[length];
int bytesRead = dis.read(messageBytes, 0, length);
message = new String(messageBytes, 0, bytesRead, "UTF-8");
}
// write response to client
if (APP_ID == null) {
dos.writeInt(-1);
}
else {
byte[] appId = APP_ID.getBytes("UTF-8");
dos.writeInt(appId.length);
dos.write(appId);
}
dos.flush();
// close writer and reader
dos.close();
dis.close();
// perform user action on message
receiveMessage(message);
// close socket
socket.close();
} catch (IOException e) {
handleException(new InstanceException(e));
}
}
};
// start socket thread
thread.start();
} catch (SocketException e) {
if (!server.isClosed()) {
handleException(new InstanceException(e));
}
} catch (IOException e) {
handleException(new InstanceException(e));
}
}
}
};
thread.start();
}
// do client tasks
private void doClient() throws InstanceException {
// get localhost address
InetAddress address = null;
try {
address = InetAddress.getByName(null);
} catch (UnknownHostException e) {
throw new InstanceException(e);
}
// try to establish connection to server
Socket socket = null;
try {
socket = new Socket(address, port);
} catch (IOException e) {
// connection failed try to start server
startServer();
}
// connection successful try to connect to server
if (socket != null) {
try {
// get message to be sent to first instance
String message = sendMessage();
// open writer
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
// open reader
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
// write message to server
if (message == null) {
dos.writeInt(-1);
}
else {
byte[] messageBytes = message.getBytes("UTF-8");
dos.writeInt(messageBytes.length);
dos.write(messageBytes);
}
dos.flush();
// read response length from server
int length = dis.readInt();
// read response string from server
String response = null;
if (length > -1) {
byte[] responseBytes = new byte[length];
int bytesRead = dis.read(responseBytes, 0, length);
response = new String(responseBytes, 0, bytesRead, "UTF-8");
}
// close writer and reader
dos.close();
dis.close();
if (response.equals(APP_ID)) {
// validation successful
if (AUTO_EXIT) {
// perform pre-exit tasks
beforeExit();
// exit this instance
System.exit(0);
}
}
else {
// validation failed, this is the first instance
startServer();
}
} catch (IOException e) {
throw new InstanceException(e);
} finally {
// close socket
try {
if (socket != null) socket.close();
} catch (IOException e) {
throw new InstanceException(e);
}
}
}
}
// try to get port from lock file
private int lockFile() throws InstanceException {
// lock file path
String filePath = TEMP_DIR + File.separator + APP_ID + ".lock";
File file = new File(filePath);
// try to get port from lock file
if (file.exists()) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
return Integer.parseInt(br.readLine());
} catch (IOException e) {
throw new InstanceException(e);
} catch (NumberFormatException e) {
// do nothing
} finally {
try {
if (br != null) br.close();
} catch (IOException e) {
throw new InstanceException(e);
}
}
}
return -1;
}
// try to write port to lock file
private void lockFile(int port) throws InstanceException {
// lock file path
String filePath = TEMP_DIR + File.separator + APP_ID + ".lock";
File file = new File(filePath);
// try to write port to lock file
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(String.valueOf(port));
} catch (IOException e) {
throw new InstanceException(e);
} finally {
try {
if (bw != null) bw.close();
} catch (IOException e) {
throw new InstanceException(e);
}
}
// try to obtain file lock
try {
lockRAF = new RandomAccessFile(file, "rw");
FileChannel fc = lockRAF.getChannel();
fileLock = fc.tryLock(0, Long.MAX_VALUE, true);
if (fileLock == null) {
throw new InstanceException("Failed to obtain file lock");
}
} catch (FileNotFoundException e) {
throw new InstanceException(e);
} catch (IOException e) {
throw new InstanceException(e);
}
}
/**
* Free the lock if possible. This is only required to be called from the first instance.
*
* @deprecated Use <code>freeLock()</code> instead.
* @throws InstanceException throws InstanceException if it is unable to stop the server or release file lock
*/
@Deprecated
public void free() throws InstanceException {
freeLock();
}
/**
* Free the lock if possible. This is only required to be called from the first instance.
*
* @since 1.2
*
* @return true if able to release lock, false otherwise
* @throws InstanceException throws InstanceException if it is unable to stop the server or release file lock
*/
public boolean freeLock() throws InstanceException {
try {
// close server socket
if (server != null) {
server.close();
// lock file path
String filePath = TEMP_DIR + File.separator + APP_ID + ".lock";
File file = new File(filePath);
// try to release file lock
if (fileLock != null) {
fileLock.release();
}
// try to close lock file RAF object
if (lockRAF != null) {
lockRAF.close();
}
// try to delete lock file
if (file.exists()) {
file.delete();
}
return true;
}
return false;
} catch (IOException e) {
throw new InstanceException(e);
}
}
/**
* Method used in first instance to receive messages from subsequent instances.<br><br>
*
* This method is not synchronized.
*
* @param message message received by first instance from subsequent instances
*/
protected abstract void receiveMessage(String message);
/**
* Method used in subsequent instances to send message to first instance.<br><br>
*
* It is not recommended to perform blocking (long running) tasks here. Use <code>beforeExit()</code> method instead.<br>
* One exception to this rule is if you intend to perform some user interaction before sending the message.<br><br>
*
* This method is not synchronized.
*
* @return message sent from subsequent instances
*/
protected abstract String sendMessage();
/**
* Method to receive and handle exceptions occurring while first instance is listening for subsequent instances.<br><br>
*
* By default prints stack trace of all exceptions. Override this method to handle exceptions explicitly.<br><br>
*
* This method is not synchronized.
*
* @param exception exception occurring while first instance is listening for subsequent instances
*/
protected void handleException(Exception exception) {
public final String applicationId;
private final boolean autoExit;
private Selector selector;
private ServerSocketChannel serverChannel;
public Instance(final String applicationId) {
this(applicationId, true);
}
public Instance(final String applicationId, final boolean autoExit) {
this.applicationId = applicationId;
this.autoExit = autoExit;
}
/**
* Try to obtain lock. If not possible, send data to first instance.
*
* @throws InstanceException throws InstanceException if it is unable to start a server or connect to server
*/
public void acquireLock(boolean findExisting) throws InstanceException {
Path lockFile = getLockFile(findExisting);
if(!Files.exists(lockFile)) {
startServer(lockFile);
} else {
doClient(lockFile);
}
}
private void startServer(Path lockFile) throws InstanceException {
try {
selector = Selector.open();
UnixDomainSocketAddress socketAddress = UnixDomainSocketAddress.of(lockFile);
serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
serverChannel.bind(socketAddress);
serverChannel.configureBlocking(false);
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
lockFile.toFile().deleteOnExit();
} catch(Exception e) {
throw new InstanceException("Could not open UNIX socket lock file for instance at " + lockFile.toAbsolutePath(), e);
}
Thread thread = new Thread(() -> {
while(true) {
try {
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iter = selectedKeys.iterator();
while(iter.hasNext()) {
SelectionKey key = iter.next();
if(key.isAcceptable()) {
SocketChannel client = serverChannel.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}
if(key.isReadable()) {
try(SocketChannel clientChannel = (SocketChannel)key.channel()) {
String message = readMessage(clientChannel);
clientChannel.write(ByteBuffer.wrap(applicationId.getBytes(StandardCharsets.UTF_8)));
receiveMessage(message);
}
}
iter.remove();
}
} catch(SocketException e) {
if(serverChannel.isOpen()) {
handleException(new InstanceException(e));
}
} catch(Exception e) {
handleException(new InstanceException(e));
}
}
});
thread.setDaemon(true);
thread.setName("SparrowInstanceListener");
thread.start();
createSymlink(lockFile);
}
private void doClient(Path lockFile) throws InstanceException {
try(SocketChannel client = SocketChannel.open(UnixDomainSocketAddress.of(lockFile))) {
String message = sendMessage();
client.write(ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)));
client.shutdownOutput();
String response = readMessage(client);
if(response.equals(applicationId) && autoExit) {
beforeExit();
System.exit(0);
}
} catch(ConnectException e) {
try {
Files.deleteIfExists(lockFile);
startServer(lockFile);
} catch(Exception ex) {
throw new InstanceException("Could not delete lock file from previous instance", e);
}
} catch(Exception e) {
throw new InstanceException("Could not open client connection to existing instance", e);
}
}
private static String readMessage(SocketChannel clientChannel) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
StringBuilder messageBuilder = new StringBuilder();
while(clientChannel.read(buffer) != -1) {
buffer.flip();
messageBuilder.append(new String(buffer.array(), 0, buffer.limit()));
buffer.clear();
}
return messageBuilder.toString();
}
private Path getLockFile(boolean findExisting) {
if(findExisting) {
Path pointer = getUserLockFilePointer();
try {
if(pointer != null && Files.exists(pointer)) {
if(Files.isSymbolicLink(pointer)) {
return Files.readSymbolicLink(pointer);
} else {
Path lockFile = Path.of(Files.readString(pointer, StandardCharsets.UTF_8));
if(Files.exists(lockFile)) {
return lockFile;
}
}
}
} catch(IOException e) {
log.warn("Could not find lock file at " + pointer.toAbsolutePath());
} catch(Exception e) {
//ignore
}
}
return Storage.getSparrowDir().toPath().resolve(applicationId + ".lock");
}
private void createSymlink(Path lockFile) {
Path pointer = getUserLockFilePointer();
try {
if(pointer != null && !Files.exists(pointer, LinkOption.NOFOLLOW_LINKS)) {
Files.createSymbolicLink(pointer, lockFile);
pointer.toFile().deleteOnExit();
}
} catch(IOException e) {
log.debug("Could not create symlink " + pointer.toAbsolutePath() + " to lockFile at " + lockFile.toAbsolutePath() + ", writing as normal file", e);
try {
Files.writeString(pointer, lockFile.toAbsolutePath().toString(), StandardCharsets.UTF_8);
pointer.toFile().deleteOnExit();
} catch(IOException ex) {
log.warn("Could not create pointer " + pointer.toAbsolutePath() + " to lockFile at " + lockFile.toAbsolutePath(), ex);
}
} catch(Exception e) {
//ignore
}
}
private Path getUserLockFilePointer() {
if(Boolean.parseBoolean(System.getenv(LINK_ENV_PROPERTY))) {
return null;
}
try {
File sparrowHome = Storage.getSparrowHome(true);
if(!sparrowHome.exists()) {
Storage.createOwnerOnlyDirectory(sparrowHome);
}
return sparrowHome.toPath().resolve(applicationId + ".default");
} catch(Exception e) {
return null;
}
}
/**
* Free the lock if possible. This is only required to be called from the first instance.
*
* @throws InstanceException throws InstanceException if it is unable to stop the server or release file lock
*/
public void freeLock() throws InstanceException {
try {
if(serverChannel != null && serverChannel.isOpen()) {
serverChannel.close();
}
if(getUserLockFilePointer() != null) {
Files.deleteIfExists(getUserLockFilePointer());
}
Files.deleteIfExists(getLockFile(false));
} catch(Exception e) {
throw new InstanceException(e);
}
}
/**
* Method used in first instance to receive messages from subsequent instances.<br><br>
*
* This method is not synchronized.
*
* @param message message received by first instance from subsequent instances
*/
protected abstract void receiveMessage(String message);
/**
* Method used in subsequent instances to send message to first instance.<br><br>
*
* It is not recommended to perform blocking (long running) tasks here. Use <code>beforeExit()</code> method instead.<br>
* One exception to this rule is if you intend to perform some user interaction before sending the message.<br><br>
*
* This method is not synchronized.
*
* @return message sent from subsequent instances
*/
protected abstract String sendMessage();
/**
* Method to receive and handle exceptions occurring while first instance is listening for subsequent instances.<br><br>
*
* By default prints stack trace of all exceptions. Override this method to handle exceptions explicitly.<br><br>
*
* This method is not synchronized.
*
* @param exception exception occurring while first instance is listening for subsequent instances
*/
protected void handleException(Exception exception) {
log.error("Error listening for instances", exception);
}
/**
* This method is called before exiting from subsequent instances.<br><br>
*
* Override this method to perform blocking tasks before exiting from subsequent instances.<br>
* This method is not invoked if auto exit is turned off.<br><br>
*
* This method is not synchronized.
*
* @since 1.2
*/
protected void beforeExit() {}
}
/**
* This method is called before exiting from subsequent instances.<br><br>
*
* Override this method to perform blocking tasks before exiting from subsequent instances.<br>
* This method is not invoked if auto exit is turned off.<br><br>
*
* This method is not synchronized.
*/
protected void beforeExit() {}
}
@@ -7,88 +7,14 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
/**
* The <code>InstanceList</code> class is a logical entry point to the library which extends the functionality of the <code>Instance</code> class.<br>
* It allows to create an application lock or free it and send and receive messages between first and subsequent instances.<br><br>
*
* This class is intended for passing a list of strings instead of a single string from the subsequent instance to the first instance.<br><br>
*
* <pre>
* // unique application ID
* String APP_ID = "tk.pratanumandal.unique4j-mlsdvo-20191511-#j.6";
*
* // create Instance instance
* Instance unique = new InstanceList(APP_ID) {
* &nbsp;&nbsp;&nbsp;&nbsp;&#64;Override
* &nbsp;&nbsp;&nbsp;&nbsp;protected List&lt;String&gt; sendMessageList() {
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List&lt;String&gt; messageList = new ArrayList&lt;String&gt;();
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;messageList.add("Message 1");
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;messageList.add("Message 2");
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;messageList.add("Message 3");
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;messageList.add("Message 4");
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return messageList;
* &nbsp;&nbsp;&nbsp;&nbsp;}
*
* &nbsp;&nbsp;&nbsp;&nbsp;&#64;Override
* &nbsp;&nbsp;&nbsp;&nbsp;protected void receiveMessageList(List&lt;String&gt; messageList) {
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for (String message : messageList) {
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(message);
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
* &nbsp;&nbsp;&nbsp;&nbsp;}
* };
*
* // try to obtain lock
* try {
* &nbsp;&nbsp;&nbsp;&nbsp;unique.acquireLock();
* } catch (InstanceException e) {
* &nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();
* }
*
* ...
*
* // try to free the lock before exiting program
* try {
* &nbsp;&nbsp;&nbsp;&nbsp;unique.freeLock();
* } catch (InstanceException e) {
* &nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();
* }
* </pre>
*
* @author Pratanu Mandal
* @since 1.3
*
*/
public abstract class InstanceList extends Instance {
/**
* Parameterized constructor.<br>
* This constructor configures to automatically exit the application for subsequent instances.<br><br>
*
* The APP_ID must be as unique as possible.
* Avoid generic names like "my_app_id" or "hello_world".<br>
* A good strategy is to use the entire package name (group ID + artifact ID) along with some random characters.
*
* @param APP_ID Unique string representing the application ID
*/
public InstanceList(String APP_ID) {
super(APP_ID);
public InstanceList(String applicationId) {
super(applicationId);
}
/**
* Parameterized constructor.<br>
* This constructor allows to explicitly specify the exit strategy for subsequent instances.<br><br>
*
* The APP_ID must be as unique as possible.
* Avoid generic names like "my_app_id" or "hello_world".<br>
* A good strategy is to use the entire package name (group ID + artifact ID) along with some random characters.
*
* @param APP_ID Unique string representing the application ID
* @param AUTO_EXIT If true, automatically exit the application for subsequent instances
*/
public InstanceList(String APP_ID, boolean AUTO_EXIT) {
super(APP_ID, AUTO_EXIT);
public InstanceList(String applicationId, boolean autoExit) {
super(applicationId, autoExit);
}
/**
@@ -101,16 +27,15 @@ public abstract class InstanceList extends Instance {
*/
@Override
protected final void receiveMessage(String message) {
if (message == null) {
if(message == null) {
receiveMessageList(null);
}
else {
} else {
// parse the JSON array string into an array of string arguments
JsonArray jsonArgs = JsonParser.parseString(message).getAsJsonArray();
List<String> stringArgs = new ArrayList<String>(jsonArgs.size());
for (int i = 0; i < jsonArgs.size(); i++) {
for(int i = 0; i < jsonArgs.size(); i++) {
JsonElement element = jsonArgs.get(i);
stringArgs.add(element.getAsString());
}
@@ -137,10 +62,11 @@ public abstract class InstanceList extends Instance {
JsonArray jsonArgs = new JsonArray();
List<String> stringArgs = sendMessageList();
if(stringArgs == null) {
return null;
}
if (stringArgs == null) return null;
for (String arg : stringArgs) {
for(String arg : stringArgs) {
jsonArgs.add(arg);
}
@@ -168,5 +94,4 @@ public abstract class InstanceList extends Instance {
* @return list of messages sent from subsequent instances
*/
protected abstract List<String> sendMessageList();
}
@@ -28,7 +28,7 @@ public class CaravanMultisig implements WalletImport, WalletExport {
@Override
public String getName() {
return "Unchained or Caravan Multisig";
return "Unchained Caravan Multisig";
}
@Override
@@ -56,7 +56,7 @@ public class CaravanMultisig implements WalletImport, WalletExport {
Keystore keystore = new Keystore(extKey.name.length() > Keystore.MAX_LABEL_LENGTH ? extKey.name.substring(0, Keystore.MAX_LABEL_LENGTH) : extKey.name);
if("Unknown".equals(extKey.bip32Path)) {
extKey.bip32Path = "m/45'/0/0/0";
extKey.bip32Path = "m/0/0/0/0";
}
try {
@@ -107,7 +107,7 @@ public class CaravanMultisig implements WalletImport, WalletExport {
CaravanFile cf = new CaravanFile();
cf.name = wallet.getFullName();
cf.addressType = wallet.getScriptType().toString().replace('-', '_');
cf.network = Network.get().getName();
cf.network = Network.getCanonical().getName();
cf.client = new Client();
Quorum quorum = new Quorum();
@@ -7,10 +7,7 @@ import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.drongo.policy.Policy;
import com.sparrowwallet.drongo.policy.PolicyType;
import com.sparrowwallet.drongo.protocol.ScriptType;
import com.sparrowwallet.drongo.wallet.Keystore;
import com.sparrowwallet.drongo.wallet.KeystoreSource;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletModel;
import com.sparrowwallet.drongo.wallet.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -36,6 +33,31 @@ public class ColdcardMultisig implements WalletImport, KeystoreFileImport, Walle
@Override
public Keystore getKeystore(ScriptType scriptType, InputStream inputStream, String password) throws ImportException {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
inputStream.transferTo(baos);
InputStream firstClone = new ByteArrayInputStream(baos.toByteArray());
InputStream secondClone = new ByteArrayInputStream(baos.toByteArray());
Keystore keystore;
try {
keystore = getKeystoreMultisig(scriptType, firstClone, password);
} catch(Exception e) {
keystore = getKeystoreSinglesig(scriptType, secondClone, password);
}
return keystore;
} catch(IOException e) {
throw new ImportException("Error importing keystore for " + scriptType, e);
}
}
private Keystore getKeystoreSinglesig(ScriptType scriptType, InputStream inputStream, String password) throws ImportException {
ColdcardSinglesig coldcardSinglesig = new ColdcardSinglesig();
return coldcardSinglesig.getKeystore(scriptType, inputStream, password);
}
public Keystore getKeystoreMultisig(ScriptType scriptType, InputStream inputStream, String password) throws ImportException {
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
ColdcardKeystore cck = JsonPersistence.getGson().fromJson(reader, ColdcardKeystore.class);
@@ -86,7 +108,7 @@ public class ColdcardMultisig implements WalletImport, KeystoreFileImport, Walle
@Override
public String getKeystoreImportDescription(int account) {
return "Import file created by using the Settings > Multisig Wallets > Export XPUB > " + account + " feature on your Coldcard.";
return "Import file or QR created by using Advanced/Tools > Export Wallet > Sparrow Wallet" + (account > 0 ? " > 1 > " + account : "") + " on your Coldcard. For older firmware use Settings > Multisig Wallets > Export XPUB > " + account + ".";
}
@Override
@@ -149,8 +171,10 @@ public class ColdcardMultisig implements WalletImport, KeystoreFileImport, Walle
wallet.setDefaultPolicy(policy);
wallet.setScriptType(scriptType);
if(!wallet.isValid()) {
throw new IllegalStateException("This file does not describe a valid wallet. " + getKeystoreImportDescription());
try {
wallet.checkWallet();
} catch(InvalidWalletException e) {
throw new IllegalStateException("This file does not describe a valid wallet: " + e.getMessage());
}
return wallet;
@@ -161,7 +185,7 @@ public class ColdcardMultisig implements WalletImport, KeystoreFileImport, Walle
@Override
public String getWalletImportDescription() {
return "Import file created by using the Settings > Multisig Wallets > [Wallet Detail] > Coldcard Export feature on your Coldcard.";
return "Import file or QR created by using Settings > Multisig Wallets > [Wallet Detail] > Coldcard Export on your Coldcard.";
}
@Override
@@ -214,7 +238,7 @@ public class ColdcardMultisig implements WalletImport, KeystoreFileImport, Walle
@Override
public String getWalletExportDescription() {
return "Export file that can be read by your Coldcard using the Settings > Multisig Wallets > Import from File feature.";
return "Export file or QR that can be read by your Coldcard using Settings > Multisig Wallets > Import from File or QR.";
}
@Override
@@ -30,7 +30,7 @@ public class ColdcardSinglesig implements KeystoreFileImport, WalletImport {
@Override
public String getKeystoreImportDescription(int account) {
return "Import file created by using the Advanced > MicroSD > Export Wallet > Generic JSON > " + account + " feature on your Coldcard. Note this requires firmware version 3.1.3 or later.";
return "Import file or QR created by using Advanced/Tools > Export Wallet > Sparrow Wallet" + (account > 0 ? " > 1 > " + account : "") + " on your Coldcard. For older firmware use Advanced > MicroSD > Export Wallet > Generic JSON > " + account + ".";
}
@Override
@@ -72,7 +72,7 @@ public class ColdcardSinglesig implements KeystoreFileImport, WalletImport {
ColdcardKeystore ck = gson.fromJson(map.get(key), ColdcardKeystore.class);
if(ck.name != null) {
ScriptType ckScriptType = ScriptType.valueOf(ck.name.replace("p2wpkh-p2sh", "p2sh_p2wpkh").replace("p2sh-p2wpkh", "p2sh_p2wpkh").toUpperCase(Locale.ROOT));
ScriptType ckScriptType = ScriptType.valueOf(ck.name.replace("p2wpkh-p2sh", "p2sh_p2wpkh").replace("-", "_").toUpperCase(Locale.ROOT));
if(ckScriptType.equals(scriptType)) {
Keystore keystore = new Keystore();
keystore.setLabel(getName());
@@ -77,7 +77,6 @@ public class Config {
private int maxServerTimeout = DEFAULT_MAX_TIMEOUT;
private int maxPageSize = DEFAULT_PAGE_SIZE;
private boolean usePayNym;
private boolean sameAppMixing;
private boolean mempoolFullRbf;
private Double appWidth;
private Double appHeight;
@@ -662,15 +661,6 @@ public class Config {
flush();
}
public boolean isSameAppMixing() {
return sameAppMixing;
}
public void setSameAppMixing(boolean sameAppMixing) {
this.sameAppMixing = sameAppMixing;
flush();
}
public boolean isMempoolFullRbf() {
return mempoolFullRbf;
}
@@ -328,8 +328,12 @@ public class Electrum implements KeystoreFileImport, WalletImport, WalletExport
ek.derivation = keystore.getKeyDerivation().getDerivationPath();
ek.root_fingerprint = keystore.getKeyDerivation().getMasterFingerprint();
ek.xpub = keystore.getExtendedPublicKey().toString(xpubHeader);
ek.type = "hardware";
ek.hw_type = keystore.getWalletModel().getType();
if(keystore.getWalletModel().hasUsb()) {
ek.type = "hardware";
ek.hw_type = keystore.getWalletModel().getType();
} else {
ek.type = "bip32";
}
ew.use_encryption = false;
} else if(keystore.getSource() == KeystoreSource.SW_SEED) {
ek.type = "bip32";
@@ -36,7 +36,7 @@ public class GordianSeedTool implements KeystoreFileImport {
@Override
public String getKeystoreImportDescription(int account) {
return "Select your seed and scan the QR code created by Authenticate > Derive Key > Other Key Derivations > " + Network.get().toDisplayString() + " > Master Key > Account Descriptor. Click the share icon at the bottom.";
return "Select your seed and scan the QR code created by Authenticate > Derive Key > Other Key Derivations > " + Network.getCanonical().getCapitalizedName() + " > Master Key > Account Descriptor. Click the share icon at the bottom.";
}
@Override
@@ -38,7 +38,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.4.0";
private static final String HWI_VERSION = "3.0.0";
private static final String HWI_VERSION_DIR = HWI_VERSION_PREFIX + HWI_VERSION;
private static boolean isPromptActive = false;
@@ -601,7 +601,7 @@ public class Hwi {
private void addChainType(List<String> elements, boolean commandPresent) {
if(Network.get() != Network.MAINNET) {
elements.add(elements.size() - (commandPresent ? 1 : 0), "--chain");
elements.add(elements.size() - (commandPresent ? 1 : 0), getChainName(Network.get()));
elements.add(elements.size() - (commandPresent ? 1 : 0), getChainName(Network.getCanonical()));
}
}
@@ -22,6 +22,9 @@ import com.sparrowwallet.drongo.protocol.ScriptType;
import com.sparrowwallet.hummingbird.UR;
import com.sparrowwallet.hummingbird.UREncoder;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.io.bbqr.BBQR;
import com.sparrowwallet.sparrow.io.bbqr.BBQREncoder;
import com.sparrowwallet.sparrow.io.bbqr.BBQREncoding;
import javafx.embed.swing.SwingFXUtils;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
@@ -39,7 +42,7 @@ public class PdfUtils {
private static final int QR_WIDTH = 480;
private static final int QR_HEIGHT = 480;
public static void saveOutputDescriptor(String walletName, String outputDescriptor, UR ur) {
public static void saveOutputDescriptor(String walletName, String outputDescriptor, UR ur, BBQR bbqr) {
Stage window = new Stage();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save PDF");
@@ -56,9 +59,22 @@ public class PdfUtils {
Chunk title = new Chunk("Output descriptor for " + walletName, titleFont);
document.add(title);
UREncoder urEncoder = new UREncoder(ur, 2000, 10, 0);
String fragment = urEncoder.nextPart();
if(urEncoder.isSinglePart()) {
String fragment = null;
if(bbqr != null) {
BBQREncoder bbqrEncoder = new BBQREncoder(bbqr.type(), BBQREncoding.ZLIB, bbqr.data(), 2000, 0);
if(bbqrEncoder.isSinglePart()) {
fragment = bbqrEncoder.nextPart();
}
}
if(fragment == null) {
UREncoder urEncoder = new UREncoder(ur, 2000, 10, 0);
if(urEncoder.isSinglePart()) {
fragment = urEncoder.nextPart();
}
}
if(fragment != null) {
Image image = Image.getInstance(SwingFXUtils.fromFXImage(getQrCode(fragment), null), Color.WHITE);
document.add(image);
}
@@ -0,0 +1,99 @@
package com.sparrowwallet.sparrow.io;
import com.google.common.io.CharStreams;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.drongo.crypto.SamouraiUtil;
import com.sparrowwallet.drongo.protocol.ScriptType;
import com.sparrowwallet.drongo.wallet.*;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@SuppressWarnings("deprecation")
public class Samourai implements KeystoreFileImport {
@Override
public String getKeystoreImportDescription(int account) {
return "Import the wallet backup file samourai.txt exported from the Samourai app. Note that see the full balance, several script types may need to imported in separate wallets.";
}
@Override
public Keystore getKeystore(ScriptType scriptType, InputStream inputStream, String password) throws ImportException {
try {
String input = CharStreams.toString(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
Gson gson = new Gson();
Type stringStringMap = new TypeToken<Map<String, JsonElement>>() {
}.getType();
Map<String, JsonElement> map = gson.fromJson(input, stringStringMap);
String payload = input;
if(map.containsKey("payload")) {
payload = map.get("payload").getAsString();
}
int version = 1;
if(map.containsKey("version")) {
version = map.get("version").getAsInt();
}
String decrypted;
if(version == 1) {
decrypted = SamouraiUtil.decrypt(payload, password, SamouraiUtil.DefaultPBKDF2Iterations);
} else if(version == 2) {
decrypted = SamouraiUtil.decryptSHA256(payload, password);
} else {
throw new ImportException("Unsupported backup version: " + version);
}
SamouraiBackup backup = gson.fromJson(decrypted, SamouraiBackup.class);
DeterministicSeed seed = new DeterministicSeed(Utils.hexToBytes(backup.wallet.seed), password, 0);
Keystore keystore = Keystore.fromSeed(seed, scriptType.getDefaultDerivation());
keystore.setLabel(getWalletModel().toDisplayString());
return keystore;
} catch(JsonParseException e) {
throw new ImportException("Failed to decrypt the wallet backup file, check if the password is correct.");
} catch(ImportException e) {
throw e;
} catch(Exception e) {
throw new ImportException("Error importing backup", e);
}
}
@Override
public boolean isKeystoreImportScannable() {
return false;
}
@Override
public boolean isEncrypted(File file) {
return true;
}
@Override
public String getName() {
return "Samourai Backup";
}
@Override
public WalletModel getWalletModel() {
return WalletModel.SAMOURAI;
}
private static class SamouraiBackup {
public SamouraiWallet wallet;
}
private static class SamouraiWallet {
public boolean testnet;
public String seed;
public String fingerprint;
}
}
@@ -8,8 +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.soroban.Soroban;
import com.sparrowwallet.sparrow.whirlpool.Whirlpool;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
@@ -21,6 +19,7 @@ import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.cert.Certificate;
@@ -174,15 +173,6 @@ public class Storage {
}
}
if(wallet.isWhirlpoolMasterWallet()) {
String walletId = getWalletId(wallet);
Whirlpool whirlpool = AppServices.getWhirlpoolServices().getWhirlpool(walletId);
whirlpool.setScode(wallet.getMasterMixConfig().getScode());
whirlpool.setHDWallet(getWalletId(wallet), copy);
Soroban soroban = AppServices.getSorobanServices().getSoroban(walletId);
soroban.setHDWallet(copy);
}
StandardAccount standardAccount = wallet.getStandardAccountType();
if(standardAccount != null && standardAccount.getMinimumGapLimit() != null && wallet.gapLimit() == null) {
wallet.setGapLimit(standardAccount.getMinimumGapLimit());
@@ -227,8 +217,8 @@ public class Storage {
}
private void checkWalletNetwork(Wallet wallet) {
if(wallet.getNetwork() != null && wallet.getNetwork() != Network.get()) {
throw new IllegalStateException("Provided " + wallet.getNetwork() + " wallet is invalid on a " + Network.get() + " network. Use a " + wallet.getNetwork() + " configuration to load this wallet.");
if(wallet.getNetwork() != null && wallet.getNetwork() != Network.getCanonical()) {
throw new IllegalStateException("Provided " + wallet.getNetwork() + " wallet is invalid on a " + Network.getCanonical() + " network. Use a " + wallet.getNetwork() + " configuration to load this wallet.");
}
}
@@ -535,10 +525,23 @@ public class Storage {
return certsDir;
}
static File getSparrowDir() {
public static File getSparrowDir() {
File sparrowDir;
if(Network.get() != Network.MAINNET) {
sparrowDir = new File(getSparrowHome(), Network.get().getName());
Network network = Network.get();
if(network != Network.MAINNET) {
sparrowDir = new File(getSparrowHome(), network.getHome());
if(!network.getName().equals(network.getHome()) && !sparrowDir.exists()) {
File networkNameDir = new File(getSparrowHome(), network.getName());
if(networkNameDir.exists() && networkNameDir.isDirectory() && !Files.isSymbolicLink(networkNameDir.toPath())) {
try {
if(networkNameDir.renameTo(sparrowDir) && !isWindows()) {
Files.createSymbolicLink(networkNameDir.toPath(), Path.of(sparrowDir.getName()));
}
} catch(Exception e) {
log.debug("Error creating symlink from " + networkNameDir.getAbsolutePath() + " to " + sparrowDir.getName(), e);
}
}
}
} else {
sparrowDir = getSparrowHome();
}
@@ -547,15 +550,36 @@ public class Storage {
createOwnerOnlyDirectory(sparrowDir);
}
if(!network.getName().equals(network.getHome()) && !isWindows()) {
try {
Path networkNamePath = getSparrowHome().toPath().resolve(network.getName());
if(Files.isSymbolicLink(networkNamePath)) {
Path symlinkTarget = getSparrowHome().toPath().resolve(Files.readSymbolicLink(networkNamePath));
if(!Files.isSameFile(sparrowDir.toPath(), symlinkTarget)) {
Files.delete(networkNamePath);
Files.createSymbolicLink(networkNamePath, Path.of(sparrowDir.getName()));
}
} else if(!Files.exists(networkNamePath)) {
Files.createSymbolicLink(networkNamePath, Path.of(sparrowDir.getName()));
}
} catch(Exception e) {
log.debug("Error updating symlink from " + network.getName() + " to " + sparrowDir.getName(), e);
}
}
return sparrowDir;
}
public static File getSparrowHome() {
if(System.getProperty(SparrowWallet.APP_HOME_PROPERTY) != null) {
return getSparrowHome(false);
}
public static File getSparrowHome(boolean useDefault) {
if(!useDefault && System.getProperty(SparrowWallet.APP_HOME_PROPERTY) != null) {
return new File(System.getProperty(SparrowWallet.APP_HOME_PROPERTY));
}
if(Platform.getCurrent() == Platform.WINDOWS) {
if(isWindows()) {
return new File(getHomeDir(), WINDOWS_SPARROW_DIR);
}
@@ -563,7 +587,7 @@ public class Storage {
}
static File getHomeDir() {
if(Platform.getCurrent() == Platform.WINDOWS) {
if(isWindows()) {
return new File(System.getenv("APPDATA"));
}
@@ -572,7 +596,7 @@ public class Storage {
public static boolean createOwnerOnlyDirectory(File directory) {
try {
if(Platform.getCurrent() == Platform.WINDOWS) {
if(isWindows()) {
Files.createDirectories(directory.toPath());
return true;
}
@@ -590,7 +614,7 @@ public class Storage {
public static boolean createOwnerOnlyFile(File file) {
try {
if(Platform.getCurrent() == Platform.WINDOWS) {
if(isWindows()) {
Files.createFile(file.toPath());
return true;
}
@@ -621,6 +645,10 @@ public class Storage {
return ownerOnly;
}
private static boolean isWindows() {
return Platform.getCurrent() == Platform.WINDOWS;
}
public static class LoadWalletService extends Service<WalletAndKey> {
private final Storage storage;
private final SecureString password;
@@ -1,8 +1,10 @@
package com.sparrowwallet.sparrow.io;
import com.csvreader.CsvReader;
import com.google.gson.Gson;
import com.sparrowwallet.drongo.KeyPurpose;
import com.sparrowwallet.drongo.OutputDescriptor;
import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.drongo.wallet.*;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.EventManager;
@@ -122,7 +124,7 @@ public class WalletLabels implements WalletImport, WalletExport {
@Override
public String getWalletImportDescription() {
return "Imports a file containing labels in the BIP329 standard format to the currently selected wallet.";
return "Imports a file containing labels in the BIP329 standard (or Electrum history CSV) format to the currently selected wallet.";
}
@Override
@@ -141,7 +143,17 @@ public class WalletLabels implements WalletImport, WalletExport {
try {
label = gson.fromJson(line, Label.class);
} catch(Exception e) {
continue;
//Try parse Electrum history CSV, or any CSV with txid,label entries
try {
CsvReader csvReader = new CsvReader(new StringReader(line));
if(csvReader.readRecord() && csvReader.getColumnCount() > 1 && csvReader.get(0).length() == 64 && Utils.isHex(csvReader.get(0))) {
label = new Label(Type.tx, csvReader.get(0), csvReader.get(1), null, null);
} else {
continue;
}
} catch(Exception ex) {
continue;
}
}
if(label == null || label.type == null || label.ref == null) {
@@ -31,6 +31,10 @@ public class WalletTransactions implements WalletExport {
private final WalletForm walletForm;
static {
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public WalletTransactions(WalletForm walletForm) {
this.walletForm = walletForm;
}
@@ -72,7 +76,7 @@ public class WalletTransactions implements WalletExport {
try {
CsvWriter writer = new CsvWriter(outputStream, ',', StandardCharsets.UTF_8);
writer.write("Date");
writer.write("Date (UTC)");
writer.write("Label");
writer.write("Value");
writer.write("Balance");
@@ -37,6 +37,7 @@ public class BBQRDecoder {
if(receivedParts.size() == totalParts) {
byte[] data = concatParts();
data = header.inflate(data);
if(type == BBQRType.PSBT) {
result = new Result(new PSBT(data));
@@ -35,7 +35,7 @@ public class BBQREncoder {
BBQREncoding encoding = desiredEncoding;
try {
encoded = encoding.encode(data);
encoded = encoding.encode(encoding.deflate(data));
if(encoding == BBQREncoding.ZLIB) {
String uncompressed = BBQREncoding.BASE32.encode(data);
if(encoded.length() > uncompressed.length()) {
@@ -42,6 +42,11 @@ public enum BBQREncoding {
}, ZLIB("Z") {
@Override
public String encode(byte[] data) throws BBQREncodingException {
return BASE32.encode(data);
}
@Override
public byte[] deflate(byte[] data) throws BBQREncodingException {
try {
Deflater deflater = new Deflater(JZlib.Z_BEST_COMPRESSION, 10, true);
ByteArrayOutputStream out = new ByteArrayOutputStream();
@@ -49,7 +54,7 @@ public enum BBQREncoding {
zOut.write(data);
zOut.close();
return BASE32.encode(out.toByteArray());
return out.toByteArray();
} catch(Exception e) {
throw new BBQREncodingException("Error deflating with zlib", e);
}
@@ -57,9 +62,14 @@ public enum BBQREncoding {
@Override
public byte[] decode(String part) throws BBQREncodingException {
return BASE32.decode(part);
}
@Override
public byte[] inflate(byte[] data) throws BBQREncodingException {
try {
Inflater inflater = new Inflater(10, true);
ByteArrayInputStream in = new ByteArrayInputStream(BASE32.decode(part));
ByteArrayInputStream in = new ByteArrayInputStream(data);
InflaterInputStream zIn = new InflaterInputStream(in, inflater);
byte[] decoded = zIn.readAllBytes();
zIn.close();
@@ -96,6 +106,14 @@ public enum BBQREncoding {
return code;
}
public byte[] deflate(byte[] data) throws BBQREncodingException {
return data;
}
public byte[] inflate(byte[] data) throws BBQREncodingException {
return data;
}
public abstract String encode(byte[] data) throws BBQREncodingException;
public abstract byte[] decode(String part) throws BBQREncodingException;
@@ -13,6 +13,10 @@ public record BBQRHeader(BBQREncoding encoding, BBQRType type, int seqTotal, int
return encoding.decode(part.substring(8));
}
public byte[] inflate(byte[] data) {
return encoding.inflate(data);
}
public static BBQRHeader fromString(String part) {
if(part.length() < 8) {
throw new IllegalArgumentException("Part too short");
@@ -256,7 +256,10 @@ public class DbPersistence implements Persistence {
}
for(Sha256Hash txid : referencedTxIds) {
BlockTransaction blkTx = wallet.getTransactions().get(txid);
blockTransactionDao.addOrUpdate(wallet, txid, blkTx);
//May be null for a nested wallet if still updating
if(blkTx != null) {
blockTransactionDao.addOrUpdate(wallet, txid, blkTx);
}
}
if(!dirtyPersistables.clearHistory) {
DetachedLabelDao detachedLabelDao = handle.attach(DetachedLabelDao.class);
@@ -31,6 +31,7 @@ public class KeystoreImportController implements Initializable {
@FXML
private StackPane importPane;
private KeyDerivation defaultDerivation;
private KeyDerivation requiredDerivation;
private WalletModel requiredModel;
@@ -110,6 +111,14 @@ public class KeystoreImportController implements Initializable {
}
}
public KeyDerivation getDefaultDerivation() {
return defaultDerivation;
}
public void setDefaultDerivation(KeyDerivation defaultDerivation) {
this.defaultDerivation = defaultDerivation;
}
public KeyDerivation getRequiredDerivation() {
return requiredDerivation;
}
@@ -29,7 +29,7 @@ public class KeystoreImportDialog extends Dialog<Keystore> {
this(wallet, initialSource, null, null, false);
}
public KeystoreImportDialog(Wallet wallet, KeystoreSource initialSource, KeyDerivation requiredDerivation, WalletModel requiredModel, boolean restrictSource) {
public KeystoreImportDialog(Wallet wallet, KeystoreSource initialSource, KeyDerivation currentDerivation, WalletModel currentModel, boolean restrictImport) {
EventManager.get().register(this);
setOnCloseRequest(event -> {
EventManager.get().unregister(this);
@@ -43,12 +43,15 @@ public class KeystoreImportDialog extends Dialog<Keystore> {
dialogPane.setContent(Borders.wrap(ksiLoader.load()).emptyBorder().buildAll());
keystoreImportController = ksiLoader.getController();
keystoreImportController.initializeView(wallet);
keystoreImportController.selectSource(initialSource, restrictSource);
keystoreImportController.setRequiredDerivation(requiredDerivation);
keystoreImportController.setRequiredModel(requiredModel);
keystoreImportController.selectSource(initialSource, restrictImport);
keystoreImportController.setDefaultDerivation(currentDerivation);
if(restrictImport) {
keystoreImportController.setRequiredDerivation(currentDerivation);
keystoreImportController.setRequiredModel(currentModel);
}
final ButtonType watchOnlyButtonType = new javafx.scene.control.ButtonType(Network.get().getXpubHeader().getDisplayName() + " / Watch Only Wallet", ButtonBar.ButtonData.LEFT);
if(!restrictSource) {
if(!restrictImport) {
dialogPane.getButtonTypes().add(watchOnlyButtonType);
}
final ButtonType cancelButtonType = new javafx.scene.control.ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
@@ -27,9 +27,9 @@ public class SwController extends KeystoreImportDetailController {
if(importer instanceof KeystoreFileImport) {
importPane = new FileKeystoreImportPane(getMasterController().getWallet(), (KeystoreFileImport)importer, getMasterController().getRequiredDerivation());
} else if(importer instanceof KeystoreMnemonicImport) {
importPane = new MnemonicKeystoreImportPane(getMasterController().getWallet(), (KeystoreMnemonicImport)importer);
importPane = new MnemonicKeystoreImportPane(getMasterController().getWallet(), (KeystoreMnemonicImport)importer, getMasterController().getDefaultDerivation());
} else if(importer instanceof KeystoreXprvImport) {
importPane = new XprvKeystoreImportPane(getMasterController().getWallet(), (KeystoreXprvImport)importer);
importPane = new XprvKeystoreImportPane(getMasterController().getWallet(), (KeystoreXprvImport)importer, getMasterController().getDefaultDerivation());
} else {
throw new IllegalArgumentException("Could not create ImportPane for importer of type " + importer.getClass());
}
@@ -5,8 +5,8 @@ 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 com.sparrowwallet.sparrow.net.http.client.HttpResponseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -46,7 +46,7 @@ public enum BroadcastSource {
@Override
public List<Network> getSupportedNetworks() {
return List.of(Network.MAINNET, Network.TESTNET, Network.SIGNET);
return List.of(Network.MAINNET, Network.TESTNET, Network.SIGNET, Network.TESTNET4);
}
protected URL getURL(HostAndPort proxy) throws MalformedURLException {
@@ -56,6 +56,8 @@ public enum BroadcastSource {
return new URL(getBaseUrl(proxy) + "/testnet/api/tx");
} else if(Network.get() == Network.SIGNET) {
return new URL(getBaseUrl(proxy) + "/signet/api/tx");
} else if(Network.get() == Network.TESTNET4) {
return new URL(getBaseUrl(proxy) + "/testnet4/api/tx");
} else {
throw new IllegalStateException("Cannot broadcast transaction to " + getName() + " on network " + Network.get());
}
@@ -77,6 +79,8 @@ public enum BroadcastSource {
return new URL(getBaseUrl(proxy) + "/api/tx");
} else if(Network.get() == Network.TESTNET) {
return new URL(getBaseUrl(proxy) + "/testnet/api/tx");
} else if(Network.get() == Network.SIGNET) {
return new URL(getBaseUrl(proxy) + "/signet/api/tx");
} else {
throw new IllegalStateException("Cannot broadcast transaction to " + getName() + " on network " + Network.get());
}
@@ -158,7 +162,7 @@ public enum BroadcastSource {
} catch(Exception e) {
throw new BroadcastException("Could not retrieve txid from broadcast, server returned: " + response);
}
} catch(JavaHttpException e) {
} catch(HttpResponseException 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);
@@ -119,7 +119,7 @@ public class Bwt {
*/
private void start(Collection<String> outputDescriptors, Collection<String> addresses, Integer rescanSince, Boolean forceRescan, Integer gapLimit, CallbackNotifier callback) {
BwtConfig bwtConfig = new BwtConfig();
bwtConfig.network = Network.get() == Network.MAINNET ? "bitcoin" : Network.get().getName();
bwtConfig.network = Network.get() == Network.MAINNET ? "bitcoin" : Network.getCanonical().getName();
if(!outputDescriptors.isEmpty()) {
bwtConfig.descriptors = outputDescriptors;
@@ -812,12 +812,18 @@ public class ElectrumServer {
return transactionMap;
}
public Map<Integer, Double> getFeeEstimates(List<Integer> targetBlocks) throws ServerException {
public Map<Integer, Double> getFeeEstimates(List<Integer> targetBlocks, boolean useCached) 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)) {
if(!feeRatesSource.isExternal()) {
targetBlocksFeeRatesSats.putAll(feeRatesSource.getBlockTargetFeeRates(targetBlocksFeeRatesSats));
} else if(useCached) {
if(AppServices.getTargetBlockFeeRates() != null) {
targetBlocksFeeRatesSats.putAll(AppServices.getTargetBlockFeeRates());
}
} else if(Network.get().equals(Network.MAINNET)) {
targetBlocksFeeRatesSats.putAll(feeRatesSource.getBlockTargetFeeRates(targetBlocksFeeRatesSats));
}
@@ -1204,7 +1210,7 @@ public class ElectrumServer {
String banner = electrumServer.getServerBanner();
Map<Integer, Double> blockTargetFeeRates = electrumServer.getFeeEstimates(AppServices.TARGET_BLOCKS_RANGE);
Map<Integer, Double> blockTargetFeeRates = electrumServer.getFeeEstimates(AppServices.TARGET_BLOCKS_RANGE, true);
Set<MempoolRateSize> mempoolRateSizes = electrumServer.getMempoolRateSizes();
feeRatesRetrievedAt = System.currentTimeMillis();
@@ -1220,7 +1226,7 @@ public class ElectrumServer {
long elapsed = System.currentTimeMillis() - feeRatesRetrievedAt;
if(elapsed > FEE_RATES_PERIOD) {
Map<Integer, Double> blockTargetFeeRates = electrumServer.getFeeEstimates(AppServices.TARGET_BLOCKS_RANGE);
Map<Integer, Double> blockTargetFeeRates = electrumServer.getFeeEstimates(AppServices.TARGET_BLOCKS_RANGE, false);
Set<MempoolRateSize> mempoolRateSizes = electrumServer.getMempoolRateSizes();
feeRatesRetrievedAt = System.currentTimeMillis();
return new FeeRatesUpdatedEvent(blockTargetFeeRates, mempoolRateSizes);
@@ -1679,9 +1685,8 @@ public class ElectrumServer {
return new Task<>() {
protected FeeRatesUpdatedEvent call() throws ServerException {
ElectrumServer electrumServer = new ElectrumServer();
Map<Integer, Double> blockTargetFeeRates = electrumServer.getFeeEstimates(AppServices.TARGET_BLOCKS_RANGE);
Set<MempoolRateSize> mempoolRateSizes = electrumServer.getMempoolRateSizes();
return new FeeRatesUpdatedEvent(blockTargetFeeRates, mempoolRateSizes);
Map<Integer, Double> blockTargetFeeRates = electrumServer.getFeeEstimates(AppServices.TARGET_BLOCKS_RANGE, false);
return new FeeRatesUpdatedEvent(blockTargetFeeRates, null);
}
};
}
@@ -1,8 +1,8 @@
package com.sparrowwallet.sparrow.net;
import com.sparrowwallet.nightjar.http.JavaHttpException;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.event.ExchangeRatesUpdatedEvent;
import com.sparrowwallet.sparrow.net.http.client.HttpResponseException;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
@@ -107,7 +107,7 @@ public enum ExchangeSource {
if(log.isDebugEnabled()) {
log.warn("Error retrieving historical currency rates", e);
} else {
if(e instanceof JavaHttpException javaHttpException && javaHttpException.getStatusCode() == 404) {
if(e instanceof HttpResponseException httpException && httpException.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() + ")");
@@ -9,27 +9,27 @@ import java.util.LinkedHashMap;
import java.util.Map;
public enum FeeRatesSource {
ELECTRUM_SERVER("Server") {
ELECTRUM_SERVER("Server", false) {
@Override
public Map<Integer, Double> getBlockTargetFeeRates(Map<Integer, Double> defaultblockTargetFeeRates) {
return Collections.emptyMap();
}
},
MEMPOOL_SPACE("mempool.space") {
MEMPOOL_SPACE("mempool.space", true) {
@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(this, defaultblockTargetFeeRates, url);
}
},
BITCOINFEES_EARN_COM("bitcoinfees.earn.com") {
BITCOINFEES_EARN_COM("bitcoinfees.earn.com", true) {
@Override
public Map<Integer, Double> getBlockTargetFeeRates(Map<Integer, Double> defaultblockTargetFeeRates) {
String url = "https://bitcoinfees.earn.com/api/v1/fees/recommended";
return getThreeTierFeeRates(this, defaultblockTargetFeeRates, url);
}
},
MINIMUM("Minimum (1 sat/vB)") {
MINIMUM("Minimum (1 sat/vB)", false) {
@Override
public Map<Integer, Double> getBlockTargetFeeRates(Map<Integer, Double> defaultblockTargetFeeRates) {
Map<Integer, Double> blockTargetFeeRates = new LinkedHashMap<>();
@@ -40,7 +40,7 @@ public enum FeeRatesSource {
return blockTargetFeeRates;
}
},
OXT_ME("oxt.me") {
OXT_ME("oxt.me", true) {
@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";
@@ -63,9 +63,11 @@ public enum FeeRatesSource {
public static final int BLOCKS_IN_TWO_HOURS = 12;
private final String name;
private final boolean external;
FeeRatesSource(String name) {
FeeRatesSource(String name, boolean external) {
this.name = name;
this.external = external;
}
public abstract Map<Integer, Double> getBlockTargetFeeRates(Map<Integer, Double> defaultblockTargetFeeRates);
@@ -74,6 +76,10 @@ public enum FeeRatesSource {
return name;
}
public boolean isExternal() {
return external;
}
private static Map<Integer, Double> getThreeTierFeeRates(FeeRatesSource feeRatesSource, Map<Integer, Double> defaultblockTargetFeeRates, String url) {
if(log.isInfoEnabled()) {
log.info("Requesting fee rates from " + url);
@@ -1,57 +1,50 @@
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 com.sparrowwallet.sparrow.net.http.client.AsyncUtil;
import com.sparrowwallet.sparrow.net.http.client.HttpUsage;
import com.sparrowwallet.sparrow.net.http.client.IHttpClient;
import com.sparrowwallet.sparrow.net.http.client.JettyHttpClientService;
import io.reactivex.Observable;
import java8.util.Optional;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import java.util.Map;
import java.util.Optional;
public class HttpClientService {
private final JavaHttpClientService httpClientService;
public class HttpClientService extends JettyHttpClientService {
private static final int REQUEST_TIMEOUT = 120000;
public HttpClientService(HostAndPort torProxy) {
this.httpClientService = new JavaHttpClientService(torProxy, 120000);
super(REQUEST_TIMEOUT, new HttpProxySupplier(torProxy));
}
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);
return getHttpClient(HttpUsage.DEFAULT).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);
return getHttpClient(HttpUsage.DEFAULT).postJson(url, responseType, headers, body).toObservable();
}
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);
}
IHttpClient httpClient = getHttpClient(HttpUsage.DEFAULT);
return AsyncUtil.getInstance().blockingGet(httpClient.postString(url, headers, contentType, content)).get();
}
public HostAndPort getTorProxy() {
return httpClientService.getTorProxy();
return getHttpProxySupplier().getTorProxy();
}
public void setTorProxy(HostAndPort torProxy) {
//Ensure all http clients are shutdown first
httpClientService.shutdown();
httpClientService.setTorProxy(torProxy);
stop();
getHttpProxySupplier()._setTorProxy(torProxy);
}
public void shutdown() {
httpClientService.shutdown();
@Override
public HttpProxySupplier getHttpProxySupplier() {
return (HttpProxySupplier)super.getHttpProxySupplier();
}
public static class ShutdownService extends Service<Boolean> {
@@ -65,7 +58,7 @@ public class HttpClientService {
protected Task<Boolean> createTask() {
return new Task<>() {
protected Boolean call() throws Exception {
httpClientService.shutdown();
httpClientService.stop();
return true;
}
};
@@ -0,0 +1,51 @@
package com.sparrowwallet.sparrow.net;
import com.google.common.net.HostAndPort;
import com.sparrowwallet.sparrow.net.http.client.HttpProxy;
import com.sparrowwallet.sparrow.net.http.client.HttpProxyProtocol;
import com.sparrowwallet.sparrow.net.http.client.HttpUsage;
import com.sparrowwallet.sparrow.net.http.client.IHttpProxySupplier;
import java.util.Optional;
public class HttpProxySupplier implements IHttpProxySupplier {
private HostAndPort torProxy;
private HttpProxy httpProxy;
public HttpProxySupplier(HostAndPort torProxy) {
this.torProxy = torProxy;
this.httpProxy = computeHttpProxy(torProxy);
}
private HttpProxy computeHttpProxy(HostAndPort hostAndPort) {
if (hostAndPort == null) {
return null;
}
return new HttpProxy(HttpProxyProtocol.SOCKS, hostAndPort.getHost(), hostAndPort.getPort());
}
public HostAndPort getTorProxy() {
return torProxy;
}
// shouldnt call directly but use httpClientService.setTorProxy()
public void _setTorProxy(HostAndPort hostAndPort) {
// set proxy
this.torProxy = hostAndPort;
this.httpProxy = computeHttpProxy(hostAndPort);
}
@Override
public Optional<HttpProxy> getHttpProxy(HttpUsage httpUsage) {
return Optional.ofNullable(httpProxy);
}
@Override
public void changeIdentity() {
HostAndPort torProxy = getTorProxy();
if(torProxy != null) {
TorUtils.changeIdentity(torProxy);
}
}
}
@@ -17,14 +17,15 @@ public enum PublicElectrumServer {
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),
SIGNET_MEMPOOL_SPACE("mempool.space", "ssl://mempool.space:60602", Network.SIGNET);
SIGNET_MEMPOOL_SPACE("mempool.space", "ssl://mempool.space:60602", Network.SIGNET),
TESTNET4_MEMPOOL_SPACE("mempool.space", "ssl://mempool.space:40002", Network.TESTNET4);
PublicElectrumServer(String name, String url, Network network) {
this.server = new Server(url, name);
this.network = network;
}
public static final List<Network> SUPPORTED_NETWORKS = List.of(Network.MAINNET, Network.TESTNET, Network.SIGNET);
public static final List<Network> SUPPORTED_NETWORKS = List.of(Network.MAINNET, Network.TESTNET, Network.SIGNET, Network.TESTNET4);
private final Server server;
private final Network network;
@@ -1,16 +1,26 @@
package com.sparrowwallet.sparrow.net;
import com.google.common.net.HostAndPort;
import com.sparrowwallet.drongo.Utils;
import com.sparrowwallet.sparrow.AppServices;
import io.matthewnelson.kmp.tor.controller.common.control.usecase.TorControlSignal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.*;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.file.AccessDeniedException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TorUtils {
private static final Logger log = LoggerFactory.getLogger(TorUtils.class);
private static final Pattern TOR_OK = Pattern.compile("^2\\d{2}[ -]OK$");
private static final Pattern TOR_AUTH_METHODS = Pattern.compile("^2\\d{2}[ -]AUTH METHODS=(\\S+)\\s?(COOKIEFILE=\"?(.+?)\"?)?$");
public static void changeIdentity(HostAndPort proxy) {
if(AppServices.isTorRunning()) {
@@ -22,16 +32,66 @@ public class TorUtils {
} else {
HostAndPort control = HostAndPort.fromParts(proxy.getHost(), proxy.getPort() + 1);
try(Socket socket = new Socket(control.getHost(), control.getPort())) {
writeNewNym(socket);
socket.setSoTimeout(1500);
if(authenticate(socket)) {
writeNewNym(socket);
}
} catch(TorAuthenticationException e) {
log.warn("Error authenticating to Tor at " + control + ", server returned " + e.getMessage());
} catch(SocketTimeoutException e) {
log.warn("Timeout reading from " + control + ", is this a Tor ControlPort?");
} catch(AccessDeniedException e) {
log.warn("Permission denied reading Tor cookie file at " + e.getFile());
} catch(FileSystemException e) {
log.warn("Error reading Tor cookie file at " + e.getFile());
} catch(Exception e) {
log.warn("Error connecting to " + control + ", no Tor ControlPort configured?");
}
}
}
private static boolean authenticate(Socket socket) throws IOException, TorAuthenticationException {
socket.getOutputStream().write("PROTOCOLINFO\r\n".getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
File cookieFile = null;
while((line = reader.readLine()) != null) {
Matcher authMatcher = TOR_AUTH_METHODS.matcher(line);
if(authMatcher.matches()) {
String methods = authMatcher.group(1);
if(methods.contains("COOKIE") && !authMatcher.group(3).isEmpty()) {
cookieFile = new File(authMatcher.group(3));
}
}
if(TOR_OK.matcher(line).matches()) {
break;
}
}
if(cookieFile != null && cookieFile.exists()) {
byte[] cookieBytes = Files.readAllBytes(cookieFile.toPath());
String authentication = "AUTHENTICATE " + Utils.bytesToHex(cookieBytes) + "\r\n";
socket.getOutputStream().write(authentication.getBytes());
} else {
socket.getOutputStream().write("AUTHENTICATE \"\"\r\n".getBytes());
}
line = reader.readLine();
if(TOR_OK.matcher(line).matches()) {
return true;
} else {
throw new TorAuthenticationException(line);
}
}
private static void writeNewNym(Socket socket) throws IOException {
log.debug("Sending NEWNYM to " + socket);
socket.getOutputStream().write("AUTHENTICATE \"\"\r\n".getBytes());
socket.getOutputStream().write("SIGNAL NEWNYM\r\n".getBytes());
}
private static class TorAuthenticationException extends Exception {
public TorAuthenticationException(String message) {
super(message);
}
}
}
@@ -130,6 +130,8 @@ public class BitcoindTransport implements Transport {
private static File getCookieDir(File bitcoindDir) {
if(Network.get() == Network.TESTNET && Files.exists(Path.of(bitcoindDir.getAbsolutePath(), "testnet3", COOKIE_FILENAME))) {
return new File(bitcoindDir, "testnet3");
} else if(Network.get() == Network.TESTNET4 && Files.exists(Path.of(bitcoindDir.getAbsolutePath(), "testnet4", COOKIE_FILENAME))) {
return new File(bitcoindDir, "testnet4");
} else if(Network.get() == Network.REGTEST && Files.exists(Path.of(bitcoindDir.getAbsolutePath(), "regtest", COOKIE_FILENAME))) {
return new File(bitcoindDir, "regtest");
} else if(Network.get() == Network.SIGNET && Files.exists(Path.of(bitcoindDir.getAbsolutePath(), "signet", COOKIE_FILENAME))) {
@@ -0,0 +1,150 @@
package com.sparrowwallet.sparrow.net.http.client;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;
import org.slf4j.MDC;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
public class AsyncUtil {
private static final ThreadUtil threadUtil = ThreadUtil.getInstance();
private static AsyncUtil instance;
public static AsyncUtil getInstance() {
if(instance == null) {
instance = new AsyncUtil();
}
return instance;
}
public <T> T unwrapException(Callable<T> c) throws Exception {
try {
return c.call();
} catch(RuntimeException e) {
// blockingXXX wraps errors with RuntimeException, unwrap it
throw unwrapException(e);
}
}
public Exception unwrapException(Exception e) throws Exception {
if(e.getCause() != null && e.getCause() instanceof Exception) {
throw (Exception) e.getCause();
}
throw e;
}
public <T> T blockingGet(Single<T> o) throws Exception {
try {
return unwrapException(o::blockingGet);
} catch(ExecutionException e) {
// blockingGet(threadUtil.runWithTimeoutAndRetry()) wraps InterruptedException("exit (done)")
// with ExecutionException, unwrap it
throw unwrapException(e);
}
}
public <T> T blockingGet(Single<T> o, long timeoutMs) throws Exception {
Callable<T> callable = () -> blockingGet(o);
return blockingGet(runAsync(callable, timeoutMs));
}
public <T> T blockingGet(Future<T> o, long timeoutMs) throws Exception {
return o.get(timeoutMs, TimeUnit.MILLISECONDS);
}
public <T> T blockingLast(Observable<T> o) throws Exception {
return unwrapException(o::blockingLast);
}
public void blockingAwait(Completable o) throws Exception {
Callable<Optional> callable = () -> {
o.blockingAwait();
return Optional.empty();
};
unwrapException(callable);
}
public void blockingAwait(Completable o, long timeoutMs) throws Exception {
Callable<Optional> callable = () -> {
o.blockingAwait();
return Optional.empty();
};
blockingGet(runAsync(callable, timeoutMs));
}
public <T> Single<T> timeout(Single<T> o, long timeoutMs) {
try {
return Single.just(blockingGet(o, timeoutMs));
} catch(Exception e) {
return Single.error(e);
}
}/*
public Completable timeout(Completable o, long timeoutMs) {
try {
return Completable.fromCallable(() -> {
blockingAwait(o, timeoutMs);
return Optional.empty();
});
} catch (Exception e) {
return Completable.error(e);
}
}*/
public <T> Single<T> runIOAsync(final Callable<T> callable) {
return Single.fromCallable(callable).subscribeOn(Schedulers.io());
}
public Completable runIOAsyncCompletable(final Action action) {
return Completable.fromAction(action).subscribeOn(Schedulers.io());
}
public <T> T runIO(final Callable<T> callable) throws Exception {
return blockingGet(runIOAsync(callable));
}
public void runIO(final Action action) throws Exception {
blockingAwait(runIOAsyncCompletable(action));
}
public Completable runAsync(Runnable runnable, long timeoutMs) {
Future<?> future = runAsync(() -> {
runnable.run();
return Optional.empty(); // must return an object for using Completable.fromSingle()
});
return Completable.fromSingle(Single.fromFuture(future, timeoutMs, TimeUnit.MILLISECONDS));
}
public <T> Future<T> runAsync(Callable<T> callable) {
// preserve logging context
String mdc = mdcAppend("runAsync=" + System.currentTimeMillis());
return threadUtil.runAsync(() -> {
MDC.put("mdc", mdc);
return callable.call();
});
}
public <T> Single<T> runAsync(Callable<T> callable, long timeoutMs) {
Future<T> future = runAsync(callable);
return Single.fromFuture(future, timeoutMs, TimeUnit.MILLISECONDS);
}
private static String mdcAppend(String info) {
String mdc = MDC.get("mdc");
if(mdc == null) {
mdc = "";
} else {
mdc += ",";
}
mdc += info;
return mdc;
}
}
@@ -0,0 +1,12 @@
package com.sparrowwallet.sparrow.net.http.client;
public abstract class HttpException extends Exception {
public HttpException(Exception cause) {
super(cause);
}
public HttpException(String message) {
super(message);
}
}
@@ -0,0 +1,11 @@
package com.sparrowwallet.sparrow.net.http.client;
public class HttpNetworkException extends HttpException {
public HttpNetworkException(String message) {
super(message);
}
public HttpNetworkException(Exception cause) {
super(cause);
}
}
@@ -0,0 +1,41 @@
package com.sparrowwallet.sparrow.net.http.client;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
public class HttpProxy {
private final HttpProxyProtocol protocol;
private final String host;
private final int port;
public HttpProxy(HttpProxyProtocol protocol, String host, int port) {
this.protocol = protocol;
this.host = host;
this.port = port;
}
public static boolean validate(String proxy) {
// check protocol
String[] protocols = Arrays.stream(HttpProxyProtocol.values()).map(p -> p.name()).toArray(String[]::new);
String regex = "^(" + StringUtils.join(protocols, "|").toLowerCase() + ")://(.+?):([0-9]+)";
return proxy.trim().toLowerCase().matches(regex);
}
public HttpProxyProtocol getProtocol() {
return protocol;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
@Override
public String toString() {
return protocol + "://" + host + ":" + port;
}
}
@@ -0,0 +1,17 @@
package com.sparrowwallet.sparrow.net.http.client;
import java.util.Optional;
public enum HttpProxyProtocol {
HTTP,
SOCKS,
SOCKS5;
public static Optional<HttpProxyProtocol> find(String value) {
try {
return Optional.of(valueOf(value));
} catch(Exception e) {
return Optional.empty();
}
}
}
@@ -0,0 +1,38 @@
package com.sparrowwallet.sparrow.net.http.client;
public class HttpResponseException extends HttpException {
private final String responseBody;
private final int statusCode;
public HttpResponseException(Exception cause, String responseBody, int statusCode) {
super(cause);
this.responseBody = responseBody;
this.statusCode = statusCode;
}
public HttpResponseException(String message, String responseBody, int statusCode) {
super(message);
this.responseBody = responseBody;
this.statusCode = statusCode;
}
public HttpResponseException(String responseBody, int statusCode) {
this("response statusCode=" + statusCode, responseBody, statusCode);
}
public String getResponseBody() {
return responseBody;
}
public int getStatusCode() {
return statusCode;
}
@Override
public String toString() {
return "HttpResponseException{" +
"message=" + getMessage() + ", " +
"responseBody='" + responseBody + '\'' +
'}';
}
}
@@ -0,0 +1,11 @@
package com.sparrowwallet.sparrow.net.http.client;
public class HttpSystemException extends HttpException {
public HttpSystemException(String message) {
super(message);
}
public HttpSystemException(Exception cause) {
super(cause);
}
}
@@ -0,0 +1,39 @@
package com.sparrowwallet.sparrow.net.http.client;
import java.util.Objects;
public class HttpUsage {
public static final HttpUsage DEFAULT = new HttpUsage("Default");
private final String name;
public HttpUsage(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(o == null || getClass() != o.getClass()) {
return false;
}
HttpUsage httpUsage = (HttpUsage) o;
return Objects.equals(name, httpUsage.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
@@ -0,0 +1,11 @@
package com.sparrowwallet.sparrow.net.http.client;
import java.util.Map;
public interface IBackendClient {
<T> T getJson(String url, Class<T> responseType, Map<String, String> headers) throws HttpException;
<T> T getJson(String url, Class<T> responseType, Map<String, String> headers, boolean async) throws HttpException;
<T> T postUrlEncoded(String url, Class<T> responseType, Map<String, String> headers, Map<String, String> body) throws Exception;
}
@@ -0,0 +1,14 @@
package com.sparrowwallet.sparrow.net.http.client;
import io.reactivex.Single;
import java.util.Map;
import java.util.Optional;
public interface IHttpClient extends IBackendClient {
void connect() throws Exception;
<T> Single<Optional<T>> postJson(String url, Class<T> responseType, Map<String, String> headers, Object body);
Single<Optional<String>> postString(String urlStr, Map<String, String> headers, String contentType, String content);
}
@@ -0,0 +1,9 @@
package com.sparrowwallet.sparrow.net.http.client;
public interface IHttpClientService {
IHttpClient getHttpClient(HttpUsage httpUsage);
void changeIdentity(); // change Tor identity if any
void stop();
}
@@ -0,0 +1,9 @@
package com.sparrowwallet.sparrow.net.http.client;
import java.util.Optional;
public interface IHttpProxySupplier {
Optional<HttpProxy> getHttpProxy(HttpUsage httpUsage);
void changeIdentity();
}
@@ -0,0 +1,28 @@
package com.sparrowwallet.sparrow.net.http.client;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JSONUtils {
private static JSONUtils instance;
private ObjectMapper objectMapper;
public JSONUtils() {
objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
public static final JSONUtils getInstance() {
if(instance == null) {
instance = new JSONUtils();
}
return instance;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
}
@@ -0,0 +1,168 @@
package com.sparrowwallet.sparrow.net.http.client;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.reactivex.Single;
import io.reactivex.schedulers.Schedulers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
@SuppressWarnings("unchecked")
public abstract class JacksonHttpClient implements IHttpClient {
private static final Logger log = LoggerFactory.getLogger(JacksonHttpClient.class);
private final Consumer<Exception> onNetworkError;
public JacksonHttpClient(Consumer<Exception> onNetworkError) {
this.onNetworkError = onNetworkError;
}
protected abstract String requestJsonGet(String urlStr, Map<String, String> headers, boolean async) throws HttpException;
protected abstract String requestJsonPost(String urlStr, Map<String, String> headers, String jsonBody) throws HttpException;
protected abstract String requestStringPost(String urlStr, Map<String, String> headers, String contentType, String content) throws HttpException;
protected abstract String requestJsonPostUrlEncoded(String urlStr, Map<String, String> headers, Map<String, String> body) throws HttpException;
@Override
public <T> T getJson(String urlStr, Class<T> responseType, Map<String, String> headers) throws HttpException {
return getJson(urlStr, responseType, headers, false);
}
@Override
public <T> T getJson(String urlStr, Class<T> responseType, Map<String, String> headers, boolean async) throws HttpException {
return httpObservableBlockingSingle(() -> { // run on ioThread
try {
String responseContent = handleNetworkError("getJson " + urlStr, () -> requestJsonGet(urlStr, headers, async));
return parseJson(responseContent, responseType, 200);
} catch(Exception e) {
if(log.isDebugEnabled()) {
log.error("getJson failed: " + urlStr + ": " + e.toString());
}
throw e;
}
});
}
@Override
public <T> Single<Optional<T>> postJson(final String urlStr, final Class<T> responseType, final Map<String, String> headers, final Object bodyObj) {
return httpObservable(
() -> {
try {
String jsonBody = getObjectMapper().writeValueAsString(bodyObj);
String responseContent = handleNetworkError("postJson " + urlStr, () -> requestJsonPost(urlStr, headers, jsonBody));
return parseJson(responseContent, responseType, 200);
} catch(HttpException e) {
if(log.isDebugEnabled()) {
log.error("postJson failed: " + urlStr + ": " + e);
}
throw e;
}
});
}
@Override
public Single<Optional<String>> postString(String urlStr, Map<String, String> headers, String contentType, String content) {
return httpObservable(
() -> {
try {
return handleNetworkError("postString " + urlStr, () -> requestStringPost(urlStr, headers, contentType, content));
} catch(HttpException e) {
if(log.isDebugEnabled()) {
log.error("postJson failed: " + urlStr + ": " + e.toString());
}
throw e;
}
});
}
@Override
public <T> T postUrlEncoded(String urlStr, Class<T> responseType, Map<String, String> headers, Map<String, String> body) throws HttpException {
return httpObservableBlockingSingle(() -> { // run on ioThread
try {
String responseContent = handleNetworkError("postUrlEncoded " + urlStr, () -> requestJsonPostUrlEncoded(urlStr, headers, body));
return parseJson(responseContent, responseType, 200);
} catch(Exception e) {
if(log.isDebugEnabled()) {
log.error("postUrlEncoded failed: " + urlStr + ": " + e);
}
throw e;
}
});
}
private <T> T parseJson(String responseContent, Class<T> responseType, int statusCode) throws HttpException {
T result;
if(log.isTraceEnabled()) {
String responseStr = (responseContent != null ? responseContent : "null");
if(responseStr.length() > 500) {
responseStr = responseStr.substring(0, 500) + "...";
}
log.trace("response[" + (responseType != null ? responseType.getCanonicalName() : "null") + "]: " + responseStr);
}
if(String.class.equals(responseType)) {
result = (T) responseContent;
} else {
try {
result = getObjectMapper().readValue(responseContent, responseType);
} catch(Exception e) {
throw new HttpResponseException(e, responseContent, statusCode);
}
}
return result;
}
protected String handleNetworkError(String logInfo, Callable<String> doHttpRequest) throws HttpException {
try {
try {
// first attempt
return doHttpRequest.call();
} catch(HttpNetworkException e) {
if(log.isDebugEnabled()) {
log.warn("HTTP_ERROR_NETWORK " + logInfo + ", retrying: " + e.getMessage());
}
// change tor proxy
onNetworkError(e);
// retry second attempt
return doHttpRequest.call();
}
} catch(HttpException e) { // forward
throw e;
} catch(Exception e) { // should never happen
throw new HttpSystemException(e);
}
}
protected void onNetworkError(HttpNetworkException e) {
if(onNetworkError != null) {
synchronized(JacksonHttpClient.class) { // avoid overlapping Tor restarts between httpClients
onNetworkError.accept(e);
}
}
}
protected <T> Single<Optional<T>> httpObservable(final Callable<T> supplier) {
return Single.fromCallable(() -> Optional.ofNullable(supplier.call())).subscribeOn(Schedulers.io());
}
protected <T> T httpObservableBlockingSingle(final Callable<T> supplier) throws HttpException {
try {
Optional<T> opt = AsyncUtil.getInstance().blockingGet(httpObservable(supplier));
return opt.orElse(null);
} catch(HttpException e) { // forward
throw e;
} catch(Exception e) { // should never happen
throw new HttpNetworkException(e);
}
}
protected ObjectMapper getObjectMapper() {
return JSONUtils.getInstance().getObjectMapper();
}
}
@@ -0,0 +1,188 @@
package com.sparrowwallet.sparrow.net.http.client;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.util.FormContentProvider;
import org.eclipse.jetty.client.util.InputStreamResponseListener;
import org.eclipse.jetty.client.util.StringContentProvider;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.util.Fields;
import org.eclipse.jetty.util.component.LifeCycle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public class JettyHttpClient extends JacksonHttpClient {
protected static Logger log = LoggerFactory.getLogger(JettyHttpClient.class);
public static final String CONTENTTYPE_APPLICATION_JSON = "application/json";
private final HttpClient httpClient;
private final long requestTimeout;
private final HttpUsage httpUsage;
public JettyHttpClient(Consumer<Exception> onNetworkError, HttpClient httpClient, long requestTimeout, HttpUsage httpUsage) {
super(onNetworkError);
this.httpClient = httpClient;
this.requestTimeout = requestTimeout;
this.httpUsage = httpUsage;
}
@Override
public void connect() throws HttpException {
try {
if(!httpClient.isRunning()) {
httpClient.start();
}
} catch(Exception e) {
throw new HttpNetworkException(e);
}
}
public void restart() {
try {
if(log.isDebugEnabled()) {
log.debug("restart");
}
if(httpClient.isRunning()) {
httpClient.stop();
}
httpClient.start();
} catch(Exception e) {
log.error("", e);
}
}
public void stop() {
try {
if(httpClient.isRunning()) {
httpClient.stop();
Executor executor = httpClient.getExecutor();
if(executor instanceof LifeCycle) {
((LifeCycle) executor).stop();
}
}
} catch(Exception e) {
log.error("Error stopping client", e);
}
}
@Override
protected String requestJsonGet(String urlStr, Map<String, String> headers, boolean async) throws HttpException {
Request req = computeHttpRequest(urlStr, HttpMethod.GET, headers);
return makeRequest(req, async);
}
@Override
protected String requestJsonPost(String urlStr, Map<String, String> headers, String jsonBody) throws HttpException {
Request req = computeHttpRequest(urlStr, HttpMethod.POST, headers);
req.content(new StringContentProvider(CONTENTTYPE_APPLICATION_JSON, jsonBody, StandardCharsets.UTF_8));
return makeRequest(req, false);
}
@Override
protected String requestStringPost(String urlStr, Map<String, String> headers, String contentType, String content) throws HttpException {
log.debug("POST " + urlStr);
Request req = computeHttpRequest(urlStr, HttpMethod.POST, headers);
req.content(new StringContentProvider(content), contentType);
return makeRequest(req, false);
}
@Override
protected String requestJsonPostUrlEncoded(String urlStr, Map<String, String> headers, Map<String, String> body) throws HttpException {
Request req = computeHttpRequest(urlStr, HttpMethod.POST, headers);
req.content(new FormContentProvider(computeBodyFields(body)));
return makeRequest(req, false);
}
private Fields computeBodyFields(Map<String, String> body) {
Fields fields = new Fields();
for(Map.Entry<String, String> entry : body.entrySet()) {
fields.put(entry.getKey(), entry.getValue());
}
return fields;
}
protected String makeRequest(Request req, boolean async) throws HttpException {
String responseContent;
if(async) {
InputStreamResponseListener listener = new InputStreamResponseListener();
req.send(listener);
// Call to the listener's get() blocks until the headers arrived
Response response;
try {
response = listener.get(requestTimeout, TimeUnit.MILLISECONDS);
} catch(Exception e) {
throw new HttpNetworkException(e);
}
// Read content
InputStream is = listener.getInputStream();
Scanner s = new Scanner(is).useDelimiter("\\A");
responseContent = s.hasNext() ? s.next() : null;
// check status
checkResponseStatus(response.getStatus(), responseContent);
} else {
ContentResponse response;
try {
response = req.send();
} catch(Exception e) {
throw new HttpNetworkException(e);
}
checkResponseStatus(response.getStatus(), response.getContentAsString());
responseContent = response.getContentAsString();
}
return responseContent;
}
private void checkResponseStatus(int status, String responseBody) throws HttpResponseException {
if(!HttpStatus.isSuccess(status)) {
log.error("Http query failed: status=" + status + ", responseBody=" + responseBody);
throw new HttpResponseException(responseBody, status);
}
}
public HttpClient getJettyHttpClient() throws HttpException {
connect();
return httpClient;
}
private Request computeHttpRequest(String url, HttpMethod method, Map<String, String> headers) throws HttpException {
if(url.endsWith("/rpc")) {
// log RPC as TRACE
if(log.isTraceEnabled()) {
String headersStr = headers != null ? " (" + headers.keySet() + ")" : "";
log.trace("+" + method + ": " + url + headersStr);
}
} else {
if(log.isDebugEnabled()) {
String headersStr = headers != null ? " (" + headers.keySet() + ")" : "";
log.debug("+" + method + ": " + url + headersStr);
}
}
Request req = getJettyHttpClient().newRequest(url);
req.method(method);
if(headers != null) {
for(Map.Entry<String, String> entry : headers.entrySet()) {
req.header(entry.getKey(), entry.getValue());
}
}
req.timeout(requestTimeout, TimeUnit.MILLISECONDS);
return req;
}
public HttpUsage getHttpUsage() {
return httpUsage;
}
}
@@ -0,0 +1,167 @@
package com.sparrowwallet.sparrow.net.http.client;
import com.google.common.util.concurrent.RateLimiter;
import com.sparrowwallet.sparrow.net.http.client.socks5.Socks5Proxy;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.ProxyConfiguration;
import org.eclipse.jetty.client.Socks4Proxy;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
@SuppressWarnings("deprecation")
public class JettyHttpClientService implements IHttpClientService {
private static final Logger log = LoggerFactory.getLogger(JettyHttpClientService.class);
private static final String NAME = "HttpClient";
public static final long DEFAULT_TIMEOUT = 30000;
// limit changing Tor identity on network error every 4 minutes
private static final double RATE_CHANGE_IDENTITY_ON_NETWORK_ERROR = 1.0 / 240;
protected Map<HttpUsage, JettyHttpClient> httpClients; // used by Sparrow
private final IHttpProxySupplier httpProxySupplier;
private final long requestTimeout;
public JettyHttpClientService(long requestTimeout, IHttpProxySupplier httpProxySupplier) {
this.httpProxySupplier = httpProxySupplier != null ? httpProxySupplier : computeHttpProxySupplierDefault();
this.requestTimeout = requestTimeout;
this.httpClients = new ConcurrentHashMap<>();
}
public JettyHttpClientService(long requestTimeout) {
this(requestTimeout, null);
}
public JettyHttpClientService() {
this(DEFAULT_TIMEOUT);
}
protected static IHttpProxySupplier computeHttpProxySupplierDefault() {
return new IHttpProxySupplier() {
@Override
public Optional<HttpProxy> getHttpProxy(HttpUsage httpUsage) {
return Optional.empty();
}
@Override
public void changeIdentity() {
}
};
}
@Override
public JettyHttpClient getHttpClient(HttpUsage httpUsage) {
JettyHttpClient httpClient = httpClients.get(httpUsage);
if(httpClient == null) {
if(log.isDebugEnabled()) {
log.debug("+httpClient[" + httpUsage + "]");
}
httpClient = computeHttpClient(httpUsage);
httpClients.put(httpUsage, httpClient);
}
return httpClient;
}
protected JettyHttpClient computeHttpClient(HttpUsage httpUsage) {
Consumer<Exception> onNetworkError = computeOnNetworkError();
HttpClient httpClient = computeJettyClient(httpUsage);
return new JettyHttpClient(onNetworkError, httpClient, requestTimeout, httpUsage);
}
protected HttpClient computeJettyClient(HttpUsage httpUsage) {
// we use jetty for proxy SOCKS support
HttpClient jettyHttpClient = new HttpClient(new SslContextFactory());
// jettyHttpClient.setSocketAddressResolver(new MySocketAddressResolver());
// prevent user-agent tracking
jettyHttpClient.setUserAgentField(null);
// configure
configureProxy(jettyHttpClient, httpUsage);
configureThread(jettyHttpClient, httpUsage);
return jettyHttpClient;
}
protected Consumer<Exception> computeOnNetworkError() {
RateLimiter rateLimiter = RateLimiter.create(RATE_CHANGE_IDENTITY_ON_NETWORK_ERROR);
return e -> {
if(!rateLimiter.tryAcquire()) {
if(log.isDebugEnabled()) {
log.debug("onNetworkError: not changing Tor identity (too many recent attempts)");
}
return;
}
// change Tor identity on network error
httpProxySupplier.changeIdentity();
};
}
protected void configureProxy(HttpClient jettyHttpClient, HttpUsage httpUsage) {
Optional<HttpProxy> httpProxyOptional = httpProxySupplier.getHttpProxy(httpUsage);
if(httpProxyOptional != null && httpProxyOptional.isPresent()) {
HttpProxy httpProxy = httpProxyOptional.get();
if(log.isDebugEnabled()) {
log.debug("+httpClient: proxy=" + httpProxy);
}
ProxyConfiguration.Proxy jettyProxy = computeJettyProxy(httpProxy);
jettyHttpClient.getProxyConfiguration().getProxies().add(jettyProxy);
} else {
if(log.isDebugEnabled()) {
log.debug("+httpClient: no proxy");
}
}
}
protected void configureThread(HttpClient jettyHttpClient, HttpUsage httpUsage) {
String name = NAME + "-" + httpUsage.toString();
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setName(name);
threadPool.setDaemon(true);
jettyHttpClient.setExecutor(threadPool);
jettyHttpClient.setScheduler(new ScheduledExecutorScheduler(name + "-scheduler", true));
}
protected ProxyConfiguration.Proxy computeJettyProxy(HttpProxy httpProxy) {
ProxyConfiguration.Proxy jettyProxy = null;
switch(httpProxy.getProtocol()) {
case SOCKS:
jettyProxy = new Socks4Proxy(httpProxy.getHost(), httpProxy.getPort());
break;
case SOCKS5:
jettyProxy = new Socks5Proxy(httpProxy.getHost(), httpProxy.getPort());
break;
case HTTP:
jettyProxy = new org.eclipse.jetty.client.HttpProxy(httpProxy.getHost(), httpProxy.getPort());
break;
}
return jettyProxy;
}
@Override
public synchronized void stop() {
for(JettyHttpClient httpClient : httpClients.values()) {
httpClient.stop();
}
httpClients.clear();
}
@Override
public void changeIdentity() {
stop();
httpProxySupplier.changeIdentity();
}
public IHttpProxySupplier getHttpProxySupplier() {
return httpProxySupplier;
}
}
@@ -0,0 +1,42 @@
package com.sparrowwallet.sparrow.net.http.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
public class ThreadUtil {
private static final Logger log = LoggerFactory.getLogger(ThreadUtil.class);
private static ThreadUtil instance;
private ExecutorService executorService;
protected ThreadUtil() {
this.executorService = computeExecutorService();
}
public static ThreadUtil getInstance() {
if(instance == null) {
instance = new ThreadUtil();
}
return instance;
}
protected ExecutorService computeExecutorService() {
return Executors.newFixedThreadPool(5,
r -> {
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setDaemon(true);
return t;
});
}
public void setExecutorService(ScheduledExecutorService executorService) {
this.executorService = executorService;
}
public <T> Future<T> runAsync(Callable<T> callable) {
return executorService.submit(callable);
}
}
@@ -0,0 +1,222 @@
/**
* Socks5 backported from Jetty12 - we still use Jetty9 for JDK8 compatibility.
*/
//
// ========================================================================
// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package com.sparrowwallet.sparrow.net.http.client.socks5;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
/**
* Helper class for SOCKS5 proxying.
*
* @see Socks5Proxy
*/
public class Socks5 {
/** The SOCKS protocol version: {@value}. */
public static final byte VERSION = 0x05;
/** The SOCKS5 {@code CONNECT} command used in SOCKS5 connect requests. */
public static final byte COMMAND_CONNECT = 0x01;
/** The reserved byte value: {@value}. */
public static final byte RESERVED = 0x00;
/** The address type for IPv4 used in SOCKS5 connect requests and responses. */
public static final byte ADDRESS_TYPE_IPV4 = 0x01;
/** The address type for domain names used in SOCKS5 connect requests and responses. */
public static final byte ADDRESS_TYPE_DOMAIN = 0x03;
/** The address type for IPv6 used in SOCKS5 connect requests and responses. */
public static final byte ADDRESS_TYPE_IPV6 = 0x04;
private Socks5() {
}
/**
* A SOCKS5 authentication method.
*
* <p>Implementations should send and receive the bytes that are specific to the particular
* authentication method.
*/
public interface Authentication {
/**
* Performs the authentication send and receive bytes exchanges specific for this {@link
* Authentication}.
*
* @param endPoint the {@link EndPoint} to send to and receive from the SOCKS5 server
* @param callback the callback to complete when the authentication is complete
*/
void authenticate(EndPoint endPoint, Callback callback);
/** A factory for {@link Authentication}s. */
interface Factory {
/**
* @return the authentication method defined by RFC 1928
*/
byte getMethod();
/**
* @return a new {@link Authentication}
*/
Authentication newAuthentication();
}
}
/**
* The implementation of the {@code NO AUTH} authentication method defined in <a
* href="https://datatracker.ietf.org/doc/html/rfc1928">RFC 1928</a>.
*/
public static class NoAuthenticationFactory implements Authentication.Factory {
public static final byte METHOD = 0x00;
@Override
public byte getMethod() {
return METHOD;
}
@Override
public Authentication newAuthentication() {
return (endPoint, callback) -> callback.succeeded();
}
}
/**
* The implementation of the {@code USERNAME/PASSWORD} authentication method defined in <a
* href="https://datatracker.ietf.org/doc/html/rfc1929">RFC 1929</a>.
*/
public static class UsernamePasswordAuthenticationFactory implements Authentication.Factory {
public static final byte METHOD = 0x02;
public static final byte VERSION = 0x01;
private static final Logger LOG =
LoggerFactory.getLogger(UsernamePasswordAuthenticationFactory.class);
private final String userName;
private final String password;
private final Charset charset;
public UsernamePasswordAuthenticationFactory(String userName, String password) {
this(userName, password, StandardCharsets.US_ASCII);
}
public UsernamePasswordAuthenticationFactory(
String userName, String password, Charset charset) {
this.userName = Objects.requireNonNull(userName);
this.password = Objects.requireNonNull(password);
this.charset = Objects.requireNonNull(charset);
}
@Override
public byte getMethod() {
return METHOD;
}
@Override
public Authentication newAuthentication() {
return new UsernamePasswordAuthentication(this);
}
private static class UsernamePasswordAuthentication implements Authentication, Callback {
private final ByteBuffer byteBuffer = BufferUtil.allocate(2);
private final UsernamePasswordAuthenticationFactory factory;
private EndPoint endPoint;
private Callback callback;
private UsernamePasswordAuthentication(UsernamePasswordAuthenticationFactory factory) {
this.factory = factory;
}
@Override
public void authenticate(EndPoint endPoint, Callback callback) {
this.endPoint = endPoint;
this.callback = callback;
byte[] userNameBytes = factory.userName.getBytes(factory.charset);
byte[] passwordBytes = factory.password.getBytes(factory.charset);
ByteBuffer byteBuffer =
(ByteBuffer)
ByteBuffer.allocate(3 + userNameBytes.length + passwordBytes.length)
.put(VERSION)
.put((byte) userNameBytes.length)
.put(userNameBytes)
.put((byte) passwordBytes.length)
.put(passwordBytes)
.flip();
endPoint.write(Callback.from(this::authenticationSent, this::failed), byteBuffer);
}
private void authenticationSent() {
if(LOG.isDebugEnabled()) {
LOG.debug("Written SOCKS5 username/password authentication request");
}
endPoint.fillInterested(this);
}
@Override
public void succeeded() {
try {
int filled = endPoint.fill(byteBuffer);
if(filled < 0) {
throw new ClosedChannelException();
}
if(byteBuffer.remaining() < 2) {
endPoint.fillInterested(this);
return;
}
if(LOG.isDebugEnabled()) {
LOG.debug("Received SOCKS5 username/password authentication response");
}
byte version = byteBuffer.get();
if(version != VERSION) {
throw new IOException(
"Unsupported username/password authentication version: " + version);
}
byte status = byteBuffer.get();
if(status != 0) {
throw new IOException("SOCK5 username/password authentication failure");
}
if(LOG.isDebugEnabled()) {
LOG.debug("SOCKS5 username/password authentication succeeded");
}
callback.succeeded();
} catch(Throwable x) {
failed(x);
}
}
@Override
public void failed(Throwable x) {
callback.failed(x);
}
@Override
public InvocationType getInvocationType() {
return InvocationType.NON_BLOCKING;
}
}
}
}
@@ -0,0 +1,419 @@
//
// ========================================================================
// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package com.sparrowwallet.sparrow.net.http.client.socks5;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpClientTransport;
import org.eclipse.jetty.client.HttpDestination;
import org.eclipse.jetty.client.Origin;
import org.eclipse.jetty.client.ProxyConfiguration.Proxy;
import org.eclipse.jetty.io.AbstractConnection;
import org.eclipse.jetty.io.ClientConnectionFactory;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.ssl.SslClientConnectionFactory;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Client-side proxy configuration for SOCKS5, defined by <a
* href="https://datatracker.ietf.org/doc/html/rfc1928">RFC 1928</a>.
*
* <p>Multiple authentication methods are supported via {@link
* #putAuthenticationFactory(Socks5.Authentication.Factory)}. By default only the {@link
* Socks5.NoAuthenticationFactory NO AUTH} authentication method is configured. The {@link
* Socks5.UsernamePasswordAuthenticationFactory USERNAME/PASSWORD} is available to applications but
* must be explicitly configured and added.
*/
public class Socks5Proxy extends Proxy {
private static final Logger LOG = LoggerFactory.getLogger(Socks5Proxy.class);
private final Map<Byte, Socks5.Authentication.Factory> authentications = new LinkedHashMap<>();
/**
* Creates a new instance with the given SOCKS5 proxy host and port.
*
* @param host the SOCKS5 proxy host name
* @param port the SOCKS5 proxy port
*/
public Socks5Proxy(String host, int port) {
this(new Origin.Address(host, port), false);
}
/**
* Creates a new instance with the given SOCKS5 proxy address.
*
* <p>When {@code secure=true} the communication between the client and the proxy will be
* encrypted (using this proxy {@link #getSslContextFactory()} which typically defaults to that of
* {@link HttpClient}.
*
* @param address the SOCKS5 proxy address (host and port)
* @param secure whether the communication between the client and the SOCKS5 proxy should be
* secure
*/
public Socks5Proxy(Origin.Address address, boolean secure) {
super(address, secure);
putAuthenticationFactory(new Socks5.NoAuthenticationFactory());
}
protected static ClientConnectionFactory newSslClientConnectionFactory(HttpClient httpClient, SslContextFactory sslContextFactory, ClientConnectionFactory connectionFactory) {
if(sslContextFactory == null) {
sslContextFactory = httpClient.getSslContextFactory();
}
return new SslClientConnectionFactory(sslContextFactory, httpClient.getByteBufferPool(), httpClient.getExecutor(), connectionFactory);
}
/**
* Provides this class with the given SOCKS5 authentication method.
*
* @param authenticationFactory the SOCKS5 authentication factory
* @return the previous authentication method of the same type, or {@code null} if there was none
* of that type already present
*/
public Socks5.Authentication.Factory putAuthenticationFactory(Socks5.Authentication.Factory authenticationFactory) {
return authentications.put(authenticationFactory.getMethod(), authenticationFactory);
}
/**
* Removes the authentication of the given {@code method}.
*
* @param method the authentication method to remove
*/
public Socks5.Authentication.Factory removeAuthenticationFactory(byte method) {
return authentications.remove(method);
}
@Override
public ClientConnectionFactory newClientConnectionFactory(ClientConnectionFactory connectionFactory) {
return new Socks5ProxyClientConnectionFactory(connectionFactory);
}
private static class Socks5ProxyConnection extends AbstractConnection implements Connection.UpgradeFrom {
private static final Pattern IPv4_PATTERN = Pattern.compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})");
// SOCKS5 response max length is 262 bytes.
private final ByteBuffer byteBuffer = BufferUtil.allocate(512);
private final ClientConnectionFactory connectionFactory;
private final Map<String, Object> context;
private final Map<Byte, Socks5.Authentication.Factory> authentications;
private State state = State.HANDSHAKE;
private Socks5ProxyConnection(EndPoint endPoint, Executor executor, ClientConnectionFactory connectionFactory, Map<String, Object> context, Map<Byte, Socks5.Authentication.Factory> authentications) {
super(endPoint, executor);
this.connectionFactory = connectionFactory;
this.context = context;
this.authentications = new LinkedHashMap<>(authentications);
}
@Override
public ByteBuffer onUpgradeFrom() {
return BufferUtil.copy(byteBuffer);
}
@Override
public void onOpen() {
super.onOpen();
sendHandshake();
}
private void sendHandshake() {
try {
// +-------------+--------------------+------------------+
// | version (1) | num of methods (1) | methods (1..255) |
// +-------------+--------------------+------------------+
int size = authentications.size();
ByteBuffer byteBuffer =
ByteBuffer.allocate(1 + 1 + size).put(Socks5.VERSION).put((byte) size);
authentications.keySet().forEach(byteBuffer::put);
byteBuffer.flip();
getEndPoint().write(Callback.from(this::handshakeSent, this::fail), byteBuffer);
} catch(Throwable x) {
fail(x);
}
}
private void handshakeSent() {
if(LOG.isDebugEnabled()) {
LOG.debug("Written SOCKS5 handshake request");
}
state = State.HANDSHAKE;
fillInterested();
}
private void fail(Throwable x) {
if(LOG.isDebugEnabled()) {
LOG.debug("SOCKS5 failure", x);
}
getEndPoint().close();
@SuppressWarnings("unchecked")
Promise<Connection> promise =
(Promise<Connection>)
this.context.get(HttpClientTransport.HTTP_CONNECTION_PROMISE_CONTEXT_KEY);
promise.failed(x);
}
@Override
public void onFillable() {
try {
switch(state) {
case HANDSHAKE:
receiveHandshake();
break;
case CONNECT:
receiveConnect();
break;
default:
throw new IllegalStateException();
}
} catch(Throwable x) {
fail(x);
}
}
private void receiveHandshake() throws IOException {
// +-------------+------------+
// | version (1) | method (1) |
// +-------------+------------+
int filled = getEndPoint().fill(byteBuffer);
if(filled < 0) {
throw new ClosedChannelException();
}
if(byteBuffer.remaining() < 2) {
fillInterested();
return;
}
if(LOG.isDebugEnabled()) {
LOG.debug("Received SOCKS5 handshake response {}", BufferUtil.toDetailString(byteBuffer));
}
byte version = byteBuffer.get();
if(version != Socks5.VERSION) {
throw new IOException("Unsupported SOCKS5 version: " + version);
}
byte method = byteBuffer.get();
if(method == -1) {
throw new IOException("Unacceptable SOCKS5 authentication methods");
}
Socks5.Authentication.Factory factory = authentications.get(method);
if(factory == null) {
throw new IOException("Unknown SOCKS5 authentication method: " + method);
}
factory
.newAuthentication()
.authenticate(getEndPoint(), Callback.from(this::sendConnect, this::fail));
}
private void sendConnect() {
try {
// +-------------+-------------+--------------+------------------+------------------------+----------+
// | version (1) | command (1) | reserved (1) | address type (1) | address bytes (4..255) |
// port (2) |
// +-------------+-------------+--------------+------------------+------------------------+----------+
HttpDestination destination = (HttpDestination) context.get(HttpClientTransport.HTTP_DESTINATION_CONTEXT_KEY);
Origin.Address address = destination.getOrigin().getAddress();
String host = address.getHost();
short port = (short) address.getPort();
ByteBuffer byteBuffer;
Matcher matcher = IPv4_PATTERN.matcher(host);
if(matcher.matches()) {
byteBuffer =
ByteBuffer.allocate(10)
.put(Socks5.VERSION)
.put(Socks5.COMMAND_CONNECT)
.put(Socks5.RESERVED)
.put(Socks5.ADDRESS_TYPE_IPV4);
for(int i = 1; i <= 4; ++i) {
byteBuffer.put(Byte.parseByte(matcher.group(i)));
}
byteBuffer.putShort(port).flip();
} else if(true /*URIUtil.isValidHostRegisteredName(host)*/) {
byte[] bytes = host.getBytes(StandardCharsets.US_ASCII);
if(bytes.length > 255) {
throw new IOException("Invalid host name: " + host);
}
byteBuffer =
(ByteBuffer)
ByteBuffer.allocate(7 + bytes.length)
.put(Socks5.VERSION)
.put(Socks5.COMMAND_CONNECT)
.put(Socks5.RESERVED)
.put(Socks5.ADDRESS_TYPE_DOMAIN)
.put((byte) bytes.length)
.put(bytes)
.putShort(port)
.flip();
} else {
// Assume IPv6.
byte[] bytes = InetAddress.getByName(host).getAddress();
byteBuffer =
(ByteBuffer)
ByteBuffer.allocate(22)
.put(Socks5.VERSION)
.put(Socks5.COMMAND_CONNECT)
.put(Socks5.RESERVED)
.put(Socks5.ADDRESS_TYPE_IPV6)
.put(bytes)
.putShort(port)
.flip();
}
getEndPoint().write(Callback.from(this::connectSent, this::fail), byteBuffer);
} catch(Throwable x) {
fail(x);
}
}
private void connectSent() {
if(LOG.isDebugEnabled()) {
LOG.debug("Written SOCKS5 connect request");
}
state = State.CONNECT;
fillInterested();
}
private void receiveConnect() throws IOException {
// +-------------+-----------+--------------+------------------+------------------------+----------+
// | version (1) | reply (1) | reserved (1) | address type (1) | address bytes (4..255) | port
// (2) |
// +-------------+-----------+--------------+------------------+------------------------+----------+
int filled = getEndPoint().fill(byteBuffer);
if(filled < 0) {
throw new ClosedChannelException();
}
if(byteBuffer.remaining() < 5) {
fillInterested();
return;
}
byte addressType = byteBuffer.get(3);
int length = 6;
if(addressType == Socks5.ADDRESS_TYPE_IPV4) {
length += 4;
} else if(addressType == Socks5.ADDRESS_TYPE_DOMAIN) {
length += 1 + (byteBuffer.get(4) & 0xFF);
} else if(addressType == Socks5.ADDRESS_TYPE_IPV6) {
length += 16;
} else {
throw new IOException("Invalid SOCKS5 address type: " + addressType);
}
if(byteBuffer.remaining() < length) {
fillInterested();
return;
}
if(LOG.isDebugEnabled()) {
LOG.debug("Received SOCKS5 connect response {}", BufferUtil.toDetailString(byteBuffer));
}
// We have all the SOCKS5 bytes.
byte version = byteBuffer.get();
if(version != Socks5.VERSION) {
throw new IOException("Unsupported SOCKS5 version: " + version);
}
byte status = byteBuffer.get();
switch(status) {
case 0: {
// Consume the buffer before upgrading to the tunnel.
byteBuffer.position(length);
tunnel();
break;
}
case 1:
throw new IOException("SOCKS5 general failure");
case 2:
throw new IOException("SOCKS5 connection not allowed");
case 3:
throw new IOException("SOCKS5 network unreachable");
case 4:
throw new IOException("SOCKS5 host unreachable");
case 5:
throw new IOException("SOCKS5 connection refused");
case 6:
throw new IOException("SOCKS5 timeout expired");
case 7:
throw new IOException("SOCKS5 unsupported command");
case 8:
throw new IOException("SOCKS5 unsupported address");
default:
throw new IOException("SOCKS5 unknown status: " + status);
}
}
private void tunnel() {
try {
HttpDestination destination =
(HttpDestination) context.get(HttpClientTransport.HTTP_DESTINATION_CONTEXT_KEY);
this.context.put("ssl.peer.host", destination.getHost());
this.context.put("ssl.peer.port", destination.getPort());
// Origin.Address address = destination.getOrigin().getAddress();
// Don't want to do DNS resolution here.
// InetSocketAddress inet = InetSocketAddress.createUnresolved(address.getHost(),
// address.getPort());
// context.put(ClientConnector.REMOTE_SOCKET_ADDRESS_CONTEXT_KEY, inet);
ClientConnectionFactory connectionFactory = this.connectionFactory;
if(destination.isSecure()) {
connectionFactory =
newSslClientConnectionFactory(destination.getHttpClient(), null, connectionFactory);
}
Connection newConnection = connectionFactory.newConnection(getEndPoint(), context);
getEndPoint().upgrade(newConnection);
if(LOG.isDebugEnabled()) {
LOG.debug("SOCKS5 tunnel established: {} over {}", this, newConnection);
}
} catch(Throwable x) {
fail(x);
}
}
private enum State {
HANDSHAKE,
CONNECT
}
}
private class Socks5ProxyClientConnectionFactory implements ClientConnectionFactory {
private final ClientConnectionFactory connectionFactory;
private Socks5ProxyClientConnectionFactory(ClientConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public Connection newConnection(EndPoint endPoint, Map<String, Object> context) {
HttpDestination destination = (HttpDestination) context.get(HttpClientTransport.HTTP_DESTINATION_CONTEXT_KEY);
Executor executor = destination.getHttpClient().getExecutor();
Socks5ProxyConnection connection = new Socks5ProxyConnection(endPoint, executor, connectionFactory, context, authentications);
return customize(connection, context);
}
}
}
@@ -2,7 +2,6 @@ package com.sparrowwallet.sparrow.payjoin;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.sparrowwallet.drongo.KeyPurpose;
import com.sparrowwallet.drongo.protocol.Script;
import com.sparrowwallet.drongo.protocol.Transaction;
import com.sparrowwallet.drongo.protocol.TransactionInput;
@@ -14,16 +13,17 @@ import com.sparrowwallet.drongo.psbt.PSBTParseException;
import com.sparrowwallet.drongo.uri.BitcoinURI;
import com.sparrowwallet.drongo.wallet.Wallet;
import com.sparrowwallet.drongo.wallet.WalletNode;
import com.sparrowwallet.nightjar.http.JavaHttpException;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.net.HttpClientService;
import com.sparrowwallet.sparrow.net.Protocol;
import com.sparrowwallet.sparrow.net.http.client.HttpResponseException;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
@@ -87,7 +87,7 @@ public class Payjoin {
checkProposal(psbt, proposalPsbt, changeOutputIndex, maxAdditionalFeeContribution, allowOutputSubstitution);
return proposalPsbt;
} catch(JavaHttpException e) {
} catch(HttpResponseException e) {
Gson gson = new Gson();
PayjoinReceiverError payjoinReceiverError = gson.fromJson(e.getResponseBody(), PayjoinReceiverError.class);
log.warn("Payjoin receiver returned an error of " + payjoinReceiverError.getErrorCode() + " (" + payjoinReceiverError.getMessage() + ")");
@@ -58,14 +58,6 @@ public class PayNym {
return followers;
}
public boolean isCollaborativeSend() {
return collaborativeSend;
}
public void setCollaborativeSend(boolean collaborativeSend) {
this.collaborativeSend = collaborativeSend;
}
public List<ScriptType> getScriptTypes() {
return segwit ? getSegwitScriptTypes() : getV1ScriptTypes();
}
@@ -1,20 +0,0 @@
package com.sparrowwallet.sparrow.paynym;
import com.sparrowwallet.drongo.address.P2WPKHAddress;
public final class PayNymAddress extends P2WPKHAddress {
private final PayNym payNym;
public PayNymAddress(PayNym payNym) {
super(new byte[20]);
this.payNym = payNym;
}
public PayNym getPayNym() {
return payNym;
}
public String toString() {
return payNym.nymName();
}
}
@@ -46,8 +46,8 @@ public class PayNymController {
public static final String INVALID_PAYMENT_CODE_LABEL = "Invalid Payment Code";
private String walletId;
private boolean selectLinkedOnly;
private PayNym walletPayNym;
private boolean requestingPassword;
@FXML
private CopyableTextField payNymName;
@@ -87,9 +87,8 @@ public class PayNymController {
private final BooleanProperty closeProperty = new SimpleBooleanProperty(false);
public void initializeView(String walletId, boolean selectLinkedOnly) {
public void initializeView(String walletId) {
this.walletId = walletId;
this.selectLinkedOnly = selectLinkedOnly;
payNymName.managedProperty().bind(payNymName.visibleProperty());
payNymRetrieve.managedProperty().bind(payNymRetrieve.visibleProperty());
@@ -353,6 +352,43 @@ public class PayNymController {
}
private void addWalletIfNotificationTransactionPresent(List<PayNym> following) {
Unlinked unlinked = getUnlinkedPayNyms(following);
Wallet wallet = getMasterWallet();
if(!unlinked.unlinkedNotifications.isEmpty()) {
if(wallet.isEncrypted()) {
Storage storage = AppServices.get().getOpenWallets().get(wallet);
requestingPassword = true;
Optional<ButtonType> optButtonType = AppServices.showAlertDialog("Link contacts?", "Some contacts were found that may be already linked. Link these contacts? Your password is required to check.", Alert.AlertType.CONFIRMATION, ButtonType.NO, ButtonType.YES);
if(optButtonType.isPresent() && optButtonType.get() == ButtonType.YES) {
WalletPasswordDialog dlg = new WalletPasswordDialog(wallet.getMasterName(), WalletPasswordDialog.PasswordRequirement.LOAD);
dlg.initOwner(payNymName.getScene().getWindow());
Optional<SecureString> password = dlg.showAndWait();
if(password.isPresent()) {
Storage.DecryptWalletService decryptWalletService = new Storage.DecryptWalletService(wallet.copy(), password.get());
decryptWalletService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(storage.getWalletId(wallet), TimedEvent.Action.END, "Done"));
Wallet decryptedWallet = decryptWalletService.getValue();
addWalletIfNotificationTransactionPresent(decryptedWallet, getUnlinkedPayNyms(following));
decryptedWallet.clearPrivate();
requestingPassword = false;
});
decryptWalletService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(storage.getWalletId(wallet), TimedEvent.Action.END, "Failed"));
AppServices.showErrorDialog("Incorrect Password", decryptWalletService.getException().getMessage());
requestingPassword = false;
});
EventManager.get().post(new StorageEvent(storage.getWalletId(wallet), TimedEvent.Action.START, "Decrypting wallet..."));
decryptWalletService.start();
}
}
} else {
addWalletIfNotificationTransactionPresent(wallet, unlinked);
}
}
}
private Unlinked getUnlinkedPayNyms(List<PayNym> following) {
Map<BlockTransaction, PayNym> unlinkedPayNyms = new HashMap<>();
Map<BlockTransaction, WalletNode> unlinkedNotifications = new HashMap<>();
for(PayNym payNym : following) {
@@ -366,44 +402,16 @@ public class PayNymController {
}
}
Wallet wallet = getMasterWallet();
if(!unlinkedNotifications.isEmpty()) {
if(wallet.isEncrypted()) {
Storage storage = AppServices.get().getOpenWallets().get(wallet);
Optional<ButtonType> optButtonType = AppServices.showAlertDialog("Link contacts?", "Some contacts were found that may be already linked. Link these contacts? Your password is required to check.", Alert.AlertType.CONFIRMATION, ButtonType.NO, ButtonType.YES);
if(optButtonType.isPresent() && optButtonType.get() == ButtonType.YES) {
WalletPasswordDialog dlg = new WalletPasswordDialog(wallet.getMasterName(), WalletPasswordDialog.PasswordRequirement.LOAD);
dlg.initOwner(payNymName.getScene().getWindow());
Optional<SecureString> password = dlg.showAndWait();
if(password.isPresent()) {
Storage.DecryptWalletService decryptWalletService = new Storage.DecryptWalletService(wallet.copy(), password.get());
decryptWalletService.setOnSucceeded(workerStateEvent -> {
EventManager.get().post(new StorageEvent(storage.getWalletId(wallet), TimedEvent.Action.END, "Done"));
Wallet decryptedWallet = decryptWalletService.getValue();
addWalletIfNotificationTransactionPresent(decryptedWallet, unlinkedPayNyms, unlinkedNotifications);
decryptedWallet.clearPrivate();
});
decryptWalletService.setOnFailed(workerStateEvent -> {
EventManager.get().post(new StorageEvent(storage.getWalletId(wallet), TimedEvent.Action.END, "Failed"));
AppServices.showErrorDialog("Incorrect Password", decryptWalletService.getException().getMessage());
});
EventManager.get().post(new StorageEvent(storage.getWalletId(wallet), TimedEvent.Action.START, "Decrypting wallet..."));
decryptWalletService.start();
}
}
} else {
addWalletIfNotificationTransactionPresent(wallet, unlinkedPayNyms, unlinkedNotifications);
}
}
return new Unlinked(unlinkedPayNyms, unlinkedNotifications);
}
private void addWalletIfNotificationTransactionPresent(Wallet decryptedWallet, Map<BlockTransaction, PayNym> unlinkedPayNyms, Map<BlockTransaction, WalletNode> unlinkedNotifications) {
private void addWalletIfNotificationTransactionPresent(Wallet decryptedWallet, Unlinked unlinked) {
List<Wallet> addedWallets = new ArrayList<>();
for(BlockTransaction blockTransaction : unlinkedNotifications.keySet()) {
for(BlockTransaction blockTransaction : unlinked.unlinkedNotifications.keySet()) {
try {
PayNym payNym = unlinkedPayNyms.get(blockTransaction);
PayNym payNym = unlinked.unlinkedPayNyms.get(blockTransaction);
PaymentCode externalPaymentCode = payNym.paymentCode();
WalletNode input0Node = unlinkedNotifications.get(blockTransaction);
WalletNode input0Node = unlinked.unlinkedNotifications.get(blockTransaction);
Keystore keystore = input0Node.getWallet().isNested() ? decryptedWallet.getChildWallet(input0Node.getWallet().getName()).getKeystores().get(0) : decryptedWallet.getKeystores().get(0);
ECKey input0Key = keystore.getKey(input0Node);
TransactionOutPoint input0Outpoint = PaymentCode.getDesignatedInput(blockTransaction.getTransaction()).getOutpoint();
@@ -658,10 +666,6 @@ public class PayNymController {
}
}
public boolean isSelectLinkedOnly() {
return selectLinkedOnly;
}
public PayNym getPayNym() {
return payNymProperty.get();
}
@@ -689,7 +693,7 @@ public class PayNymController {
Platform.runLater(() -> EventManager.get().post(new WalletEntryLabelsChangedEvent(event.getWallet(), changedLabelEntries)));
}
if(walletPayNym != null) {
if(walletPayNym != null && !requestingPassword) {
//If we have just linked a PayNym wallet that paid for another notification transaction, attempt to link
Platform.runLater(() -> addWalletIfNotificationTransactionPresent(walletPayNym.following()));
}
@@ -761,4 +765,6 @@ public class PayNymController {
public void selectNext() {
}
}
private record Unlinked(Map<BlockTransaction, PayNym> unlinkedPayNyms, Map<BlockTransaction, WalletNode> unlinkedNotifications) {}
}
@@ -9,10 +9,10 @@ import java.io.IOException;
public class PayNymDialog extends Dialog<PayNym> {
public PayNymDialog(String walletId) {
this(walletId, Operation.SHOW, false);
this(walletId, Operation.SHOW);
}
public PayNymDialog(String walletId, Operation operation, boolean selectLinkedOnly) {
public PayNymDialog(String walletId, Operation operation) {
final DialogPane dialogPane = getDialogPane();
AppServices.setStageIcon(dialogPane.getScene().getWindow());
AppServices.onEscapePressed(dialogPane.getScene(), this::close);
@@ -21,7 +21,7 @@ public class PayNymDialog extends Dialog<PayNym> {
FXMLLoader payNymLoader = new FXMLLoader(AppServices.class.getResource("paynym/paynym.fxml"));
dialogPane.setContent(payNymLoader.load());
PayNymController payNymController = payNymLoader.getController();
payNymController.initializeView(walletId, selectLinkedOnly);
payNymController.initializeView(walletId);
EventManager.get().register(payNymController);
@@ -33,26 +33,13 @@ public class PayNymDialog extends Dialog<PayNym> {
dialogPane.getStylesheets().add(AppServices.class.getResource("app.css").toExternalForm());
dialogPane.getStylesheets().add(AppServices.class.getResource("paynym/paynym.css").toExternalForm());
final ButtonType sendDirectlyButtonType = new javafx.scene.control.ButtonType("Send Directly", ButtonBar.ButtonData.APPLY);
final ButtonType sendCollaborativelyButtonType = new javafx.scene.control.ButtonType("Send Collaboratively", ButtonBar.ButtonData.OK_DONE);
final ButtonType sendDirectlyButtonType = new javafx.scene.control.ButtonType("Send To Contact", ButtonBar.ButtonData.APPLY);
final ButtonType selectButtonType = new javafx.scene.control.ButtonType("Select Contact", ButtonBar.ButtonData.APPLY);
final ButtonType cancelButtonType = new javafx.scene.control.ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
final ButtonType doneButtonType = new javafx.scene.control.ButtonType("Done", ButtonBar.ButtonData.OK_DONE);
if(operation == Operation.SEND) {
if(selectLinkedOnly) {
dialogPane.getButtonTypes().addAll(sendDirectlyButtonType, cancelButtonType);
} else {
dialogPane.getButtonTypes().addAll(sendDirectlyButtonType, sendCollaborativelyButtonType, cancelButtonType);
Button sendCollaborativelyButton = (Button)dialogPane.lookupButton(sendCollaborativelyButtonType);
sendCollaborativelyButton.setDisable(true);
sendCollaborativelyButton.setDefaultButton(false);
payNymController.payNymProperty().addListener((observable, oldValue, payNym) -> {
sendCollaborativelyButton.setDisable(payNym == null);
sendCollaborativelyButton.setDefaultButton(payNym != null && !payNymController.isLinked(payNym));
});
}
dialogPane.getButtonTypes().addAll(sendDirectlyButtonType, cancelButtonType);
Button sendDirectlyButton = (Button)dialogPane.lookupButton(sendDirectlyButtonType);
sendDirectlyButton.setDisable(true);
sendDirectlyButton.setDefaultButton(true);
@@ -66,7 +53,7 @@ public class PayNymDialog extends Dialog<PayNym> {
selectButton.setDisable(true);
selectButton.setDefaultButton(true);
payNymController.payNymProperty().addListener((observable, oldValue, payNym) -> {
selectButton.setDisable(payNym == null || (selectLinkedOnly && !payNymController.isLinked(payNym)));
selectButton.setDisable(payNym == null || !payNymController.isLinked(payNym));
});
} else {
dialogPane.getButtonTypes().add(doneButtonType);
@@ -83,14 +70,8 @@ public class PayNymDialog extends Dialog<PayNym> {
});
setResultConverter(dialogButton -> {
if(dialogButton == sendCollaborativelyButtonType) {
PayNym payNym = payNymController.getPayNym();
payNym.setCollaborativeSend(true);
return payNym;
} else if(dialogButton == sendDirectlyButtonType || dialogButton == selectButtonType) {
PayNym payNym = payNymController.getPayNym();
payNym.setCollaborativeSend(false);
return payNym;
if(dialogButton == sendDirectlyButtonType || dialogButton == selectButtonType) {
return payNymController.getPayNym();
}
return null;
@@ -52,7 +52,7 @@ public class PayNymService {
return AppServices.getHttpClientService().postJson(url, Map.class, headers, body)
.subscribeOn(Schedulers.io())
.observeOn(JavaFxScheduler.platform())
.map(Optional::get);
.map(o -> o.get());
}
public static Observable<Map<String, Object>> updateToken(PaymentCode paymentCode) {
@@ -74,7 +74,7 @@ public class PayNymService {
return AppServices.getHttpClientService().postJson(url, Map.class, headers, body)
.subscribeOn(Schedulers.io())
.observeOn(JavaFxScheduler.platform())
.map(Optional::get);
.map(o -> o.get());
}
public static void claimPayNym(Wallet wallet, Map<String, Object> createMap, boolean segwit) {
@@ -123,7 +123,7 @@ public class PayNymService {
return AppServices.getHttpClientService().postJson(url, Map.class, headers, body)
.subscribeOn(Schedulers.io())
.observeOn(JavaFxScheduler.platform())
.map(Optional::get);
.map(o -> o.get());
}
public static Observable<Map<String, Object>> addPaymentCode(PaymentCode paymentCode, String authToken, String signature, boolean segwit) {
@@ -152,11 +152,7 @@ public class PayNymService {
return AppServices.getHttpClientService().postJson(url, Map.class, headers, body)
.subscribeOn(Schedulers.io())
.observeOn(JavaFxScheduler.platform())
.map(Optional::get);
}
public static Observable<Map<String, Object>> followPaymentCode(com.samourai.wallet.bip47.rpc.PaymentCode paymentCode, String authToken, String signature) {
return followPaymentCode(PaymentCode.fromString(paymentCode.toString()), authToken, signature);
.map(o -> o.get());
}
public static Observable<Map<String, Object>> followPaymentCode(PaymentCode paymentCode, String authToken, String signature) {
@@ -176,7 +172,7 @@ public class PayNymService {
return AppServices.getHttpClientService().postJson(url, Map.class, headers, body)
.subscribeOn(Schedulers.io())
.observeOn(JavaFxScheduler.platform())
.map(Optional::get);
.map(o -> o.get());
}
public static Observable<Map<String, Object>> fetchPayNym(String nymIdentifier, boolean compact) {
@@ -194,7 +190,7 @@ public class PayNymService {
return AppServices.getHttpClientService().postJson(url, Map.class, headers, body)
.subscribeOn(Schedulers.io())
.observeOn(JavaFxScheduler.platform())
.map(Optional::get);
.map(o -> o.get());
}
public static Observable<PayNym> getPayNym(String nymIdentifier) {
@@ -1,432 +0,0 @@
package com.sparrowwallet.sparrow.soroban;
import com.samourai.soroban.cahoots.CahootsContext;
import com.samourai.soroban.client.cahoots.OnlineCahootsMessage;
import com.samourai.soroban.client.cahoots.SorobanCahootsService;
import com.samourai.wallet.bip47.rpc.PaymentCode;
import com.samourai.wallet.cahoots.Cahoots;
import com.samourai.wallet.cahoots.CahootsType;
import com.sparrowwallet.drongo.protocol.Transaction;
import com.sparrowwallet.drongo.psbt.PSBTParseException;
import com.sparrowwallet.drongo.wallet.*;
import com.sparrowwallet.sparrow.AppServices;
import com.sparrowwallet.sparrow.control.*;
import com.sparrowwallet.sparrow.paynym.PayNymDialog;
import com.sparrowwallet.sparrow.paynym.PayNymService;
import io.reactivex.rxjavafx.schedulers.JavaFxScheduler;
import io.reactivex.schedulers.Schedulers;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.util.StringConverter;
import org.controlsfx.glyphfont.Glyph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import static com.sparrowwallet.sparrow.AppServices.showErrorDialog;
import static com.sparrowwallet.sparrow.soroban.Soroban.TIMEOUT_MS;
public class CounterpartyController extends SorobanController {
private static final Logger log = LoggerFactory.getLogger(CounterpartyController.class);
private String walletId;
private Wallet wallet;
@FXML
private VBox step1;
@FXML
private VBox step2;
@FXML
private VBox step3;
@FXML
private VBox step4;
@FXML
private CopyableTextField payNym;
@FXML
private Button showPayNym;
@FXML
private PayNymAvatar payNymAvatar;
@FXML
private Button payNymButton;
@FXML
private PaymentCodeTextField paymentCode;
@FXML
private Button paymentCodeQR;
@FXML
private ComboBox<Wallet> mixWallet;
@FXML
private ProgressTimer step2Timer;
@FXML
private Label step2Desc;
@FXML
private Label mixingPartner;
@FXML
private PayNymAvatar mixPartnerAvatar;
@FXML
private Hyperlink meetingFail;
@FXML
private VBox mixDetails;
@FXML
private Label mixType;
@FXML
private Label mixFee;
@FXML
private ProgressTimer step3Timer;
@FXML
private Label step3Desc;
@FXML
private ProgressBar sorobanProgressBar;
@FXML
private Label sorobanProgressLabel;
@FXML
private Glyph mixDeclined;
@FXML
private TransactionDiagram transactionDiagram;
private final ObjectProperty<Boolean> meetingReceived = new SimpleObjectProperty<>(null);
private final ObjectProperty<Boolean> meetingAccepted = new SimpleObjectProperty<>(null);
private final ObjectProperty<Transaction> transactionProperty = new SimpleObjectProperty<>(null);
public void initializeView(String walletId, Wallet wallet) {
this.walletId = walletId;
this.wallet = wallet;
step1.managedProperty().bind(step1.visibleProperty());
step2.managedProperty().bind(step2.visibleProperty());
step3.managedProperty().bind(step3.visibleProperty());
step4.managedProperty().bind(step4.visibleProperty());
mixWallet.setConverter(new StringConverter<>() {
@Override
public String toString(Wallet wallet) {
return wallet == null ? "" : wallet.getFullDisplayName();
}
@Override
public Wallet fromString(String string) {
return null;
}
});
mixWallet.setItems(FXCollections.observableList(wallet.getAllWallets()));
mixWallet.setValue(wallet);
mixWallet.valueProperty().addListener((observable, oldValue, selectedWallet) -> setWallet(selectedWallet));
sorobanProgressBar.managedProperty().bind(sorobanProgressBar.visibleProperty());
sorobanProgressLabel.managedProperty().bind(sorobanProgressLabel.visibleProperty());
mixDeclined.managedProperty().bind(mixDeclined.visibleProperty());
sorobanProgressBar.visibleProperty().bind(sorobanProgressLabel.visibleProperty());
mixDeclined.visibleProperty().bind(sorobanProgressLabel.visibleProperty().not());
step2Timer.visibleProperty().bind(mixingPartner.visibleProperty());
step3Timer.visibleProperty().bind(sorobanProgressLabel.visibleProperty());
step2.setVisible(false);
step3.setVisible(false);
step4.setVisible(false);
Soroban soroban = AppServices.getSorobanServices().getSoroban(walletId);
if(soroban.getHdWallet() == null) {
throw new IllegalStateException("Soroban HD wallet must be set");
}
payNym.managedProperty().bind(payNym.visibleProperty());
showPayNym.managedProperty().bind(showPayNym.visibleProperty());
showPayNym.visibleProperty().bind(payNym.visibleProperty());
payNymAvatar.managedProperty().bind(payNymAvatar.visibleProperty());
payNymAvatar.visibleProperty().bind(payNym.visibleProperty());
payNymButton.managedProperty().bind(payNymButton.visibleProperty());
payNymButton.visibleProperty().bind(payNym.visibleProperty().not());
if(isUsePayNym(wallet)) {
retrievePayNym(null);
} else {
payNym.setVisible(false);
}
Wallet masterWallet = wallet.isMasterWallet() ? wallet : wallet.getMasterWallet();
paymentCode.setPaymentCode(masterWallet.getPaymentCode());
paymentCodeQR.prefHeightProperty().bind(paymentCode.heightProperty());
paymentCodeQR.prefWidthProperty().bind(showPayNym.widthProperty());
mixingPartner.managedProperty().bind(mixingPartner.visibleProperty());
meetingFail.managedProperty().bind(meetingFail.visibleProperty());
meetingFail.visibleProperty().bind(mixingPartner.visibleProperty().not());
meetingFail.setOnAction(event -> {
step2Desc.setText("Ask your mix partner to initiate the Soroban communication.");
mixingPartner.setVisible(true);
startCounterpartyMeetingReceive();
step2Timer.start(e -> {
step2Desc.setText("Mix declined due to timeout.");
meetingReceived.set(Boolean.FALSE);
});
});
mixDetails.managedProperty().bind(mixDetails.visibleProperty());
mixDetails.setVisible(false);
meetingAccepted.addListener((observable, oldValue, accepted) -> {
Platform.exitNestedEventLoop(meetingAccepted, accepted);
meetingReceived.set(null);
});
step2.visibleProperty().addListener((observable, oldValue, visible) -> {
if(visible) {
startCounterpartyMeetingReceive();
step2Timer.start(e -> {
step2Desc.setText("Mix declined due to timeout.");
meetingReceived.set(Boolean.FALSE);
});
}
});
step3.visibleProperty().addListener((observable, oldValue, visible) -> {
if(visible) {
meetingAccepted.set(Boolean.TRUE);
}
});
}
private void setWallet(Wallet wallet) {
this.walletId = AppServices.get().getOpenWallets().get(wallet).getWalletId(wallet);
this.wallet = wallet;
}
private void startCounterpartyMeetingReceive() {
Soroban soroban = AppServices.getSorobanServices().getSoroban(walletId);
SparrowCahootsWallet counterpartyCahootsWallet = soroban.getCahootsWallet(wallet, 1);
try {
SorobanCahootsService sorobanMeetingService = soroban.getSorobanCahootsService(counterpartyCahootsWallet);
sorobanMeetingService.receiveMeetingRequest(TIMEOUT_MS)
.subscribeOn(Schedulers.io())
.observeOn(JavaFxScheduler.platform())
.subscribe(requestMessage -> {
String code = requestMessage.getSender();
CahootsType cahootsType = requestMessage.getType();
PaymentCode paymentCodeInitiator = new PaymentCode(code);
updateMixPartner(paymentCodeInitiator, cahootsType);
Boolean accepted = (Boolean)Platform.enterNestedEventLoop(meetingAccepted);
sorobanMeetingService.sendMeetingResponse(paymentCodeInitiator, requestMessage, accepted)
.subscribeOn(Schedulers.io())
.observeOn(JavaFxScheduler.platform())
.subscribe(responseMessage -> {
requestUserAttention();
if(accepted) {
startCounterpartyCollaboration(counterpartyCahootsWallet, paymentCodeInitiator, cahootsType);
followPaymentCode(paymentCodeInitiator);
}
}, error -> {
log.error("Error sending meeting response", error);
mixingPartner.setVisible(false);
requestUserAttention();
});
}, error -> {
log.error("Failed to receive meeting request", error);
mixingPartner.setVisible(false);
requestUserAttention();
});
} catch(Exception e) {
log.error("Error sending meeting response", e);
}
}
private void updateMixPartner(PaymentCode paymentCodeInitiator, CahootsType cahootsType) {
String code = paymentCodeInitiator.toString();
mixingPartner.setText(code.substring(0, 12) + "..." + code.substring(code.length() - 5));
if(isUsePayNym(wallet)) {
mixPartnerAvatar.setPaymentCode(paymentCodeInitiator);
PayNymService.getPayNym(paymentCodeInitiator.toString()).subscribe(payNym -> {
mixingPartner.setText(payNym.nymName());
}, error -> {
//ignore, may not be a PayNym
});
}
if(cahootsType == CahootsType.STONEWALLX2) {
mixType.setText("Two person coinjoin (" + cahootsType.getLabel() + ")");
mixFee.setText("You pay half the miner fee");
} else if(cahootsType == CahootsType.STOWAWAY) {
mixType.setText("Payjoin (" + cahootsType.getLabel() + ")");
mixFee.setText("None");
} else {
mixType.setText(cahootsType.getLabel());
mixFee.setText("None");
}
mixDetails.setVisible(true);
meetingReceived.set(Boolean.TRUE);
}
private void startCounterpartyCollaboration(SparrowCahootsWallet counterpartyCahootsWallet, PaymentCode initiatorPaymentCode, CahootsType cahootsType) {
sorobanProgressLabel.setText("Creating mix transaction...");
Soroban soroban = AppServices.getSorobanServices().getSoroban(walletId);
Map<BlockTransactionHashIndex, WalletNode> walletUtxos = wallet.getSpendableUtxos();
for(Map.Entry<BlockTransactionHashIndex, WalletNode> entry : walletUtxos.entrySet()) {
counterpartyCahootsWallet.addUtxo(entry.getValue(), wallet.getWalletTransaction(entry.getKey().getHash()), (int)entry.getKey().getIndex());
}
try {
SorobanCahootsService sorobanCahootsService = soroban.getSorobanCahootsService(counterpartyCahootsWallet);
CahootsContext cahootsContext = cahootsType == CahootsType.STONEWALLX2 ? CahootsContext.newCounterpartyStonewallx2() : CahootsContext.newCounterpartyStowaway();
sorobanCahootsService.contributor(counterpartyCahootsWallet.getAccount(), cahootsContext, initiatorPaymentCode, TIMEOUT_MS)
.subscribeOn(Schedulers.io())
.observeOn(JavaFxScheduler.platform())
.subscribe(sorobanMessage -> {
OnlineCahootsMessage cahootsMessage = (OnlineCahootsMessage)sorobanMessage;
if(cahootsMessage != null) {
Cahoots cahoots = cahootsMessage.getCahoots();
sorobanProgressBar.setProgress((double)(cahoots.getStep() + 1) / 5);
if(cahoots.getStep() == 3) {
sorobanProgressLabel.setText("Your mix partner is reviewing the transaction...");
step3Timer.start();
} else if(cahoots.getStep() >= 4) {
try {
Transaction transaction = getTransaction(cahoots);
if(transaction != null) {
transactionProperty.set(transaction);
updateTransactionDiagram(transactionDiagram, wallet, null, transaction);
next();
}
} catch(PSBTParseException e) {
log.error("Invalid collaborative PSBT created", e);
step3Desc.setText("Invalid transaction created.");
sorobanProgressLabel.setVisible(false);
}
}
}
}, error -> {
log.error("Error creating mix transaction", error);
String cutFrom = "Exception: ";
int index = error.getMessage().lastIndexOf(cutFrom);
String msg = index < 0 ? error.getMessage() : error.getMessage().substring(index + cutFrom.length());
msg = msg.replace("#Cahoots", "mix transaction");
step3Desc.setText(msg);
sorobanProgressLabel.setVisible(false);
});
} catch(Exception e) {
log.error("Error creating mix transaction", e);
sorobanProgressLabel.setText(e.getMessage());
}
}
private void followPaymentCode(PaymentCode paymentCodeInitiator) {
if(isUsePayNym(wallet)) {
PayNymService.getAuthToken(wallet, new HashMap<>()).subscribe(authToken -> {
String signature = PayNymService.getSignature(wallet, authToken);
PayNymService.followPaymentCode(paymentCodeInitiator, authToken, signature).subscribe(followMap -> {
log.debug("Followed payment code " + followMap.get("following"));
}, error -> {
log.warn("Could not follow payment code", error);
});
}, error -> {
log.warn("Could not follow payment code", error);
});
}
}
public boolean next() {
if(step1.isVisible()) {
step1.setVisible(false);
step2.setVisible(true);
return true;
}
if(step2.isVisible()) {
step2.setVisible(false);
step3.setVisible(true);
return true;
}
if(step3.isVisible()) {
step3.setVisible(false);
step4.setVisible(true);
return true;
}
return false;
}
public void cancel() {
meetingAccepted.set(Boolean.FALSE);
}
public void retrievePayNym(ActionEvent event) {
setUsePayNym(wallet, true);
PayNymService.createPayNym(wallet).subscribe(createMap -> {
payNym.setText((String)createMap.get("nymName"));
payNymAvatar.setPaymentCode(wallet.isMasterWallet() ? wallet.getPaymentCode() : wallet.getMasterWallet().getPaymentCode());
payNym.setVisible(true);
PayNymService.claimPayNym(wallet, createMap, true);
}, error -> {
log.error("Error retrieving PayNym", error);
Optional<ButtonType> optResponse = showErrorDialog("Error retrieving PayNym", "Could not retrieve PayNym. Try again?", ButtonType.CANCEL, ButtonType.OK);
if(optResponse.isPresent() && optResponse.get().equals(ButtonType.OK)) {
retrievePayNym(null);
} else {
payNym.setVisible(false);
}
});
}
public void showPayNym(ActionEvent event) {
PayNymDialog payNymDialog = new PayNymDialog(walletId);
payNymDialog.initOwner(payNym.getScene().getWindow());
payNymDialog.showAndWait();
}
public void showPayNymQR(ActionEvent event) {
Wallet masterWallet = wallet.isMasterWallet() ? wallet : wallet.getMasterWallet();
QRDisplayDialog qrDisplayDialog = new QRDisplayDialog(masterWallet.getPaymentCode().toString());
qrDisplayDialog.initOwner(payNym.getScene().getWindow());
qrDisplayDialog.showAndWait();
}
public ObjectProperty<Boolean> meetingReceivedProperty() {
return meetingReceived;
}
public ObjectProperty<Boolean> meetingAcceptedProperty() {
return meetingAccepted;
}
public ObjectProperty<Transaction> transactionProperty() {
return transactionProperty;
}
}

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