|
| 1 | +package bisq.core; |
| 2 | + |
| 3 | +import org.bitcoinj.core.Address; |
| 4 | +import org.bitcoinj.core.Coin; |
| 5 | +import org.bitcoinj.wallet.Wallet; |
| 6 | +import org.bitcoinj.wallet.listeners.WalletCoinsReceivedEventListener; |
| 7 | + |
| 8 | +import java.util.concurrent.CountDownLatch; |
| 9 | +import java.util.concurrent.TimeUnit; |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +import bisq.wallets.regtest.bitcoind.BitcoindRegtestSetup; |
| 14 | + |
| 15 | +public class BitcoinjRegtestSetup { |
| 16 | + private final BitcoindRegtestSetup bitcoindRegtestSetup; |
| 17 | + |
| 18 | + public BitcoinjRegtestSetup(BitcoindRegtestSetup bitcoindRegtestSetup) { |
| 19 | + this.bitcoindRegtestSetup = bitcoindRegtestSetup; |
| 20 | + } |
| 21 | + |
| 22 | + public void fundWallet(Wallet wallet, double amount) throws InterruptedException { |
| 23 | + var walletReceivedLatch = new CountDownLatch(1); |
| 24 | + WalletCoinsReceivedEventListener coinsReceivedEventListener = |
| 25 | + (affectedWallet, tx, prevBalance, newBalance) -> { |
| 26 | + walletReceivedLatch.countDown(); |
| 27 | + }; |
| 28 | + |
| 29 | + wallet.addCoinsReceivedEventListener(coinsReceivedEventListener); |
| 30 | + Coin previousBalance = wallet.getBalance(); |
| 31 | + |
| 32 | + Address currentReceiveAddress = wallet.currentReceiveAddress(); |
| 33 | + String address = currentReceiveAddress.toString(); |
| 34 | + bitcoindRegtestSetup.fundAddress(address, amount); |
| 35 | + bitcoindRegtestSetup.mineOneBlock(); |
| 36 | + |
| 37 | + boolean isSuccess = walletReceivedLatch.await(30, TimeUnit.SECONDS); |
| 38 | + wallet.removeCoinsReceivedEventListener(coinsReceivedEventListener); |
| 39 | + if (!isSuccess) { |
| 40 | + throw new IllegalStateException("Wallet not funded after 30 seconds."); |
| 41 | + } |
| 42 | + |
| 43 | + Coin balance = wallet.getBalance(); |
| 44 | + Coin receivedAmount = balance.minus(previousBalance); |
| 45 | + |
| 46 | + long receivedAmountAsLong = receivedAmount.value; |
| 47 | + long fundedAmount = (long) amount * 100_000_000; |
| 48 | + if (receivedAmount.value != fundedAmount) { |
| 49 | + throw new IllegalStateException("Wallet balance is " + receivedAmountAsLong + |
| 50 | + " but should be " + fundedAmount + "."); |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments