org.bitcoinj.script.Script Java Examples

The following examples show how to use org.bitcoinj.script.Script. 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: LNPaymentLogicImpl.java    From thunder with GNU Affero General Public License v3.0 6 votes vote down vote up
private static Transaction addPayments
        (Transaction transaction, ChannelStatus channelStatus, RevocationHash revocationHash, ECKey keyServer, ECKey keyClient) {
    Iterable<PaymentData> allPayments = new ArrayList<>(channelStatus.paymentList);

    for (PaymentData payment : allPayments) {
        Coin value = Coin.valueOf(payment.amount);
        Script script;
        if (payment.sending) {
            script = ScriptTools.getChannelTxOutputPaymentSending(keyServer, keyClient, revocationHash, payment.secret, payment.timestampRefund);
        } else {
            script = ScriptTools.getChannelTxOutputPaymentReceiving(keyServer, keyClient, revocationHash, payment.secret, payment.timestampRefund);
        }
        transaction.addOutput(value, script);
    }
    return transaction;
}
 
Example #2
Source File: SimpleTransaction.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    NetworkParameters params = TestNet3Params.get();

    final String wif = "cVXrjQt281reTcZ6eieWnbDgZsFHKApoKnU4P7j82jEBrecJB75G";
    final ECKey key = DumpedPrivateKey.fromBase58(params, wif).getKey();
    final Address address = key.toAddress(params); // mhrwYyunFdkP7RuBZLMND7fhu8aH1QETfE
    final Sha256Hash txid = Sha256Hash.wrap("488d7c1595a8aee30ccf7bd82b2cc5b7fb94c5f256b55baa519675b72cbf2fdd");
    final Long index = 1L;
    final Coin amount = Coin.MILLICOIN;
    final TransactionOutPoint outPoint = new TransactionOutPoint(params, index, txid);
    final Script pkScript = ScriptBuilder.createOutputScript(address);

    // Build transaction
    final Address spendto = Address.fromBase58(params, "mpeoG6pjLH6yDodyjqTaLZuEz7LEjEbYa5");
    final Transaction transaction = new Transaction(params);
    final Coin fee = Coin.SATOSHI.times(10000);
    transaction.addOutput(amount.minus(fee), spendto);
    transaction.addSignedInput(outPoint, pkScript, key);
    final String id = Hex.toHexString(transaction.getHash().getBytes());
    System.out.println(Hex.toHexString(transaction.bitcoinSerialize()));
}
 
Example #3
Source File: LegacyAddressTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void p2shAddressCreationFromKeys() throws Exception {
    // import some keys from this example: https://gist.github.com/gavinandresen/3966071
    ECKey key1 = DumpedPrivateKey.fromBase58(MAINNET, "5JaTXbAUmfPYZFRwrYaALK48fN6sFJp4rHqq2QSXs8ucfpE4yQU").getKey();
    key1 = ECKey.fromPrivate(key1.getPrivKeyBytes());
    ECKey key2 = DumpedPrivateKey.fromBase58(MAINNET, "5Jb7fCeh1Wtm4yBBg3q3XbT6B525i17kVhy3vMC9AqfR6FH2qGk").getKey();
    key2 = ECKey.fromPrivate(key2.getPrivKeyBytes());
    ECKey key3 = DumpedPrivateKey.fromBase58(MAINNET, "5JFjmGo5Fww9p8gvx48qBYDJNAzR9pmH5S389axMtDyPT8ddqmw").getKey();
    key3 = ECKey.fromPrivate(key3.getPrivKeyBytes());

    List<ECKey> keys = Arrays.asList(key1, key2, key3);
    Script p2shScript = ScriptBuilder.createP2SHOutputScript(2, keys);
    LegacyAddress address = LegacyAddress.fromScriptHash(MAINNET,
            ScriptPattern.extractHashFromPayToScriptHash(p2shScript));
    assertEquals("3N25saC4dT24RphDAwLtD8LUN4E2gZPJke", address.toString());
}
 
Example #4
Source File: MarriedKeyChain.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void maybeLookAheadScripts() {
    super.maybeLookAheadScripts();
    int numLeafKeys = getLeafKeys().size();

    checkState(marriedKeysRedeemData.size() <= numLeafKeys, "Number of scripts is greater than number of leaf keys");
    if (marriedKeysRedeemData.size() == numLeafKeys)
        return;

    maybeLookAhead();
    for (DeterministicKey followedKey : getLeafKeys()) {
        RedeemData redeemData = getRedeemData(followedKey);
        Script scriptPubKey = ScriptBuilder.createP2SHOutputScript(redeemData.redeemScript);
        marriedKeysRedeemData.put(ByteString.copyFrom(scriptPubKey.getPubKeyHash()), redeemData);
    }
}
 
