org.bitcoinj.script.ScriptBuilder Java Examples

The following examples show how to use org.bitcoinj.script.ScriptBuilder. 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: PaymentProtocolTest.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testPaymentRequest() throws Exception {
    // Create
    PaymentRequest paymentRequest = PaymentProtocol.createPaymentRequest(TestNet3Params.get(), AMOUNT, TO_ADDRESS, MEMO,
            PAYMENT_URL, MERCHANT_DATA).build();
    byte[] paymentRequestBytes = paymentRequest.toByteArray();

    // Parse
    PaymentSession parsedPaymentRequest = PaymentProtocol.parsePaymentRequest(PaymentRequest
            .parseFrom(paymentRequestBytes));
    final List<Output> parsedOutputs = parsedPaymentRequest.getOutputs();
    assertEquals(1, parsedOutputs.size());
    assertEquals(AMOUNT, parsedOutputs.get(0).amount);
    assertArrayEquals(ScriptBuilder.createOutputScript(TO_ADDRESS).getProgram(), parsedOutputs.get(0).scriptData);
    assertEquals(MEMO, parsedPaymentRequest.getMemo());
    assertEquals(PAYMENT_URL, parsedPaymentRequest.getPaymentUrl());
    assertArrayEquals(MERCHANT_DATA, parsedPaymentRequest.getMerchantData());
}
 
Example #2
Source File: WalletProtobufSerializerTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void empty() throws Exception {
    // Check the base case of a wallet with one key and no transactions.
    Wallet wallet1 = roundTrip(myWallet);
    assertEquals(0, wallet1.getTransactions(true).size());
    assertEquals(Coin.ZERO, wallet1.getBalance());
    assertArrayEquals(myKey.getPubKey(),
            wallet1.findKeyFromPubHash(myKey.getPubKeyHash()).getPubKey());
    assertArrayEquals(myKey.getPrivKeyBytes(),
            wallet1.findKeyFromPubHash(myKey.getPubKeyHash()).getPrivKeyBytes());
    assertEquals(myKey.getCreationTimeSeconds(),
            wallet1.findKeyFromPubHash(myKey.getPubKeyHash()).getCreationTimeSeconds());
    assertEquals(mScriptCreationTime,
            wallet1.getWatchedScripts().get(0).getCreationTimeSeconds());
    assertEquals(1, wallet1.getWatchedScripts().size());
    assertEquals(ScriptBuilder.createOutputScript(myWatchedKey.toAddress(PARAMS)),
            wallet1.getWatchedScripts().get(0));
    assertEquals(WALLET_DESCRIPTION, wallet1.getDescription());
}
 
Example #3
Source File: Transaction.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check block height is in coinbase input script, for use after BIP 34
 * enforcement is enabled.
 */
public void checkCoinBaseHeight(final int height)
        throws VerificationException {
    checkArgument(height >= Block.BLOCK_HEIGHT_GENESIS);
    checkState(isCoinBase());

    // Check block height is in coinbase input script
    final TransactionInput in = this.getInputs().get(0);
    final ScriptBuilder builder = new ScriptBuilder();
    builder.number(height);
    final byte[] expected = builder.build().getProgram();
    final byte[] actual = in.getScriptBytes();
    if (actual.length < expected.length) {
        throw new VerificationException.CoinbaseHeightMismatch("Block height mismatch in coinbase.");
    }
    for (int scriptIdx = 0; scriptIdx < expected.length; scriptIdx++) {
        if (actual[scriptIdx] != expected[scriptIdx]) {
            throw new VerificationException.CoinbaseHeightMismatch("Block height mismatch in coinbase.");
        }
    }
}
 
Example #4
Source File: FakeTxBuilder.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a fake TX of sufficient realism to exercise the unit tests. Two outputs, one to us, one to somewhere
 * else to simulate change. There is one random input.
 */
public static Transaction createFakeTxWithChangeAddress(NetworkParameters params, Coin value, Address to, Address changeOutput) {
    Transaction t = new Transaction(params);
    TransactionOutput outputToMe = new TransactionOutput(params, t, value, to);
    t.addOutput(outputToMe);
    TransactionOutput change = new TransactionOutput(params, t, valueOf(1, 11), changeOutput);
    t.addOutput(change);
    // Make a previous tx simply to send us sufficient coins. This prev tx is not really valid but it doesn't
    // matter for our purposes.
    Transaction prevTx = new Transaction(params);
    TransactionOutput prevOut = new TransactionOutput(params, prevTx, value, to);
    prevTx.addOutput(prevOut);
    // Connect it.
    t.addInput(prevOut).setScriptSig(ScriptBuilder.createInputScript(TransactionSignature.dummy()));
    // Fake signature.
    // Serialize/deserialize to ensure internal state is stripped, as if it had been read from the wire.
    return roundTripTransaction(params, t);
}
 
Example #5
Source File: PaymentProtocolTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testPaymentRequest() throws Exception {
    // Create
    PaymentRequest paymentRequest = PaymentProtocol.createPaymentRequest(TESTNET, AMOUNT, TO_ADDRESS, MEMO,
            PAYMENT_URL, MERCHANT_DATA).build();
    byte[] paymentRequestBytes = paymentRequest.toByteArray();

    // Parse
    PaymentSession parsedPaymentRequest = PaymentProtocol.parsePaymentRequest(PaymentRequest
            .parseFrom(paymentRequestBytes));
    final List<Output> parsedOutputs = parsedPaymentRequest.getOutputs();
    assertEquals(1, parsedOutputs.size());
    assertEquals(AMOUNT, parsedOutputs.get(0).amount);
    assertArrayEquals(ScriptBuilder.createOutputScript(TO_ADDRESS).getProgram(), parsedOutputs.get(0).scriptData);
    assertEquals(MEMO, parsedPaymentRequest.getMemo());
    assertEquals(PAYMENT_URL, parsedPaymentRequest.getPaymentUrl());
    assertArrayEquals(MERCHANT_DATA, parsedPaymentRequest.getMerchantData());
}
 
Example #6
Source File: Transaction.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check block height is in coinbase input script, for use after BIP 34
 * enforcement is enabled.
 */
public void checkCoinBaseHeight(final int height)
        throws VerificationException {
    checkArgument(height >= Block.BLOCK_HEIGHT_GENESIS);
    checkState(isCoinBase());

    // Check block height is in coinbase input script
    final TransactionInput in = this.getInputs().get(0);
    final ScriptBuilder builder = new ScriptBuilder();
    builder.number(height);
    final byte[] expected = builder.build().getProgram();
    final byte[] actual = in.getScriptBytes();
    if (actual.length < expected.length) {
        throw new VerificationException.CoinbaseHeightMismatch("Block height mismatch in coinbase.");
    }
    for (int scriptIdx = 0; scriptIdx < expected.length; scriptIdx++) {
        if (actual[scriptIdx] != expected[scriptIdx]) {
            throw new VerificationException.CoinbaseHeightMismatch("Block height mismatch in coinbase.");
        }
    }
}
 
Example #7
Source File: MarriedKeyChain.java    From GreenBits 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 #8
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 #9
Source File: SegWitP2WPKHTransaction.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 Coin fee = Coin.SATOSHI.times(10000);
    final Coin fundAmount = Coin.SATOSHI.times(405000000);

    final String segwitWIF = "cRynQP5ysWF3jmz5bFy16kqKRoSYzzArJru5349ADBwsoyKoh8aq";
    final ECKey segwitKey = DumpedPrivateKey.fromBase58(params, segwitWIF).getKey();
    final Script segwitPkScript = ScriptBuilder.createP2WPKHOutputScript(segwitKey);

    final Sha256Hash fundTxHash =
        Sha256Hash.wrap("e7e953f119179f71a58865f3d1ae2157847778404f89b48d0f695f786fba1dd4");

    // Sign segwit transaction
    final Address sendTo = Address.fromBase58(params, "mvpr4mkDSPYcbN6XW6xCveCLa38x23fs7B");
    final Coin outAmount = fundAmount.minus(fee);
    final Script outPkScript = ScriptBuilder.createOutputScript(sendTo);
    final TransactionOutPoint segwitOutPoint = new TransactionOutPoint(params, 0L, fundTxHash, fundAmount);
    final Transaction outTx = new Transaction(params);
    outTx.addOutput(outAmount, outPkScript);
    outTx.addSignedInput(segwitOutPoint, segwitPkScript, segwitKey);
    final Sha256Hash outTxHash = outTx.getHash();
    System.out.println(Hex.toHexString(outTx.bitcoinSerialize()));
    System.out.println(Hex.toHexString(outTxHash.getBytes()));
}
 
Example #10
Source File: TransactionOutputTest.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMultiSigOutputToString() throws Exception {
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN);
    ECKey myKey = new ECKey();
    this.wallet.importKey(myKey);

    // Simulate another signatory
    ECKey otherKey = new ECKey();

    // Create multi-sig transaction
    Transaction multiSigTransaction = new Transaction(UNITTEST);
    ImmutableList<ECKey> keys = ImmutableList.of(myKey, otherKey);

    Script scriptPubKey = ScriptBuilder.createMultiSigOutputScript(2, keys);
    multiSigTransaction.addOutput(Coin.COIN, scriptPubKey);

    SendRequest req = SendRequest.forTx(multiSigTransaction);
    this.wallet.completeTx(req);
    TransactionOutput multiSigTransactionOutput = multiSigTransaction.getOutput(0);

    assertThat(multiSigTransactionOutput.toString(), CoreMatchers.containsString("CHECKMULTISIG"));
}
 
Example #11
Source File: AddressTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void p2shAddress() throws Exception {
    // Test that we can construct P2SH addresses
    Address mainNetP2SHAddress = Address.fromBase58(MainNetParams.get(), "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU");
    assertEquals(mainNetP2SHAddress.version, MainNetParams.get().p2shHeader);
    assertTrue(mainNetP2SHAddress.isP2SHAddress());
    Address testNetP2SHAddress = Address.fromBase58(TestNet3Params.get(), "2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe");
    assertEquals(testNetP2SHAddress.version, TestNet3Params.get().p2shHeader);
    assertTrue(testNetP2SHAddress.isP2SHAddress());

    // Test that we can determine what network a P2SH address belongs to
    NetworkParameters mainNetParams = Address.getParametersFromAddress("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU");
    assertEquals(MainNetParams.get().getId(), mainNetParams.getId());
    NetworkParameters testNetParams = Address.getParametersFromAddress("2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe");
    assertEquals(TestNet3Params.get().getId(), testNetParams.getId());

    // Test that we can convert them from hashes
    byte[] hex = HEX.decode("2ac4b0b501117cc8119c5797b519538d4942e90e");
    Address a = Address.fromP2SHHash(mainParams, hex);
    assertEquals("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU", a.toString());
    Address b = Address.fromP2SHHash(testParams, HEX.decode("18a0e827269b5211eb51a4af1b2fa69333efa722"));
    assertEquals("2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe", b.toString());
    Address c = Address.fromP2SHScript(mainParams, ScriptBuilder.createP2SHOutputScript(hex));
    assertEquals("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU", c.toString());
}
 
Example #12
Source File: TransactionOutputTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMultiSigOutputToString() throws Exception {
    sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN);
    ECKey myKey = new ECKey();
    this.wallet.importKey(myKey);

    // Simulate another signatory
    ECKey otherKey = new ECKey();

    // Create multi-sig transaction
    Transaction multiSigTransaction = new Transaction(PARAMS);
    ImmutableList<ECKey> keys = ImmutableList.of(myKey, otherKey);

    Script scriptPubKey = ScriptBuilder.createMultiSigOutputScript(2, keys);
    multiSigTransaction.addOutput(Coin.COIN, scriptPubKey);

    SendRequest req = SendRequest.forTx(multiSigTransaction);
    this.wallet.completeTx(req);
    TransactionOutput multiSigTransactionOutput = multiSigTransaction.getOutput(0);

    assertThat(multiSigTransactionOutput.toString(), CoreMatchers.containsString("CHECKMULTISIG"));
}
 
Example #13
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 #14
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 #15
Source File: Tools.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
  * Gets the multisig input script.
  *
  * @param client the client
  * @param server the server
  * @return the multisig input script
  */
 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 #16
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 #17
Source File: OutputScript.java    From balzac with Apache License 2.0 5 votes vote down vote up
public static OutputScript createP2PKH(byte[] addressByte) {
    return new OutputScript() {

        private static final long serialVersionUID = 1L;

        @Override
        public boolean isP2SH() {
            return false;
        }

        @Override
        public boolean isP2PKH() {
            return true;
        }

        @Override
        public boolean isOP_RETURN() {
            return false;
        }

        @Override
        public Script getOutputScript() {
            return new ScriptBuilder().op(OP_DUP).op(OP_HASH160).data(addressByte).op(OP_EQUALVERIFY)
                .op(OP_CHECKSIG).build();
        }

        @Override
        public Script build() {
            return getOutputScript();
        }
    };
}
 
