Java Code Examples for org.bitcoinj.script.ScriptBuilder#createP2SHOutputScript()

The following examples show how to use org.bitcoinj.script.ScriptBuilder#createP2SHOutputScript() . 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: 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 2
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 3
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 4
Source File: MarriedKeyChain.java    From green_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: 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 6
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 shouldThrowExceptionBecauseOfWrongSecretWhenTryingToSpendEscapeTransaction () {
    Script outputScript = ScriptTools.getEscapeOutputScript(secretServerHash, 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 signatureClient = Tools.getSignature(transactionInput, 0, outputScript.getProgram(), keyClient);

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

    Script inputScript = ScriptTools.getEscapeInputRevocationScript(secretServerHash, keyServer, keyClient, 60 * 60 * 1000, signatureClient
            .encodeToBitcoin(), secretServer);

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

    inputScript.correctlySpends(transactionInput, 0, outputScriptP2SH);
}
 
Example 7
Source File: MarriedKeyChain.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a new married key and return the matching output script
 */
@Override
public Script freshOutputScript(KeyPurpose purpose) {
    DeterministicKey followedKey = getKey(purpose);
    ImmutableList.Builder<ECKey> keys = ImmutableList.<ECKey>builder().add(followedKey);
    for (DeterministicKeyChain keyChain : followingKeyChains) {
        DeterministicKey followingKey = keyChain.getKey(purpose);
        checkState(followedKey.getChildNumber().equals(followingKey.getChildNumber()), "Following keychains should be in sync");
        keys.add(followingKey);
    }
    List<ECKey> marriedKeys = keys.build();
    Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
    return ScriptBuilder.createP2SHOutputScript(redeemScript);
}
 
Example 8
Source File: MarriedKeyChain.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/** Create a new married key and return the matching output script */
@Override
public Script freshOutputScript(KeyPurpose purpose) {
    DeterministicKey followedKey = getKey(purpose);
    ImmutableList.Builder<ECKey> keys = ImmutableList.<ECKey>builder().add(followedKey);
    for (DeterministicKeyChain keyChain : followingKeyChains) {
        DeterministicKey followingKey = keyChain.getKey(purpose);
        checkState(followedKey.getChildNumber().equals(followingKey.getChildNumber()), "Following keychains should be in sync");
        keys.add(followingKey);
    }
    List<ECKey> marriedKeys = keys.build();
    Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
    return ScriptBuilder.createP2SHOutputScript(redeemScript);
}
 
Example 9
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 10
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 11
Source File: MarriedKeyChain.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/** Create a new married key and return the matching output script */
@Override
public Script freshOutputScript(KeyPurpose purpose) {
    DeterministicKey followedKey = getKey(purpose);
    ImmutableList.Builder<ECKey> keys = ImmutableList.<ECKey>builder().add(followedKey);
    for (DeterministicKeyChain keyChain : followingKeyChains) {
        DeterministicKey followingKey = keyChain.getKey(purpose);
        checkState(followedKey.getChildNumber().equals(followingKey.getChildNumber()), "Following keychains should be in sync");
        keys.add(followingKey);
    }
    List<ECKey> marriedKeys = keys.build();
    Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
    return ScriptBuilder.createP2SHOutputScript(redeemScript);
}
 
Example 12
Source File: ScriptToolsTest.java    From thundernetwork with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void shouldCreateSpendableAnchorTransactionWithCommitmentTransaction () {

    Script outputScript = ScriptTools.getAnchorOutputScript(secretServerHash, keyClient, keyClientA, keyServer);
    Script outputScriptP2SH = ScriptBuilder.createP2SHOutputScript(outputScript);

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

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

    Script inputScript = ScriptTools.getCommitInputScript(signatureClient.encodeToBitcoin(), signatureServer.encodeToBitcoin(),
            secretServerHash, keyClient, keyClientA, keyServer);

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

    inputScript.correctlySpends(transactionInput, 0, outputScriptP2SH);
}
 
Example 13
Source File: ScriptToolsTest.java    From thundernetwork with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void shouldCreateSpendableFastEscapeTransactionWithTimeoutTransaction () {

    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 signatureClient = Tools.getSignature(transactionInput, 0, outputScript.getProgram(), keyClient);

    Script inputScript = ScriptTools.getFastEscapeInputTimeoutScript(secretClientHash, keyServer, keyClient, 60 * 60 * 1000, signatureClient
            .encodeToBitcoin());

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

    inputScript.correctlySpends(transactionInput, 0, outputScriptP2SH);
}
 
Example 14
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
private Script get2of2MultiSigOutputScript(byte[] buyerPubKey, byte[] sellerPubKey) {
    return ScriptBuilder.createP2SHOutputScript(get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey));
}
 