Example #5
Source File: Channel.java    From thundernetwork with GNU Affero General Public License v3.0 6 votes vote down vote up
public Transaction getAnchorTransactionServer (WalletHelper walletHelper) {
    if (anchorTransactionServer != null) {
        return anchorTransactionServer;
    }

    long serverAmount = getInitialAmountServer();

    Script anchorScriptServer = getScriptAnchorOutputServer();
    Script anchorScriptServerP2SH = ScriptBuilder.createP2SHOutputScript(anchorScriptServer);

    Transaction transaction = new Transaction(Constants.getNetwork());
    transaction.addOutput(Coin.valueOf(serverAmount), anchorScriptServerP2SH);

    anchorTransactionServer = walletHelper.completeInputs(transaction);

    setAnchorTxHashServer(anchorTransactionServer.getHash());
    return anchorTransactionServer;
}
 
Example #6
Source File: SimpleTransaction.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    NetworkParameters params = TestNet3Params.get();

    final String wif = "cVXrjQt281reTcZ6eieWnbDgZsFHKApoKnU4P7j82jEBrecJB75G";
    final ECKey key = DumpedPrivateKey.fromBase58(params, wif).getKey();
    final Address address = key.toAddress(params); // mhrwYyunFdkP7RuBZLMND7fhu8aH1QETfE
    final Sha256Hash txid = Sha256Hash.wrap("488d7c1595a8aee30ccf7bd82b2cc5b7fb94c5f256b55baa519675b72cbf2fdd");
    final Long index = 1L;
    final Coin amount = Coin.MILLICOIN;
    final TransactionOutPoint outPoint = new TransactionOutPoint(params, index, txid);
    final Script pkScript = ScriptBuilder.createOutputScript(address);

    // Build transaction
    final Address spendto = Address.fromBase58(params, "mpeoG6pjLH6yDodyjqTaLZuEz7LEjEbYa5");
    final Transaction transaction = new Transaction(params);
    final Coin fee = Coin.SATOSHI.times(10000);
    transaction.addOutput(amount.minus(fee), spendto);
    transaction.addSignedInput(outPoint, pkScript, key);
    final String id = Hex.toHexString(transaction.getHash().getBytes());
    System.out.println(Hex.toHexString(transaction.bitcoinSerialize()));
}
 
Example #7
Source File: ScriptToolsTest.java    From thundernetwork with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test(expected = ScriptException.class)
public void shouldThrowExceptionBecauseOfWrongSecretWhenTryingToSpendFastEscapeTransaction () {
    Script outputScript = ScriptTools.getFastEscapeOutputScript(secretClientHash, keyServer, keyClient, 60 * 60 * 1000);
    Script outputScriptP2SH = ScriptBuilder.createP2SHOutputScript(outputScript);

    transactionInput.addInput(Sha256Hash.wrap("6d651fd23456606298348f7e750321cba2e3e752d433aa537ea289593645d2e4"), 0, Tools.getDummyScript());
    transactionInput.addOutput(Coin.valueOf(999000), Tools.getDummyScript());

    TransactionSignature signatureServer = Tools.getSignature(transactionInput, 0, outputScript.getProgram(), keyServer);

    byte[] b = new byte[]{0x00};
    System.arraycopy(b, 0, secretClient, 15, 1); //Copy a wrong byte into the secret, should not work anymore now

    Script inputScript = ScriptTools.getFastEscapeInputSecretScript(secretClientHash, keyServer, keyClient, 60 * 60 * 1000, signatureServer
            .encodeToBitcoin(), secretClient);

    transactionInput.getInput(0).setScriptSig(inputScript);

    inputScript.correctlySpends(transactionInput, 0, outputScriptP2SH);
}
 
