Java Code Examples for org.bitcoinj.core.ECKey#ECDSASignature

The following examples show how to use org.bitcoinj.core.ECKey#ECDSASignature . 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-core with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signInput(Transaction transaction, TransactionInput input, int inputIndex) throws SigningException {
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    Script scriptPubKey = input.getConnectedOutput().getScriptPubKey();
    checkNotNull(wallet);
    ECKey sigKey = input.getOutpoint().getConnectedKey(wallet);
    checkNotNull(sigKey, "signInput: sigKey must not be null. input.getOutpoint()=" + input.getOutpoint().toString());
    if (sigKey.isEncrypted())
        checkNotNull(aesKey);
    Sha256Hash hash = transaction.hashForSignature(inputIndex, scriptPubKey, Transaction.SigHash.ALL, false);
    ECKey.ECDSASignature signature = sigKey.sign(hash, aesKey);
    TransactionSignature txSig = new TransactionSignature(signature, Transaction.SigHash.ALL, false);
    if (scriptPubKey.isSentToRawPubKey()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig));
    } else if (scriptPubKey.isSentToAddress()) {
        input.setScriptSig(ScriptBuilder.createInputScript(txSig, sigKey));
    } else {
        throw new SigningException("Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey);
    }
}
 
Example 2
Source File: MeritConsensus.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@VisibleForTesting
private static boolean isSignatureValid(byte[] signatureFromMerit, String pubKeyAsHex, String blindVoteTxId) {
    // We verify if signature of hash of blindVoteTxId is correct. EC key from first input for blind vote tx is
    // used for signature.
    if (pubKeyAsHex == null) {
        log.error("Error at isSignatureValid: pubKeyAsHex is null");
        return false;
    }

    boolean result = false;
    try {
        ECKey pubKey = ECKey.fromPublicOnly(Utilities.decodeFromHex(pubKeyAsHex));
        ECKey.ECDSASignature signature = ECKey.ECDSASignature.decodeFromDER(signatureFromMerit).toCanonicalised();
        Sha256Hash msg = Sha256Hash.wrap(blindVoteTxId);
        result = pubKey.verify(msg, signature);
    } catch (Throwable t) {
        log.error("Signature verification of issuance failed: " + t.toString());
    }
    if (!result) {
        log.error("Signature verification of issuance failed: blindVoteTxId={}, pubKeyAsHex={}",
                blindVoteTxId, pubKeyAsHex);
    }
    return result;
}
 
Example 3
Source File: HWWallet.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String[] signChallenge(final String challengeString, final String[] challengePath) {

    // Generate a path for the challenge.
    // We use "GA" + 0xB11E as the child path as this allows btchip to skip HID auth.
    final HWWallet child = derive(0x4741b11e); // 0x4741 = Ascii G << 8 + A

    // Generate a message to sign from the challenge
    final String challenge = "greenaddress.it      login " + challengeString;
    final byte[] rawHash = Wally.format_bitcoin_message(challenge.getBytes(),
                                                        Wally.BITCOIN_MESSAGE_FLAG_HASH);
    final Sha256Hash hash = Sha256Hash.wrap(rawHash);

    // Return the path to the caller for them to pass in the server RPC call
    challengePath[0] = "GA";

    // Compute and return the challenge signatures
    final ECKey.ECDSASignature signature = child.signMessage(challenge);
    int recId;
    for (recId = 0; recId < 4; ++recId) {
        final ECKey recovered = ECKey.recoverFromSignature(recId, signature, hash, true);
        if (recovered != null && recovered.equals(child.getPubKey()))
            break;
    }
    return new String[]{signature.r.toString(), signature.s.toString(), String.valueOf(recId)};
}
 
Example 4
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public byte[] signDelayedPayoutTx(Transaction delayedPayoutTx,
                                  DeterministicKey myMultiSigKeyPair,
                                  byte[] buyerPubKey,
                                  byte[] sellerPubKey)
        throws AddressFormatException, TransactionVerificationException {

    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    Sha256Hash sigHash = delayedPayoutTx.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("delayedPayoutTx for sig creation", delayedPayoutTx);
    WalletService.verifyTransaction(delayedPayoutTx);
    return mySignature.encodeToDER();
}
 
