org.bitcoinj.core.AddressFormatException Java Examples

The following examples show how to use org.bitcoinj.core.AddressFormatException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public Transaction finalizeDelayedPayoutTx(Transaction delayedPayoutTx,
                                           byte[] buyerPubKey,
                                           byte[] sellerPubKey,
                                           byte[] buyerSignature,
                                           byte[] sellerSignature)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    ECKey.ECDSASignature buyerECDSASignature = ECKey.ECDSASignature.decodeFromDER(buyerSignature);
    ECKey.ECDSASignature sellerECDSASignature = ECKey.ECDSASignature.decodeFromDER(sellerSignature);
    TransactionSignature buyerTxSig = new TransactionSignature(buyerECDSASignature, Transaction.SigHash.ALL, false);
    TransactionSignature sellerTxSig = new TransactionSignature(sellerECDSASignature, Transaction.SigHash.ALL, false);
    Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(sellerTxSig, buyerTxSig), redeemScript);
    TransactionInput input = delayedPayoutTx.getInput(0);
    input.setScriptSig(inputScript);
    WalletService.printTx("finalizeDelayedPayoutTx", delayedPayoutTx);
    WalletService.verifyTransaction(delayedPayoutTx);
    WalletService.checkWalletConsistency(wallet);
    WalletService.checkScriptSig(delayedPayoutTx, input, 0);
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    input.verify(input.getConnectedOutput());
    return delayedPayoutTx;
}
 
Example #2
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public PreparedDepositTxAndMakerInputs sellerAsMakerCreatesDepositTx(byte[] contractHash,
                                                                     Coin makerInputAmount,
                                                                     Coin msOutputAmount,
                                                                     List<RawTransactionInput> takerRawTransactionInputs,
                                                                     long takerChangeOutputValue,
                                                                     @Nullable String takerChangeAddressString,
                                                                     Address makerAddress,
                                                                     Address makerChangeAddress,
                                                                     byte[] buyerPubKey,
                                                                     byte[] sellerPubKey)
        throws SigningException, TransactionVerificationException, WalletException, AddressFormatException {
    return makerCreatesDepositTx(false,
            contractHash,
            makerInputAmount,
            msOutputAmount,
            takerRawTransactionInputs,
            takerChangeOutputValue,
            takerChangeAddressString,
            makerAddress,
            makerChangeAddress,
            buyerPubKey,
            sellerPubKey);
}
 
Example #3
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private Transaction createPayoutTx(Transaction depositTx,
                                   Coin buyerPayoutAmount,
                                   Coin sellerPayoutAmount,
                                   String buyerAddressString,
                                   String sellerAddressString) throws AddressFormatException {
    TransactionOutput p2SHMultiSigOutput = depositTx.getOutput(0);
    Transaction transaction = new Transaction(params);
    transaction.addInput(p2SHMultiSigOutput);
    if (buyerPayoutAmount.isPositive()) {
        transaction.addOutput(buyerPayoutAmount, Address.fromBase58(params, buyerAddressString));
    }
    if (sellerPayoutAmount.isPositive()) {
        transaction.addOutput(sellerPayoutAmount, Address.fromBase58(params, sellerAddressString));
    }
    checkArgument(transaction.getOutputs().size() >= 1, "We need at least one output.");
    return transaction;
}
 
Example #4
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public PreparedDepositTxAndMakerInputs buyerAsMakerCreatesAndSignsDepositTx(byte[] contractHash,
                                                                            Coin makerInputAmount,
                                                                            Coin msOutputAmount,
                                                                            List<RawTransactionInput> takerRawTransactionInputs,
                                                                            long takerChangeOutputValue,
                                                                            @Nullable String takerChangeAddressString,
                                                                            Address makerAddress,
                                                                            Address makerChangeAddress,
                                                                            byte[] buyerPubKey,
                                                                            byte[] sellerPubKey)
        throws SigningException, TransactionVerificationException, WalletException, AddressFormatException {
    return makerCreatesDepositTx(true,
            contractHash,
            makerInputAmount,
            msOutputAmount,
            takerRawTransactionInputs,
            takerChangeOutputValue,
            takerChangeAddressString,
            makerAddress,
            makerChangeAddress,
            buyerPubKey,
            sellerPubKey);
}
 
