verify wallet input signatures of unconfirmed transactions before adding them to the wallet history
What changed, and why it matters
This commit adds a security check in the Sparrow bitcoin wallet. When the wallet connects to an external Electrum-style server, the server can tell the wallet about unconfirmed transactions that appear to spend from the wallet. Before this change, the wallet would add those transactions to its history without checking whether they were actually signed by the wallet's own keys. A dishonest or compromised server could therefore make the wallet believe money was spent or received when it really wasn't. The new code verifies the signatures on any unconfirmed transaction that spends from the wallet, and if the signatures are invalid, the transaction is kept out of the wallet history and the user is warned.
Users should upgrade to a Sparrow release containing this commit. After upgrading, when using public or third-party Electrum servers, the wallet will now reject server-reported unconfirmed spends that are not properly signed and will alert the user. Users who see the new 'Invalid Transaction' dialog should switch to a different, trusted server or use a local Bitcoin Core node. Developers should review the drongo submodule bump for any related API or behavior changes in wallet.getUnsignedInputs() and wallet.getSigningNodes().
Security signals we found
New signature-verification gate for unconfirmed spends before wallet history update
Removal of invalidly-signed unconfirmed transactions and their descendants from wallet state
User-visible warning when server reports unsigned spends from the wallet
Taproot-specific fetching of spent parent transactions to validate signature commitments
Per-session deduplication of warnings (unsignedWarnedTxids) with reset on server change
Skip verification when connected to local Bitcoin Core (trusted full node)
Large test suite added demonstrating attack scenarios (altered outputs, fake child transactions, payjoin-like taproot cases)
Evidence from the diff
The patch introduces signature verification for unconfirmed transactions reported by Electrum/Electrum-style servers. In ElectrumServer.getReferencedTransactions() and the silent-payment batch path, unconfirmed transactions spending from the wallet are passed to a new getUnsignedTransactions() helper. That helper uses wallet.getUnsignedInputs() to detect inputs that spend wallet outputs but lack valid signatures, with special handling for P2TR (taproot) spends that require fetching the spent parent transaction because taproot signatures commit to all spent outputs. Invalidly-signed transactions and their descendants are removed from nodeTransactionMap and transactionMap before wallet.updateTransactions() is called, so they never enter the wallet history. A new UnsignedTransactionsEvent is posted once per offending txid per server session, and AppServices shows a modal error dialog telling the user the server may be faulty or dishonest. The check is skipped for Bitcoin Core connections because the user’s own node is trusted to have validated every transaction. A comprehensive unit-test file (UnconfirmedSpendTest.java) is added covering signed spends, altered outputs, descendant chains, taproot commitment fetching, caching, and warning deduplication.
Changed components
src/main/java/com/sparrowwallet/sparrow/net/ElectrumServer.javasrc/main/java/com/sparrowwallet/sparrow/AppServices.javasrc/main/java/com/sparrowwallet/sparrow/event/UnsignedTransactionsEvent.javadrongo submodule (wallet signing/verification logic)src/test/java/com/sparrowwallet/sparrow/net/UnconfirmedSpendTest.javaInspect captured patch +605 / −1
### drongo
@@ -1 +1 @@
-Subproject commit 6236bf0eedeeac6cdb004c9df45c633b2dc7b080
+Subproject commit 13059ebc2979640b30bc1534b4584e2191578672
### src/main/java/com/sparrowwallet/sparrow/AppServices.java
@@ -1589,6 +1589,16 @@ public void transactionProofsRefused(TransactionProofsRefusedEvent event) {
+ " A server contradicting itself in this way may be faulty or overloaded, and what it reported cannot be taken as confirmed.");
}
+ @Subscribe
+ public void unsignedTransactions(UnsignedTransactionsEvent event) {
+ String firstId = event.getTxids().iterator().next().toString().substring(0, 8) + "..";
+ String content = (event.getTxids().size() == 1 ? "Transaction " + firstId + " was" : event.getTxids().size() + " transactions, the first being " + firstId + ", were")
+ + " reported by the connected server as spending from " + event.getWallet().getFullName() + " but " + (event.getTxids().size() == 1 ? "is" : "are")
+ + " not validly signed, and " + (event.getTxids().size() == 1 ? "has" : "have") + " not been added to the wallet."
+ + " This means the server is either faulty or dishonest.\n\nConsider switching servers.";
+ Platform.runLater(() -> showErrorDialog("Invalid Transaction", content));
+ }
+
private void showProofsDialog(TransactionProofsEvent event, String title, String content) {
Platform.runLater(() -> {
if(event.getWallet() == null) {
### src/main/java/com/sparrowwallet/sparrow/event/UnsignedTransactionsEvent.java
@@ -0,0 +1,30 @@
+package com.sparrowwallet.sparrow.event;
+
+import com.sparrowwallet.drongo.protocol.Sha256Hash;
+import com.sparrowwallet.drongo.wallet.Wallet;
+
+import java.util.Set;
+
+/**
+ * Posted where the connected server reported unconfirmed transactions spending from a wallet that are not validly signed by it, which have been left
+ * out of its history. Once per transaction per session.
+ * <p>
+ * Dispatched on the thread that fetched the history, so a handler must hop to the application thread itself.
+ */
+public class UnsignedTransactionsEvent {
+ private final Wallet wallet;
+ private final Set<Sha256Hash> txids;
+
+ public UnsignedTransactionsEvent(Wallet wallet, Set<Sha256Hash> txids) {
+ this.wallet = wallet;
+ this.txids = txids;
+ }
+
+ public Wallet getWallet() {
+ return wallet;
+ }
+
+ public Set<Sha256Hash> getTxids() {
+ return txids;
+ }
+}
### src/main/java/com/sparrowwallet/sparrow/net/ElectrumServer.java
@@ -184,6 +184,15 @@ public class ElectrumServer {
//count them: a wallet whose used nodes are all demoted would otherwise abort into a full refresh on every open, the demotion being stored
private final Set<String> demotedScriptHashes = new HashSet<>();
+ //Per pass, since each of the several calls a pass makes to getReferencedTransactions judges every unconfirmed reference it has collected so far.
+ //Only what stays true as the gap limit derives more addresses is kept: an unsigned spend stays unsigned, while one that was not yet seen to spend
+ //from this wallet may do so once another address is derived. The transactions a taproot spend commits to are kept so they are fetched only once
+ private final Map<Wallet, Set<Sha256Hash>> unsignedThisPass = new HashMap<>();
+
+ private final Map<Sha256Hash, Transaction> spentTransactionsThisPass = new HashMap<>();
+
+ private static final Set<Sha256Hash> unsignedWarnedTxids = ConcurrentHashMap.newKeySet();
+
private static synchronized CloseableTransport getTransport() throws ServerException {
if(transport == null) {
try {
@@ -261,6 +270,7 @@ static void clearPreviousServerState() {
reorgInvalidatedScriptHashes.clear();
proofWarnedPairs.clear();
proofsShownFalseWarnedPairs.clear();
+ unsignedWarnedTxids.clear();
walletSyncLocks.values().forEach(syncLock -> {
syncLock.scriptHashesInitialized = false;
syncLock.storedProofsChecked = false;
@@ -672,6 +682,10 @@ public Map<WalletNode, Set<BlockTransactionHash>> getHistory(Wallet wallet, Coll
Map<String, WalletNode> walletScriptHashes = getAllScriptHashes(wallet);
for(BlockTransactionHash reference : newReferences) {
BlockTransaction blockTransaction = wallet.getTransactions().get(reference.getHash());
+ if(blockTransaction == null) {
+ continue;
+ }
+
for(TransactionOutput txOutput : blockTransaction.getTransaction().getOutputs()) {
WalletNode node = walletScriptHashes.get(getScriptHash(txOutput));
if(node != null && !historyNodes.contains(node)) {
@@ -1031,6 +1045,30 @@ public void getReferencedTransactions(Wallet wallet, Map<WalletNode, Set<BlockTr
transactionMap = getTransactions(wallet, references, blockHeaderMap, proven);
}
+ if(isVerifyingSignatures()) {
+ Map<Sha256Hash, BlockTransaction> fetched = transactionMap;
+ Function<Sha256Hash, Transaction> inputTransactions = txid -> {
+ BlockTransaction blockTransaction = fetched.containsKey(txid) ? fetched.get(txid) : wallet.getWalletTransaction(txid);
+ return blockTransaction == null ? null : blockTransaction.getTransaction();
+ };
+
+ Map<Sha256Hash, Transaction> unconfirmed = new HashMap<>();
+ for(Set<BlockTransactionHash> nodeReferences : nodeTransactionMap.values()) {
+ for(BlockTransactionHash reference : nodeReferences) {
+ Transaction transaction = reference.getHeight() <= 0 ? inputTransactions.apply(reference.getHash()) : null;
+ if(transaction != null) {
+ unconfirmed.put(reference.getHash(), transaction);
+ }
+ }
+ }
+
+ Set<Sha256Hash> unsigned = getUnsignedTransactions(wallet, unconfirmed, inputTransactions);
+ if(!unsigned.isEmpty()) {
+ transactionMap.keySet().removeAll(unsigned);
+ removeReferences(nodeTransactionMap, unsigned);
+ }
+ }
+
//A re-proof at an unchanged height leaves the map equal to what the wallet holds, since a block hash is not part of that comparison
if(!transactionMap.equals(wallet.getTransactions()) || !proven.isEmpty()) {
wallet.updateTransactions(transactionMap);
@@ -1173,6 +1211,113 @@ private void demoteReferences(Map<WalletNode, Set<BlockTransactionHash>> nodeTra
}
}
+ /**
+ * Removes every reference to the given transactions from every node that holds one, so that they reach neither the wallet transactions nor the node
+ * transaction outputs. The nodes are recorded as demoted ones are, since they too disagree with the server's status by construction.
+ */
+ private void removeReferences(Map<WalletNode, Set<BlockTransactionHash>> nodeTransactionMap, Set<Sha256Hash> txids) {
+ for(Map.Entry<WalletNode, Set<BlockTransactionHash>> entry : nodeTransactionMap.entrySet()) {
+ if(entry.getValue().removeIf(reference -> txids.contains(reference.getHash()))) {
+ demotedScriptHashes.add(getScriptHash(entry.getKey()));
+ }
+ }
+ }
+
+ private static boolean isVerifyingSignatures() {
+ //A Bitcoin Core connection is the user's own node, which has validated every transaction it reports
+ return Config.get().getServerType() != ServerType.BITCOIN_CORE;
+ }
+
+ /**
+ * The given unconfirmed transactions that spend this wallet's outputs without valid signatures from it, together with those spending what they
+ * create. Until it is mined a transaction is only what the server reports, and where it spends from this wallet that report can be checked here.
+ * A taproot signature commits to every output its transaction spends, so those of a spend from a taproot wallet not already known are fetched.
+ * Everything judged unsigned this pass is returned again by each later call.
+ */
+ Set<Sha256Hash> getUnsignedTransactions(Wallet wallet, Map<Sha256Hash, Transaction> unconfirmed, Function<Sha256Hash, Transaction> inputTransactions) throws ServerException {
+ Set<Sha256Hash> unsigned = unsignedThisPass.computeIfAbsent(wallet, w -> new LinkedHashSet<>());
+ Set<Sha256Hash> found = new LinkedHashSet<>();
+
+ Map<Sha256Hash, Transaction> unjudged = new LinkedHashMap<>(unconfirmed);
+ unjudged.keySet().removeAll(unsigned);
+ if(!unjudged.isEmpty()) {
+ //Built once per call rather than per transaction, since it visits every address node, and not kept across calls, since the gap limit adds
+ //nodes during a pass and a spend from one missing here would not be checked at all
+ Map<Script, WalletNode> walletOutputScripts = wallet.getWalletOutputScripts();
+ fetchSpentTransactions(wallet, unjudged.values(), inputTransactions, walletOutputScripts);
+ Function<Sha256Hash, Transaction> lookup = txid -> {
+ Transaction transaction = inputTransactions.apply(txid);
+ return transaction == null ? spentTransactionsThisPass.get(txid) : transaction;
+ };
+
+ for(Map.Entry<Sha256Hash, Transaction> entry : unjudged.entrySet()) {
+ try {
+ if(!wallet.getUnsignedInputs(entry.getValue(), lookup, walletOutputScripts).isEmpty()) {
+ found.add(entry.getKey());
+ }
+ } catch(Exception e) {
+ log.warn("Could not verify the signatures of " + entry.getKey(), e);
+ found.add(entry.getKey());
+ }
+ }
+ }
+
+ for(boolean added = !found.isEmpty() || !unsigned.isEmpty(); added; ) {
+ added = false;
+ for(Map.Entry<Sha256Hash, Transaction> entry : unconfirmed.entrySet()) {
+ Sha256Hash txid = entry.getKey();
+ if(!found.contains(txid) && !unsigned.contains(txid) && entry.getValue().getInputs().stream().map(input -> input.getOutpoint().getHash())
+ .anyMatch(spent -> found.contains(spent) || unsigned.contains(spent))) {
+ found.add(entry.getKey());
+ added = true;
+ }
+ }
+ }
+
+ if(!found.isEmpty()) {
+ unsigned.addAll(found);
+ log.warn("The connected server reported transactions spending from " + wallet.getFullName() + " that are not validly signed: " + found);
+ Set<Sha256Hash> unwarned = found.stream().filter(unsignedWarnedTxids::add).collect(Collectors.toCollection(LinkedHashSet::new));
+ if(!unwarned.isEmpty()) {
+ EventManager.get().post(new UnsignedTransactionsEvent(wallet, unwarned));
+ }
+ }
+
+ return new LinkedHashSet<>(unsigned);
+ }
+
+ private void fetchSpentTransactions(Wallet wallet, Collection<Transaction> transactions, Function<Sha256Hash, Transaction> inputTransactions,
+ Map<Script, WalletNode> walletOutputScripts) throws ServerException {
+ Set<String> txids = new LinkedHashSet<>();
+ for(Transaction transaction : transactions) {
+ Map<TransactionInput, WalletNode> signingNodes = wallet.getSigningNodes(transaction, inputTransactions, walletOutputScripts);
+ if(signingNodes.values().stream().anyMatch(node -> node.getWallet().getScriptType() == ScriptType.P2TR)) {
+ transaction.getInputs().stream().map(input -> input.getOutpoint().getHash())
+ .filter(txid -> !spentTransactionsThisPass.containsKey(txid) && inputTransactions.apply(txid) == null).forEach(txid -> txids.add(txid.toString()));
+ }
+ }
+
+ if(txids.isEmpty()) {
+ return;
+ }
+
+ try {
+ Map<String, String> result = electrumServerRpc.getTransactions(getTransport(), wallet, txids);
+ for(Map.Entry<String, String> entry : result.entrySet()) {
+ try {
+ Transaction transaction = new Transaction(Utils.hexToBytes(entry.getValue()));
+ if(transaction.getTxId().toString().equals(entry.getKey())) {
+ spentTransactionsThisPass.put(transaction.getTxId(), transaction);
+ }
+ } catch(Exception e) {
+ log.debug("Could not parse spent transaction " + entry.getKey(), e);
+ }
+ }
+ } catch(ElectrumServerRpcException e) {
+ throw new ServerException(e.getMessage(), e.getCause());
+ }
+ }
+
/**
* Whether a stored transaction is held at a height that is still numerically what the server reports but was proven against a block the chain no
* longer holds, which is the form a reorg takes when a transaction is re-included at the same height. Above the last fork point this session only,
@@ -2788,6 +2933,15 @@ public Set<WalletNode> processSilentPaymentBatch(Wallet wallet, List<SilentPayme
Map<BlockTransactionHash, BlockHeader> proven = isVerifyingTransactions() ? verifySilentPaymentReferences(wallet, referencesToFetch) : Collections.emptyMap();
Map<Integer, BlockHeader> blockHeaderMap = getBlockHeaders(wallet, referencesToFetch.keySet());
Map<Sha256Hash, BlockTransaction> fetched = getTransactions(wallet, referencesToFetch, blockHeaderMap, proven);
+ if(isVerifyingSignatures()) {
+ Function<Sha256Hash, Transaction> inputTransactions = txid -> {
+ BlockTransaction blockTransaction = fetched.containsKey(txid) ? fetched.get(txid) : wallet.getWalletTransaction(txid);
+ return blockTransaction == null ? null : blockTransaction.getTransaction();
+ };
+ Map<Sha256Hash, Transaction> unconfirmed = fetched.values().stream().filter(blkTx -> blkTx.getHeight() <= 0 && blkTx.getTransaction() != null)
+ .collect(Collectors.toMap(BlockTransaction::getHash, BlockTransaction::getTransaction));
+ fetched.keySet().removeAll(getUnsignedTransactions(wallet, unconfirmed, inputTransactions));
+ }
transactionMap.putAll(fetched);
wallet.updateTransactions(fetched);
} finally {
### src/test/java/com/sparrowwallet/sparrow/net/UnconfirmedSpendTest.java
@@ -0,0 +1,410 @@
+package com.sparrowwallet.sparrow.net;
+
+import com.google.common.eventbus.Subscribe;
+import com.google.common.net.HostAndPort;
+import com.github.arteam.simplejsonrpc.client.Transport;
+import com.sparrowwallet.drongo.KeyPurpose;
+import com.sparrowwallet.drongo.Utils;
+import com.sparrowwallet.drongo.crypto.ECKey;
+import com.sparrowwallet.drongo.policy.Policy;
+import com.sparrowwallet.drongo.policy.PolicyType;
+import com.sparrowwallet.drongo.protocol.Script;
+import com.sparrowwallet.drongo.protocol.ScriptType;
+import com.sparrowwallet.drongo.protocol.Sha256Hash;
+import com.sparrowwallet.drongo.protocol.SigHash;
+import com.sparrowwallet.drongo.protocol.Transaction;
+import com.sparrowwallet.drongo.protocol.TransactionOutput;
+import com.sparrowwallet.drongo.protocol.TransactionSignature;
+import com.sparrowwallet.drongo.protocol.TransactionWitness;
+import com.sparrowwallet.drongo.psbt.PSBT;
+import com.sparrowwallet.drongo.wallet.*;
+import com.sparrowwallet.sparrow.EventManager;
+import com.sparrowwallet.sparrow.SparrowWallet;
+import com.sparrowwallet.sparrow.event.UnsignedTransactionsEvent;
+import com.sparrowwallet.sparrow.io.Config;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+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 java.nio.file.Path;
+import java.util.*;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Which unconfirmed transactions spending from a wallet reach its history. Until it is mined a transaction is only what the server reports, so where
+ * it spends the wallet's own outputs it must carry the wallet's signatures for them.
+ */
+public class UnconfirmedSpendTest {
+ private static final int FUNDING_HEIGHT = 800000;
+
+ private static final String FOREIGN_TXID = "1100000000000000000000000000000000000000000000000000000000000000";
+
+ @TempDir
+ private static Path tempHome;
+
+ private ServerType previousServerType;
+ private ElectrumServerRpc previousElectrumServerRpc;
+ private CloseableTransport previousTransport;
+ private ServerCapability previousServerCapability;
+ private RecordingServer server;
+
+ @BeforeAll
+ public static void setUpAll() {
+ System.setProperty(SparrowWallet.APP_HOME_PROPERTY, tempHome.toString());
+ }
+
+ @AfterAll
+ public static void tearDownAll() {
+ System.clearProperty(SparrowWallet.APP_HOME_PROPERTY);
+ }
+
+ @BeforeEach
+ public void setUp() {
+ previousServerType = Config.get().getServerType();
+ Config.get().setServerType(ServerType.PUBLIC_ELECTRUM_SERVER);
+ previousElectrumServerRpc = ElectrumServer.electrumServerRpc;
+ previousTransport = ElectrumServer.transport;
+ previousServerCapability = ElectrumServer.serverCapability;
+ server = new RecordingServer();
+ ElectrumServer.electrumServerRpc = server;
+ ElectrumServer.transport = new UnusedTransport();
+ ElectrumServer.serverCapability = null;
+ }
+
+ @AfterEach
+ public void tearDown() {
+ Config.get().setServerType(previousServerType);
+ ElectrumServer.electrumServerRpc = previousElectrumServerRpc;
+ ElectrumServer.transport = previousTransport;
+ ElectrumServer.serverCapability = previousServerCapability;
+ ElectrumServer.clearPreviousServerState();
+ }
+
+ @Test
+ public void keepsASignedSpend() throws Exception {
+ Wallet wallet = signingWallet(ScriptType.P2WPKH);
+ Transaction funding = fund(wallet);
+ Transaction spend = signedSpend(wallet);
+
+ Map<WalletNode, Set<BlockTransactionHash>> nodeTransactionMap = history(wallet, funding, spend);
+ getReferencedTransactions(wallet, nodeTransactionMap);
+
+ assertTrue(holds(nodeTransactionMap, spend));
+ assertTrue(wallet.getTransactions().containsKey(spend.getTxId()));
+ }
+
+ @Test
+ public void leavesOutASpendWithAlteredOutputs() throws Exception {
+ for(ScriptType scriptType : List.of(ScriptType.P2PKH, ScriptType.P2SH_P2WPKH, ScriptType.P2WPKH, ScriptType.P2TR)) {
+ Wallet wallet = signingWallet(scriptType);
+ Transaction funding = fund(wallet);
+ Transaction altered = alterOutputs(signedSpend(wallet));
+
+ Map<WalletNode, Set<BlockTransactionHash>> nodeTransactionMap = history(wallet, funding, altered);
+ getReferencedTransactions(wallet, nodeTransactionMap);
+
+ assertFalse(holds(nodeTransactionMap, altered), scriptType + " spend must be left out");
+ assertTrue(holds(nodeTransactionMap, funding), scriptType + " funding must be kept");
+ new ElectrumServer().calculateNodeHistory(wallet, nodeTransactionMap);
+ assertTrue(wallet.getWalletUtxos().keySet().stream().anyMatch(utxo -> utxo.getHash().equals(funding.getTxId())), scriptType + " output must be unspent");
+ }
+ }
+
+ @Test
+ public void leavesOutWhatSpendsALeftOutTransaction() throws Exception {
+ Wallet wallet = signingWallet(ScriptType.P2WPKH);
+ fund(wallet);
+ Transaction altered = alterOutputs(signedSpend(wallet));
+
+ Transaction child = new Transaction();
+ child.addInput(altered.getTxId(), 0, new Script(new byte[0]));
+ child.addOutput(100_000L, wallet.getAddress(wallet.getNode(KeyPurpose.RECEIVE).getChildren().iterator().next()));
+
+ Map<Sha256Hash, Transaction> unconfirmed = new LinkedHashMap<>();
+ unconfirmed.put(child.getTxId(), child);
+ unconfirmed.put(altered.getTxId(), altered);
+
+ Set<Sha256Hash> unsigned = new ElectrumServer().getUnsignedTransactions(wallet, unconfirmed, txid -> body(wallet, txid));
+
+ assertEquals(Set.of(altered.getTxId(), child.getTxId()), unsigned);
+ }
+
+ @Test
+ public void keepsAnIncomingPayment() throws Exception {
+ Wallet wallet = signingWallet(ScriptType.P2TR);
+ Transaction incoming = new Transaction();
+ incoming.addInput(Sha256Hash.wrap(FOREIGN_TXID), 0, new Script(new byte[0]));
+ incoming.addOutput(100_000L, wallet.getAddress(wallet.getNode(KeyPurpose.RECEIVE).getChildren().iterator().next()));
+
+ Set<Sha256Hash> unsigned = new ElectrumServer().getUnsignedTransactions(wallet, Map.of(incoming.getTxId(), incoming), txid -> body(wallet, txid));
+
+ assertTrue(unsigned.isEmpty());
+ assertTrue(server.requested.isEmpty());
+ }
+
+ @Test
+ public void fetchesTheTransactionsATaprootSpendCommitsTo() throws Exception {
+ Wallet wallet = signingWallet(ScriptType.P2TR);
+ fund(wallet);
+ Transaction signed = signedSpend(wallet);
+ Transaction withForeignInput = new Transaction(signed.bitcoinSerialize());
+ withForeignInput.addInput(Sha256Hash.wrap(FOREIGN_TXID), 0, new Script(new byte[0]));
+
+ Set<Sha256Hash> unsigned = new ElectrumServer().getUnsignedTransactions(wallet, Map.of(withForeignInput.getTxId(), withForeignInput), txid -> body(wallet, txid));
+
+ assertEquals(Set.of(FOREIGN_TXID), server.requested);
+ assertEquals(Set.of(withForeignInput.getTxId()), unsigned);
+ }
+
+ @Test
+ public void fetchesTheTransactionsATaprootSpendCommitsToOncePerPass() throws Exception {
+ Wallet wallet = signingWallet(ScriptType.P2TR);
+ Transaction funding = fund(wallet);
+ WalletNode addressNode = wallet.getNode(KeyPurpose.RECEIVE).getChildren().iterator().next();
+
+ //A payjoin: the other party's input sits beside the wallet's, and the wallet's taproot signature commits to the output it spends too
+ Transaction foreignParent = new Transaction();
+ foreignParent.addInput(Sha256Hash.ZERO_HASH, 0, new Script(new byte[0]));
+ foreignParent.addOutput(50_000L, ScriptType.P2WPKH.getOutputScript(Utils.hexToBytes("bb00000000000000000000000000000000000022")));
+ server.serve(foreignParent);
+
+ Transaction payjoin = new Transaction();
+ payjoin.setVersion(2);
+ payjoin.setSegwitFlag(Transaction.DEFAULT_SEGWIT_FLAG);
+ payjoin.addInput(funding.getTxId(), 0, new Script(new byte[0]));
+ payjoin.addInput(foreignParent.getTxId(), 0, new Script(new byte[0]));
+ payjoin.addOutput(1_040_000L, ScriptType.P2WPKH.getOutputScript(Utils.hexToBytes("cc00000000000000000000000000000000000033")));
+ List<TransactionOutput> spentOutputs = List.of(funding.getOutputs().getFirst(), foreignParent.getOutputs().getFirst());
+ Sha256Hash hash = payjoin.hashForTaprootSignature(spentOutputs, 0, false, funding.getOutputs().getFirst().getScript(), SigHash.DEFAULT, null);
+ ECKey privKey = ScriptType.P2TR.getOutputKey(PolicyType.SINGLE_HD, wallet.getKeystores().getFirst().getKey(addressNode));
+ payjoin.getInputs().getFirst().setWitness(new TransactionWitness(payjoin, privKey.sign(hash, SigHash.DEFAULT, TransactionSignature.Type.SCHNORR)));
+ payjoin = new Transaction(payjoin.bitcoinSerialize());
+ Map<Sha256Hash, Transaction> unconfirmed = Map.of(payjoin.getTxId(), payjoin);
+
+ ElectrumServer electrumServer = new ElectrumServer();
+ Set<Sha256Hash> first = electrumServer.getUnsignedTransactions(wallet, unconfirmed, txid -> body(wallet, txid));
+ assertTrue(first.isEmpty());
+ assertEquals(Set.of(foreignParent.getTxId().toString()), server.requested);
+
+ server.requested.clear();
+ Set<Sha256Hash> second = electrumServer.getUnsignedTransactions(wallet, unconfirmed, txid -> body(wallet, txid));
+ assertTrue(second.isEmpty());
+ assertTrue(server.requested.isEmpty());
+ }
+
+ @Test
+ public void doesNotFetchAgainForASpendAlreadyLeftOut() throws Exception {
+ Wallet wallet = signingWallet(ScriptType.P2TR);
+ fund(wallet);
+ Transaction signed = signedSpend(wallet);
+ Transaction withForeignInput = new Transaction(signed.bitcoinSerialize());
+ withForeignInput.addInput(Sha256Hash.wrap(FOREIGN_TXID), 0, new Script(new byte[0]));
+ Map<Sha256Hash, Transaction> unconfirmed = Map.of(withForeignInput.getTxId(), withForeignInput);
+
+ ElectrumServer electrumServer = new ElectrumServer();
+ electrumServer.getUnsignedTransactions(wallet, unconfirmed, txid -> body(wallet, txid));
+ server.requested.clear();
+ Set<Sha256Hash> unsigned = electrumServer.getUnsignedTransactions(wallet, unconfirmed, txid -> body(wallet, txid));
+
+ assertEquals(Set.of(withForeignInput.getTxId()), unsigned);
+ assertTrue(server.requested.isEmpty());
+ }
+
+ @Test
+ public void judgesASpendAgainOnceItsFundingTransactionIsKnown() throws Exception {
+ Wallet wallet = signingWallet(ScriptType.P2WPKH);
+ Transaction funding = fund(wallet);
+ Transaction altered = alterOutputs(signedSpend(wallet));
+ Map<Sha256Hash, Transaction> unconfirmed = Map.of(altered.getTxId(), altered);
+
+ //The first call of a pass may reach a spend before the transaction it spends, when that arrives with the history of another node
+ ElectrumServer electrumServer = new ElectrumServer();
+ Set<Sha256Hash> before = electrumServer.getUnsignedTransactions(wallet, unconfirmed, txid -> txid.equals(funding.getTxId()) ? null : body(wallet, txid));
+ Set<Sha256Hash> after = electrumServer.getUnsignedTransactions(wallet, unconfirmed, txid -> body(wallet, txid));
+
+ assertTrue(before.isEmpty());
+ assertEquals(Set.of(altered.getTxId()), after);
+ }
+
+ @Test
+ public void judgesASpendAgainOnceTheAddressItSpendsFromIsDerived() throws Exception {
+ //A restore derives addresses in rounds up to the gap limit, so a spend reached before the address it spends from is derived must be judged again
+ Wallet derived = signingWallet(ScriptType.P2WPKH);
+ derived.getNode(KeyPurpose.RECEIVE).fillToIndex(30);
+ WalletNode addressNode = derived.getNode(KeyPurpose.RECEIVE).getChildren().stream().filter(node -> node.getIndex() == 30).findFirst().orElseThrow();
+ Transaction funding = new Transaction();
+ funding.addInput(Sha256Hash.ZERO_HASH, 0, new Script(new byte[0]));
+ funding.addOutput(1_000_000L, derived.getAddress(addressNode));
+ derived.updateTransactions(Map.of(funding.getTxId(), new BlockTransaction(funding.getTxId(), FUNDING_HEIGHT, new Date(), 0L, funding)));
+ addressNode.getTransactionOutputs().add(new BlockTransactionHashIndex(funding.getTxId(), FUNDING_HEIGHT, new Date(), 0L, 0, 1_000_000L));
+ Transaction altered = alterOutputs(signedSpend(derived));
+
+ Wallet wallet = signingWallet(ScriptType.P2WPKH);
+ wallet.getNode(KeyPurpose.RECEIVE).fillToIndex(19);
+ wallet.updateTransactions(Map.of(funding.getTxId(), new BlockTransaction(funding.getTxId(), FUNDING_HEIGHT, new Date(), 0L, funding)));
+ Map<Sha256Hash, Transaction> unconfirmed = Map.of(altered.getTxId(), altered);
+
+ ElectrumServer electrumServer = new ElectrumServer();
+ Set<Sha256Hash> before = electrumServer.getUnsignedTransactions(wallet, unconfirmed, txid -> body(wallet, txid));
+ wallet.getNode(KeyPurpose.RECEIVE).fillToIndex(30);
+ Set<Sha256Hash> after = electrumServer.getUnsignedTransactions(wallet, unconfirmed, txid -> body(wallet, txid));
+
+ assertTrue(before.isEmpty());
+ assertEquals(Set.of(altered.getTxId()), after);
+ }
+
+ @Test
+ public void warnsOncePerServer() throws Exception {
+ Wallet wallet = signingWallet(ScriptType.P2WPKH);
+ fund(wallet);
+ Transaction altered = alterOutputs(signedSpend(wallet));
+ Map<Sha256Hash, Transaction> unconfirmed = Map.of(altered.getTxId(), altered);
+
+ List<Set<Sha256Hash>> warnings = new ArrayList<>();
+ Object listener = new Object() {
+ @Subscribe
+ public void unsignedTransactions(UnsignedTransactionsEvent event) {
+ warnings.add(event.getTxids());
+ }
+ };
+ EventManager.get().register(listener);
+ try {
+ new ElectrumServer().getUnsignedTransactions(wallet, unconfirmed, txid -> body(wallet, txid));
+ new ElectrumServer().getUnsignedTransactions(wallet, unconfirmed, txid -> body(wallet, txid));
+ assertEquals(1, warnings.size());
+
+ //Switching servers asks the next one afresh, so the same transaction reported by it is raised again
+ ElectrumServer.clearPreviousServerState();
+ new ElectrumServer().getUnsignedTransactions(wallet, unconfirmed, txid -> body(wallet, txid));
+ assertEquals(List.of(Set.of(altered.getTxId()), Set.of(altered.getTxId())), warnings);
+ } finally {
+ EventManager.get().unregister(listener);
+ }
+ }
+
+ @Test
+ public void doesNotCheckOnABitcoinCoreConnection() throws Exception {
+ Config.get().setServerType(ServerType.BITCOIN_CORE);
+ Wallet wallet = signingWallet(ScriptType.P2WPKH);
+ Transaction funding = fund(wallet);
+ Transaction altered = alterOutputs(signedSpend(wallet));
+
+ Map<WalletNode, Set<BlockTransactionHash>> nodeTransactionMap = history(wallet, funding, altered);
+ getReferencedTransactions(wallet, nodeTransactionMap);
+
+ assertTrue(holds(nodeTransactionMap, altered));
+ }
+
+ private static void getReferencedTransactions(Wallet wallet, Map<WalletNode, Set<BlockTransactionHash>> nodeTransactionMap) throws ServerException {
+ new ElectrumServer().getReferencedTransactions(wallet, nodeTransactionMap);
+ }
+
+ /**
+ * The history the server reports for the funded address, with the spend unconfirmed. The wallet already holds both transactions at those heights,
+ * so nothing is fetched.
+ */
+ private static Map<WalletNode, Set<BlockTransactionHash>> history(Wallet wallet, Transaction funding, Transaction spend) {
+ wallet.updateTransactions(Map.of(spend.getTxId(), new BlockTransaction(spend.getTxId(), 0, null, 1000L, spend)));
+ WalletNode node = wallet.getNode(KeyPurpose.RECEIVE).getChildren().iterator().next();
+ Map<WalletNode, Set<BlockTransactionHash>> nodeTransactionMap = new LinkedHashMap<>();
+ nodeTransactionMap.put(node, new TreeSet<>(List.of(new BlockTransaction(funding.getTxId(), FUNDING_HEIGHT, new Date(), 0L, null),
+ new BlockTransaction(spend.getTxId(), 0, null, 1000L, null))));
+
+ return nodeTransactionMap;
+ }
+
+ private static boolean holds(Map<WalletNode, Set<BlockTransactionHash>> nodeTransactionMap, Transaction transaction) {
+ return nodeTransactionMap.values().stream().flatMap(Collection::stream).anyMatch(reference -> reference.getHash().equals(transaction.getTxId()));
+ }
+
+ private static Transaction alterOutputs(Transaction signed) {
+ Transaction altered = new Transaction(signed.bitcoinSerialize());
+ altered.getOutputs().getFirst().setScriptBytes(ScriptType.P2WPKH.getOutputScript(Utils.hexToBytes("bb00000000000000000000000000000000000022")).getProgram());
+ altered = new Transaction(altered.bitcoinSerialize());
+ assertNotEquals(signed.getTxId(), altered.getTxId());
+
+ return altered;
+ }
+
+ private static Transaction fund(Wallet wallet) {
+ WalletNode addressNode = wallet.getNode(KeyPurpose.RECEIVE).getChildren().iterator().next();
+ Transaction funding = new Transaction();
+ funding.addInput(Sha256Hash.ZERO_HASH, 0, new Script(new byte[0]));
+ funding.addOutput(1_000_000L, wallet.getAddress(addressNode));
+ wallet.updateTransactions(Map.of(funding.getTxId(), new BlockTransaction(funding.getTxId(), FUNDING_HEIGHT, new Date(), 0L, funding)));
+ addressNode.getTransactionOutputs().add(new BlockTransactionHashIndex(funding.getTxId(), FUNDING_HEIGHT, new Date(), 0L, 0, 1_000_000L));
+
+ return funding;
+ }
+
+ private static Transaction signedSpend(Wallet wallet) throws Exception {
+ WalletNode addressNode = wallet.getNode(KeyPurpose.RECEIVE).getChildren().iterator().next();
+ TransactionParameters params = new TransactionParameters(List.of(new PriorityUtxoSelector(FUNDING_HEIGHT + 6)), Collections.emptyList(),
+ List.of(new Payment(wallet.getAddress(addressNode), "test", 500_000L, false)), Collections.emptyList(),
+ Collections.emptySet(), 10.0d, 1.0d, 1.0d, null, FUNDING_HEIGHT + 6, false, false, true);
+ PSBT psbt = wallet.createWalletTransaction(params).createPSBT();
+ wallet.sign(psbt);
+ wallet.finalise(psbt);
+
+ return psbt.extractTransaction();
+ }
+
+ private static Wallet signingWallet(ScriptType scriptType) throws MnemonicException {
+ Wallet wallet = new Wallet("test");
+ wallet.setPolicyType(PolicyType.SINGLE_HD);
+ wallet.setScriptType(scriptType);
+ DeterministicSeed seed = new DeterministicSeed(Utils.hexToBytes(String.format("%032x", 1)), "", 0);
+ Keystore keystore = Keystore.fromSeed(seed, PolicyType.SINGLE_HD, scriptType.getDefaultDerivation());
+ wallet.getKeystores().add(keystore);
+ wallet.setDefaultPolicy(Policy.getPolicy(PolicyType.SINGLE_HD, scriptType, wallet.getKeystores(), null));
+ wallet.setStoredBlockHeight(FUNDING_HEIGHT + 6);
+ wallet.getNode(KeyPurpose.RECEIVE).fillToIndex(0);
+
+ return wallet;
+ }
+
+ private static Transaction body(Wallet wallet, Sha256Hash txid) {
+ BlockTransaction blockTransaction = wallet.getWalletTransaction(txid);
+ return blockTransaction == null ? null : blockTransaction.getTransaction();
+ }
+
+ private static class RecordingServer extends SimpleElectrumServerRpc {
+ private final Set<String> requested = new LinkedHashSet<>();
+ private final Map<String, String> served = new HashMap<>();
+
+ public void serve(Transaction transaction) {
+ served.put(transaction.getTxId().toString(), Utils.bytesToHex(transaction.bitcoinSerialize()));
+ }
+
+ @Override
+ public Map<String, String> getTransactions(Transport transport, Wallet wallet, Set<String> txids) {
+ requested.addAll(txids);
+ Map<String, String> result = new LinkedHashMap<>();
+ txids.forEach(txid -> result.put(txid, served.getOrDefault(txid, Sha256Hash.ZERO_HASH.toString())));
+ return result;
+ }
+ }
+
+ private static class UnusedTransport extends TcpTransport {
+ public UnusedTransport() {
+ super(HostAndPort.fromParts("localhost", 1));
+ }
+
+ @Override
+ public String pass(String request) {
+ throw new UnsupportedOperationException("The fake server answers without the transport");
+ }
+
+ @Override
+ public boolean isConnected() {
+ return true;
+ }
+ }
+}Why this scored 73/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.