Example 5
Source File: TransactionUtil.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static Signature btcCoinSign(byte[] data, byte[] privateKey) {
	byte[] sha256 = TransactionUtil.Sha256(data);
	Sha256Hash sha256Hash = Sha256Hash.wrap(sha256);
	ECKey ecKey = ECKey.fromPrivate(privateKey);
	ECKey.ECDSASignature ecdsas = ecKey.sign(sha256Hash);
	byte[] signByte = ecdsas.encodeToDER();
	Signature signature = new Signature();
	signature.setPubkey(ecKey.getPubKey());
	signature.setSignature(signByte);
	signature.setTy(SignType.SECP256K1.getType());
	return signature;
}
 
Example 6
Source File: EOSSign.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
private static ECKey.ECDSASignature eosSign(byte[] input, BigInteger privateKeyForSigning) {
  EOSECDSASigner signer = new EOSECDSASigner(new MyHMacDSAKCalculator(new SHA256Digest()));
  ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE);
  signer.init(true, privKey);
  BigInteger[] components = signer.generateSignature(input);
  return new ECKey.ECDSASignature(components[0], components[1]).toCanonicalised();
}
 
Example 7
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Seller creates and signs payout transaction and adds signature of buyer to complete the transaction.
 *
 * @param depositTx                 deposit transaction
 * @param buyerSignature            DER encoded canonical signature of buyer
 * @param buyerPayoutAmount         payout amount for buyer
 * @param sellerPayoutAmount        payout amount for seller
 * @param buyerPayoutAddressString  address for buyer
 * @param sellerPayoutAddressString address for seller
 * @param multiSigKeyPair           seller's key pair for MultiSig
 * @param buyerPubKey               the public key of the buyer
 * @param sellerPubKey              the public key of the seller
 * @return the payout transaction
 * @throws AddressFormatException if the buyer or seller base58 address doesn't parse or its checksum is invalid
 * @throws TransactionVerificationException if there was an unexpected problem with the payout tx or its signatures
 * @throws WalletException if the seller's wallet is null or structurally inconsistent
 */
public Transaction sellerSignsAndFinalizesPayoutTx(Transaction depositTx,
                                                   byte[] buyerSignature,
                                                   Coin buyerPayoutAmount,
                                                   Coin sellerPayoutAmount,
                                                   String buyerPayoutAddressString,
                                                   String sellerPayoutAddressString,
                                                   DeterministicKey multiSigKeyPair,
                                                   byte[] buyerPubKey,
                                                   byte[] sellerPubKey)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    Transaction payoutTx = createPayoutTx(depositTx, buyerPayoutAmount, sellerPayoutAmount, buyerPayoutAddressString, sellerPayoutAddressString);
    // MS redeemScript
    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    // MS output from prev. tx is index 0
    Sha256Hash sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
    checkNotNull(multiSigKeyPair, "multiSigKeyPair must not be null");
    if (multiSigKeyPair.isEncrypted()) {
        checkNotNull(aesKey);
    }
    ECKey.ECDSASignature sellerSignature = multiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
    TransactionSignature buyerTxSig = new TransactionSignature(ECKey.ECDSASignature.decodeFromDER(buyerSignature),
            Transaction.SigHash.ALL, false);
    TransactionSignature sellerTxSig = new TransactionSignature(sellerSignature, Transaction.SigHash.ALL, false);
    // Take care of order of signatures. Need to be reversed here. See comment below at getMultiSigRedeemScript (seller, buyer)
    Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(sellerTxSig, buyerTxSig),
            redeemScript);
    TransactionInput input = payoutTx.getInput(0);
    input.setScriptSig(inputScript);
    WalletService.printTx("payoutTx", payoutTx);
    WalletService.verifyTransaction(payoutTx);
    WalletService.checkWalletConsistency(wallet);
    WalletService.checkScriptSig(payoutTx, input, 0);
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    input.verify(input.getConnectedOutput());
    return payoutTx;
}
 