Example #5
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public byte[] signMediatedPayoutTx(Transaction depositTx,
                                   Coin buyerPayoutAmount,
                                   Coin sellerPayoutAmount,
                                   String buyerPayoutAddressString,
                                   String sellerPayoutAddressString,
                                   DeterministicKey myMultiSigKeyPair,
                                   byte[] buyerPubKey,
                                   byte[] sellerPubKey)
        throws AddressFormatException, TransactionVerificationException {
    Transaction preparedPayoutTx = createPayoutTx(depositTx, buyerPayoutAmount, sellerPayoutAmount, buyerPayoutAddressString, sellerPayoutAddressString);
    // MS redeemScript
    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    // MS output from prev. tx is index 0
    Sha256Hash sigHash = preparedPayoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
    checkNotNull(myMultiSigKeyPair, "myMultiSigKeyPair must not be null");
    if (myMultiSigKeyPair.isEncrypted()) {
        checkNotNull(aesKey);
    }
    ECKey.ECDSASignature mySignature = myMultiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
    WalletService.printTx("prepared mediated payoutTx for sig creation", preparedPayoutTx);
    WalletService.verifyTransaction(preparedPayoutTx);
    return mySignature.encodeToDER();
}
 
Example #6
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public String sendFundsForMultipleAddresses(Set<String> fromAddresses,
                                            String toAddress,
                                            Coin receiverAmount,
                                            Coin fee,
                                            @Nullable String changeAddress,
                                            @Nullable KeyParameter aesKey,
                                            FutureCallback<Transaction> callback) throws AddressFormatException,
        AddressEntryException, InsufficientMoneyException {

    SendRequest request = getSendRequestForMultipleAddresses(fromAddresses, toAddress, receiverAmount, fee, changeAddress, aesKey);
    Wallet.SendResult sendResult = wallet.sendCoins(request);
    Futures.addCallback(sendResult.broadcastComplete, callback);

    printTx("sendFunds", sendResult.tx);
    return sendResult.tx.getHashAsString();
}
 
Example #7
Source File: BsqWalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
public Transaction getPreparedSendTx(String receiverAddress, Coin receiverAmount)
        throws AddressFormatException, InsufficientBsqException, WalletException, TransactionVerificationException {
    Transaction tx = new Transaction(params);
    checkArgument(Restrictions.isAboveDust(receiverAmount),
            "The amount is too low (dust limit).");
    tx.addOutput(receiverAmount, Address.fromBase58(params, receiverAddress));

    SendRequest sendRequest = SendRequest.forTx(tx);
    sendRequest.fee = Coin.ZERO;
    sendRequest.feePerKb = Coin.ZERO;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.aesKey = aesKey;
    sendRequest.shuffleOutputs = false;
    sendRequest.signInputs = false;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.changeAddress = getUnusedAddress();
    try {
        wallet.completeTx(sendRequest);
    } catch (InsufficientMoneyException e) {
        throw new InsufficientBsqException(e.missing);
    }
    checkWalletConsistency(wallet);
    verifyTransaction(tx);
    // printTx("prepareSendTx", tx);
    return tx;
}
 
Example #8
Source File: WalletService.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
public void emptyWallet(String toAddress, KeyParameter aesKey, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler)
        throws InsufficientMoneyException, AddressFormatException {
    SendRequest sendRequest = SendRequest.emptyWallet(Address.fromBase58(params, toAddress));
    sendRequest.fee = Coin.ZERO;
    sendRequest.feePerKb = getTxFeeForWithdrawalPerByte().multiply(1000);
    sendRequest.aesKey = aesKey;
    Wallet.SendResult sendResult = wallet.sendCoins(sendRequest);
    printTx("empty wallet", sendResult.tx);
    Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() {
        @Override
        public void onSuccess(Transaction result) {
            log.info("emptyWallet onSuccess Transaction=" + result);
            resultHandler.handleResult();
        }

        @Override
        public void onFailure(@NotNull Throwable t) {
            log.error("emptyWallet onFailure " + t.toString());
            errorMessageHandler.handleErrorMessage(t.getMessage());
        }
    });
}
 