Example #8
Source File: GATx.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public static PreparedTransaction signTransaction(final GaService service, final Transaction tx,
                                                  final List<JSONMap> usedUtxos,
                                                  final int subAccount,
                                                  final ChangeOutput changeOutput) {

    // Fetch previous outputs
    final List<Output> prevOuts = createPrevouts(service, usedUtxos);
    final PreparedTransaction ptx;
    ptx = new PreparedTransaction(changeOutput, subAccount, tx,
                                  service.findSubaccountByType(subAccount, "2of3"));
    ptx.mPrevoutRawTxs = new HashMap<>();
    for (final Transaction prevTx : getPreviousTransactions(service, tx)) {
        if (prevTx == null)
            throw new RuntimeException("Previous transaction not found");
        ptx.mPrevoutRawTxs.put(Wally.hex_from_bytes(prevTx.getHash().getBytes()), prevTx);
    }

    // Sign the tx
    final List<byte[]> signatures = service.signTransaction(tx, ptx, prevOuts);
    for (int i = 0; i < signatures.size(); ++i) {
        final byte[] sig = signatures.get(i);
        final JSONMap utxo = usedUtxos.get(i);
        final int scriptType = utxo.getInt("script_type");
        final byte[] outscript = createOutScript(service, utxo);
        final List<byte[]> userSigs = ImmutableList.of(new byte[]{0}, sig);
        final byte[] inscript = createInScript(userSigs, outscript, scriptType);

        tx.getInput(i).setScriptSig(new Script(inscript));
        if (getOutScriptType(scriptType) == P2SH_P2WSH_FORTIFIED_OUT) {
            // Replace the witness data with just the user signature:
            // the server will recreate the witness data to include the
            // dummy OP_CHECKMULTISIG push, user + server sigs and script.
            final TransactionWitness witness = new TransactionWitness(1);
            witness.setPush(0, sig);
            tx.setWitness(i, witness);
        }
    }
    return ptx;
}
 
Example #9
Source File: ValidationResult.java    From balzac with Apache License 2.0 5 votes vote down vote up
public InputValidationError(int index, String message, Script input, Script output) {
    super(true, message);
    this.index = index;
    this.inputScript = input.toString();
    this.outputScript = output.toString();
    this.reedemScript = isP2SH(output) ? decode(getLastChunk(input)).toString() : null;
}
 