Example 8
Source File: EthereumSign.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
public static SignatureData signAsRecoverable(byte[] value, ECKey ecKey) {

    ECKey.ECDSASignature sig = ecKey.sign(Sha256Hash.wrap(value));

    // Now we have to work backwards to figure out the recId needed to recover the signature.
    int recId = -1;
    for (int i = 0; i < 4; i++) {
      ECKey recoverKey = ECKey.recoverFromSignature(i, sig, Sha256Hash.wrap(value), false);
      if (recoverKey != null && recoverKey.getPubKeyPoint().equals(ecKey.getPubKeyPoint())) {
        recId = i;
        break;
      }
    }
    if (recId == -1) {
      throw new RuntimeException(
          "Could not construct a recoverable key. This should never happen.");
    }

    int headerByte = recId + 27;

    // 1 header + 32 bytes for R + 32 bytes for S
    byte v = (byte) headerByte;
    byte[] r = NumericUtil.bigIntegerToBytesWithZeroPadded(sig.r, 32);
    byte[] s = NumericUtil.bigIntegerToBytesWithZeroPadded(sig.s, 32);

    return new SignatureData(v, r, s);
  }
 
Example 9
Source File: Trezor.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public ECKey.ECDSASignature signMessage(final List<Integer> path, final String message) {
    final byte[] sig;
    sig = h2b(io(SignMessage.newBuilder()
                            .clearAddressN().addAllAddressN(path)
                            .setMessage(ByteString.copyFromUtf8(message))));
    return new ECKey.ECDSASignature(new BigInteger(1, Arrays.copyOfRange(sig, 1, 33)),
                                    new BigInteger(1, Arrays.copyOfRange(sig, 33, 65)));
}
 
Example 10
Source File: SWWallet.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String[] signChallenge(final String challengeString, final String[] challengePath) {

    // Generate a path for the challenge. This is really a nonce so we aren't
    // tricked into signing the same challenge (and thus revealing our key)
    // by a compromised server.
    final byte[] path = CryptoHelper.randomBytes(8);

    // Return the path to the caller for them to pass in the server RPC call
    challengePath[0] = Wally.hex_from_bytes(path);

    // Derive the private key for signing the challenge from the path
    DeterministicKey key = mRootKey;
    for (int i = 0; i < path.length / 2; ++i) {
        final int step = u8(path[i * 2]) * 256 + u8(path[i * 2 + 1]);
        key = HDKey.deriveChildKey(key, step);
    }

    // Get rid of initial 0 byte if challenge > 2^31
    // FIXME: The server should not send us challenges that we have to munge!
    byte[] challenge = new BigInteger(challengeString).toByteArray();
    if (challenge.length == 33 && challenge[0] == 0)
        challenge = Arrays.copyOfRange(challenge, 1, 33);

    // Compute and return the challenge signatures
    final ECKey.ECDSASignature sig;
    sig = ECKey.fromPrivate(key.getPrivKey()).sign(Sha256Hash.wrap(challenge));
    return new String[]{ sig.r.toString(), sig.s.toString() };
}
 