Example #9
Source File: WalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public void emptyWallet(String toAddress,
                        KeyParameter aesKey,
                        ResultHandler resultHandler,
                        ErrorMessageHandler errorMessageHandler)
        throws InsufficientMoneyException, AddressFormatException {
    SendRequest sendRequest = SendRequest.emptyWallet(Address.fromBase58(params, toAddress));
    sendRequest.fee = Coin.ZERO;
    sendRequest.feePerKb = getTxFeeForWithdrawalPerByte().multiply(1000);
    sendRequest.aesKey = aesKey;
    Wallet.SendResult sendResult = wallet.sendCoins(sendRequest);
    printTx("empty wallet", sendResult.tx);
    Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() {
        @Override
        public void onSuccess(Transaction result) {
            log.info("emptyWallet onSuccess Transaction=" + result);
            resultHandler.handleResult();
        }

        @Override
        public void onFailure(@NotNull Throwable t) {
            log.error("emptyWallet onFailure " + t.toString());
            errorMessageHandler.handleErrorMessage(t.getMessage());
        }
    });
}
 
Example #10
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public String cashAddressToLegacy(String cashAddress) {
    try {
        CashAddressFactory cashAddressFactory = CashAddressFactory.create();
        Address leg = cashAddressFactory.getFromFormattedAddress(params, cashAddress);
        Log.d("psd", "cash to addr: leg addr = " + leg.toBase58());
        return leg.toBase58();
    } catch (AddressFormatException afe) {
        afe.printStackTrace();
        return "";
    }
}
 
Example #11
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private SendRequest getSendRequest(String fromAddress,
                                   String toAddress,
                                   Coin amount,
                                   Coin fee,
                                   @Nullable KeyParameter aesKey,
                                   AddressEntry.Context context) throws AddressFormatException,
        AddressEntryException {
    Transaction tx = new Transaction(params);
    final Coin receiverAmount = amount.subtract(fee);
    Preconditions.checkArgument(Restrictions.isAboveDust(receiverAmount),
            "The amount is too low (dust limit).");
    tx.addOutput(receiverAmount, Address.fromBase58(params, toAddress));

    SendRequest sendRequest = SendRequest.forTx(tx);
    sendRequest.fee = fee;
    sendRequest.feePerKb = Coin.ZERO;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.aesKey = aesKey;
    sendRequest.shuffleOutputs = false;
    Optional<AddressEntry> addressEntry = findAddressEntry(fromAddress, context);
    if (!addressEntry.isPresent())
        throw new AddressEntryException("WithdrawFromAddress is not found in our wallet.");

    checkNotNull(addressEntry.get(), "addressEntry.get() must not be null");
    checkNotNull(addressEntry.get().getAddress(), "addressEntry.get().getAddress() must not be null");
    sendRequest.coinSelector = new BtcCoinSelector(addressEntry.get().getAddress(), preferences.getIgnoreDustThreshold());
    sendRequest.changeAddress = addressEntry.get().getAddress();
    return sendRequest;
}
 
Example #12
Source File: Ergo.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public AddressValidationResult validate(String address) {
    try {
        byte[] decoded  = Base58.decode(address);
        if (decoded.length < 4) {
            return AddressValidationResult.invalidAddress("Input too short: " + decoded.length);
        }
        if (decoded[0] != 1 && decoded[0] != 2 && decoded[0] != 3) {
            return AddressValidationResult.invalidAddress("Invalid prefix");
        }
    } catch (AddressFormatException e) {
        return AddressValidationResult.invalidAddress(e);
    }
    return AddressValidationResult.validAddress();
}
 
Example #13
Source File: Utils.java    From evt4j with MIT License 5 votes vote down vote up
public static byte[] base58CheckDecode(String key, @Nullable String keyType) throws Base58CheckException {
    byte[] decoded;

    try {
        // base58 decode
        decoded = Base58.decode(key);
    } catch (AddressFormatException ex) {
        throw new Base58CheckException(ex.getMessage(), ex);
    }
    // split the byte slice
    byte[] data = ArrayUtils.subarray(decoded, 0, decoded.length - 4);
    byte[] checksum = ArrayUtils.subarray(decoded, decoded.length - 4, decoded.length);

    if (keyType != null) {
        data = ArrayUtils.addAll(data, keyType.getBytes());
    }

    // ripemd160 input, sign 4 bytes to compare
    byte[] hash = ripemd160(data);

    // if pass, return data, otherwise throw ex
    // compare two checksum
    boolean isEqual = true;

    for (int i = 0; i < checksum.length; i++) {
        if (hash[i] != checksum[i]) {
            isEqual = false;
        }
    }

    if (!isEqual) {
        throw new Base58CheckException();
    }

    if (keyType != null) {
        return ArrayUtils.subarray(data, 0, data.length - keyType.getBytes().length);
    }

    return data;
}
 
Example #14
Source File: BitcoinAddressValidator.java    From devcoretalk with GNU General Public License v2.0 5 votes vote down vote up
private boolean testAddr(String text) {
    try {
        new Address(params, text);
        return true;
    } catch (AddressFormatException e) {
        return false;
    }
}
 
Example #15
Source File: ECKeyDeserializer.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Override
public ECKey deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken token = p.getCurrentToken();
    switch (token) {
        case VALUE_STRING:
            try {
                return DumpedPrivateKey.fromBase58(null, p.getValueAsString()).getKey();
            } catch (AddressFormatException e) {
                throw new InvalidFormatException(p, "Invalid Key", p.getValueAsString(), ECKey.class);
            }
        default:
            return (ECKey) ctxt.handleUnexpectedToken(ECKey.class, p);
    }
}
 
Example #16
Source File: BtcWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public String sendFunds(String fromAddress,
                        String toAddress,
                        Coin receiverAmount,
                        Coin fee,
                        @Nullable KeyParameter aesKey,
                        @SuppressWarnings("SameParameterValue") AddressEntry.Context context,
                        FutureCallback<Transaction> callback) throws AddressFormatException,
        AddressEntryException, InsufficientMoneyException {
    SendRequest sendRequest = getSendRequest(fromAddress, toAddress, receiverAmount, fee, aesKey, context);
    Wallet.SendResult sendResult = wallet.sendCoins(sendRequest);
    Futures.addCallback(sendResult.broadcastComplete, callback);

    printTx("sendFunds", sendResult.tx);
    return sendResult.tx.getHashAsString();
}
 
Example #17
Source File: NmcLookup.java    From consensusj with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws URISyntaxException, IOException, JsonRpcStatusException, AddressFormatException {
    NamecoinClient client = new NamecoinClient(NamecoinClient.readConfig());
    NameData result = client.nameShow("d/beelin");
    System.out.println(result.getValue());
    Address owningAddress = result.getAddress();
    System.out.println("Owning Address: " + owningAddress);
}
 
Example #18
Source File: BitcoinAddressValidator.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private boolean testAddr(String text) {
    try {
        Address.fromBase58(params, text);
        return true;
    } catch (AddressFormatException e) {
        return false;
    }
}
 
Example #19
Source File: BitcoinAddressValidator.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean testAddr(String text) {
    try {
        new Address(params, text);
        return true;
    } catch (AddressFormatException e) {
        return false;
    }
}
 
Example #20
Source File: TradeManager.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public void onWithdrawRequest(String toAddress, Coin amount, Coin fee, KeyParameter aesKey,
                              Trade trade, ResultHandler resultHandler, FaultHandler faultHandler) {
    String fromAddress = btcWalletService.getOrCreateAddressEntry(trade.getId(),
            AddressEntry.Context.TRADE_PAYOUT).getAddressString();
    FutureCallback<Transaction> callback = new FutureCallback<>() {
        @Override
        public void onSuccess(@javax.annotation.Nullable Transaction transaction) {
            if (transaction != null) {
                log.debug("onWithdraw onSuccess tx ID:" + transaction.getHashAsString());
                addTradeToClosedTrades(trade);
                trade.setState(Trade.State.WITHDRAW_COMPLETED);
                resultHandler.handleResult();
            }
        }

        @Override
        public void onFailure(@NotNull Throwable t) {
            t.printStackTrace();
            log.error(t.getMessage());
            faultHandler.handleFault("An exception occurred at requestWithdraw (onFailure).", t);
        }
    };
    try {
        btcWalletService.sendFunds(fromAddress, toAddress, amount, fee, aesKey, AddressEntry.Context.TRADE_PAYOUT, callback);
    } catch (AddressFormatException | InsufficientMoneyException | AddressEntryException e) {
        e.printStackTrace();
        log.error(e.getMessage());
        faultHandler.handleFault("An exception occurred at requestWithdraw.", e);
    }
}
 