Example 15
Source File: GaService.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Generate new address to the selected sub account, bitcoin or elements
 * @param subAccount sub account ID
 * @param waitFn eventually callback to execute (e.g. waiting popup)
 * @return the address in string format
 */
public ListenableFuture<String> getNewAddress(final int subAccount,
                                              final Callable<Void> waitFn) {
    // Fetch any cached address
    final JSONMap cachedAddress = getCachedAddress(subAccount);

    // Use either the cached address or a new address
    final ListenableFuture<JSONMap> addrFn;
    if (cachedAddress != null)
        addrFn = Futures.immediateFuture(cachedAddress);
    else {
        try {
            if (waitFn != null)
                waitFn.call();
        } catch (final Exception e) {
        }
        addrFn = getNewAddressAsync(subAccount, false);
    }

    // Fetch and cache another address in the background
    if (!isWatchOnly())
        getNewAddressAsync(subAccount, true);

    // Convert the address into a bitmap and return it
    final AsyncFunction<JSONMap, String> verifyAddress = new AsyncFunction<JSONMap, String>() {
        @Override
        public ListenableFuture<String> apply(final JSONMap input) {
            if (input == null)
                throw new IllegalArgumentException("Failed to generate a new address");

            final Integer pointer = input.getInt("pointer");
            final byte[] script = input.getBytes("script");
            final byte[] scriptHash;
            final String addrType = input.get("addr_type");
            if (addrType.equals("p2wsh"))
                scriptHash = Wally.hash160(getSegWitScript(script));
            else if (addrType.equals("p2sh"))
                scriptHash = Wally.hash160(script);
            else
                throw new IllegalArgumentException("Unknown address type " + addrType);

            final ListenableFuture<Boolean> verify;
            if (isWatchOnly())
                verify = Futures.immediateFuture(true);
            else {
                final Script sc;
                sc = ScriptBuilder.createP2SHOutputScript(scriptHash);
                verify = verifyP2SHSpendableBy(sc, subAccount, pointer);
            }

            return Futures.transform(verify,
                    new Function<Boolean, String>() {
                @Override
                public String apply(final Boolean isValid) {
                    if (!isValid)
                        throw new IllegalArgumentException("Address validation failed");

                    final String address;
                    if (isElements()) {
                        final byte[] pubKey = getBlindingPubKey(subAccount, pointer);
                        address = ConfidentialAddress.fromP2SHHash(getNetworkParameters(), scriptHash, pubKey).toString();
                    } else
                        address = Address.fromP2SHHash(getNetworkParameters(), scriptHash).toString();
                    return address;
                }
            });
        }
    };
    return Futures.transformAsync(addrFn, verifyAddress, mExecutor);
}
 
Example 16
Source File: ScriptTools.java    From thunder with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Script getAnchorOutputScriptP2SH (ECKey keyClient, ECKey keyServer) {
    return ScriptBuilder.createP2SHOutputScript(getAnchorOutputScript(keyClient, keyServer));
}
 
Example 17
Source File: ScriptToolsTest.java    From thundernetwork with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void shouldCreateSpendableEscapeTransactionWithTimeoutTransaction () {

    Script outputScript = ScriptTools.getEscapeOutputScript(revocationServerHash, 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);

    Script inputScript = ScriptTools.getEscapeInputTimeoutScript(revocationServerHash, keyServer, keyClient, 60 * 60 * 1000, signatureServer
            .encodeToBitcoin());

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

    inputScript.correctlySpends(transactionInput, 0, outputScriptP2SH);
}
 
Example 18
Source File: PaymentChannelV2ServerState.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates a P2SH script outputting to the client and server pubkeys
 * @return
 */
@Override
protected Script createOutputScript() {
    return ScriptBuilder.createP2SHOutputScript(createP2SHRedeemScript());
}
 
Example 19
Source File: TradeWalletService.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
private Script getP2SHMultiSigOutputScript(byte[] buyerPubKey, byte[] sellerPubKey, byte[] arbitratorPubKey) {
    return ScriptBuilder.createP2SHOutputScript(getMultiSigRedeemScript(buyerPubKey, sellerPubKey, arbitratorPubKey));
}
 
Example 20
Source File: PaymentChannelV2ServerState.java    From bcm-android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Creates a P2SH script outputting to the client and server pubkeys
 *
 * @return a P2SH script.
 */
@Override
protected Script createOutputScript() {
    return ScriptBuilder.createP2SHOutputScript(createP2SHRedeemScript());
}