Example 11
Source File: BTChipHWWallet.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected ECKey.ECDSASignature signMessage(final String message) {
    try {
        mDongle.signMessagePrepare(getPath(), message.getBytes());
        final BTChipDongle.BTChipSignature sig = mDongle.signMessageSign(new byte[]{0});
        return ECKey.ECDSASignature.decodeFromDER(sig.getSignature());
    } catch (final BTChipException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 12
Source File: TransactionSignature.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public ECKey.ECDSASignature toCanonicalised() {
    return new TransactionSignature(super.toCanonicalised(), sigHashMode(), anyoneCanPay());
}
 
Example 13
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * A trader who got the signed tx from the arbitrator finalizes the payout tx
 *
 * @param depositTxSerialized    Serialized deposit tx
 * @param arbitratorSignature    DER encoded canonical signature of arbitrator
 * @param buyerPayoutAmount      Payout amount of the buyer
 * @param sellerPayoutAmount     Payout amount of the seller
 * @param buyerAddressString     The address of the buyer.
 * @param sellerAddressString    The address of the seller.
 * @param tradersMultiSigKeyPair The keypair for the MultiSig of the trader who calls that method
 * @param buyerPubKey            The public key of the buyer.
 * @param sellerPubKey           The public key of the seller.
 * @param arbitratorPubKey       The public key of the arbitrator.
 * @return The completed payout tx
 * @throws AddressFormatException
 * @throws TransactionVerificationException
 * @throws WalletException
 */
public Transaction traderSignAndFinalizeDisputedPayoutTx(byte[] depositTxSerialized,
                                                         byte[] arbitratorSignature,
                                                         Coin buyerPayoutAmount,
                                                         Coin sellerPayoutAmount,
                                                         String buyerAddressString,
                                                         String sellerAddressString,
                                                         DeterministicKey tradersMultiSigKeyPair,
                                                         byte[] buyerPubKey,
                                                         byte[] sellerPubKey,
                                                         byte[] arbitratorPubKey)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    Transaction depositTx = new Transaction(params, depositTxSerialized);

    log.trace("signAndFinalizeDisputedPayoutTx called");
    log.trace("depositTx " + depositTx);
    log.trace("arbitratorSignature r " + ECKey.ECDSASignature.decodeFromDER(arbitratorSignature).r.toString());
    log.trace("arbitratorSignature s " + ECKey.ECDSASignature.decodeFromDER(arbitratorSignature).s.toString());
    log.trace("buyerPayoutAmount " + buyerPayoutAmount.toFriendlyString());
    log.trace("sellerPayoutAmount " + sellerPayoutAmount.toFriendlyString());
    log.trace("buyerAddressString " + buyerAddressString);
    log.trace("sellerAddressString " + sellerAddressString);
    log.trace("tradersMultiSigKeyPair (not displayed for security reasons)");
    log.info("buyerPubKey " + ECKey.fromPublicOnly(buyerPubKey).toString());
    log.info("sellerPubKey " + ECKey.fromPublicOnly(sellerPubKey).toString());
    log.info("arbitratorPubKey " + ECKey.fromPublicOnly(arbitratorPubKey).toString());


    TransactionOutput p2SHMultiSigOutput = depositTx.getOutput(0);
    Transaction payoutTx = new Transaction(params);
    payoutTx.addInput(p2SHMultiSigOutput);
    if (buyerPayoutAmount.isGreaterThan(Coin.ZERO))
        payoutTx.addOutput(buyerPayoutAmount, Address.fromBase58(params, buyerAddressString));
    if (sellerPayoutAmount.isGreaterThan(Coin.ZERO))
        payoutTx.addOutput(sellerPayoutAmount, Address.fromBase58(params, sellerAddressString));

    // take care of sorting!
    Script redeemScript = getMultiSigRedeemScript(buyerPubKey, sellerPubKey, arbitratorPubKey);
    Sha256Hash sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
    checkNotNull(tradersMultiSigKeyPair, "tradersMultiSigKeyPair must not be null");
    if (tradersMultiSigKeyPair.isEncrypted())
        checkNotNull(aesKey);
    ECKey.ECDSASignature tradersSignature = tradersMultiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();

    TransactionSignature tradersTxSig = new TransactionSignature(tradersSignature, Transaction.SigHash.ALL, false);
    TransactionSignature arbitratorTxSig = new TransactionSignature(ECKey.ECDSASignature.decodeFromDER(arbitratorSignature),
            Transaction.SigHash.ALL, false);
    // Take care of order of signatures. See comment below at getMultiSigRedeemScript (sort order needed here: arbitrator, seller, buyer)
    Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(arbitratorTxSig, tradersTxSig), redeemScript);
    TransactionInput input = payoutTx.getInput(0);
    input.setScriptSig(inputScript);

    WalletService.printTx("disputed payoutTx", payoutTx);

    WalletService.verifyTransaction(payoutTx);
    WalletService.checkWalletConsistency(wallet);
    WalletService.checkScriptSig(payoutTx, input, 0);
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    input.verify(input.getConnectedOutput());
    return payoutTx;
}
 