Example #21
Source File: WIFValidator.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
@Override
public String validate() {
  try {
    DumpedPrivateKey.fromBase58(network, wif);
  } catch (WrongNetworkException addressException) {
    throw new TokenException(Messages.WIF_WRONG_NETWORK);
  } catch (AddressFormatException addressFormatException) {
    throw new TokenException(Messages.WIF_INVALID);
  }
  if (requireCompressed && !DumpedPrivateKey.fromBase58(network, wif).getKey().isCompressed()) {
    throw new TokenException(Messages.SEGWIT_NEEDS_COMPRESS_PUBLIC_KEY);
  }
  return this.wif;
}
 
Example #22
Source File: ZenCash.java    From bisq-assets with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public AddressValidationResult validate(String address) {
    byte[] byteAddress;
    try {
        // Get the non Base58 form of the address and the bytecode of the first two bytes
        byteAddress = Base58.decodeChecked(address);
    } catch (AddressFormatException e) {
        // Unhandled Exception (probably a checksum error)
        return AddressValidationResult.invalidAddress(e);
    }
    int version0 = byteAddress[0] & 0xFF;
    int version1 = byteAddress[1] & 0xFF;

    // We only support public ("zn" (0x20,0x89), "t1" (0x1C,0xB8))
    // and multisig ("zs" (0x20,0x96), "t3" (0x1C,0xBD)) addresses

    // Fail for private addresses
    if (version0 == 0x16 && version1 == 0x9A)
        // Address starts with "zc"
        return AddressValidationResult.invalidAddress("", "validation.altcoin.zAddressesNotSupported");

    if (version0 == 0x1C && (version1 == 0xB8 || version1 == 0xBD))
        // "t1" or "t3" address
        return AddressValidationResult.validAddress();

    if (version0 == 0x20 && (version1 == 0x89 || version1 == 0x96))
        // "zn" or "zs" address
        return AddressValidationResult.validAddress();

    // Unknown Type
    return AddressValidationResult.invalidStructure();
}
 
Example #23
Source File: WorldMobileCoin.java    From bisq-assets with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Helper
 */
private static byte[] convertBits(final byte[] in, final int inStart, final int inLen, final int fromBits,
                                  final int toBits, final boolean pad) throws AddressFormatException {
    int acc = 0;
    int bits = 0;
    ByteArrayOutputStream out = new ByteArrayOutputStream(64);
    final int maxv = (1 << toBits) - 1;
    final int max_acc = (1 << (fromBits + toBits - 1)) - 1;
    for (int i = 0; i < inLen; i++) {
        int value = in[i + inStart] & 0xff;
        if ((value >>> fromBits) != 0) {
            throw new AddressFormatException(
                    String.format("Input value '%X' exceeds '%d' bit size", value, fromBits));
        }
        acc = ((acc << fromBits) | value) & max_acc;
        bits += fromBits;
        while (bits >= toBits) {
            bits -= toBits;
            out.write((acc >>> bits) & maxv);
        }
    }
    if (pad) {
        if (bits > 0)
            out.write((acc << (toBits - bits)) & maxv);
    } else if (bits >= fromBits || ((acc << (toBits - bits)) & maxv) != 0) {
        throw new AddressFormatException("Could not convert bits, invalid padding");
    }
    return out.toByteArray();
}
 
Example #24
Source File: WorldMobileCoin.java    From bisq-assets with GNU Affero General Public License v3.0 5 votes vote down vote up
static WitnessAddress fromBech32(@Nullable NetworkParameters params, String bech32)
        throws AddressFormatException {
    Bech32.Bech32Data bechData = Bech32.decode(bech32);
    if (params == null) {
        for (NetworkParameters p : Networks.get()) {
            if (bechData.hrp.equals(WITNESS_ADDRESS_HRP))
                return new WitnessAddress(p, bechData.data);
        }
        throw new AddressFormatException("Invalid Prefix: No network found for " + bech32);
    } else {
        if (bechData.hrp.equals(WITNESS_ADDRESS_HRP))
            return new WitnessAddress(params, bechData.data);
        throw new AddressFormatException("Wrong Network: " + bechData.hrp);
    }
}
 
