diff --git a/src/main/java/org/qortal/crosschain/PirateChainHTLC.java b/src/main/java/org/qortal/crosschain/PirateChainHTLC.java index 0220e718..f28897dc 100644 --- a/src/main/java/org/qortal/crosschain/PirateChainHTLC.java +++ b/src/main/java/org/qortal/crosschain/PirateChainHTLC.java @@ -236,6 +236,37 @@ public class PirateChainHTLC { return null; } + /** + * Returns a string containing the unspent txid of the transaction that funded supplied p2shAddress + * and is at least the value specified in minimumAmount + *

+ * @throws ForeignBlockchainException if error occurs + */ + public static String getUnspentFundingTxid(BitcoinyBlockchainProvider blockchain, String p2shAddress, long minimumAmount) throws ForeignBlockchainException { + byte[] ourScriptPubKey = addressToScriptPubKey(p2shAddress); + + // Note: we can't include unconfirmed transactions here because the Pirate light wallet server requires a block range + List unspentOutputs = blockchain.getUnspentOutputs(p2shAddress, false); + for (UnspentOutput unspentOutput : unspentOutputs) { + + if (!Arrays.equals(ourScriptPubKey, unspentOutput.script)) { + // Not funding our specific HTLC script hash + continue; + } + + if (unspentOutput.value < minimumAmount) { + // Not funding the required amount + continue; + } + + return HashCode.fromBytes(unspentOutput.hash).toString(); + } + + + // No valid unspent outputs, so must be already spent + return null; + } + /** * Returns HTLC status, given P2SH address and expected redeem/refund amount *

diff --git a/src/test/java/org/qortal/test/crosschain/PirateChainTests.java b/src/test/java/org/qortal/test/crosschain/PirateChainTests.java index 8c8a1e88..847d703d 100644 --- a/src/test/java/org/qortal/test/crosschain/PirateChainTests.java +++ b/src/test/java/org/qortal/test/crosschain/PirateChainTests.java @@ -124,6 +124,21 @@ public class PirateChainTests extends Common { assertEquals(expectedTxidBE, txid); } + @Test + public void testGetTxidForUnspentAddressWithMinimumAmount() throws ForeignBlockchainException { + String p2shAddress = "ba6Q5HWrWtmfU2WZqQbrFdRYsafA45cUAt"; + long p2shFee = 10000; + final long minimumAmount = 10000 + p2shFee; + String txid = PirateChainHTLC.getUnspentFundingTxid(pirateChain.getBlockchainProvider(), p2shAddress, minimumAmount); + + // Reverse the byte order of the txid used by block explorers, to get to big-endian form + byte[] expectedTxidLE = HashCode.fromString("fea4b0c1abcf8f0f3ddc2fa2f9438501ee102aad62a9ff18a5ce7d08774755c0").asBytes(); + Bytes.reverse(expectedTxidLE); + String expectedTxidBE = HashCode.fromBytes(expectedTxidLE).toString(); + + assertEquals(expectedTxidBE, txid); + } + @Test public void testGetTxidForSpentAddress() throws ForeignBlockchainException { String p2shAddress = "bE49izfVxz8odhu8c2BcUaVFUnt7NLFRgv"; //"t3KtVxeEb8srJofo6atMEpMpEP6TjEi8VqA";