Example 14
Source File: TrezorHWWallet.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected ECKey.ECDSASignature signMessage(final String message) {
    return trezor.signMessage(addrn, message);
}
 
Example 15
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Buyer creates and signs payout transaction and adds signature of seller to complete the transaction
 *
 * @param depositTx                 Deposit transaction
 * @param buyerSignature            DER encoded canonical signature of seller
 * @param buyerPayoutAmount         Payout amount for buyer
 * @param sellerPayoutAmount        Payout amount for seller
 * @param buyerPayoutAddressString  Address for buyer
 * @param sellerPayoutAddressString Address for seller
 * @param multiSigKeyPair           Buyer's keypair for MultiSig
 * @param buyerPubKey               The public key of the buyer.
 * @param sellerPubKey              The public key of the seller.
 * @param arbitratorPubKey          The public key of the arbitrator.
 * @return The payout transaction
 * @throws AddressFormatException
 * @throws TransactionVerificationException
 * @throws WalletException
 */
public Transaction sellerSignsAndFinalizesPayoutTx(Transaction depositTx,
                                                   byte[] buyerSignature,
                                                   Coin buyerPayoutAmount,
                                                   Coin sellerPayoutAmount,
                                                   String buyerPayoutAddressString,
                                                   String sellerPayoutAddressString,
                                                   DeterministicKey multiSigKeyPair,
                                                   byte[] buyerPubKey,
                                                   byte[] sellerPubKey,
                                                   byte[] arbitratorPubKey)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    log.trace("buyerSignsAndFinalizesPayoutTx called");
    log.trace("depositTx " + depositTx.toString());
    log.trace("buyerSignature r " + ECKey.ECDSASignature.decodeFromDER(buyerSignature).r.toString());
    log.trace("buyerSignature s " + ECKey.ECDSASignature.decodeFromDER(buyerSignature).s.toString());
    log.trace("buyerPayoutAmount " + buyerPayoutAmount.toFriendlyString());
    log.trace("sellerPayoutAmount " + sellerPayoutAmount.toFriendlyString());
    log.trace("buyerPayoutAddressString " + buyerPayoutAddressString);
    log.trace("sellerPayoutAddressString " + sellerPayoutAddressString);
    log.trace("multiSigKeyPair (not displayed for security reasons)");
    log.info("buyerPubKey " + ECKey.fromPublicOnly(buyerPubKey).toString());
    log.info("sellerPubKey " + ECKey.fromPublicOnly(sellerPubKey).toString());
    log.info("arbitratorPubKey " + ECKey.fromPublicOnly(arbitratorPubKey).toString());

    Transaction payoutTx = createPayoutTx(depositTx,
            buyerPayoutAmount,
            sellerPayoutAmount,
            buyerPayoutAddressString,
            sellerPayoutAddressString);
    // MS redeemScript
    Script redeemScript = getMultiSigRedeemScript(buyerPubKey, sellerPubKey, arbitratorPubKey);
    // MS output from prev. tx is index 0
    Sha256Hash sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
    checkNotNull(multiSigKeyPair, "multiSigKeyPair must not be null");
    if (multiSigKeyPair.isEncrypted())
        checkNotNull(aesKey);


    ECKey.ECDSASignature sellerSignature = multiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();

    TransactionSignature buyerTxSig = new TransactionSignature(ECKey.ECDSASignature.decodeFromDER(buyerSignature),
            Transaction.SigHash.ALL, false);
    TransactionSignature sellerTxSig = new TransactionSignature(sellerSignature, Transaction.SigHash.ALL, false);
    // Take care of order of signatures. Need to be reversed here. See comment below at getMultiSigRedeemScript (arbitrator, seller, buyer)
    Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(sellerTxSig, buyerTxSig), redeemScript);

    TransactionInput input = payoutTx.getInput(0);
    input.setScriptSig(inputScript);

    WalletService.printTx("payoutTx", payoutTx);

    WalletService.verifyTransaction(payoutTx);
    WalletService.checkWalletConsistency(wallet);
    WalletService.checkScriptSig(payoutTx, input, 0);
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    input.verify(input.getConnectedOutput());
    return payoutTx;
}
 