Example #25
Source File: WorldMobileCoin.java    From bisq-assets with GNU Affero General Public License v3.0 5 votes vote down vote up
private WitnessAddress(NetworkParameters params, byte[] data) throws AddressFormatException {
    super(params.getAddressHeader(), data);
    if (data.length < 1)
        throw new AddressFormatException("Zero data found");
    final int version = getWitnessVersion();
    if (version < 0 || version > 16)
        throw new AddressFormatException("Invalid script version: " + version);
    byte[] program = getWitnessProgram();
    if (program.length < PROGRAM_MIN_LENGTH || program.length > PROGRAM_MAX_LENGTH)
        throw new AddressFormatException("Invalid length: " + program.length);
    if (version == 0 && program.length != PROGRAM_LENGTH_PKH
            && program.length != PROGRAM_LENGTH_SH)
        throw new AddressFormatException(
                "Invalid length for address version 0: " + program.length);
}
 
Example #26
Source File: WorldMobileCoin.java    From bisq-assets with GNU Affero General Public License v3.0 5 votes vote down vote up
public AddressValidationResult validate(String address) {
    if (!isLowerCase(address)) {
        return base58BitcoinAddressValidator.validate(address);
    }

    try {
        WitnessAddress.fromBech32(networkParameters, address);
    } catch (AddressFormatException ex) {
        return AddressValidationResult.invalidAddress(ex);
    }

    return AddressValidationResult.validAddress();
}
 
Example #27
Source File: BsqWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private Transaction getPreparedSendTx(String receiverAddress, Coin receiverAmount, CoinSelector coinSelector)
        throws AddressFormatException, InsufficientBsqException, WalletException, TransactionVerificationException, BsqChangeBelowDustException {
    daoKillSwitch.assertDaoIsNotDisabled();
    Transaction tx = new Transaction(params);
    checkArgument(Restrictions.isAboveDust(receiverAmount),
            "The amount is too low (dust limit).");
    tx.addOutput(receiverAmount, Address.fromBase58(params, receiverAddress));

    SendRequest sendRequest = SendRequest.forTx(tx);
    sendRequest.fee = Coin.ZERO;
    sendRequest.feePerKb = Coin.ZERO;
    sendRequest.ensureMinRequiredFee = false;
    sendRequest.aesKey = aesKey;
    sendRequest.shuffleOutputs = false;
    sendRequest.signInputs = false;
    sendRequest.changeAddress = getChangeAddress();
    sendRequest.coinSelector = coinSelector;
    try {
        wallet.completeTx(sendRequest);
        checkWalletConsistency(wallet);
        verifyTransaction(tx);
        // printTx("prepareSendTx", tx);

        // Tx has as first output BSQ and an optional second BSQ change output.
        // At that stage we do not have added the BTC inputs so there is no BTC change output here.
        if (tx.getOutputs().size() == 2) {
            Coin bsqChangeOutputValue = tx.getOutputs().get(1).getValue();
            if (!Restrictions.isAboveDust(bsqChangeOutputValue)) {
                String msg = "BSQ change output is below dust limit. outputValue=" + bsqChangeOutputValue.value / 100 + " BSQ";
                log.warn(msg);
                throw new BsqChangeBelowDustException(msg, bsqChangeOutputValue);
            }
        }

        return tx;
    } catch (InsufficientMoneyException e) {
        log.error(e.toString());
        throw new InsufficientBsqException(e.missing);
    }
}
 
Example #28
Source File: Base58BitcoinAddressValidator.java    From bisq-assets with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public AddressValidationResult validate(String address) {
    try {
        Address.fromBase58(networkParameters, address);
    } catch (AddressFormatException ex) {
        return AddressValidationResult.invalidAddress(ex);
    }

    return AddressValidationResult.validAddress();
}
 
Example #29
Source File: BtcAddressValidator.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private ValidationResult validateBtcAddress(String input) {
    try {
        Address.fromBase58(Config.baseCurrencyNetworkParameters(), input);
        return new ValidationResult(true);
    } catch (AddressFormatException e) {
        return new ValidationResult(false, Res.get("validation.btc.invalidFormat"));
    }
}
 
Example #30
Source File: ConfidentialAddress.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
protected ConfidentialAddress(final NetworkParameters params, final String address) throws AddressFormatException {
    super(address);

    checkNotNull(params);

    if (version != 4)
        throw new WrongNetworkException(version, params.getAcceptableAddressCodes());

    final byte[] hash = bytes;
    if (!isAcceptableLength(params, version, hash.length - 1 - 33)) // len - version - pubkey
        throw new WrongLengthException(hash.length);
}