Example #18
Source File: UTXOTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testJavaSerialization() throws Exception {
    ECKey key = new ECKey();
    UTXO utxo = new UTXO(Sha256Hash.of(new byte[]{1,2,3}), 1, Coin.COIN, 10, true, ScriptBuilder.createOutputScript(key));
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    new ObjectOutputStream(os).writeObject(utxo);
    UTXO utxoCopy = (UTXO) new ObjectInputStream(
            new ByteArrayInputStream(os.toByteArray())).readObject();
    assertEquals(utxo, utxoCopy);
    assertEquals(utxo.getValue(), utxoCopy.getValue());
    assertEquals(utxo.getHeight(), utxoCopy.getHeight());
    assertEquals(utxo.isCoinbase(), utxoCopy.isCoinbase());
    assertEquals(utxo.getScript(), utxoCopy.getScript());
}
 
Example #19
Source File: PaymentChannelV2ServerState.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private void signP2SHInput(Transaction tx, Transaction.SigHash hashType,
                           boolean anyoneCanPay, @Nullable KeyParameter userKey) {
    TransactionSignature signature = tx.calculateSignature(0, serverKey, userKey, createP2SHRedeemScript(), hashType, anyoneCanPay);
    byte[] mySig = signature.encodeToBitcoin();
    Script scriptSig = ScriptBuilder.createCLTVPaymentChannelP2SHInput(bestValueSignature, mySig, createP2SHRedeemScript());
    tx.getInput(0).setScriptSig(scriptSig);
}
 
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: PaymentChannelV1ServerState.java    From green_android 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 #22
Source File: MarriedKeyChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void formatAddresses(boolean includePrivateKeys, NetworkParameters params, StringBuilder builder2) {
    for (DeterministicKeyChain followingChain : followingKeyChains)
        builder2.append("Following chain:  ").append(followingChain.getWatchingKey().serializePubB58(params))
                .append('\n');
    builder2.append('\n');
    for (RedeemData redeemData : marriedKeysRedeemData.values())
        formatScript(ScriptBuilder.createP2SHOutputScript(redeemData.redeemScript), builder2, params);
}
 
Example #23
Source File: TransactionInputTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testUTXOWalletDisconnect() throws Exception {
    Wallet w = new Wallet(new Context(UNITTEST));
    Address a = w.currentReceiveAddress();
    final UTXO utxo = new UTXO(Sha256Hash.of(new byte[]{1, 2, 3}), 1, Coin.COIN, 0, false,
            ScriptBuilder.createOutputScript(a));
    w.setUTXOProvider(new UTXOProvider() {
        @Override
        public NetworkParameters getParams() {
            return UNITTEST;
        }

        @Override
        public List<UTXO> getOpenTransactionOutputs(List<ECKey> addresses) throws UTXOProviderException {
            return Lists.newArrayList(utxo);
        }

        @Override
        public int getChainHeadHeight() throws UTXOProviderException {
            return Integer.MAX_VALUE;
        }
    });

    Transaction tx2 = new Transaction(UNITTEST);
    tx2.addOutput(Coin.valueOf(99000000), new ECKey());
    w.completeTx(SendRequest.forTx(tx2));

    TransactionInput txInToDisconnect = tx2.getInput(0);

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertEquals(utxo.getHash(), txInToDisconnect.getOutpoint().connectedOutput.getParentTransactionHash());

    txInToDisconnect.disconnect();

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);
}
 
Example #24
Source File: TransactionInputTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testUTXOWalletDisconnect() throws Exception {
    final NetworkParameters params = UnitTestParams.get();
    Wallet w = new Wallet(new Context(params));
    Address a = w.currentReceiveAddress();
    final UTXO utxo = new UTXO(Sha256Hash.of(new byte[] { 1, 2, 3 }), 1, Coin.COIN, 0, false,
            ScriptBuilder.createOutputScript(a));
    w.setUTXOProvider(new UTXOProvider() {
        @Override
        public NetworkParameters getParams() {
            return params;
        }

        @Override
        public List<UTXO> getOpenTransactionOutputs(List<Address> addresses) throws UTXOProviderException {
            return Lists.newArrayList(utxo);
        }

        @Override
        public int getChainHeadHeight() throws UTXOProviderException {
            return Integer.MAX_VALUE;
        }
    });

    Transaction tx2 = new Transaction(params);
    tx2.addOutput(Coin.valueOf(99000000), new ECKey());
    w.completeTx(SendRequest.forTx(tx2));

    TransactionInput txInToDisconnect = tx2.getInput(0);

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertEquals(utxo.getHash(), txInToDisconnect.getOutpoint().connectedOutput.getParentTransactionHash());

    txInToDisconnect.disconnect();

    assertNull(txInToDisconnect.getOutpoint().fromTx);
    assertNull(txInToDisconnect.getOutpoint().connectedOutput);
}
 