Example 16
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Seller signs payout transaction, buyer has not signed yet.
 *
 * @param depositTx                 Deposit transaction
 * @param buyerPayoutAmount         Payout amount for buyer
 * @param sellerPayoutAmount        Payout amount for seller
 * @param buyerPayoutAddressString  Address for buyer
 * @param sellerPayoutAddressString Address for seller
 * @param multiSigKeyPair           DeterministicKey for MultiSig from seller
 * @param buyerPubKey               The public key of the buyer.
 * @param sellerPubKey              The public key of the seller.
 * @param arbitratorPubKey          The public key of the arbitrator.
 * @return DER encoded canonical signature
 * @throws AddressFormatException
 * @throws TransactionVerificationException
 */
public byte[] buyerSignsPayoutTx(Transaction depositTx,
                                 Coin buyerPayoutAmount,
                                 Coin sellerPayoutAmount,
                                 String buyerPayoutAddressString,
                                 String sellerPayoutAddressString,
                                 DeterministicKey multiSigKeyPair,
                                 byte[] buyerPubKey,
                                 byte[] sellerPubKey,
                                 byte[] arbitratorPubKey)
        throws AddressFormatException, TransactionVerificationException {
    log.trace("sellerSignsPayoutTx called");
    log.trace("depositTx " + depositTx.toString());
    log.trace("buyerPayoutAmount " + buyerPayoutAmount.toFriendlyString());
    log.trace("sellerPayoutAmount " + sellerPayoutAmount.toFriendlyString());
    log.trace("buyerPayoutAddressString " + buyerPayoutAddressString);
    log.trace("sellerPayoutAddressString " + sellerPayoutAddressString);
    log.trace("multiSigKeyPair (not displayed for security reasons)");
    log.info("buyerPubKey HEX=" + ECKey.fromPublicOnly(buyerPubKey).getPublicKeyAsHex());
    log.info("sellerPubKey HEX=" + ECKey.fromPublicOnly(sellerPubKey).getPublicKeyAsHex());
    log.info("arbitratorPubKey HEX=" + ECKey.fromPublicOnly(arbitratorPubKey).getPublicKeyAsHex());
    Transaction preparedPayoutTx = createPayoutTx(depositTx,
            buyerPayoutAmount,
            sellerPayoutAmount,
            buyerPayoutAddressString,
            sellerPayoutAddressString);
    // MS redeemScript
    Script redeemScript = getMultiSigRedeemScript(buyerPubKey, sellerPubKey, arbitratorPubKey);
    // MS output from prev. tx is index 0
    Sha256Hash sigHash = preparedPayoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
    checkNotNull(multiSigKeyPair, "multiSigKeyPair must not be null");
    if (multiSigKeyPair.isEncrypted())
        checkNotNull(aesKey);

    ECKey.ECDSASignature buyerSignature = multiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();

    WalletService.printTx("prepared payoutTx", preparedPayoutTx);

    WalletService.verifyTransaction(preparedPayoutTx);

    return buyerSignature.encodeToDER();
}
 