Example #10
Source File: PaymentChannelV1ServerState.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Called when the client provides the refund transaction.
 * The refund transaction must have one input from the multisig contract (that we don't have yet) and one output
 * that the client creates to themselves. This object will later be modified when we start getting paid.
 *
 * @param refundTx The refund transaction, this object will be mutated when payment is incremented.
 * @param clientMultiSigPubKey The client's pubkey which is required for the multisig output
 * @return Our signature that makes the refund transaction valid
 * @throws VerificationException If the transaction isnt valid or did not meet the requirements of a refund transaction.
 */
public synchronized byte[] provideRefundTransaction(Transaction refundTx, byte[] clientMultiSigPubKey) throws VerificationException {
    checkNotNull(refundTx);
    checkNotNull(clientMultiSigPubKey);
    stateMachine.checkState(State.WAITING_FOR_REFUND_TRANSACTION);
    log.info("Provided with refund transaction: {}", refundTx);
    // Do a few very basic syntax sanity checks.
    refundTx.verify();
    // Verify that the refund transaction has a single input (that we can fill to sign the multisig output).
    if (refundTx.getInputs().size() != 1)
        throw new VerificationException("Refund transaction does not have exactly one input");
    // Verify that the refund transaction has a time lock on it and a sequence number that does not disable lock time.
    if (refundTx.getInput(0).getSequenceNumber() == TransactionInput.NO_SEQUENCE)
        throw new VerificationException("Refund transaction's input's sequence number disables lock time");
    if (refundTx.getLockTime() < minExpireTime)
        throw new VerificationException("Refund transaction has a lock time too soon");
    // Verify the transaction has one output (we don't care about its contents, its up to the client)
    // Note that because we sign with SIGHASH_NONE|SIGHASH_ANYOENCANPAY the client can later add more outputs and
    // inputs, but we will need only one output later to create the paying transactions
    if (refundTx.getOutputs().size() != 1)
        throw new VerificationException("Refund transaction does not have exactly one output");

    refundTransactionUnlockTimeSecs = refundTx.getLockTime();

    // Sign the refund tx with the scriptPubKey and return the signature. We don't have the spending transaction
    // so do the steps individually.
    clientKey = ECKey.fromPublicOnly(clientMultiSigPubKey);
    Script multisigPubKey = ScriptBuilder.createMultiSigOutputScript(2, ImmutableList.of(clientKey, serverKey));
    // We are really only signing the fact that the transaction has a proper lock time and don't care about anything
    // else, so we sign SIGHASH_NONE and SIGHASH_ANYONECANPAY.
    TransactionSignature sig = refundTx.calculateSignature(0, serverKey, multisigPubKey, Transaction.SigHash.NONE, true);
    log.info("Signed refund transaction.");
    this.clientOutput = refundTx.getOutput(0);
    stateMachine.transition(State.WAITING_FOR_MULTISIG_CONTRACT);
    return sig.encodeToBitcoin();
}
 
Example #11
Source File: SendRequest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static SendRequest toCLTVPaymentChannel(NetworkParameters params, BigInteger time, ECKey from, ECKey to, Coin value) {
    SendRequest req = new SendRequest();
    Script output = ScriptBuilder.createCLTVPaymentChannelOutput(time, from, to);
    req.tx = new Transaction(params);
    req.tx.addOutput(value, output);
    return req;
}
 
Example #12
Source File: Channel.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
public Transaction getFastEscapeRevocationRedemptionTransaction (Address payoutAddress, Sha256Hash parent) {
    if (getAnchorSecretClient() == null) {
        throw new RuntimeException("We don't have the secret of the client, can't construct revocation..");
    }
    Transaction redeem = new Transaction(Constants.getNetwork());

    redeem.addInput(parent, 0, Tools.getDummyScript());
    redeem.addOutput(Coin.valueOf(getInitialAmountClient() - Tools.getTransactionFees(5, 5)), payoutAddress); //TODO

    //Have to take care here with the server-client notation, since the escape is from the client points of view
    Script outputScript = ScriptTools.getFastEscapeOutputScript(
            getAnchorSecretHashClient(),
            getKeyClient(),
            getKeyServer(),
            Constants.ESCAPE_REVOCATION_TIME
    );

    TransactionSignature serverSig = Tools.getSignature(redeem, 0, outputScript.getProgram(), keyServer);

    Script inputScript = ScriptTools.getEscapeInputRevocationScript(
            getAnchorSecretHashClient(),
            getKeyClient(),
            getKeyServer(),
            Constants.ESCAPE_REVOCATION_TIME,
            serverSig.encodeToBitcoin(),
            getAnchorSecretClient());

    redeem.getInput(0).setScriptSig(inputScript);

    return redeem;
}
 
Example #13
Source File: Transaction.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public TransactionSignature calculateWitnessSignature(int inputIndex, ECKey key,
                                                      @Nullable KeyParameter aesKey,
                                                      Script redeemScript,
                                                      Coin value,
                                                      SigHash hashType, boolean anyoneCanPay) {
    Sha256Hash hash = hashForSignatureWitness(inputIndex, redeemScript.getProgram(), value, hashType, anyoneCanPay);
    return new TransactionSignature(key.sign(hash, aesKey), hashType, anyoneCanPay);
}
 
Example #14
Source File: Channel.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
public void fillAnchorTransactionWithoutSignatures (WalletHelper walletHelper) {
    long totalAmount = channelStatus.amountServer + channelStatus.amountClient;

    if (anchorTx == null) {
        Script anchorScriptServer = getAnchorScriptOutput();
        Script anchorScriptServerP2SH = ScriptBuilder.createP2SHOutputScript(anchorScriptServer);
        anchorTx = new Transaction(Constants.getNetwork());
        anchorTx.addOutput(Coin.valueOf(totalAmount), anchorScriptServerP2SH);
    }

    anchorTx = walletHelper.addInputs(anchorTx, channelStatus.amountServer, channelStatus.feePerByte);

    anchorTxHash = anchorTx.getHash();
}
 
Example #15
Source File: AddressTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void p2shAddressCreationFromKeys() throws Exception {
    // import some keys from this example: https://gist.github.com/gavinandresen/3966071
    ECKey key1 = DumpedPrivateKey.fromBase58(mainParams, "5JaTXbAUmfPYZFRwrYaALK48fN6sFJp4rHqq2QSXs8ucfpE4yQU").getKey();
    key1 = ECKey.fromPrivate(key1.getPrivKeyBytes());
    ECKey key2 = DumpedPrivateKey.fromBase58(mainParams, "5Jb7fCeh1Wtm4yBBg3q3XbT6B525i17kVhy3vMC9AqfR6FH2qGk").getKey();
    key2 = ECKey.fromPrivate(key2.getPrivKeyBytes());
    ECKey key3 = DumpedPrivateKey.fromBase58(mainParams, "5JFjmGo5Fww9p8gvx48qBYDJNAzR9pmH5S389axMtDyPT8ddqmw").getKey();
    key3 = ECKey.fromPrivate(key3.getPrivKeyBytes());

    List<ECKey> keys = Arrays.asList(key1, key2, key3);
    Script p2shScript = ScriptBuilder.createP2SHOutputScript(2, keys);
    Address address = Address.fromP2SHScript(mainParams, p2shScript);
    assertEquals("3N25saC4dT24RphDAwLtD8LUN4E2gZPJke", address.toString());
}
 
Example #16
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void opReturnMaxBytes() throws Exception {
    receiveATransaction(wallet, myAddress);
    Transaction tx = new Transaction(PARAMS);
    Script script = ScriptBuilder.createOpReturnScript(new byte[80]);
    tx.addOutput(Coin.ZERO, script);
    SendRequest request = SendRequest.forTx(tx);
    request.ensureMinRequiredFee = true;
    wallet.completeTx(request);
}
 
Example #17
Source File: PaymentChannelV1ServerState.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private void signMultisigInput(Transaction tx, Transaction.SigHash hashType,
                               boolean anyoneCanPay, @Nullable KeyParameter userKey) {
    TransactionSignature signature = tx.calculateSignature(0, serverKey, userKey, getContractScript(), hashType, anyoneCanPay);
    byte[] mySig = signature.encodeToBitcoin();
    Script scriptSig = ScriptBuilder.createMultiSigInputScriptBytes(ImmutableList.of(bestValueSignature, mySig));
    tx.getInput(0).setScriptSig(scriptSig);
}
 
Example #18
Source File: WalletTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = Wallet.MultipleOpReturnRequested.class)
public void twoOpReturnsPerTransactionTest() throws Exception {
    // Tests sending transaction where there are 2 attempts to write OP_RETURN scripts - this should fail and throw MultipleOpReturnRequested.
    receiveATransaction(wallet, myAddress);
    Transaction tx = new Transaction(UNITTEST);
    Coin messagePrice = Coin.ZERO;
    Script script1 = ScriptBuilder.createOpReturnScript("hello world 1!".getBytes());
    Script script2 = ScriptBuilder.createOpReturnScript("hello world 2!".getBytes());
    tx.addOutput(messagePrice, script1);
    tx.addOutput(messagePrice, script2);
    SendRequest request = SendRequest.forTx(tx);
    request.ensureMinRequiredFee = true;
    wallet.completeTx(request);
}
 
