Search in sources :

Example 11 with DeterministicKey

use of org.bitcoinj.crypto.DeterministicKey in project bisq-core by bisq-network.

the class BtcWalletService method decryptWallet.

// /////////////////////////////////////////////////////////////////////////////////////////
// Overridden Methods
// /////////////////////////////////////////////////////////////////////////////////////////
@Override
void decryptWallet(@NotNull KeyParameter key) {
    super.decryptWallet(key);
    addressEntryList.stream().forEach(e -> {
        final DeterministicKey keyPair = e.getKeyPair();
        if (keyPair.isEncrypted())
            e.setDeterministicKey(keyPair.decrypt(key));
    });
    addressEntryList.persist();
}
Also used : DeterministicKey(org.bitcoinj.crypto.DeterministicKey)

Example 12 with DeterministicKey

use of org.bitcoinj.crypto.DeterministicKey in project bisq-core by bisq-network.

the class BtcWalletService method encryptWallet.

@Override
void encryptWallet(KeyCrypterScrypt keyCrypterScrypt, KeyParameter key) {
    super.encryptWallet(keyCrypterScrypt, key);
    addressEntryList.stream().forEach(e -> {
        final DeterministicKey keyPair = e.getKeyPair();
        if (keyPair.isEncrypted())
            e.setDeterministicKey(keyPair.encrypt(keyCrypterScrypt, key));
    });
    addressEntryList.persist();
}
Also used : DeterministicKey(org.bitcoinj.crypto.DeterministicKey)

Example 13 with DeterministicKey

use of org.bitcoinj.crypto.DeterministicKey in project bisq-core by bisq-network.

the class WalletService method signTransactionInput.

// /////////////////////////////////////////////////////////////////////////////////////////
// Sign tx
// /////////////////////////////////////////////////////////////////////////////////////////
public static void signTransactionInput(Wallet wallet, KeyParameter aesKey, Transaction tx, TransactionInput txIn, int index) {
    KeyBag maybeDecryptingKeyBag = new DecryptingKeyBag(wallet, aesKey);
    if (txIn.getConnectedOutput() != null) {
        try {
            // We assume if its already signed, its hopefully got a SIGHASH type that will not invalidate when
            // we sign missing pieces (to check this would require either assuming any signatures are signing
            // standard output types or a way to get processed signatures out of script execution)
            txIn.getScriptSig().correctlySpends(tx, index, txIn.getConnectedOutput().getScriptPubKey(), Script.ALL_VERIFY_FLAGS);
            log.warn("Input {} already correctly spends output, assuming SIGHASH type used will be safe and skipping signing.", index);
            return;
        } catch (ScriptException e) {
        // Expected.
        }
        Script scriptPubKey = txIn.getConnectedOutput().getScriptPubKey();
        RedeemData redeemData = txIn.getConnectedRedeemData(maybeDecryptingKeyBag);
        checkNotNull(redeemData, "Transaction exists in wallet that we cannot redeem: %s", txIn.getOutpoint().getHash());
        txIn.setScriptSig(scriptPubKey.createEmptyInputScript(redeemData.keys.get(0), redeemData.redeemScript));
        TransactionSigner.ProposedTransaction propTx = new TransactionSigner.ProposedTransaction(tx);
        Transaction partialTx = propTx.partialTx;
        txIn = partialTx.getInput(index);
        if (txIn.getConnectedOutput() != null) {
            // If we dont have a sig we don't do the check to avoid error reports of failed sig checks
            final List<ScriptChunk> chunks = txIn.getConnectedOutput().getScriptPubKey().getChunks();
            if (!chunks.isEmpty() && chunks.get(0).data != null && chunks.get(0).data.length > 0) {
                try {
                    // We assume if its already signed, its hopefully got a SIGHASH type that will not invalidate when
                    // we sign missing pieces (to check this would require either assuming any signatures are signing
                    // standard output types or a way to get processed signatures out of script execution)
                    txIn.getScriptSig().correctlySpends(tx, index, txIn.getConnectedOutput().getScriptPubKey(), Script.ALL_VERIFY_FLAGS);
                    log.warn("Input {} already correctly spends output, assuming SIGHASH type used will be safe and skipping signing.", index);
                    return;
                } catch (ScriptException e) {
                // Expected.
                }
            }
            redeemData = txIn.getConnectedRedeemData(maybeDecryptingKeyBag);
            scriptPubKey = txIn.getConnectedOutput().getScriptPubKey();
            checkNotNull(redeemData, "redeemData must not be null");
            ECKey pubKey = redeemData.keys.get(0);
            if (pubKey instanceof DeterministicKey)
                propTx.keyPaths.put(scriptPubKey, (((DeterministicKey) pubKey).getPath()));
            ECKey key;
            if ((key = redeemData.getFullKey()) == null) {
                log.warn("No local key found for input {}", index);
                return;
            }
            Script inputScript = txIn.getScriptSig();
            byte[] script = redeemData.redeemScript.getProgram();
            try {
                TransactionSignature signature = partialTx.calculateSignature(index, key, script, Transaction.SigHash.ALL, false);
                inputScript = scriptPubKey.getScriptSigWithSignature(inputScript, signature.encodeToBitcoin(), 0);
                txIn.setScriptSig(inputScript);
            } catch (ECKey.KeyIsEncryptedException e1) {
                throw e1;
            } catch (ECKey.MissingPrivateKeyException e1) {
                log.warn("No private key in keypair for input {}", index);
            }
        } else {
            log.warn("Missing connected output, assuming input {} is already signed.", index);
        }
    } else {
        log.error("Missing connected output, assuming already signed.");
    }
}
Also used : Script(org.bitcoinj.script.Script) TransactionSigner(org.bitcoinj.signers.TransactionSigner) ECKey(org.bitcoinj.core.ECKey) TransactionSignature(org.bitcoinj.crypto.TransactionSignature) KeyBag(org.bitcoinj.wallet.KeyBag) DecryptingKeyBag(org.bitcoinj.wallet.DecryptingKeyBag) RedeemData(org.bitcoinj.wallet.RedeemData) ScriptChunk(org.bitcoinj.script.ScriptChunk) DecryptingKeyBag(org.bitcoinj.wallet.DecryptingKeyBag) ScriptException(org.bitcoinj.core.ScriptException) Transaction(org.bitcoinj.core.Transaction) DeterministicKey(org.bitcoinj.crypto.DeterministicKey)