Example 17
Source File: SegWitWalletTest.java    From token-core-android with Apache License 2.0 4 votes vote down vote up
@Test
public void transactionSignTest() {
  String address = "1Fyxts6r24DpEieygQiNnWxUdb18ANa5p7";
  byte[] hash160 = Address.fromBase58(MainNetParams.get(), address).getHash160();
  System.out.println("Public Key: " + NumericUtil.bytesToHex(hash160));

  String privateKey = "eb696a065ef48a2192da5b28b694f87544b30fae8327c4510137a922f32c6dcf";
  ECKey ecKey = ECKey.fromPrivate(NumericUtil.hexToBytes(privateKey), true);
  assertEquals("public key", "03ad1d8e89212f0b92c74d23bb710c00662ad1470198ac48c43f7d6f93a2a26873", ecKey.getPublicKeyAsHex());
  byte[] pubKeyHash = ecKey.getPubKeyHash();
  String redeemScript = String.format("0x0014%s", NumericUtil.bytesToHex(pubKeyHash));
  assertEquals("redeem script", "0x001479091972186c449eb1ded22b78e40d009bdf0089", redeemScript);
  byte[] redeemScriptBytes = Utils.sha256hash160(NumericUtil.hexToBytes(redeemScript));
  byte[] scriptCode = NumericUtil.hexToBytes(String.format("0x1976a914%s88ac", NumericUtil.bytesToHex(pubKeyHash)));
  String scriptPub = Integer.toHexString(169) + Integer.toHexString(redeemScriptBytes.length) + NumericUtil.bytesToHex(redeemScriptBytes) + Integer.toHexString(135);
  assertEquals("scriptPubKey", "a9144733f37cf4db86fbc2efed2500b4f4e49f31202387", scriptPub);
  byte[] hashPrevouts = Sha256Hash.hashTwice(NumericUtil.hexToBytes("db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a547701000000"));
  assertEquals("hash Prevouts", "b0287b4a252ac05af83d2dcef00ba313af78a3e9c329afa216eb3aa2a7b4613a", NumericUtil.bytesToHex(hashPrevouts));
  byte[] hashSequence = Sha256Hash.hashTwice(NumericUtil.hexToBytes("feffffff"));
  assertEquals("hashSequence", "18606b350cd8bf565266bc352f0caddcf01e8fa789dd8a15386327cf8cabe198", NumericUtil.bytesToHex(hashSequence));
  byte[] hashOutputs = Sha256Hash.hashTwice(NumericUtil.hexToBytes("b8b4eb0b000000001976a914a457b684d7f0d539a46a45bbc043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fea7ad0402e8bd8ad6d77c88ac"));
  assertEquals("hashOutputs", "de984f44532e2173ca0d64314fcefe6d30da6f8cf27bafa706da61df8a226c83", NumericUtil.bytesToHex(hashOutputs));

  UnsafeByteArrayOutputStream stream = new UnsafeByteArrayOutputStream();
  try {
    Utils.uint32ToByteStreamLE(1L, stream);
    stream.write(hashPrevouts);
    stream.write(hashSequence);
    stream.write(NumericUtil.hexToBytes("db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a547701000000"));
    stream.write(scriptCode);
    stream.write(NumericUtil.hexToBytes("00ca9a3b00000000"));
    stream.write(NumericUtil.hexToBytes("feffffff"));
    stream.write(hashOutputs);
    Utils.uint32ToByteStreamLE(1170, stream);
    Utils.uint32ToByteStreamLE(1, stream);
    String hashPreimage = NumericUtil.bytesToHex(stream.toByteArray());
    String expectedHashPreimage = "01000000b0287b4a252ac05af83d2dcef00ba313af78a3e9c329afa216eb3aa2a7b4613a18606b350cd8bf565266bc352f0caddcf01e8fa789dd8a15386327cf8cabe198db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a5477010000001976a91479091972186c449eb1ded22b78e40d009bdf008988ac00ca9a3b00000000feffffffde984f44532e2173ca0d64314fcefe6d30da6f8cf27bafa706da61df8a226c839204000001000000";
    assertEquals(hashPreimage, expectedHashPreimage);
    byte[] sigHash = Sha256Hash.hashTwice(stream.toByteArray());
    assertEquals("64f3b0f4dd2bb3aa1ce8566d220cc74dda9df97d8490cc81d89d735c92e59fb6", NumericUtil.bytesToHex(sigHash));
    ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.wrap(sigHash));
    byte hashType = 0x01;
    System.out.println(NumericUtil.bytesToHex(ByteUtil.concat(signature.encodeToDER(), new byte[]{hashType})));

  } catch (IOException e) {
    e.printStackTrace();
  }

}
 