Example #19
Source File: KeyTimeCoinSelector.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public CoinSelection select(Coin target, List<TransactionOutput> candidates) {
    try {
        LinkedList<TransactionOutput> gathered = Lists.newLinkedList();
        Coin valueGathered = Coin.ZERO;
        for (TransactionOutput output : candidates) {
            if (ignorePending && !isConfirmed(output))
                continue;
            // Find the key that controls output, assuming it's a regular P2PK or P2PKH output.
            // We ignore any other kind of exotic output on the assumption we can't spend it ourselves.
            final Script scriptPubKey = output.getScriptPubKey();
            ECKey controllingKey;
            if (ScriptPattern.isPayToPubKey(scriptPubKey)) {
                controllingKey = wallet.findKeyFromPubKey(ScriptPattern.extractKeyFromPayToPubKey(scriptPubKey));
            } else if (ScriptPattern.isPayToPubKeyHash(scriptPubKey)) {
                controllingKey = wallet.findKeyFromPubHash(ScriptPattern.extractHashFromPayToPubKeyHash(scriptPubKey));
            } else {
                log.info("Skipping tx output {} because it's not of simple form.", output);
                continue;
            }
            checkNotNull(controllingKey, "Coin selector given output as candidate for which we lack the key");
            if (controllingKey.getCreationTimeSeconds() >= unixTimeSeconds)
                continue;
            // It's older than the cutoff time so select.
            valueGathered = valueGathered.add(output.getValue());
            gathered.push(output);
            if (gathered.size() >= MAX_SIMULTANEOUS_INPUTS) {
                log.warn("Reached {} inputs, going further would yield a tx that is too large, stopping here.", gathered.size());
                break;
            }
        }
        return new CoinSelection(valueGathered, gathered);
    } catch (ScriptException e) {
        throw new RuntimeException(e);  // We should never have problems understanding scripts in our wallet.
    }
}
 