Example 14 with DeterministicKey

use of org.bitcoinj.crypto.DeterministicKey in project bisq-core by bisq-network.

the class CompensationRequestService method prepareCompensationRequest.

// TODO move code to consensus package
public CompensationRequest prepareCompensationRequest(CompensationRequestPayload compensationRequestPayload) throws InsufficientMoneyException, TransactionVerificationException, WalletException, CompensationAmountException, ChangeBelowDustException {
    final Coin minRequestAmount = Restrictions.getMinCompensationRequestAmount();
    if (compensationRequestPayload.getRequestedBsq().compareTo(minRequestAmount) < 0) {
        throw new CompensationAmountException(minRequestAmount, compensationRequestPayload.getRequestedBsq());
    }
    CompensationRequest compensationRequest = new CompensationRequest(compensationRequestPayload);
    final Transaction preparedBurnFeeTx = bsqWalletService.getPreparedBurnFeeTx(ProposalConsensus.getCreateCompensationRequestFee(readableBsqBlockChain));
    checkArgument(!preparedBurnFeeTx.getInputs().isEmpty(), "preparedTx inputs must not be empty");
    // We use the key of the first BSQ input for signing the data
    TransactionOutput connectedOutput = preparedBurnFeeTx.getInputs().get(0).getConnectedOutput();
    checkNotNull(connectedOutput, "connectedOutput must not be null");
    DeterministicKey bsqKeyPair = bsqWalletService.findKeyFromPubKeyHash(connectedOutput.getScriptPubKey().getPubKeyHash());
    checkNotNull(bsqKeyPair, "bsqKeyPair must not be null");
    // We get the JSON of the object excluding signature and feeTxId
    String payloadAsJson = StringUtils.deleteWhitespace(Utilities.objectToJson(compensationRequestPayload));
    // Signs a text message using the standard Bitcoin messaging signing format and returns the signature as a base64
    // encoded string.
    String signature = bsqKeyPair.signMessage(payloadAsJson);
    compensationRequestPayload.setSignature(signature);
    // TODO should we store the hash in the compensationRequestPayload object?
    String dataAndSig = payloadAsJson + signature;
    byte[] opReturnData = OpReturnData.getBytes(dataAndSig);
    // TODO 1 Btc output (small payment to own vote receiving address)
    final Transaction txWithBtcFee = btcWalletService.completePreparedCompensationRequestTx(compensationRequest.getRequestedBsq(), compensationRequest.getBsqAddress(bsqWalletService), preparedBurnFeeTx, opReturnData);
    compensationRequest.setTx(bsqWalletService.signTx(txWithBtcFee));
    return compensationRequest;
}
Also used : Coin(org.bitcoinj.core.Coin) TransactionOutput(org.bitcoinj.core.TransactionOutput) Transaction(org.bitcoinj.core.Transaction) DeterministicKey(org.bitcoinj.crypto.DeterministicKey)

Example 15 with DeterministicKey

use of org.bitcoinj.crypto.DeterministicKey in project toshi-android-client by toshiapp.

the class EthereumDeterministicKeyChain method getKeys.

@Override
public List<DeterministicKey> getKeys(KeyPurpose purpose, int numberOfKeys) {
    final List<DeterministicKey> keys = new ArrayList<>(1);
    final DeterministicKey key;
    switch(purpose) {
        case AUTHENTICATION:
            key = getKeyByPath(IDENTITY_PATH, true);
            break;
        case RECEIVE_FUNDS:
            key = getKeyByPath(ETH44_ACCOUNT_ZERO_PATH, true);
            break;
        case CHANGE:
        case REFUND:
        default:
            throw new RuntimeException("unsupported keypurpose");
    }
    keys.add(key);
    return keys;
}
Also used : ArrayList(java.util.ArrayList) DeterministicKey(org.bitcoinj.crypto.DeterministicKey)

Aggregations

DeterministicKey (org.bitcoinj.crypto.DeterministicKey)19 Transaction (org.bitcoinj.core.Transaction)5 ByteBuffer (java.nio.ByteBuffer)3 Coin (org.bitcoinj.core.Coin)3 ChildNumber (org.bitcoinj.crypto.ChildNumber)3 AddressEntry (bisq.core.btc.AddressEntry)2 BtcWalletService (bisq.core.btc.wallet.BtcWalletService)2 TransactionOutput (org.bitcoinj.core.TransactionOutput)2 Timer (bisq.common.Timer)1 DisputeCommunicationMessage (bisq.core.arbitration.messages.DisputeCommunicationMessage)1 TransactionVerificationException (bisq.core.btc.exceptions.TransactionVerificationException)1 WalletException (bisq.core.btc.exceptions.WalletException)1 Offer (bisq.core.offer.Offer)1 Contract (bisq.core.trade.Contract)1 Tradable (bisq.core.trade.Tradable)1 Trade (bisq.core.trade.Trade)1 TradingPeer (bisq.core.trade.protocol.TradingPeer)1 ArrayList (java.util.ArrayList)1 Optional (java.util.Optional)1 AddressFormatException (org.bitcoinj.core.AddressFormatException)1