upgrade tern to v1.1.2 and use it for bitcoin core rpc and paynym avatar requests
What changed, and why it matters
This commit upgrades an internal networking library called 'tern' and switches Bitcoin Core RPC, PayNym avatar, and Payjoin requests to use it. The change is mostly a refactoring to consolidate HTTP handling, fix proxy-switching races, and add timeouts so unreachable nodes cannot freeze the wallet. It also adds many tests that verify traffic goes through Tor for onion addresses, does not follow HTTP redirects, and pins self-signed HTTPS certificates. There is no direct evidence in the commit that this fixes a known exploit, but it removes risky behaviors such as infinite connection hangs and redirect following that could be abused.
Review the tern 1.1.2 source/diff for any behavioral changes in HttpEndpointClient (redirect policy, cookie handling, certificate validation, proxy resolution). Confirm that the new idle timeout does not break long-polling or rescan RPC calls; the code already disables read timeout for rescanning methods. Run the new tests and consider backporting if prior releases used the old HttpURLConnection path with infinite timeouts and redirect following.
Security signals we found
Replaced infinite HttpURLConnection timeouts with explicit 15s/60s connect and 10s idle timeouts
Added synchronized proxy update path to prevent use of stale Tor proxy
Added Closeable lifecycle to BitcoindTransport so connections are closed on stop/initialization failure
HTTP redirect following is now rejected for Bitcoin Core RPC and Payjoin (tested)
Onion Bitcoin Core RPC is forced through SOCKS5 proxy; clearnet/local nodes are direct
Self-signed HTTPS certificates pinned on first use for Bitcoin Core RPC
Removed Jetty client module requirement and logging configuration
Added tests verifying proxy routing, redirect rejection, certificate pinning, and connection reuse
Evidence from the diff
The patch bumps com.sparrowwallet:tern from 1.0.6 to 1.1.2 and replaces direct java.net.HttpURLConnection/Jetty usage with tern’s HttpEndpointClient for BitcoindTransport, PayNymAvatar, and Payjoin. Key security-relevant changes: finite connect/read/idle timeouts replace infinite HttpURLConnection defaults; BitcoindTransport now keeps a persistent, closable HTTP client and refuses calls after close(); proxy changes are synchronized to prevent clients from being created with a stale proxy; HTTP redirects are no longer followed (verified by new tests); onion RPC traffic is forced through the configured SOCKS proxy while clearnet/local nodes are reached directly; self-signed certificates are pinned on first use. The Jetty client dependency is removed from the runtime module graph. Extensive unit tests cover proxy routing, connection reuse, certificate pinning, redirect rejection, and authentication failure handling.
Changed components
Bitcoin Core RPC client (Cormorant / BitcoindTransport)PayNym avatar fetcherPayjoin senderHttpClientService proxy managementtern HTTP client library (upgraded 1.0.6 -> 1.1.2)Gradle dependency verification metadataInspect captured patch +868 / −149
### build.gradle
@@ -99,7 +99,7 @@ dependencies {
exclude group: 'org.slf4j'
}
implementation('com.sparrowwallet.bokmakierie:bokmakierie:1.0')
- implementation('com.sparrowwallet:tern:1.0.6')
+ implementation('com.sparrowwallet:tern:1.1.2')
implementation('io.reactivex.rxjava2:rxjava:2.2.21')
implementation('io.reactivex.rxjava2:rxjavafx:2.2.2')
implementation('org.apache.commons:commons-lang3:3.20.0')
@@ -202,7 +202,6 @@ jlink {
requires 'java.management'
requires 'io.leangen.geantyref'
requires 'static jdk.jfr'
- uses 'org.eclipse.jetty.http.HttpFieldPreEncoder'
}
options = ['--strip-native-commands', '--strip-java-debug-attributes', '--compress', 'zip-6',
### gradle/verification-keyring.keys
@@ -593,6 +593,21 @@ mQ==
=f998
-----END PGP PUBLIC KEY BLOCK-----
+pub B54011358B352F85
+uid Hibernate CI <ci@hibernate.org>
+
+sub AFF991DD6BE0242B
+-----BEGIN PGP PUBLIC KEY BLOCK-----
+
+xjMEZwlfmRYJKwYBBAHaRw8BAQdA0ZVao17fCCG8/hpKEDnRxkcjzRoT5kmnyZnm
+uI6Omga0H0hpYmVybmF0ZSBDSSA8Y2lAaGliZXJuYXRlLm9yZz7OOARnCV+ZEgor
+BgEEAZdVAQUBAQdAZa1sNRHAwybohdKbrQc5WSz+Sfl+dShvdR2GFq9FaXoDAQgH
+wn4EGBYKACYWIQQUUvNYSbUHUPaju7S1QBE1izUvhQUCZwlfmQIbDAUJBaOagAAK
+CRC1QBE1izUvhWpMAPwJHGSU4W/BQxFSOFxSilxMHppQbv7tGRzYBmHBWzJp1AD/
+eipSJKo5kDL0w8TH1kXEzDc0EzTG/pdKs9TNwY9kUgs=
+=Xwtt
+-----END PGP PUBLIC KEY BLOCK-----
+
pub BAC30622339994C4
uid Chris Povirk <cpovirk@google.com>
@@ -862,6 +877,39 @@ OhemOO8PfYD0piMAZHpQExX4drPjhUxNvA6Dbt5WJJ6Q6UycHgT1yIM5vTCcKKFp
=v/f7
-----END PGP PUBLIC KEY BLOCK-----
+pub D9C565AA72BA2FDD
+sub 9121AD263441EEDD
+-----BEGIN PGP PUBLIC KEY BLOCK-----
+
+xsDNBFrjUQUBDADTMQL/4d9EyVhsO4XBH9wbGWxcEJvsu/HvppN5fY8hpMV0+Cr9
+wjAeJ7d9zdFJVB8vPLN7bb5dm6SNyK3KiOugqVgZrQ+ZPTvCCgFbFyEXuZwDiOa1
+9oMwKypq+GyAqXnfNkQTx8+7PAKslPoEKeft6g7T2+hb73nf2vpnOfpp5ljQhWPe
+YEO2kXIikCxVXK5uSpuq1JLjLB+AFsnERCEGqOCueQgrLyPZnGrk6i3pEyz8b6Mh
+8NdFjztqBWUta+e26Z00CKEpmGYzoV3sHD8Bhf8aHPWUHp9lGIAW3klLbsp1+FVM
+20eF+a/f7XK9YBzd2dqIYWELdYUB+XU0EPFTgYAsXG1Z34ObgOVjU5gjDSNYfvz7
+tPPngDB7k9w7n2NatF3aHpHvkgekaLlflmZ5rQnMadhBUWgJoiwsx2q4TnSh70/t
+TI3dPBbdVG+8YQ/LpNzOVshY2uMHHxJq6lUGVl6BIIy83Yslu0gFYHzL7H2tXKpg
+Q0qAQBktmX6H/P0AEQEAAc7AzQRa41EFAQwAquSR3AR/8vClCEfG5TjqL9+eHEIF
++MfnheM58ONv+ZW96S6WBfYALTzLNM0BYcIChRwq/EsWWPp2IvYdaVC6miyV3jS2
+YqWqFLn8lwC8lyaI7wX+ee1JY5b2TOCep9MRzFTOTbh8RpJDaGcjK6g6rGq27C2N
++bLIs3Pn8F6uHT5shp+YQksMHNWfw16hWnSvI0naO5JVccLZwZThZUqkN4k9KPaa
+QeYdd+coJBmN730rKq8VxNgoNWO70AXa4Qt7ddnSAmQM6iP7H2C+RI8NQ2GNh+HO
+b21jyI+ZkUDQrFJKLReAbfyADhzedJT6aAyzA60wJwab05lP77CzVn2dOpzCY/hZ
+uM2faz33YEZ03RapYeYhRIUYpXT0nR03dc8NbRVtUqYFSKOPab0CI5UmnML82v6G
+o8N6eRTiSXHGwGEbr3pCLwTFUJTYdku0xGA9TCnXTjUsNW7+Cco6bTUmtEZOGomR
+GBhI0qG9Uj73jWXNZLgLvfFYj27Sjb/spVARABEBAAHCwPYEGAEKACAWIQSwIzWq
+VMzyHlK7+avZxWWqcrov3QUCWuNRBQIbDAAKCRDZxWWqcrov3fslDACSodXt2F9p
+haTM9aArlcNszxMLSb0ixO6ufdm9PS8kzlziot3lZrxVcEDEkqM9CUHyDaAf4ZB3
+geb81NGrYDdrFEwNYVaxK19ay3aYxKyfup+r1V32XKxTF348JsboZ72wKig0OQpt
+ZnspDq14BkSIJR1SQbOCkJwnHUv29Lsro7NxN4QUddYwLoOHlFwO51jlSO1ngsYy
+5QOfoAszn4kV9zY5eJAUF/npCHMTvPACZn/zZUo0ycxAt7f6NE3OnTfmWMaTk9Hi
+AgucaxI9lmk6BN3FOOeUqt2VslIMb4k1pX7FRRsvzNuWTJO9S8DPlpg4WjzWtu/c
+HYCSq6h3mwojlt+h7SA6Ctl1uA+umidvPp7ozubbxsGdCCdxGSVg4zX/L02i+5fE
+zU7kkPUpKBx6hHg/zJnwTVAY/g4+Iw6CHwBhw+2/KoMpjQ63VqjwQZ6+VIwdsSCh
+4wzAJkf+DhvDmH/G9sIawu3JcVj1Pza0Iw3gLf/9xZrbnl+HUEcs+F4=
+=r0xI
+-----END PGP PUBLIC KEY BLOCK-----
+
pub DB9F4F2943F9BBC7
uid Abhinay Agarwal <abhinay_agarwal@live.com>
@@ -1069,6 +1117,18 @@ T2Pyh+fy0MK9TmH/0PLbOoUKyJO/b1enQliz2e34AmB6yZJNgrqq0RSMiw==
=/kF9
-----END PGP PUBLIC KEY BLOCK-----
+pub E7D88DB8427DE651
+sub D557964963279019
+-----BEGIN PGP PUBLIC KEY BLOCK-----
+
+xjMEaFwfvhYJKwYBBAHaRw8BAQdAEsx4lY6imvhSy+Um2DbNEfH7oOJmws4i/oBy
+iepGULTOOARoXB++EgorBgEEAZdVAQUBAQdA3bv22tzo93V7jbULXk6BHxf5rzi8
+bX0oEyiHHRfShBMDAQgHwn4EGBYKACYWIQRuf5EAF2VWIqiZY57n2I24Qn3mUQUC
+aFwfvgIbDAUJBaOagAAKCRDn2I24Qn3mUYlGAP9My4h88h8XASO55IhMca7EpfZz
+ZanyHDxGUmeaiSAzUwEAw9oqWpF+Gi+ymc7tayOZygabbDeneSgUe1lxCyGDHgM=
+=sv5V
+-----END PGP PUBLIC KEY BLOCK-----
+
pub F2A01147D830C125
uid Eddu Melendez <eddu.melendez@gmail.com>
@@ -2608,6 +2668,21 @@ RGXo6d4JGgZhOFNGmqjkidVCl3/GpgMkBnHSM0Tcft2qRR59IdsmjLo=
=nrJW
-----END PGP PUBLIC KEY BLOCK-----
+pub 4DB5EA09F2E3C800
+uid Olivier Lamy <olamy@apache.org>
+
+sub 195EA2AF25C01AFB
+-----BEGIN PGP PUBLIC KEY BLOCK-----
+
+xjMEajtiuxYJKwYBBAHaRw8BAQdAu9n6HjScTA+FNmuLwyoJ7/4/DHju7Mf1nJgV
+usnAHE20H09saXZpZXIgTGFteSA8b2xhbXlAYXBhY2hlLm9yZz7OOARqO2K7Egor
+BgEEAZdVAQUBAQdAeHshMpESy5EWC56c0WFzzug+6MZAisbUgtT2FRlQjy0DAQgH
+wncEGBYKACAWIQRxbuMCZ0zbsuZg4bRNteoJ8uPIAAUCajtiuwIbDAAKCRBNteoJ
+8uPIAAOAAPY5ZDyRO8VjKrC81V47yOKr/xK02JH2hL+EmesuXTJSAQDEF17KfttR
+KcddyYjlZLhE3F/NHw26R1ldfGWvTDe4AQ==
+=QM2A
+-----END PGP PUBLIC KEY BLOCK-----
+
pub 530AA5F25C25011F
uid Gary Gregory <ggregory@apache.org>
### gradle/verification-metadata.xml
@@ -33,7 +33,6 @@
<trusted-key id="3F05DDA9F317301E927136D417A27CE7A60FF5F0" group="io.opentelemetry"/>
<trusted-key id="41B962CF9AA2A26FF1F234D2A6144824624A3CBA" group="io.leangen.geantyref" name="geantyref" version="2.0.1"/>
<trusted-key id="41CD49B4EF5876F9E9F691DABAC30622339994C4" group="org.jspecify" name="jspecify" version="1.0.0"/>
- <trusted-key id="5989BAF76217B843D66BE55B2D0E1FB8FE4B68B4" group="org.eclipse.jetty"/>
<trusted-key id="5E13B520F0BCBB359C6ED54A4A23006A8E767508" group="org.reactfx" name="reactfx" version="2.0-M5"/>
<trusted-key id="60200AC4AE761F1614D6C46766D68DAA073BE985">
<trusting group="ch.qos.logback"/>
@@ -44,6 +43,7 @@
<trusted-key id="66D7CBFF956830FE9F5A723AFE6C7D77A1CE15A6" group="org.gradlex" name="extra-java-module-info" version="1.13.1"/>
<trusted-key id="698B135CC8820C57837DE099597CBBDBE4F6F054" group="org.pgpainless" name="pgpainless-core" version="1.7.8"/>
<trusted-key id="6F538074CCEBF35F28AF9B066A0975F8B1127B83" group="org.jetbrains.kotlin"/>
+ <trusted-key id="716EE302674CDBB2E660E1B44DB5EA09F2E3C800" group="^org[.]eclipse[.]jetty($|([.].*))" regex="true"/>
<trusted-key id="7616EB882DAF57A11477AAF559A252FB1199D873" group="com.google.code.findbugs" name="jsr305" version="3.0.2"/>
<trusted-key id="782AF7972653864E80AD3CFD20DBD25146A6FAF1" group="^org[.]kotlincrypto($|([.].*))" regex="true"/>
<trusted-key id="794BD400C665C604EB077BDAC64BEB3E97C774F7" group="com.github.librepdf"/>
@@ -480,12 +480,12 @@
<sha512 value="4fcc8623b33f16a54e1d6bbd6c1f8eba5ca5d55cbcabc34a0d182d9a6b20c9206bfedc11f9523421560c88659e5a68a9ad0a6f7325f1069003dd4574deeef498" origin="Generated by Gradle"/>
</artifact>
</component>
- <component group="com.sparrowwallet" name="tern" version="1.0.6">
- <artifact name="tern-1.0.6.jar">
- <sha512 value="f51c19cea90cd8e80d1f2ded2c93fa9c3a13f12f05941cc2b6069572aa90b4f1263c3a11cbc295d2491b0c11077fd973e99f8fd1adb2f0afb5b381ee3168e572" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ <component group="com.sparrowwallet" name="tern" version="1.1.2">
+ <artifact name="tern-1.1.2.jar">
+ <sha512 value="e576f8f434999456257a281758795b2becf539d2afaaddf2214c7b2d7a3058f77fb30ae007070d6ce38d86d0d3f544a1ecd728a269c6053396806af361874555" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
- <artifact name="tern-1.0.6.module">
- <sha512 value="af9ea71741a2091b85b1942c0680e03a33ad14a50e8d8107537e50afa808f64512bd5e1908ae86a2bbd8f72740bb20305684b9994594a8d02e2a3afd975feab4" origin="Generated by Gradle" reason="Artifact is not signed"/>
+ <artifact name="tern-1.1.2.module">
+ <sha512 value="3f3074389a190111e2d7884bf523de2c3a72d661d09e016db9750f1b4fe0deed9e093cd322e6cc87e59e1180a32eab4cef7a544ff8c7ac51f11150c7da5fc7a0" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
</component>
<component group="com.sparrowwallet" name="toucan" version="0.9.0">
@@ -608,6 +608,11 @@
<sha512 value="3a65cf891db8bb75fbe5873d387f376a3a27f47ef42cb0c1822ad1d4b15f5df763a735e716a8929b4ce354715fd6ba2fe22669cd7445c877ea38c7d2f7434f8a" origin="Generated by Gradle"/>
</artifact>
</component>
+ <component group="io.grpc" name="grpc-bom" version="1.85.1">
+ <artifact name="grpc-bom-1.85.1.pom">
+ <pgp value="B02335AA54CCF21E52BBF9ABD9C565AA72BA2FDD"/>
+ </artifact>
+ </component>
<component group="io.leangen.geantyref" name="geantyref" version="2.0.1">
<artifact name="geantyref-2.0.1.jar">
<sha512 value="c6655ef00ede5d9bb17d4e7556200acaeb5babd67295e9f72e26e8ea48fd50978cc147156e35feada204163163292ad3a0daf0d6b1366c9e933f13a1b4a9eb2f" origin="Generated by Gradle"/>
@@ -1054,43 +1059,6 @@
<sha512 value="283935c2ec0adba07286c09f333be41fb63e92703ba11fe8aba38325e0bfe268570063b9f409d2d142b326568f2f7aea428c4fbefa81eaec198f6baf1e8ef11a" origin="Generated by Gradle"/>
</artifact>
</component>
- <component group="org.eclipse.jetty" name="jetty-client" version="9.4.54.v20240208">
- <artifact name="jetty-client-9.4.54.v20240208.jar">
- <sha512 value="ccfdf2f7cf773f4f131caa2709e167a7d2dd2a926062b1df0034eceaba9d878fb792dc2874402be133dda72fc8395cc1919919b6df0e4a582c62d50522926e91" origin="Generated by Gradle"/>
- </artifact>
- <artifact name="jetty-client-9.4.54.v20240208.pom">
- <sha512 value="2eee046bf84165d222a0d3fa06fea23a34f21010a816f40df231942fc8f34707633239ec4000bec4092f36dfc045610bca96b9e238f9b21039d84838dfb018d1" origin="Generated by Gradle"/>
- </artifact>
- </component>
- <component group="org.eclipse.jetty" name="jetty-http" version="9.4.54.v20240208">
- <artifact name="jetty-http-9.4.54.v20240208.jar">
- <sha512 value="6e1d6fdffcb2acf8daa9ce5b3ad973526a30b3556dc8e950254c68c64cd70e101b28a8acac41b3bd74de6b9c8eac10676afdc3c58ccb1f61a74323721592e0b5" origin="Generated by Gradle"/>
- </artifact>
- <artifact name="jetty-http-9.4.54.v20240208.pom">
- <sha512 value="417d434506bf6e8e34d87d398aa60bc73a1b75f894468c92cdf8aeac697e5bcbacc091fbb85447deb01973199c9f682928b52473aaa6818d5ddcffd9de04e7db" origin="Generated by Gradle"/>
- </artifact>
- </component>
- <component group="org.eclipse.jetty" name="jetty-io" version="9.4.54.v20240208">
- <artifact name="jetty-io-9.4.54.v20240208.jar">
- <sha512 value="72af20a535ea6cc8d55d651a661a10548036ac800d902ffbdfe8c57afbc166043c0e467a9a5b59c31c9b6d8a10f65d1ee17bf6b5c37e9b3c46b896df9ca52614" origin="Generated by Gradle"/>
- </artifact>
- <artifact name="jetty-io-9.4.54.v20240208.pom">
- <sha512 value="a7d5bb2e0a56b4c552ad06446b1ed24ebd443126479de6422ee541be275aaf14103f0cc2197f2b8d659e631e45a9c1234e3ce397cfdffe91e95593cb88ff7aba" origin="Generated by Gradle"/>
- </artifact>
- </component>
- <component group="org.eclipse.jetty" name="jetty-project" version="9.4.54.v20240208">
- <artifact name="jetty-project-9.4.54.v20240208.pom">
- <sha512 value="fb4345ab4fc71acb3c381d9e8155bd2966dfced6c89770abb642d8d964a43e4f8c61fc6ae6ab239b6ecca575dc28aa13b3511280d7283ae1991b0040553aeb5c" origin="Generated by Gradle"/>
- </artifact>
- </component>
- <component group="org.eclipse.jetty" name="jetty-util" version="9.4.54.v20240208">
- <artifact name="jetty-util-9.4.54.v20240208.jar">
- <sha512 value="fbe9cf7efeba9f29297f75de3f1c2d98f0e02816a1dc9e6eaddcabb84c3a699a9332218c532017a3707ec57f4f99066bc671708bde4ec84dd873b8403422d7e9" origin="Generated by Gradle"/>
- </artifact>
- <artifact name="jetty-util-9.4.54.v20240208.pom">
- <sha512 value="fd3753fd4c6718365f92979b4fc771d10e8cd6b3bd98aba71df5f8b66aa60d7a4b510859e4120f1c3223df2d68751d2a4700dec69e4d8b439cb4603bcb0c306f" origin="Generated by Gradle"/>
- </artifact>
- </component>
<component group="org.flywaydb" name="flyway-core" version="13.12.1">
<artifact name="flyway-core-13.12.1.jar">
<sha512 value="9950a94f092e61c761ecbf36380382283bd9178a93eea06f2fc6286b16a56b933d3c99bdb20b535735cb29b94ff9207479fbb4c8202ff0e9433dd915d5695291" origin="Generated by Gradle"/>
@@ -1162,6 +1130,11 @@
<sha512 value="b363990000a0f8ae4c4251ffde2e5bf51c8fed93a667d2232fd6c08a916cd42089cb8bed127a877926488fe677b9457445aad755bef6bf18f0116275d03558bd" origin="Generated by Gradle" reason="Artifact is not signed"/>
</artifact>
</component>
+ <component group="org.hibernate.search" name="hibernate-search-bom" version="8.4.0.Final">
+ <artifact name="hibernate-search-bom-8.4.0.Final.pom">
+ <pgp value="1452F35849B50750F6A3BBB4B54011358B352F85"/>
+ </artifact>
+ </component>
<component group="org.infinispan" name="infinispan-bom" version="11.0.18.Final">
<artifact name="infinispan-bom-11.0.18.Final.pom">
<sha512 value="07b3f880b40e112422da5e0409517c72cc1a8d4e900a139060868235b8d462f32865aa3c3506217a4300e55571a230835fd3bcf7bf39a52ad8b871ccc2c479b1" origin="Generated by Gradle"/>
@@ -1686,6 +1659,11 @@
<sha512 value="a34a1cc4ac50724e0798f4d8ee677207ba68e4f311d9d5cc200dd9351ea63f556589aa42c7a0df90b53634ae41bae3646d5115eb029aab11077a20f7b144bf3f" origin="Generated by Gradle"/>
</artifact>
</component>
+ <component group="org.ow2.asm" name="asm-bom" version="9.11.1">
+ <artifact name="asm-bom-9.11.1.pom">
+ <pgp value="A5BD02B93E7A40482EB1D66A5F69AD087600B22C"/>
+ </artifact>
+ </component>
<component group="org.pgpainless" name="pgpainless-core" version="1.7.8">
<artifact name="pgpainless-core-1.7.8.jar">
<sha512 value="3df2c2ec8d47f17eecdab906625cab630a4293ca8b88373418f049e906eca751af02a1e787bacafeccf36ea925642d22f70a4b48fe694d76cad81962a842e438" origin="Generated by Gradle"/>
@@ -1764,6 +1742,11 @@
<sha512 value="011934b4af3997113dab331c923fa168761a97cf21f408a9d857d9f78a4a81443a37141f8a030c2937b487fb6130e0eee09e8be00e5266e0513ae10dc1d60f3c" origin="Generated by Gradle"/>
</artifact>
</component>
+ <component group="org.testcontainers" name="testcontainers-bom" version="2.0.5">
+ <artifact name="testcontainers-bom-2.0.5.pom">
+ <pgp value="6E7F910017655622A899639EE7D88DB8427DE651"/>
+ </artifact>
+ </component>
<component group="tools.jackson" name="jackson-bom" version="3.0.3">
<artifact name="jackson-bom-3.0.3.pom">
<pgp value="28118C070CB22A0175A2E8D43D12CA2AC19F3181"/>
### lark
@@ -1 +1 @@
-Subproject commit d6fa9ed1c7517a5281c14a06ab10251d0c9257d4
+Subproject commit 5fc7c4516d07499d44ca96921f423997a253ec59
### src/main/java/com/sparrowwallet/sparrow/control/PayNymAvatar.java
@@ -5,6 +5,7 @@
import com.sparrowwallet.sparrow.EventManager;
import com.sparrowwallet.sparrow.event.PayNymImageLoadedEvent;
import com.sparrowwallet.sparrow.io.Config;
+import com.sparrowwallet.sparrow.net.HttpClientService;
import com.sparrowwallet.sparrow.paynym.PayNymService;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
@@ -17,9 +18,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.io.ByteArrayInputStream;
import java.io.InputStream;
-import java.net.Proxy;
-import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@@ -116,14 +116,14 @@ protected Image call() throws Exception {
}
synchronized(lock) {
- Proxy proxy = AppServices.getProxy();
- String url = PayNymService.getHostUrl(proxy != null) + "/" + paymentCodeStr + "/avatar";
+ HttpClientService httpClientService = AppServices.getHttpClientService();
+ String url = PayNymService.getHostUrl(httpClientService.getTorProxy() != null) + "/" + paymentCodeStr + "/avatar";
if(log.isDebugEnabled()) {
log.debug("Requesting PayNym avatar from " + url);
}
- try(InputStream is = (proxy == null ? new URI(url).toURL().openStream() : new URI(url).toURL().openConnection(proxy).getInputStream())) {
+ try(InputStream is = new ByteArrayInputStream(httpClientService.requestBytes(url, null))) {
Image image = new Image(is, 150, 150, true, true);
if(image.getException() != null) {
throw image.getException();
### src/main/java/com/sparrowwallet/sparrow/net/HttpClientService.java
@@ -19,9 +19,12 @@ public HostAndPort getTorProxy() {
public void setTorProxy(HostAndPort torProxy) {
if(getHttpProxySupplier() instanceof TorHttpProxySupplier torHttpProxySupplier) {
- //Ensure all http clients are shutdown first
- stop();
- torHttpProxySupplier._setTorProxy(torProxy);
+ //A client takes its proxy when created, so the proxy is changed before the clients created with the previous one are stopped. Holding the lock that
+ //getHttpClient() takes ensures no client is created in between.
+ synchronized(this) {
+ torHttpProxySupplier._setTorProxy(torProxy);
+ stop();
+ }
}
}
### src/main/java/com/sparrowwallet/sparrow/net/cormorant/Cormorant.java
@@ -42,7 +42,12 @@ public Server start() throws CormorantBitcoindException {
}
bitcoindClient = new BitcoindClient(useWallets);
- bitcoindClient.initialize();
+ try {
+ bitcoindClient.initialize();
+ } catch(CormorantBitcoindException | RuntimeException e) {
+ bitcoindClient.stop();
+ throw e;
+ }
Thread importThread = new Thread(() -> {
try {
### src/main/java/com/sparrowwallet/sparrow/net/cormorant/bitcoind/BitcoindClient.java
@@ -61,6 +61,7 @@ public class BitcoindClient {
private final JsonRpcClient jsonRpcClient;
private final Timer timer = new Timer(true);
+ private final BitcoindTransport bitcoindTransport;
private final Store store = new Store();
private NetworkInfo networkInfo;
@@ -103,8 +104,6 @@ public class BitcoindClient {
private long timerTaskCount;
public BitcoindClient(boolean useWallets) {
- BitcoindTransport bitcoindTransport;
-
Config config = Config.get();
if((config.getCoreAuthType() == CoreAuthType.COOKIE || config.getCoreAuth() == null || config.getCoreAuth().length() < 2) && config.getCoreDataDir() != null) {
bitcoindTransport = new BitcoindTransport(config.getCoreServer(), CORE_WALLET_NAME, config.getCoreDataDir());
@@ -464,6 +463,7 @@ private Set<String> addDescriptors(Map<String, ScanDate> descriptors) throws Sca
public void stop() {
timer.cancel();
+ bitcoindTransport.close();
pruneWarnedDescriptors.clear();
importFailedDescriptors.clear();
stopped = true;
### src/main/java/com/sparrowwallet/sparrow/net/cormorant/bitcoind/BitcoindTransport.java
@@ -11,6 +11,9 @@
import com.sparrowwallet.sparrow.io.Storage;
import com.sparrowwallet.sparrow.net.Protocol;
import com.sparrowwallet.sparrow.net.TcpOverTlsTransport;
+import com.sparrowwallet.tern.http.client.HttpEndpointClient;
+import com.sparrowwallet.tern.http.client.HttpProxy;
+import com.sparrowwallet.tern.http.client.HttpProxyProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -21,17 +24,18 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.cert.Certificate;
-import java.util.Base64;
-import java.util.Set;
+import java.time.Duration;
+import java.util.*;
-public class BitcoindTransport implements Transport {
+public class BitcoindTransport implements Transport, Closeable {
private static final Logger log = LoggerFactory.getLogger(BitcoindTransport.class);
public static final String COOKIE_FILENAME = ".cookie";
- //Neither timeout was set, and HttpURLConnection defaults both to 0 (infinite), so a node that could not be reached, or that accepted the connection but never replied, hung
- //the calling thread forever. A node is expected to be quickly reachable, but connecting to an onion address must first build a circuit.
- private static final int CONNECT_TIMEOUT_MILLIS = 15_000;
- private static final int ONION_CONNECT_TIMEOUT_MILLIS = 60_000;
+ //A node that cannot be reached must not hang the calling thread. A node is expected to be quickly reachable, but connecting to an onion address must first build a circuit.
+ private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(15);
+ private static final Duration ONION_CONNECT_TIMEOUT = Duration.ofSeconds(60);
+ //Below Bitcoin Core's default rpcservertimeout of 30 seconds, so that the node does not close a connection as it is reused
+ private static final Duration IDLE_TIMEOUT = Duration.ofSeconds(10);
//A backstop against a hung thread rather than a limit on how long the user waits, since TcpTransport already bounds the Electrum requests these calls serve. Set well beyond
//any legitimate call, and never below the timeout the Electrum layer above allows.
private static final int READ_TIMEOUT_MILLIS = 300_000;
@@ -42,11 +46,13 @@ public class BitcoindTransport implements Transport {
private final Server bitcoindServer;
//Package visible so tests need not wait it out
int readTimeoutMillis;
- private URL bitcoindUrl;
+ private URI bitcoindUri;
private File cookieFile;
private Long cookieFileTimestamp;
private String bitcoindAuthEncoded;
- private SSLSocketFactory sslSocketFactory;
+ private HttpEndpointClient httpClient;
+ private String httpClientProxy;
+ private boolean closed;
public BitcoindTransport(Server bitcoindServer, String bitcoindWallet, String bitcoindAuth) {
this(bitcoindServer, bitcoindWallet);
@@ -66,91 +72,57 @@ private BitcoindTransport(Server bitcoindServer, String bitcoindWallet) {
if(!bitcoindServer.getHostAndPort().hasPort()) {
serverUrl += ":" + Network.get().getDefaultPort();
}
- this.bitcoindUrl = new URI(serverUrl + "/wallet/" + bitcoindWallet).toURL();
- } catch(MalformedURLException | URISyntaxException e) {
+ this.bitcoindUri = new URI(serverUrl + "/wallet/" + bitcoindWallet);
+ } catch(URISyntaxException e) {
log.error("Malformed Bitcoin Core RPC URL", e);
}
}
@Override
public String pass(String request) throws IOException {
- //Bitcoin Core RPC is a connection to the user's own node, expected to be on this computer or the local network, or reached over its onion service or a VPN or SSH tunnel.
- //A configured proxy is therefore applied to onion addresses only - AppServices.getProxy() is also non-null whenever the internal Tor is running, and Tor can reach neither
- //loopback nor private addresses, while routing a clearnet node through it would expose the RPC credentials below to an exit node.
- //Configuring a node that is neither local nor onion warns the user on testing the connection or closing the dialog, see ServerSettingsController.
- Proxy proxy = AppServices.getProxy();
- boolean useProxy = proxy != null && Protocol.isOnionAddress(bitcoindServer);
- HttpURLConnection connection = useProxy ? (HttpURLConnection)bitcoindUrl.openConnection(proxy) : (HttpURLConnection)bitcoindUrl.openConnection();
-
- if(connection instanceof HttpsURLConnection httpsURLConnection) {
- SSLSocketFactory sslSocketFactory = getSSLSocketFactory();
- if(sslSocketFactory != null) {
- httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
- //A private node's RPC certificate is necessarily self-signed, so the certificate pinned on first use below authenticates it - there is no hostname to verify
- httpsURLConnection.setHostnameVerifier((_, _) -> true);
- }
- }
-
- connection.setRequestMethod("POST");
- connection.setRequestProperty("Content-Type", "application/json");
+ HttpProxy proxy = getHttpProxy();
+ HttpEndpointClient client = getHttpClient(proxy);
+ Map<String, String> headers = new HashMap<>();
String auth = getBitcoindAuthEncoded();
if(auth != null) {
- connection.setRequestProperty("Authorization", "Basic " + auth);
+ headers.put("Authorization", "Basic " + auth);
}
- connection.setDoOutput(true);
- connection.setConnectTimeout(useProxy ? ONION_CONNECT_TIMEOUT_MILLIS : CONNECT_TIMEOUT_MILLIS);
- connection.setReadTimeout(isRescanningMethod(request) ? 0 : readTimeoutMillis);
+ Duration readTimeout = isRescanningMethod(request) ? Duration.ZERO : Duration.ofMillis(readTimeoutMillis);
log.debug("> " + request);
//From v32.1 Bitcoin Core closes the connection from a client outside rpcallowip without answering, where earlier versions answered 403 below
- String closedMessage = "Bitcoin Core at " + bitcoindUrl.getAuthority() + " closed the connection without responding, check its rpcallowip settings";
-
- try(OutputStream os = connection.getOutputStream()) {
- byte[] jsonBytes = request.getBytes(StandardCharsets.UTF_8);
- os.write(jsonBytes);
- } catch(SocketException e) {
- //The close can also reset the connection before the connect completes, where other socket errors (unreachable network, local firewall) never reached the node,
- //and a reset from a SOCKS proxy is the proxy's own failure
- if(!useProxy && e.getMessage() != null && e.getMessage().contains("Connection reset")) {
- throw new IOException(closedMessage, e);
- }
- throw e;
- }
+ String closedMessage = "Bitcoin Core at " + bitcoindUri.getAuthority() + " closed the connection without responding, check its rpcallowip settings";
- int statusCode;
+ HttpEndpointClient.Response httpResponse;
try {
- statusCode = connection.getResponseCode();
- } catch(InterruptedIOException e) {
- throw e;
- } catch(IOException e) {
+ httpResponse = client.send("POST", bitcoindUri, headers, "application/json", request.getBytes(StandardCharsets.UTF_8), readTimeout);
+ } catch(EOFException e) {
+ //Also thrown where the node resets the connection instead of closing it, as the client reports a failed read or write on a connected socket as its end
throw new IOException(closedMessage, e);
}
+ int statusCode = httpResponse.statusCode();
+
//Trust on first use, as for non-CA-certified Electrum servers: the certificate presented by the node on the first connection is saved, and required on all connections thereafter
- if(connection instanceof HttpsURLConnection httpsConn && Storage.getCertificateFile(bitcoindServer.getHost()) == null) {
- try {
- Certificate[] certs = httpsConn.getServerCertificates();
- if(certs.length > 0) {
- Storage.saveCertificate(bitcoindServer.getHost(), certs[0]);
- sslSocketFactory = null;
- }
- } catch(SSLPeerUnverifiedException e) {
- log.warn("Could not retrieve certificate for saving", e);
+ if(isHttps() && Storage.getCertificateFile(bitcoindServer.getHost()) == null) {
+ Certificate[] certs = httpResponse.serverCertificates();
+ if(certs.length > 0) {
+ Storage.saveCertificate(bitcoindServer.getHost(), certs[0]);
+ closeHttpClient();
}
}
if(statusCode == 401) {
throw new IOException((cookieFile == null ? "User/pass" : "Cookie file") + " authentication failed");
} else if(statusCode == 403) {
- throw new IOException("Bitcoin Core at " + bitcoindUrl.getAuthority() + " refused RPC access from this computer, check its rpcallowip and rpcwhitelist settings");
+ throw new IOException("Bitcoin Core at " + bitcoindUri.getAuthority() + " refused RPC access from this computer, check its rpcallowip and rpcwhitelist settings");
}
- InputStream inputStream = connection.getErrorStream() == null ? connection.getInputStream() : connection.getErrorStream();
StringBuilder res = new StringBuilder();
- try(BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
+ try(BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(httpResponse.body()), StandardCharsets.UTF_8))) {
String responseLine;
while((responseLine = br.readLine()) != null) {
//Bitcoin Core returns a null result alongside the error on a failed call, which the client deserializes to a null return value instead of throwing the error.
@@ -169,12 +141,61 @@ public String pass(String request) throws IOException {
//A response carrying neither a result nor an error leaves the client constructing a JsonRpcException from a null error message, which throws a NullPointerException naming nothing.
//Bitcoin Core always answers with a JSON-RPC object, so an empty or HTML body here comes from something else on the network path - typically a TLS terminating proxy sent a plain HTTP request.
if(!response.startsWith("{")) {
- throw new IOException("Bitcoin Core at " + bitcoindUrl.getAuthority() + " did not return a JSON-RPC response to the " + bitcoindUrl.getProtocol() + " request (HTTP " + statusCode + ")");
+ throw new IOException("Bitcoin Core at " + bitcoindUri.getAuthority() + " did not return a JSON-RPC response to the " + bitcoindUri.getScheme() + " request (HTTP " + statusCode + ")");
}
return response;
}
+ //Bitcoin Core RPC is a connection to the user's own node, expected to be on this computer or the local network, or reached over its onion service or a VPN or SSH tunnel.
+ //A configured proxy is therefore applied to onion addresses only - AppServices.getProxy() is also non-null whenever the internal Tor is running, and Tor can reach neither
+ //loopback nor private addresses, while routing a clearnet node through it would expose the RPC credentials to an exit node.
+ //Configuring a node that is neither local nor onion warns the user on testing the connection or closing the dialog, see ServerSettingsController.
+ private HttpProxy getHttpProxy() {
+ Proxy proxy = AppServices.getProxy();
+ if(proxy == null || !Protocol.isOnionAddress(bitcoindServer) || !(proxy.address() instanceof InetSocketAddress proxyAddress)) {
+ return null;
+ }
+
+ return new HttpProxy(HttpProxyProtocol.SOCKS5, proxyAddress.getHostString(), proxyAddress.getPort());
+ }
+
+ //The client keeps connections open between calls, and is replaced when the proxy changes or a certificate is saved on first use
+ private synchronized HttpEndpointClient getHttpClient(HttpProxy proxy) throws IOException {
+ if(closed) {
+ throw new IOException("Bitcoin Core connection to " + bitcoindUri.getAuthority() + " is closed");
+ }
+
+ String proxyKey = String.valueOf(proxy);
+ if(httpClient != null && !proxyKey.equals(httpClientProxy)) {
+ closeHttpClient();
+ }
+
+ if(httpClient == null) {
+ httpClient = new HttpEndpointClient("BitcoindTransport", proxy, isHttps() ? createSSLContext() : null, proxy == null ? CONNECT_TIMEOUT : ONION_CONNECT_TIMEOUT, IDLE_TIMEOUT);
+ httpClientProxy = proxyKey;
+ }
+
+ return httpClient;
+ }
+
+ private synchronized void closeHttpClient() {
+ if(httpClient != null) {
+ httpClient.close();
+ httpClient = null;
+ }
+ }
+
+ @Override
+ public synchronized void close() {
+ closed = true;
+ closeHttpClient();
+ }
+
+ private boolean isHttps() {
+ return "https".equalsIgnoreCase(bitcoindUri.getScheme());
+ }
+
//Parses the method as TcpTransport does for Electrum notifications, so that a parameter value cannot match
static boolean isRescanningMethod(String request) {
try(JsonParser parser = JSON_FACTORY.createParser(request)) {
@@ -230,23 +251,16 @@ private static File getCookieDir(File bitcoindDir) {
return bitcoindDir;
}
- private SSLSocketFactory getSSLSocketFactory() {
- if(sslSocketFactory == null) {
- sslSocketFactory = createSSLSocketFactory();
- }
-
- return sslSocketFactory;
- }
-
- private SSLSocketFactory createSSLSocketFactory() {
+ //A private node's RPC certificate is necessarily self-signed, so the certificate pinned on first use authenticates it - there is no hostname to verify
+ private SSLContext createSSLContext() {
try {
String host = bitcoindServer.getHost();
TrustManager[] trustManagers = TcpOverTlsTransport.getTrustManagers(Storage.getCertificateFile(host), host);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, null);
- return sslContext.getSocketFactory();
+ return sslContext;
} catch(Exception e) {
- log.error("Error creating SSL socket factory", e);
+ log.error("Error creating SSL context", e);
return null;
}
}
### src/main/java/com/sparrowwallet/sparrow/payjoin/Payjoin.java
@@ -16,6 +16,7 @@
import com.sparrowwallet.sparrow.net.HttpClientService;
import com.sparrowwallet.sparrow.net.Protocol;
import com.sparrowwallet.tern.http.client.HttpResponseException;
+import com.sparrowwallet.tern.http.client.HttpUsage;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import org.slf4j.Logger;
@@ -29,6 +30,8 @@
public class Payjoin {
private static final Logger log = LoggerFactory.getLogger(Payjoin.class);
+ //The PSBT is sent only to the payjoin url given in the payment request, which was checked to be https or onion
+ private static final HttpUsage HTTP_USAGE = new HttpUsage("Payjoin", false);
private final BitcoinURI payjoinURI;
private final Wallet wallet;
@@ -92,7 +95,7 @@ public PSBT requestPayjoinPSBT(boolean allowOutputSubstitution) throws PayjoinRe
throw new PayjoinReceiverException("Configure a Tor proxy to get a payjoin transaction from " + finalUri.getHost() + ".");
}
- String response = httpClientService.postString(finalUri.toString(), null, "text/plain", base64Psbt);
+ String response = httpClientService.postString(HTTP_USAGE, finalUri.toString(), null, "text/plain", base64Psbt);
PSBT proposalPsbt = PSBT.fromString(response.trim());
checkProposal(psbt, proposalPsbt, changeOutputIndex, maxAdditionalFeeContribution, minFeeRate, allowOutputSubstitution);
### src/main/resources/logback.xml
@@ -15,21 +15,7 @@
<logger name="org.flywaydb.core.internal.database.base.Schema" level="WARN" />
<logger name="org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory" level="WARN" />
<logger name="org.flywaydb.core.internal.license.VersionPrinter" level="WARN" />
- <logger name="org.eclipse.jetty.util.thread.ReservedThreadExecutor" level="OFF" />
- <logger name="org.eclipse.jetty.util.thread.QueuedThreadPool" level="OFF" />
- <logger name="org.eclipse.jetty.io.ManagedSelector" level="OFF" />
- <logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="OFF" />
- <logger name="org.eclipse.jetty.io.ChannelEndPoint" level="OFF" />
- <logger name="org.eclipse.jetty.io.ssl.SslConnection" level="OFF" />
- <logger name="org.eclipse.jetty.client.HttpReceiver" level="OFF" />
- <logger name="org.eclipse.jetty.client.TimeoutCompleteListener" level="OFF" />
- <logger name="org.eclipse.jetty.client.AbstractConnectionPool" level="OFF" />
- <logger name="org.eclipse.jetty.client.HttpDestination" level="OFF" />
- <logger name="org.eclipse.jetty.client.HttpChannel" level="OFF" />
- <logger name="org.eclipse.jetty.client.HttpExchange" level="OFF" />
- <logger name="org.eclipse.jetty.client.HttpParser" level="OFF" />
- <logger name="org.eclipse.jetty.http.HttpParser" level="OFF" />
- <logger name="org.eclipse.jetty.util.log" level="OFF" />
+ <logger name="org.eclipse.jetty" level="INFO" />
<logger name="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler" level="OFF" />
<logger name="org.springframework.core.KotlinDetector" level="OFF" />
<logger name="org.springframework.http.converter.json.Jackson2ObjectMapperBuilder" level="OFF" />
### src/test/java/com/sparrowwallet/sparrow/net/HttpClientServiceTest.java
@@ -0,0 +1,146 @@
+package com.sparrowwallet.sparrow.net;
+
+import com.google.common.net.HostAndPort;
+import com.sparrowwallet.tern.http.client.HttpUsage;
+import org.junit.jupiter.api.Test;
+
+import java.io.Closeable;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class HttpClientServiceTest {
+ private static final String BODY = "{\"value\":1}";
+
+ @Test
+ public void clientRequestedWhileChangingProxyUsesTheNewProxy() throws Exception {
+ try(SocksProxy proxy = new SocksProxy()) {
+ RequestingWhileStoppingService service = new RequestingWhileStoppingService();
+ try {
+ service.requestDuringStop = true;
+ service.setTorProxy(HostAndPort.fromParts("127.0.0.1", proxy.getPort()));
+ assertFalse(service.requestDuringStop, "The client was not requested during stop()");
+
+ Map<?, ?> result = assertTimeoutPreemptively(Duration.ofSeconds(10), () -> service.requestJson("http://httpclientservice.invalid:8080/", Map.class, null));
+ assertEquals(1, result.get("value"));
+ assertEquals(List.of("httpclientservice.invalid:8080"), proxy.connectTargets);
+ } finally {
+ service.stop();
+ }
+ }
+ }
+
+ //Requests a client from another thread as the clients are stopped, as a concurrent request arriving while the proxy is changed would
+ private static class RequestingWhileStoppingService extends HttpClientService {
+ private volatile boolean requestDuringStop;
+
+ RequestingWhileStoppingService() {
+ super(null);
+ }
+
+ @Override
+ public synchronized void stop() {
+ super.stop();
+ if(requestDuringStop) {
+ requestDuringStop = false;
+ Thread requester = new Thread(() -> getHttpClient(HttpUsage.DEFAULT));
+ requester.setDaemon(true);
+ requester.start();
+ try {
+ //Waits for the client to be created where nothing prevents it, but not indefinitely where the lock held here does
+ requester.join(500);
+ } catch(InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+ }
+
+ //Stands in for a SOCKS4a proxy and the server behind it: records each CONNECT target, then answers the request with a JSON body
+ private static class SocksProxy implements Closeable {
+ private final ServerSocket serverSocket = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
+ private final List<String> connectTargets = new CopyOnWriteArrayList<>();
+
+ SocksProxy() throws IOException {
+ Thread acceptor = new Thread(() -> {
+ try {
+ while(true) {
+ Socket socket = serverSocket.accept();
+ Thread handler = new Thread(() -> serve(socket));
+ handler.setDaemon(true);
+ handler.start();
+ }
+ } catch(IOException e) {
+ //Closed at the end of the test
+ }
+ });
+ acceptor.setDaemon(true);
+ acceptor.start();
+ }
+
+ int getPort() {
+ return serverSocket.getLocalPort();
+ }
+
+ private void serve(Socket socket) {
+ try(socket) {
+ DataInputStream in = new DataInputStream(socket.getInputStream());
+ OutputStream out = socket.getOutputStream();
+
+ //SOCKS4a CONNECT: version, command, port, address 0.0.0.x, user id, hostname. Reply: granted.
+ in.readUnsignedByte();
+ in.readUnsignedByte();
+ int port = in.readUnsignedShort();
+ byte[] address = in.readNBytes(4);
+ readNullTerminated(in);
+ String host = address[0] == 0 && address[1] == 0 && address[2] == 0 && address[3] != 0 ? readNullTerminated(in) : InetAddress.getByAddress(address).getHostAddress();
+ connectTargets.add(host + ":" + port);
+ out.write(new byte[] {0, 0x5A, 0, 0, 0, 0, 0, 0});
+
+ for(String line = readLine(in); line != null && !line.isEmpty(); line = readLine(in)) {
+ //Request headers, no body
+ }
+ out.write(("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " + BODY.length() + "\r\nConnection: close\r\n\r\n" + BODY)
+ .getBytes(StandardCharsets.US_ASCII));
+ out.flush();
+ } catch(IOException e) {
+ //Closed by the client
+ }
+ }
+
+ private static String readNullTerminated(InputStream in) throws IOException {
+ StringBuilder value = new StringBuilder();
+ for(int b = in.read(); b > 0; b = in.read()) {
+ value.append((char)b);
+ }
+ return value.toString();
+ }
+
+ private static String readLine(InputStream in) throws IOException {
+ StringBuilder line = new StringBuilder();
+ int b;
+ while((b = in.read()) != -1 && b != '\n') {
+ if(b != '\r') {
+ line.append((char)b);
+ }
+ }
+ return b == -1 && line.isEmpty() ? null : line.toString();
+ }
+
+ @Override
+ public void close() throws IOException {
+ serverSocket.close();
+ }
+ }
+}
### src/test/java/com/sparrowwallet/sparrow/net/cormorant/bitcoind/BitcoindTransportProxyTest.java
@@ -0,0 +1,366 @@
+package com.sparrowwallet.sparrow.net.cormorant.bitcoind;
+
+import com.sparrowwallet.sparrow.SparrowWallet;
+import com.sparrowwallet.sparrow.io.Config;
+import com.sparrowwallet.sparrow.io.Server;
+import com.sparrowwallet.sparrow.io.Storage;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocket;
+import java.io.*;
+import java.net.*;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.security.KeyStore;
+import java.time.Duration;
+import java.util.Base64;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class BitcoindTransportProxyTest {
+ private static final String RPC_AUTH = "rpcuser:rpcpassword";
+ private static final String RPC_RESPONSE = "{\"result\":{\"chain\":\"main\"},\"error\":null,\"id\":1}";
+ private static final String STORE_PASSWORD = "changeit";
+
+ @TempDir
+ private static Path tempHome;
+
+ private static SocksProxy proxy;
+
+ @BeforeAll
+ public static void setUp() throws Exception {
+ //Config.get() caches its instance for the life of the JVM, so keep these tests from loading the developer's real config and leaving it cached for those that follow
+ System.setProperty(SparrowWallet.APP_HOME_PROPERTY, tempHome.toString());
+ proxy = new SocksProxy();
+ Config.get().setProxyServer("127.0.0.1:" + proxy.getPort());
+ Config.get().setUseProxy(true);
+ }
+
+ @AfterAll
+ public static void tearDown() throws Exception {
+ Config.get().setUseProxy(false);
+ Config.get().setProxyServer(null);
+ proxy.close();
+ System.clearProperty(SparrowWallet.APP_HOME_PROPERTY);
+ }
+
+ @BeforeEach
+ public void reset() {
+ proxy.connectTargets.clear();
+ proxy.authReceived.clear();
+ proxy.response = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " + RPC_RESPONSE.length() + "\r\n\r\n" + RPC_RESPONSE;
+ proxy.sslContext = null;
+ }
+
+ @Test
+ public void onionNodeIsReachedThroughProxy() {
+ String host = onionHost('a');
+ BitcoindTransport transport = new BitcoindTransport(new Server("http://" + host + ":8332"), "cormorant", RPC_AUTH);
+ assertEquals(RPC_RESPONSE, pass(transport));
+ assertEquals(List.of("DOMAIN:" + host + ":8332"), proxy.connectTargets);
+ assertEquals(List.of(RPC_AUTH), proxy.authReceived);
+ }
+
+ @Test
+ public void connectionIsReusedBetweenCalls() {
+ String host = onionHost('i');
+ BitcoindTransport transport = new BitcoindTransport(new Server("http://" + host + ":8332"), "cormorant", RPC_AUTH);
+ for(int i = 0; i < 3; i++) {
+ assertEquals(RPC_RESPONSE, pass(transport));
+ }
+ assertEquals(List.of("DOMAIN:" + host + ":8332"), proxy.connectTargets);
+ assertEquals(List.of(RPC_AUTH, RPC_AUTH, RPC_AUTH), proxy.authReceived);
+ transport.close();
+ }
+
+ @Test
+ public void closedTransportRefusesCalls() {
+ BitcoindTransport transport = new BitcoindTransport(new Server("http://" + onionHost('j') + ":8332"), "cormorant", RPC_AUTH);
+ transport.close();
+ assertPassThrows(transport);
+ assertTrue(proxy.connectTargets.isEmpty());
+ }
+
+ @Test
+ public void undelimitedBodyIsReadToTheEnd() {
+ proxy.response = "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n" + RPC_RESPONSE;
+ BitcoindTransport transport = new BitcoindTransport(new Server("http://" + onionHost('b') + ":8332"), "cormorant", RPC_AUTH);
+ assertEquals(RPC_RESPONSE, pass(transport));
+ }
+
+ @Test
+ public void errorResponseIsReturnedWithoutTheNullResult() {
+ String error = "{\"result\":null,\"error\":{\"code\":-32601,\"message\":\"Method not found\"},\"id\":1}";
+ proxy.response = "HTTP/1.1 404 Not Found\r\nContent-Length: " + error.length() + "\r\n\r\n" + error;
+ BitcoindTransport transport = new BitcoindTransport(new Server("http://" + onionHost('c') + ":8332"), "cormorant", RPC_AUTH);
+ assertEquals(error.replace("\"result\":null,", ""), pass(transport));
+ }
+
+ @Test
+ public void authenticationFailureIsReported() {
+ proxy.response = "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n";
+ BitcoindTransport transport = new BitcoindTransport(new Server("http://" + onionHost('d') + ":8332"), "cormorant", RPC_AUTH);
+ IOException thrown = assertPassThrows(transport);
+ assertTrue(thrown.getMessage().contains("authentication failed"), thrown.toString());
+ }
+
+ @Test
+ public void closedConnectionPointsToRpcAllowIp() {
+ proxy.response = "";
+ BitcoindTransport transport = new BitcoindTransport(new Server("http://" + onionHost('e') + ":8332"), "cormorant", RPC_AUTH);
+ IOException thrown = assertPassThrows(transport);
+ assertTrue(thrown.getMessage().contains("rpcallowip"), thrown.toString());
+ }
+
+ @Test
+ public void truncatedBodyFails() {
+ proxy.response = "HTTP/1.1 200 OK\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n" + RPC_RESPONSE;
+ BitcoindTransport transport = new BitcoindTransport(new Server("http://" + onionHost('f') + ":8332"), "cormorant", RPC_AUTH);
+ IOException thrown = assertPassThrows(transport);
+ assertTrue(thrown.getMessage().contains("before the response") && !thrown.getMessage().contains("rpcallowip"), thrown.toString());
+ }
+
+ @Test
+ public void proxiedRedirectIsNotFollowed() throws Exception {
+ try(CountingServer redirectTarget = new CountingServer()) {
+ proxy.response = "HTTP/1.0 305 Use Proxy\r\nLocation: http://127.0.0.1:" + redirectTarget.getPort() + "/\r\nContent-Length: 0\r\n\r\n";
+ BitcoindTransport transport = new BitcoindTransport(new Server("http://" + onionHost('g') + ":8332"), "cormorant", RPC_AUTH);
+ IOException thrown = assertPassThrows(transport);
+ assertTrue(thrown.getMessage().contains("HTTP 305"), thrown.toString());
+ assertEquals(0, redirectTarget.connections.get());
+ }
+ }
+
+ @Test
+ public void directRedirectIsNotFollowed() throws Exception {
+ try(CountingServer redirectTarget = new CountingServer(); CountingServer node = new CountingServer()) {
+ node.response = "HTTP/1.0 302 Found\r\nLocation: http://127.0.0.1:" + redirectTarget.getPort() + "/\r\nContent-Length: 0\r\n\r\n";
+ BitcoindTransport transport = new BitcoindTransport(new Server("http://127.0.0.1:" + node.getPort()), "cormorant", RPC_AUTH);
+ IOException thrown = assertPassThrows(transport);
+ assertTrue(thrown.getMessage().contains("HTTP 302"), thrown.toString());
+ assertEquals(0, redirectTarget.connections.get());
+ }
+ }
+
+ @Test
+ public void localNodeIsReachedDirectly() throws Exception {
+ try(CountingServer node = new CountingServer()) {
+ node.response = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " + RPC_RESPONSE.length() + "\r\nConnection: close\r\n\r\n" + RPC_RESPONSE;
+ BitcoindTransport transport = new BitcoindTransport(new Server("http://127.0.0.1:" + node.getPort()), "cormorant", RPC_AUTH);
+ assertEquals(RPC_RESPONSE, pass(transport));
+ assertEquals(1, node.connections.get());
+ assertTrue(proxy.connectTargets.isEmpty());
+ }
+ }
+
+ @Test
+ public void proxiedHttpsCertificateIsPinnedOnFirstUse() throws Exception {
+ String host = onionHost('h');
+ SSLContext first = createServerContext("first");
+ SSLContext second = createServerContext("second");
+ BitcoindTransport transport = new BitcoindTransport(new Server("https://" + host + ":8332"), "cormorant", RPC_AUTH);
+
+ proxy.sslContext = first;
+ assertEquals(RPC_RESPONSE, pass(transport));
+ assertNotNull(Storage.getCertificateFile(host));
+ assertEquals(List.of(RPC_AUTH), proxy.authReceived);
+
+ assertEquals(RPC_RESPONSE, pass(transport));
+ transport.close();
+
+ proxy.authReceived.clear();
+ proxy.sslContext = second;
+ BitcoindTransport newTransport = new BitcoindTransport(new Server("https://" + host + ":8332"), "cormorant", RPC_AUTH);
+ assertPassThrows(newTransport);
+ assertTrue(proxy.authReceived.isEmpty());
+ }
+
+ private static String pass(BitcoindTransport transport) {
+ return assertTimeoutPreemptively(Duration.ofSeconds(10), () -> transport.pass(request()));
+ }
+
+ private static IOException assertPassThrows(BitcoindTransport transport) {
+ return assertTimeoutPreemptively(Duration.ofSeconds(10), () -> assertThrows(IOException.class, () -> transport.pass(request())));
+ }
+
+ private static String request() {
+ return "{\"id\":1,\"method\":\"getblockchaininfo\",\"params\":[]}";
+ }
+
+ private static String onionHost(char c) {
+ return "sparrowtestnode" + String.valueOf(c).repeat(40) + "d.onion";
+ }
+
+ private static SSLContext createServerContext(String name) throws Exception {
+ File keyStoreFile = tempHome.resolve(name + ".p12").toFile();
+ String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString();
+ Process process = new ProcessBuilder(keytool, "-genkeypair", "-alias", name, "-keyalg", "EC", "-groupname", "secp256r1", "-dname", "CN=" + name, "-validity", "2",
+ "-keystore", keyStoreFile.getAbsolutePath(), "-storetype", "PKCS12", "-storepass", STORE_PASSWORD).redirectErrorStream(true).start();
+ process.getInputStream().readAllBytes();
+ assertTrue(process.waitFor(30, TimeUnit.SECONDS) && process.exitValue() == 0, "keytool failed");
+
+ KeyStore keyStore = KeyStore.getInstance("PKCS12");
+ try(FileInputStream fis = new FileInputStream(keyStoreFile)) {
+ keyStore.load(fis, STORE_PASSWORD.toCharArray());
+ }
+ KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ keyManagerFactory.init(keyStore, STORE_PASSWORD.toCharArray());
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
+ return sslContext;
+ }
+
+ private static String readHttpRequest(InputStream is, List<String> authReceived) throws IOException {
+ DataInputStream in = new DataInputStream(is);
+ int contentLength = 0;
+ String firstLine = null;
+ for(String line = readLine(in); line != null && !line.isEmpty(); line = readLine(in)) {
+ if(firstLine == null) {
+ firstLine = line;
+ } else if(line.startsWith("Authorization: Basic ")) {
+ authReceived.add(new String(Base64.getDecoder().decode(line.substring("Authorization: Basic ".length())), StandardCharsets.UTF_8));
+ } else if(line.toLowerCase().startsWith("content-length: ")) {
+ contentLength = Integer.parseInt(line.substring("content-length: ".length()));
+ }
+ }
+ in.readNBytes(contentLength);
+ return firstLine;
+ }
+
+ private static String readLine(InputStream in) throws IOException {
+ StringBuilder line = new StringBuilder();
+ int b;
+ while((b = in.read()) != -1 && b != '\n') {
+ if(b != '\r') {
+ line.append((char)b);
+ }
+ }
+ return b == -1 && line.isEmpty() ? null : line.toString();
+ }
+
+ //Stands in for a SOCKS5 proxy and the server it connects to: records the CONNECT target, then answers one HTTP request with the configured response
+ private static class SocksProxy implements Closeable {
+ private final List<String> connectTargets = new CopyOnWriteArrayList<>();
+ private final List<String> authReceived = new CopyOnWriteArrayList<>();
+ private final ServerSocket serverSocket = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
+ private volatile String response;
+ private volatile SSLContext sslContext;
+
+ SocksProxy() throws IOException {
+ Thread acceptor = new Thread(() -> {
+ try {
+ while(true) {
+ Socket socket = serverSocket.accept();
+ Thread handler = new Thread(() -> serve(socket));
+ handler.setDaemon(true);
+ handler.start();
+ }
+ } catch(IOException e) {
+ //Closed at the end of the tests
+ }
+ });
+ acceptor.setDaemon(true);
+ acceptor.start();
+ }
+
+ int getPort() {
+ return serverSocket.getLocalPort();
+ }
+
+ private void serve(Socket socket) {
+ try(socket) {
+ DataInputStream in = new DataInputStream(socket.getInputStream());
+ OutputStream out = socket.getOutputStream();
+
+ //Greeting: version, number of methods, methods. Reply: no authentication.
+ in.readUnsignedByte();
+ in.readNBytes(in.readUnsignedByte());
+ out.write(new byte[] {5, 0});
+
+ //CONNECT: version, command, reserved, address type, address, port. Reply: succeeded.
+ in.readNBytes(3);
+ String address = switch(in.readUnsignedByte()) {
+ case 1 -> "IPV4:" + InetAddress.getByAddress(in.readNBytes(4)).getHostAddress();
+ case 3 -> "DOMAIN:" + new String(in.readNBytes(in.readUnsignedByte()), StandardCharsets.US_ASCII);
+ case 4 -> "IPV6:" + InetAddress.getByAddress(in.readNBytes(16)).getHostAddress();
+ default -> throw new IOException("Unknown SOCKS5 address type");
+ };
+ connectTargets.add(address + ":" + in.readUnsignedShort());
+ out.write(new byte[] {5, 0, 0, 1, 0, 0, 0, 0, 0, 0});
+ out.flush();
+
+ Socket stream = socket;
+ SSLContext context = sslContext;
+ if(context != null) {
+ SSLSocket sslSocket = (SSLSocket)context.getSocketFactory().createSocket(socket, socket.getInputStream(), true);
+ sslSocket.setUseClientMode(false);
+ sslSocket.startHandshake();
+ stream = sslSocket;
+ }
+
+ //Keeps the connection open for further requests where the response is delimited
+ try(Socket far = stream) {
+ while(readHttpRequest(far.getInputStream(), authReceived) != null) {
+ String current = response;
+ far.getOutputStream().write(current.getBytes(StandardCharsets.US_ASCII));
+ far.getOutputStream().flush();
+ if(!current.contains("Content-Length") || current.contains("Connection: close")) {
+ break;
+ }
+ }
+ }
+ } catch(IOException e) {
+ //A failed handshake or a client that closed the connection
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ serverSocket.close();
+ }
+ }
+
+ //A plain HTTP server that counts the connections it receives and answers each with the configured response
+ private static class CountingServer implements Closeable {
+ private final AtomicInteger connections = new AtomicInteger();
+ private final ServerSocket serverSocket = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
+ private volatile String response = "";
+
+ CountingServer() throws IOException {
+ Thread acceptor = new Thread(() -> {
+ try {
+ while(true) {
+ try(Socket socket = serverSocket.accept()) {
+ connections.incrementAndGet();
+ readHttpRequest(socket.getInputStream(), new CopyOnWriteArrayList<>());
+ socket.getOutputStream().write(response.getBytes(StandardCharsets.US_ASCII));
+ }
+ }
+ } catch(IOException e) {
+ //Closed at the end of the test
+ }
+ });
+ acceptor.setDaemon(true);
+ acceptor.start();
+ }
+
+ int getPort() {
+ return serverSocket.getLocalPort();
+ }
+
+ @Override
+ public void close() throws IOException {
+ serverSocket.close();
+ }
+ }
+}
### src/test/java/com/sparrowwallet/sparrow/payjoin/PayjoinTest.java
@@ -1,5 +1,6 @@
package com.sparrowwallet.sparrow.payjoin;
+import com.sparrowwallet.drongo.OutputDescriptor;
import com.sparrowwallet.drongo.crypto.ECKey;
import com.sparrowwallet.drongo.policy.PolicyType;
import com.sparrowwallet.drongo.protocol.Script;
@@ -14,11 +15,29 @@
import com.sparrowwallet.drongo.silentpayments.SilentPaymentAddress;
import com.sparrowwallet.drongo.uri.BitcoinURI;
import com.sparrowwallet.drongo.wallet.Wallet;
+import com.sparrowwallet.sparrow.AppServices;
+import com.sparrowwallet.sparrow.SparrowWallet;
+import com.sparrowwallet.sparrow.io.Config;
+import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.Closeable;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.math.BigInteger;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.time.Duration;
import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
public class PayjoinTest {
private static final ECKey SENDER_KEY = ECKey.fromPrivate(BigInteger.valueOf(1001));
@@ -39,6 +58,45 @@ public class PayjoinTest {
private static final int CHANGE_OUTPUT_INDEX = 1;
private static final long MAX_ADDITIONAL_FEE_CONTRIBUTION = 5000L;
private static final double MIN_FEE_RATE = 1.0d;
+ private static final String WATCH_ONLY_XPUB = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8";
+ private static final String RECEIVER_ONION = "payjoinreceiver" + "a".repeat(40) + "d.onion";
+
+ @TempDir
+ private static Path tempHome;
+
+ @BeforeAll
+ public static void setUp() {
+ //Config.get() caches its instance for the life of the JVM, so keep these tests from loading the developer's real config and leaving it cached for those that follow
+ System.setProperty(SparrowWallet.APP_HOME_PROPERTY, tempHome.toString());
+ }
+
+ @AfterAll
+ public static void tearDown() {
+ System.clearProperty(SparrowWallet.APP_HOME_PROPERTY);
+ }
+
+ @Test
+ public void receiverRedirectIsNotFollowed() throws Exception {
+ try(RedirectingReceiver receiver = new RedirectingReceiver()) {
+ Config.get().setProxyServer("127.0.0.1:" + receiver.getPort());
+ Config.get().setUseProxy(true);
+ try {
+ //A watch-only wallet, so that the change output can be looked up before the request is sent
+ Wallet wallet = OutputDescriptor.getOutputDescriptor("wpkh([d34db33f/84h/0h/0h]" + WATCH_ONLY_XPUB + "/0/*)").toWallet();
+ BitcoinURI payjoinURI = new BitcoinURI("bitcoin:" + ScriptType.P2WPKH.getAddress(PAYMENT_KEY.getPubKeyHash()) + "?pj=http://" + RECEIVER_ONION + "/pj");
+ Payjoin payjoin = new Payjoin(payjoinURI, wallet, getOriginalPSBT());
+ PayjoinReceiverException thrown = Assertions.assertTimeoutPreemptively(Duration.ofSeconds(20),
+ () -> Assertions.assertThrows(PayjoinReceiverException.class, () -> payjoin.requestPayjoinPSBT(true)));
+ Assertions.assertTrue(thrown.getMessage().contains("HTTP 307"), thrown.getMessage());
+ Assertions.assertEquals(List.of(RECEIVER_ONION + ":80"), receiver.connectTargets);
+ } finally {
+ Config.get().setUseProxy(false);
+ Config.get().setProxyServer(null);
+ //Reconfigures the shared client without the proxy, stopping the clients that used it
+ AppServices.getHttpClientService();
+ }
+ }
+ }
@Test
public void unsubstitutedProposalIsAccepted() throws Exception {
@@ -259,4 +317,85 @@ private Script getPaymentScript() {
private Script getSubstituteScript() {
return ScriptType.P2WPKH.getOutputScript(SUBSTITUTE_KEY.getPubKeyHash());
}
+
+ //Stands in for a SOCKS4a proxy and the payjoin receiver behind it: records each CONNECT target, then answers the request with a redirect to a local address
+ private static class RedirectingReceiver implements Closeable {
+ private final ServerSocket serverSocket = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
+ private final List<String> connectTargets = new CopyOnWriteArrayList<>();
+
+ RedirectingReceiver() throws IOException {
+ Thread acceptor = new Thread(() -> {
+ try {
+ while(true) {
+ Socket socket = serverSocket.accept();
+ Thread handler = new Thread(() -> serve(socket));
+ handler.setDaemon(true);
+ handler.start();
+ }
+ } catch(IOException e) {
+ //Closed at the end of the test
+ }
+ });
+ acceptor.setDaemon(true);
+ acceptor.start();
+ }
+
+ int getPort() {
+ return serverSocket.getLocalPort();
+ }
+
+ private void serve(Socket socket) {
+ try(socket) {
+ DataInputStream in = new DataInputStream(socket.getInputStream());
+ OutputStream out = socket.getOutputStream();
+
+ //SOCKS4a CONNECT: version, command, port, address 0.0.0.x, user id, hostname. Reply: granted.
+ in.readUnsignedByte();
+ in.readUnsignedByte();
+ int port = in.readUnsignedShort();
+ byte[] address = in.readNBytes(4);
+ readNullTerminated(in);
+ String host = address[0] == 0 && address[1] == 0 && address[2] == 0 && address[3] != 0 ? readNullTerminated(in) : InetAddress.getByAddress(address).getHostAddress();
+ connectTargets.add(host + ":" + port);
+ out.write(new byte[] {0, 0x5A, 0, 0, 0, 0, 0, 0});
+
+ int contentLength = 0;
+ for(String line = readLine(in); line != null && !line.isEmpty(); line = readLine(in)) {
+ if(line.toLowerCase().startsWith("content-length:")) {
+ contentLength = Integer.parseInt(line.substring("content-length:".length()).trim());
+ }
+ }
+ in.readNBytes(contentLength);
+ out.write(("HTTP/1.1 307 Temporary Redirect\r\nLocation: http://127.0.0.1:" + getPort() + "/pj\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
+ .getBytes(StandardCharsets.US_ASCII));
+ out.flush();
+ } catch(IOException e) {
+ //Closed by the client
+ }
+ }
+
+ private static String readNullTerminated(InputStream in) throws IOException {
+ StringBuilder value = new StringBuilder();
+ for(int b = in.read(); b > 0; b = in.read()) {
+ value.append((char)b);
+ }
+ return value.toString();
+ }
+
+ private static String readLine(InputStream in) throws IOException {
+ StringBuilder line = new StringBuilder();
+ int b;
+ while((b = in.read()) != -1 && b != '\n') {
+ if(b != '\r') {
+ line.append((char)b);
+ }
+ }
+ return b == -1 && line.isEmpty() ? null : line.toString();
+ }
+
+ @Override
+ public void close() throws IOException {
+ serverSocket.close();
+ }
+ }
}Why this scored 47/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.