Example #25
Source File: WalletTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void opReturnOneOutputTest() throws Exception {
    // Tests basic send of transaction with one output that doesn't transfer any value but just writes OP_RETURN.
    receiveATransaction(wallet, myAddress);
    Transaction tx = new Transaction(PARAMS);
    Coin messagePrice = Coin.ZERO;
    Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes());
    tx.addOutput(messagePrice, script);
    SendRequest request = SendRequest.forTx(tx);
    request.ensureMinRequiredFee = true;
    wallet.completeTx(request);
}
 
Example #26
Source File: WalletTest.java    From green_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(PARAMS);
    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 #27
Source File: ScriptTools.java    From thundernetwork with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Script produceScript (byte[] template, byte[]... parameters) {
    try {

        ScriptBuilder builder = new ScriptBuilder();

        int parameter = 0;
        for (byte chunk : template) {
            int op = chunk;
            if (op < 0) {
                op = op + 256;
            }

            if (op == 255) {
                builder.data(parameters[parameter]);
                parameter++;
            } else if (op == 0) {
                builder.data(new byte[0]);
            } else {
                builder.op(op);
            }
        }

        //Bug in bitcoinJ when dealing with OP_0. Gets solved by reserializing.
        Script s = builder.build();
        return new Script(s.getProgram());

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #28
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void setUTXO(List<UTXOItem> utxoList) {
    Address a;
    if (restFromWif) {
        a = wallet.getImportedKeys().get(0).toAddress(params);
    } else {
        a = wallet.currentReceiveAddress();
    }

    final List<UTXO> utxos = new ArrayList<>();

    for (UTXOItem utxo : utxoList) {
        Sha256Hash hash = Sha256Hash.wrap(utxo.getTxHash());
        utxos.add(new UTXO(hash, utxo.getTxOutputN(), Coin.valueOf(utxo.getSatoshiValue()),
                0, false, ScriptBuilder.createOutputScript(a)));
    }

    UTXOProvider utxoProvider = new UTXOProvider() {
        @Override
        public List<UTXO> getOpenTransactionOutputs(List<Address> addresses) throws UTXOProviderException {
            return utxos;
        }

        @Override
        public int getChainHeadHeight() throws UTXOProviderException {
            return Integer.MAX_VALUE;
        }

        @Override
        public NetworkParameters getParams() {
            return wallet.getParams();
        }
    };
    wallet.setUTXOProvider(utxoProvider);
}
 
Example #29
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
private Script getMultiSigRedeemScript(byte[] buyerPubKey, byte[] sellerPubKey, byte[] arbitratorPubKey) {
    ECKey buyerKey = ECKey.fromPublicOnly(buyerPubKey);
    ECKey sellerKey = ECKey.fromPublicOnly(sellerPubKey);
    ECKey arbitratorKey = ECKey.fromPublicOnly(arbitratorPubKey);
    // Take care of sorting! Need to reverse to the order we use normally (buyer, seller, arbitrator)
    List<ECKey> keys = ImmutableList.of(arbitratorKey, sellerKey, buyerKey);
    return ScriptBuilder.createMultiSigOutputScript(2, keys);
}
 
Example #30
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void setUTXO(List<UTXOItemDgb> utxoList) {
    Address a;
    if (restFromWif) {
        if (wallet.getImportedKeys().size() == 0) return;
        a = wallet.getImportedKeys().get(0).toAddress(params);
    } else {
        a = wallet.currentReceiveAddress();
    }

    final List<UTXO> utxos = new ArrayList<>();

    for (UTXOItemDgb utxo : utxoList) {
        Sha256Hash hash = Sha256Hash.wrap(utxo.getTxHash());
        utxos.add(new UTXO(hash, utxo.getTxOutputN(), Coin.valueOf(utxo.getSatoshiValue()),
                0, false, ScriptBuilder.createOutputScript(a)));
    }

    UTXOProvider utxoProvider = new UTXOProvider() {
        @Override
        public List<UTXO> getOpenTransactionOutputs(List<Address> addresses) throws UTXOProviderException {
            return utxos;
        }

        @Override
        public int getChainHeadHeight() throws UTXOProviderException {
            return Integer.MAX_VALUE;
        }

        @Override
        public NetworkParameters getParams() {
            return wallet.getParams();
        }
    };
    wallet.setUTXOProvider(utxoProvider);
}