Example 18
Source File: TransactionSignature.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
/** Constructs a transaction signature based on the ECDSA signature. */
public TransactionSignature(ECKey.ECDSASignature signature, Transaction.SigHash mode, boolean anyoneCanPay) {
    super(signature.r, signature.s);
    sighashFlags = calcSigHashValue(mode, anyoneCanPay);
}
 
Example 19
Source File: ISigningWallet.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] getTxSignature(final ECKey.ECDSASignature sig) {
    final TransactionSignature txSig = new TransactionSignature(sig, Transaction.SigHash.ALL, false);
    return txSig.encodeToBitcoin();
}
 
Example 20
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public void emergencySignAndPublishPayoutTxFrom2of2MultiSig(String depositTxHex,
                                                            Coin buyerPayoutAmount,
                                                            Coin sellerPayoutAmount,
                                                            Coin txFee,
                                                            String buyerAddressString,
                                                            String sellerAddressString,
                                                            String buyerPrivateKeyAsHex,
                                                            String sellerPrivateKeyAsHex,
                                                            String buyerPubKeyAsHex,
                                                            String sellerPubKeyAsHex,
                                                            TxBroadcaster.Callback callback)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    byte[] buyerPubKey = ECKey.fromPublicOnly(Utils.HEX.decode(buyerPubKeyAsHex)).getPubKey();
    byte[] sellerPubKey = ECKey.fromPublicOnly(Utils.HEX.decode(sellerPubKeyAsHex)).getPubKey();

    Script p2SHMultiSigOutputScript = get2of2MultiSigOutputScript(buyerPubKey, sellerPubKey);

    Coin msOutput = buyerPayoutAmount.add(sellerPayoutAmount).add(txFee);
    TransactionOutput p2SHMultiSigOutput = new TransactionOutput(params, null, msOutput, p2SHMultiSigOutputScript.getProgram());
    Transaction depositTx = new Transaction(params);
    depositTx.addOutput(p2SHMultiSigOutput);

    Transaction payoutTx = new Transaction(params);
    Sha256Hash spendTxHash = Sha256Hash.wrap(depositTxHex);
    payoutTx.addInput(new TransactionInput(params, depositTx, p2SHMultiSigOutputScript.getProgram(), new TransactionOutPoint(params, 0, spendTxHash), msOutput));

    if (buyerPayoutAmount.isPositive()) {
        payoutTx.addOutput(buyerPayoutAmount, Address.fromBase58(params, buyerAddressString));
    }
    if (sellerPayoutAmount.isPositive()) {
        payoutTx.addOutput(sellerPayoutAmount, Address.fromBase58(params, sellerAddressString));
    }

    // take care of sorting!
    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    Sha256Hash sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);

    ECKey buyerPrivateKey = ECKey.fromPrivate(Utils.HEX.decode(buyerPrivateKeyAsHex));
    checkNotNull(buyerPrivateKey, "key must not be null");
    ECKey.ECDSASignature buyerECDSASignature = buyerPrivateKey.sign(sigHash, aesKey).toCanonicalised();

    ECKey sellerPrivateKey = ECKey.fromPrivate(Utils.HEX.decode(sellerPrivateKeyAsHex));
    checkNotNull(sellerPrivateKey, "key must not be null");
    ECKey.ECDSASignature sellerECDSASignature = sellerPrivateKey.sign(sigHash, aesKey).toCanonicalised();

    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 = payoutTx.getInput(0);
    input.setScriptSig(inputScript);
    WalletService.printTx("payoutTx", payoutTx);
    WalletService.verifyTransaction(payoutTx);
    WalletService.checkWalletConsistency(wallet);
    broadcastTx(payoutTx, callback, 20);
}