org.bitcoinj.crypto.TransactionSignature Java Examples
The following examples show how to use
org.bitcoinj.crypto.TransactionSignature.
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: FullBlockTestGenerator.java From bcm-android with GNU General Public License v3.0 | 7 votes |
private void addOnlyInputToTransaction(Transaction t, TransactionOutPointWithValue prevOut, long sequence) throws ScriptException { TransactionInput input = new TransactionInput(params, t, new byte[]{}, prevOut.outpoint); input.setSequenceNumber(sequence); t.addInput(input); if (prevOut.scriptPubKey.getChunks().get(0).equalsOpCode(OP_TRUE)) { input.setScriptSig(new ScriptBuilder().op(OP_1).build()); } else { // Sign input checkState(ScriptPattern.isPayToPubKey(prevOut.scriptPubKey)); Sha256Hash hash = t.hashForSignature(0, prevOut.scriptPubKey, SigHash.ALL, false); input.setScriptSig(ScriptBuilder.createInputScript( new TransactionSignature(coinbaseOutKey.sign(hash), SigHash.ALL, false)) ); } }
Example #2
Source File: ECKeyTest.java From GreenBits with GNU General Public License v3.0 | 6 votes |
@Test public void testNonCanonicalSigs() throws Exception { // Tests the noncanonical sigs from Bitcoin Core unit tests InputStream in = getClass().getResourceAsStream("sig_noncanonical.json"); // Poor man's JSON parser (because pulling in a lib for this is overkill) while (in.available() > 0) { while (in.available() > 0 && in.read() != '"') ; if (in.available() < 1) break; StringBuilder sig = new StringBuilder(); int c; while (in.available() > 0 && (c = in.read()) != '"') sig.append((char)c); try { final String sigStr = sig.toString(); assertFalse(TransactionSignature.isEncodingCanonical(HEX.decode(sigStr))); } catch (IllegalArgumentException e) { // Expected for non-hex strings in the JSON that we should ignore } } in.close(); }
Example #3
Source File: ScriptBuilder.java From bcm-android with GNU General Public License v3.0 | 6 votes |
/** * Create a program that satisfies a P2SH OP_CHECKMULTISIG program. * If given signature list is null, incomplete scriptSig will be created with OP_0 instead of signatures */ public static Script createP2SHMultiSigInputScript(@Nullable List<TransactionSignature> signatures, Script multisigProgram) { List<byte[]> sigs = new ArrayList<>(); if (signatures == null) { // create correct number of empty signatures int numSigs = multisigProgram.getNumberOfSignaturesRequiredToSpend(); for (int i = 0; i < numSigs; i++) sigs.add(new byte[]{}); } else { for (TransactionSignature signature : signatures) { sigs.add(signature.encodeToBitcoin()); } } return createMultiSigInputScriptBytes(sigs, multisigProgram.getProgram()); }
Example #4
Source File: ECKeyTest.java From green_android with GNU General Public License v3.0 | 6 votes |
@Test public void testCanonicalSigs() throws Exception { // Tests the canonical sigs from Bitcoin Core unit tests InputStream in = getClass().getResourceAsStream("sig_canonical.json"); // Poor man's JSON parser (because pulling in a lib for this is overkill) while (in.available() > 0) { while (in.available() > 0 && in.read() != '"') ; if (in.available() < 1) break; StringBuilder sig = new StringBuilder(); int c; while (in.available() > 0 && (c = in.read()) != '"') sig.append((char)c); assertTrue(TransactionSignature.isEncodingCanonical(HEX.decode(sig.toString()))); } in.close(); }
Example #5
Source File: ECKeyTest.java From green_android with GNU General Public License v3.0 | 6 votes |
@Test public void testNonCanonicalSigs() throws Exception { // Tests the noncanonical sigs from Bitcoin Core unit tests InputStream in = getClass().getResourceAsStream("sig_noncanonical.json"); // Poor man's JSON parser (because pulling in a lib for this is overkill) while (in.available() > 0) { while (in.available() > 0 && in.read() != '"') ; if (in.available() < 1) break; StringBuilder sig = new StringBuilder(); int c; while (in.available() > 0 && (c = in.read()) != '"') sig.append((char)c); try { final String sigStr = sig.toString(); assertFalse(TransactionSignature.isEncodingCanonical(HEX.decode(sigStr))); } catch (IllegalArgumentException e) { // Expected for non-hex strings in the JSON that we should ignore } } in.close(); }
Example #6
Source File: FakeTxBuilder.java From GreenBits with GNU General Public License v3.0 | 6 votes |
/** * 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 #7
Source File: Transaction.java From bcm-android with GNU General Public License v3.0 | 6 votes |
/** * Adds a new and fully signed input for the given parameters. Note that this method is <b>not</b> thread safe * and requires external synchronization. Please refer to general documentation on Bitcoin scripting and contracts * to understand the values of sigHash and anyoneCanPay: otherwise you can use the other form of this method * that sets them to typical defaults. * * @throws ScriptException if the scriptPubKey is not a pay to address or pay to pubkey script. */ public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey, SigHash sigHash, boolean anyoneCanPay) throws ScriptException { // Verify the API user didn't try to do operations out of order. checkState(!outputs.isEmpty(), "Attempting to sign tx without outputs."); TransactionInput input = new TransactionInput(params, this, new byte[]{}, prevOut); addInput(input); Sha256Hash hash = hashForSignature(inputs.size() - 1, scriptPubKey, sigHash, anyoneCanPay); ECKey.ECDSASignature ecSig = sigKey.sign(hash); TransactionSignature txSig = new TransactionSignature(ecSig, sigHash, anyoneCanPay); if (ScriptPattern.isPayToPubKey(scriptPubKey)) input.setScriptSig(ScriptBuilder.createInputScript(txSig)); else if (ScriptPattern.isPayToPubKeyHash(scriptPubKey)) input.setScriptSig(ScriptBuilder.createInputScript(txSig, sigKey)); else throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey); return input; }
Example #8
Source File: DefaultRiskAnalysis.java From green_android with GNU General Public License v3.0 | 6 votes |
/** Checks if the given input passes some of the AreInputsStandard checks. Not complete. */ public static RuleViolation isInputStandard(TransactionInput input) { for (ScriptChunk chunk : input.getScriptSig().getChunks()) { if (chunk.data != null && !chunk.isShortestPossiblePushData()) return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA; if (chunk.isPushData()) { ECDSASignature signature; try { signature = ECKey.ECDSASignature.decodeFromDER(chunk.data); } catch (RuntimeException x) { // Doesn't look like a signature. signature = null; } if (signature != null) { if (!TransactionSignature.isEncodingCanonical(chunk.data)) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; if (!signature.isCanonical()) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; } } } return RuleViolation.NONE; }
Example #9
Source File: ECKeyTest.java From bcm-android with GNU General Public License v3.0 | 6 votes |
@Test public void testCanonicalSigs() throws Exception { // Tests the canonical sigs from Bitcoin Core unit tests InputStream in = getClass().getResourceAsStream("sig_canonical.json"); // Poor man's JSON parser (because pulling in a lib for this is overkill) while (in.available() > 0) { while (in.available() > 0 && in.read() != '"') ; if (in.available() < 1) break; StringBuilder sig = new StringBuilder(); int c; while (in.available() > 0 && (c = in.read()) != '"') sig.append((char) c); assertTrue(TransactionSignature.isEncodingCanonical(HEX.decode(sig.toString()))); } in.close(); }
Example #10
Source File: Channel.java From thundernetwork with GNU Affero General Public License v3.0 | 6 votes |
public Transaction getFastEscapeTransactionServer () { Transaction escape = new Transaction(Constants.getNetwork()); escape.addInput(getAnchorTxHashServer(), 0, Tools.getDummyScript()); Coin output = Coin.valueOf(getInitialAmountServer() - Tools.getTransactionFees(5, 5)); //TODO maybe a better choice for fees? escape.addOutput(output, ScriptBuilder.createP2SHOutputScript(getScriptFastEscapeOutputServer())); if (getFastEscapeTxSig() != null) { //We have everything we need to sign it.. Script outputScript = ScriptTools.getAnchorOutputScript(getAnchorSecretHashServer(), keyClient, keyClientA, keyServer); TransactionSignature serverSig = Tools.getSignature(escape, 0, outputScript.getProgram(), keyServer); Script inputScript = ScriptTools.getEscapeInputScript( getEscapeTxSig().encodeToBitcoin(), serverSig.encodeToBitcoin(), getAnchorSecretServer(), getAnchorSecretHashServer(), getKeyClient(), getKeyClientA(), getKeyServer()); escape.getInput(0).setScriptSig(inputScript); } return escape; }
Example #11
Source File: TradeWalletService.java From bisq-core with GNU Affero General Public License v3.0 | 6 votes |
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 #12
Source File: ScriptBuilder.java From GreenBits with GNU General Public License v3.0 | 6 votes |
/** * Create a program that satisfies a pay-to-script hashed OP_CHECKMULTISIG program. * If given signature list is null, incomplete scriptSig will be created with OP_0 instead of signatures */ public static Script createP2SHMultiSigInputScript(@Nullable List<TransactionSignature> signatures, Script multisigProgram) { List<byte[]> sigs = new ArrayList<>(); if (signatures == null) { // create correct number of empty signatures int numSigs = multisigProgram.getNumberOfSignaturesRequiredToSpend(); for (int i = 0; i < numSigs; i++) sigs.add(new byte[]{}); } else { for (TransactionSignature signature : signatures) { sigs.add(signature.encodeToBitcoin()); } } return createMultiSigInputScriptBytes(sigs, multisigProgram.getProgram()); }
Example #13
Source File: ScriptBuilder.java From bcm-android with GNU General Public License v3.0 | 5 votes |
public static Script createCLTVPaymentChannelP2SHRefund(TransactionSignature signature, Script redeemScript) { ScriptBuilder builder = new ScriptBuilder(); builder.data(signature.encodeToBitcoin()); builder.data(new byte[]{0}); // Use the CHECKLOCKTIMEVERIFY if branch builder.data(redeemScript.getProgram()); return builder.build(); }
Example #14
Source File: Transaction.java From green_android with GNU General Public License v3.0 | 5 votes |
public TransactionSignature calculateWitnessSignature(int inputIndex, ECKey key, @Nullable KeyParameter aesKey, byte[] redeemScript, Coin value, SigHash hashType, boolean anyoneCanPay) { Sha256Hash hash = hashForSignatureWitness(inputIndex, redeemScript, value, hashType, anyoneCanPay); return new TransactionSignature(key.sign(hash, aesKey), hashType, anyoneCanPay); }
Example #15
Source File: LNEstablishMessageFactoryImpl.java From thunder with GNU Affero General Public License v3.0 | 5 votes |
@Override public LNEstablishBMessage getEstablishMessageB (TransactionSignature channelSignature) { LNEstablishBMessage message = new LNEstablishBMessage( channelSignature ); return message; }
Example #16
Source File: LNCloseProcessorImpl.java From thunder with GNU Affero General Public License v3.0 | 5 votes |
private void checkClosingMessage (LNCloseAMessage message) { if (!checkFee(message)) { //TODO return some error message //TODO handle the error message appropriately.. throw new LNCloseException("Fee not within allowed boundaries.."); } if (channelHashToClose == null) { channelHashToClose = Sha256Hash.wrap(message.channelHash); } this.channel = getChannel(); //TODO fix working out the correct reverse strategy for channels that still have payments included //ChannelStatus status = getChannelStatus(channel.channelStatus.getCloneReversed()).getCloneReversed(); ChannelStatus status = channel.channelStatus; Transaction transaction = getClosingTransaction(status, message.feePerByte); List<TransactionSignature> signatureList = message.getSignatureList(); int i = 0; for (TransactionSignature signature : signatureList) { boolean correct = Tools.checkSignature(transaction, i, ScriptTools.getAnchorOutputScript(channel.keyClient, channel.keyServer), channel.keyClient, signature); if (!correct) { throw new LNCloseException("Signature is not correct.."); } i++; } }
Example #17
Source File: Tools.java From thunder with GNU Affero General Public License v3.0 | 5 votes |
public static List<TransactionSignature> getChannelSignatures (Channel channel, Transaction transaction) { //TODO only one anchor allowed for now TransactionSignature signature1 = Tools.getSignature( transaction, 0, ScriptTools.getAnchorOutputScript(channel.keyClient, channel.keyServer).getProgram(), channel.keyServer); List<TransactionSignature> channelSignatures = new ArrayList<>(); channelSignatures.add(signature1); return channelSignatures; }
Example #18
Source File: ScriptBuilder.java From GreenBits with GNU General Public License v3.0 | 5 votes |
/** Create a program that satisfies an OP_CHECKMULTISIG program. */ public static Script createMultiSigInputScript(List<TransactionSignature> signatures) { List<byte[]> sigs = new ArrayList<>(signatures.size()); for (TransactionSignature signature : signatures) { sigs.add(signature.encodeToBitcoin()); } return createMultiSigInputScriptBytes(sigs, null); }
Example #19
Source File: TransactionWitness.java From GreenBits with GNU General Public License v3.0 | 5 votes |
/** * Create a witness that can redeem a pay-to-witness-pubkey-hash output. */ public static TransactionWitness createWitness(@Nullable final TransactionSignature signature, final ECKey pubKey) { final byte[] sigBytes = signature != null ? signature.encodeToBitcoin() : new byte[]{}; final byte[] pubKeyBytes = pubKey.getPubKey(); final TransactionWitness witness = new TransactionWitness(2); witness.setPush(0, sigBytes); witness.setPush(1, pubKeyBytes); return witness; }
Example #20
Source File: TradeWalletService.java From bisq with GNU Affero General Public License v3.0 | 5 votes |
/** * 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 #21
Source File: LNPaymentLogicImpl.java From thundernetwork with GNU Affero General Public License v3.0 | 5 votes |
public List<TransactionSignature> getPaymentSignatures () { List<Transaction> paymentTransactions = getClientPaymentTransactions(); List<TransactionSignature> signatureList = new ArrayList<>(); int index = 2; for (Transaction t : paymentTransactions) { TransactionSignature sig = Tools.getSignature(t, 0, getClientTransaction().getOutput(index).getScriptBytes(), channel.getKeyServer()); signatureList.add(sig); index++; } return signatureList; }
Example #22
Source File: FakeTxBuilder.java From bcm-android with GNU General Public License v3.0 | 5 votes |
/** * Create a fake TX for unit tests, for use with unit tests that need greater control. One outputs, 2 random inputs, * split randomly to create randomness. */ public static Transaction createFakeTxWithoutChangeAddress(NetworkParameters params, Coin value, Address to) { Transaction t = new Transaction(params); TransactionOutput outputToMe = new TransactionOutput(params, t, value, to); t.addOutput(outputToMe); // Make a random split in the output value so we get a distinct hash when we call this multiple times with same args long split = new Random().nextLong(); if (split < 0) { split *= -1; } if (split == 0) { split = 15; } while (split > value.getValue()) { split /= 2; } // 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 prevTx1 = new Transaction(params); TransactionOutput prevOut1 = new TransactionOutput(params, prevTx1, Coin.valueOf(split), to); prevTx1.addOutput(prevOut1); // Connect it. t.addInput(prevOut1).setScriptSig(ScriptBuilder.createInputScript(TransactionSignature.dummy())); // Fake signature. // Do it again Transaction prevTx2 = new Transaction(params); TransactionOutput prevOut2 = new TransactionOutput(params, prevTx2, Coin.valueOf(value.getValue() - split), to); prevTx2.addOutput(prevOut2); t.addInput(prevOut2).setScriptSig(ScriptBuilder.createInputScript(TransactionSignature.dummy())); // Serialize/deserialize to ensure internal state is stripped, as if it had been read from the wire. return roundTripTransaction(params, t); }
Example #23
Source File: Script.java From green_android with GNU General Public License v3.0 | 5 votes |
private int findSigInRedeem(byte[] signatureBytes, Sha256Hash hash) { checkArgument(chunks.get(0).isOpCode()); // P2SH scriptSig int numKeys = Script.decodeFromOpN(chunks.get(chunks.size() - 2).opcode); TransactionSignature signature = TransactionSignature.decodeFromBitcoin(signatureBytes, true); for (int i = 0 ; i < numKeys ; i++) { if (ECKey.fromPublicOnly(chunks.get(i + 1).data).verify(hash, signature)) { return i; } } throw new IllegalStateException("Could not find matching key for signature on " + hash.toString() + " sig " + HEX.encode(signatureBytes)); }
Example #24
Source File: LNEstablishProcessorImpl.java From thundernetwork with GNU Affero General Public License v3.0 | 5 votes |
private void sendEstablishMessageD () { Transaction escape = channel.getEscapeTransactionClient(); Transaction fastEscape = channel.getFastEscapeTransactionClient(); TransactionSignature escapeSig = Tools.getSignature(escape, 0, channel.getScriptAnchorOutputClient().getProgram(), channel.getKeyServerA()); TransactionSignature fastEscapeSig = Tools.getSignature(fastEscape, 0, channel.getScriptAnchorOutputClient().getProgram(), channel .getKeyServerA()); Message message = messageFactory.getEstablishMessageD(escapeSig, fastEscapeSig); messageExecutor.sendMessageUpwards(message); status = 5; }
Example #25
Source File: PaymentChannelV1ServerState.java From green_android with GNU General Public License v3.0 | 5 votes |
/** * 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 #26
Source File: Transaction.java From GreenBits with GNU General Public License v3.0 | 5 votes |
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 #27
Source File: ScriptBuilder.java From GreenBits with GNU General Public License v3.0 | 5 votes |
public static Script createCLTVPaymentChannelP2SHRefund(TransactionSignature signature, Script redeemScript) { ScriptBuilder builder = new ScriptBuilder(); builder.data(signature.encodeToBitcoin()); builder.data(new byte[] { 0 }); // Use the CHECKLOCKTIMEVERIFY if branch builder.data(redeemScript.getProgram()); return builder.build(); }
Example #28
Source File: TransactionTest.java From green_android with GNU General Public License v3.0 | 5 votes |
/** * Native P2WPKH transaction. From BIP-143. */ @Test public void testNativeP2WPKH() { final byte[] unsignedTxBin = HEX.decode("0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac11000000"); final Transaction tx = new Transaction(MainNetParams.get(), unsignedTxBin); final byte[] input0 = HEX.decode("4830450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01"); tx.getInput(0).setScriptBytes(input0); final Script scriptPubKey = new Script(HEX.decode("00141d0f172a0ecb48aee1be1f2687d2963ae33f71a1")); final Script scriptCode = scriptPubKey.scriptCode(); final ECKey prvKey = ECKey.fromPrivate(HEX.decode("619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9")); final Coin value = Coin.valueOf(6,0); final byte[] expectedSigHash = HEX.decode("c37af31116d1b27caf68aae9e3ac82f1477929014d5b917657d0eb49478cb670"); final byte[] expectedSignature = HEX.decode("304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee"); final byte[] signedTx = HEX.decode("01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac000247304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee0121025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee635711000000"); final Sha256Hash sigHash = tx.hashForSignatureWitness( 1, scriptCode, value, Transaction.SigHash.ALL, false); assertArrayEquals(expectedSigHash, sigHash.getBytes()); final TransactionSignature sig = tx.calculateWitnessSignature( 1, prvKey, scriptCode, value, Transaction.SigHash.ALL, false); assertArrayEquals(expectedSignature, sig.encodeToDER()); final TransactionWitness witness = new TransactionWitness(2); witness.setPush(0, sig.encodeToBitcoin()); witness.setPush(1, prvKey.getPubKey()); tx.setWitness(1, witness); assertArrayEquals(signedTx, tx.bitcoinSerialize()); tx.getInput(1).getScriptSig().correctlySpends( tx, 1, scriptPubKey, value, Script.ALL_VERIFY_FLAGS); }
Example #29
Source File: BitcoinUtils.java From balzac with Apache License 2.0 | 5 votes |
public static Script toScript(Object obj) { if (obj instanceof Number) return new ScriptBuilder().number(((Number) obj).longValue()).build(); else if (obj instanceof String) return new ScriptBuilder().data(((String) obj).getBytes(Charset.forName("UTF-8"))).build(); else if (obj instanceof Hash) return new ScriptBuilder().data(((Hash) obj).getBytes()).build(); else if (obj instanceof Boolean) return ((Boolean) obj) ? new ScriptBuilder().opTrue().build() : new ScriptBuilder().opFalse().build(); else if (obj instanceof TransactionSignature) return new ScriptBuilder().data(((TransactionSignature) obj).encodeToBitcoin()).build(); else if (obj instanceof Signature) { Signature sig = (Signature) obj; ScriptBuilder sb = new ScriptBuilder(); sb.data(sig.getSignature()); if (sig.getPubkey().isPresent()) sb.data(sig.getPubkey().get().getBytes()); return sb.build(); } throw new IllegalArgumentException(); }
Example #30
Source File: ScriptBuilder.java From green_android with GNU General Public License v3.0 | 5 votes |
/** Create a program that satisfies an OP_CHECKMULTISIG program. */ public static Script createMultiSigInputScript(List<TransactionSignature> signatures) { List<byte[]> sigs = new ArrayList<>(signatures.size()); for (TransactionSignature signature : signatures) { sigs.add(signature.encodeToBitcoin()); } return createMultiSigInputScriptBytes(sigs, null); }