Example #20
Source File: AbstractScriptBuilderTest.java    From balzac with Apache License 2.0 5 votes vote down vote up
@Test
public void test_optimize4() {
    Script s = new ScriptBuilder().op(OP_TOALTSTACK).op(OP_TOALTSTACK).op(OP_FROMALTSTACK).op(OP_FROMALTSTACK)
        .number(4).build();

    Script opt = AbstractScriptBuilder.optimize(s);

    assertTrue(s != opt);
    assertEquals(5, s.getChunks().size());
    assertEquals(1, opt.getChunks().size());
    assertArrayEquals(s.getProgram(),
        new byte[] { OP_TOALTSTACK, OP_TOALTSTACK, OP_FROMALTSTACK, OP_FROMALTSTACK, OP_4 });
    assertArrayEquals(opt.getProgram(), new byte[] { OP_4 });
}
 
Example #21
Source File: AbstractScriptBuilderTest.java    From balzac with Apache License 2.0 5 votes vote down vote up
@Test
public void test_optimize4_sb() {
    Script s = new ScriptBuilderWithVar().op(OP_TOALTSTACK).op(OP_TOALTSTACK).op(OP_FROMALTSTACK)
        .op(OP_FROMALTSTACK).number(4).optimize().build();

    assertEquals(1, s.getChunks().size());
    assertArrayEquals(s.getProgram(), new byte[] { OP_4 });
}
 
Example #22
Source File: PaymentChannelV1ClientState.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * <p>When the servers signature for the refund transaction is received, call this to verify it and sign the
 * complete refund ourselves.</p>
 *
 * <p>If this does not throw an exception, we are secure against the loss of funds and can safely provide the server
 * with the multi-sig contract to lock in the agreement. In this case, both the multisig contract and the refund
 * transaction are automatically committed to wallet so that it can handle broadcasting the refund transaction at
 * the appropriate time if necessary.</p>
 */
public synchronized void provideRefundSignature(byte[] theirSignature, @Nullable KeyParameter userKey)
        throws VerificationException {
    checkNotNull(theirSignature);
    stateMachine.checkState(State.WAITING_FOR_SIGNED_REFUND);
    TransactionSignature theirSig = TransactionSignature.decodeFromBitcoin(theirSignature, true);
    if (theirSig.sigHashMode() != Transaction.SigHash.NONE || !theirSig.anyoneCanPay())
        throw new VerificationException("Refund signature was not SIGHASH_NONE|SIGHASH_ANYONECANPAY");
    // Sign the refund transaction ourselves.
    final TransactionOutput multisigContractOutput = multisigContract.getOutput(0);
    try {
        multisigScript = multisigContractOutput.getScriptPubKey();
    } catch (ScriptException e) {
        throw new RuntimeException(e);  // Cannot happen: we built this ourselves.
    }
    TransactionSignature ourSignature =
            refundTx.calculateSignature(0, myKey.maybeDecrypt(userKey),
                    multisigScript, Transaction.SigHash.ALL, false);
    // Insert the signatures.
    Script scriptSig = ScriptBuilder.createMultiSigInputScript(ourSignature, theirSig);
    log.info("Refund scriptSig: {}", scriptSig);
    log.info("Multi-sig contract scriptPubKey: {}", multisigScript);
    TransactionInput refundInput = refundTx.getInput(0);
    refundInput.setScriptSig(scriptSig);
    refundInput.verify(multisigContractOutput);
    stateMachine.transition(State.SAVE_STATE_IN_WALLET);
}
 
Example #23
Source File: Transaction.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
public TransactionSignature calculateWitnessSignature(int inputIndex, ECKey key,
                                                      @Nullable KeyParameter aesKey,
                                                      Script redeemScript,
                                                      Coin value,
                                                      SigHash hashType, boolean anyoneCanPay) {
    Sha256Hash hash = hashForSignatureWitness(inputIndex, redeemScript.getProgram(), value, hashType, anyoneCanPay);
    return new TransactionSignature(key.sign(hash, aesKey), hashType, anyoneCanPay);
}
 
Example #24
Source File: Tools.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Script getMultisigInputScript (ECDSASignature client, ECDSASignature server) {
     ArrayList<TransactionSignature> signList = new ArrayList<TransactionSignature>();
     signList.add(new TransactionSignature(client, SigHash.ALL, false));
     signList.add(new TransactionSignature(server, SigHash.ALL, false));
     Script inputScript = ScriptBuilder.createMultiSigInputScript(signList);
     /*
      * Seems there is a bug here,
* https://groups.google.com/forum/#!topic/bitcoinj/A9R8TdUsXms
*/
     Script workaround = new Script(inputScript.getProgram());
     return workaround;
 }
 
Example #25
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public void sellerAsMakerFinalizesDepositTx(Transaction myDepositTx,
                                            Transaction takersDepositTx,
                                            int numTakersInputs)
        throws TransactionVerificationException, AddressFormatException {

    // We add takers signature from his inputs and add it to out tx which was already signed earlier.
    for (int i = 0; i < numTakersInputs; i++) {
        TransactionInput input = takersDepositTx.getInput(i);
        Script scriptSig = input.getScriptSig();
        myDepositTx.getInput(i).setScriptSig(scriptSig);
    }

    WalletService.printTx("sellerAsMakerFinalizesDepositTx", myDepositTx);
    WalletService.verifyTransaction(myDepositTx);
}
 
Example #26
Source File: FullPrunedBlockChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
@Override
public VerificationException call() throws Exception {
    try {
        ListIterator<Script> prevOutIt = prevOutScripts.listIterator();
        for (int index = 0; index < tx.getInputs().size(); index++) {
            tx.getInputs().get(index).getScriptSig().correctlySpends(tx, index, prevOutIt.next(), verifyFlags);
        }
    } catch (VerificationException e) {
        return e;
    }
    return null;
}
 
Example #27
Source File: AddressTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void p2shAddressCreationFromKeys() throws Exception {
    // import some keys from this example: https://gist.github.com/gavinandresen/3966071
    ECKey key1 = DumpedPrivateKey.fromBase58(mainParams, "5JaTXbAUmfPYZFRwrYaALK48fN6sFJp4rHqq2QSXs8ucfpE4yQU").getKey();
    key1 = ECKey.fromPrivate(key1.getPrivKeyBytes());
    ECKey key2 = DumpedPrivateKey.fromBase58(mainParams, "5Jb7fCeh1Wtm4yBBg3q3XbT6B525i17kVhy3vMC9AqfR6FH2qGk").getKey();
    key2 = ECKey.fromPrivate(key2.getPrivKeyBytes());
    ECKey key3 = DumpedPrivateKey.fromBase58(mainParams, "5JFjmGo5Fww9p8gvx48qBYDJNAzR9pmH5S389axMtDyPT8ddqmw").getKey();
    key3 = ECKey.fromPrivate(key3.getPrivKeyBytes());

    List<ECKey> keys = Arrays.asList(key1, key2, key3);
    Script p2shScript = ScriptBuilder.createP2SHOutputScript(2, keys);
    Address address = Address.fromP2SHScript(mainParams, p2shScript);
    assertEquals("3N25saC4dT24RphDAwLtD8LUN4E2gZPJke", address.toString());
}
 
Example #28
Source File: FullPrunedBlockChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the address from the {@link Script} if it exists otherwise return empty string "".
 *
 * @param script The script.
 * @return The address.
 */
private String getScriptAddress(@Nullable Script script) {
    String address = "";
    try {
        if (script != null) {
            address = script.getToAddress(params, true).toString();
        }
    } catch (Exception e) {
    }
    return address;
}
 
Example #29
Source File: TransactionOutputTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testP2SHOutputScript() throws Exception {
    String P2SHAddressString = "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU";
    Address P2SHAddress = Address.fromBase58(MainNetParams.get(), P2SHAddressString);
    Script script = ScriptBuilder.createOutputScript(P2SHAddress);
    Transaction tx = new Transaction(MainNetParams.get());
    tx.addOutput(Coin.COIN, script);
    assertEquals(P2SHAddressString, tx.getOutput(0).getAddressFromP2SH(MainNetParams.get()).toString());
}
 
Example #30
Source File: MarriedKeyChain.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/** Get the redeem data for a key in this married chain */
@Override
public RedeemData getRedeemData(DeterministicKey followedKey) {
    List<ECKey> marriedKeys = getMarriedKeysWithFollowed(followedKey);
    Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
    return RedeemData.of(marriedKeys, redeemScript);
}