本文整理汇总了Java中com.google.bitcoin.crypto.TransactionSignature类的典型用法代码示例。如果您正苦于以下问题:Java TransactionSignature类的具体用法?Java TransactionSignature怎么用?Java TransactionSignature使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
TransactionSignature类属于com.google.bitcoin.crypto包,在下文中一共展示了TransactionSignature类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: addSignedInput
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
/**
* 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 {
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 (scriptPubKey.isSentToRawPubKey())
input.setScriptSig(ScriptBuilder.createInputScript(txSig));
else if (scriptPubKey.isSentToAddress())
input.setScriptSig(ScriptBuilder.createInputScript(txSig, sigKey));
else
throw new ScriptException("Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey);
return input;
}
示例2: provideRefundSignature
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
/**
* <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) throws VerificationException {
checkNotNull(theirSignature);
checkState(state == 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, 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);
state = State.SAVE_STATE_IN_WALLET;
}
示例3: testNonCanonicalSigs
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
@Test
public void testNonCanonicalSigs() throws Exception {
// Tests the noncanonical sigs from the reference client 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 {
assertFalse(TransactionSignature.isEncodingCanonical(Hex.decode(sig.toString())));
} catch (StringIndexOutOfBoundsException e) { } // Expected for non-hex strings in the JSON that we should ignore
}
in.close();
}
示例4: testCanonicalSigs
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
@Test
public void testCanonicalSigs() throws Exception {
// Tests the canonical sigs from the reference client 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();
}
示例5: testCreatedSigAndPubkeyAreCanonical
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
@Test
public void testCreatedSigAndPubkeyAreCanonical() throws Exception {
// Tests that we will not generate non-canonical pubkeys or signatures
// We dump failed data to error log because this test is not expected to be deterministic
ECKey key = new ECKey();
if (!ECKey.isPubKeyCanonical(key.getPubKey())) {
log.error(Utils.bytesToHexString(key.getPubKey()));
fail();
}
byte[] hash = new byte[32];
new Random().nextBytes(hash);
byte[] sigBytes = key.sign(new Sha256Hash(hash)).encodeToDER();
byte[] encodedSig = Arrays.copyOf(sigBytes, sigBytes.length + 1);
encodedSig[sigBytes.length] = (byte) (Transaction.SigHash.ALL.ordinal() + 1);
if (!TransactionSignature.isEncodingCanonical(encodedSig)) {
log.error(Utils.bytesToHexString(sigBytes));
fail();
}
}
示例6: signInput
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
private static byte[] signInput(NetworkParameters params, Transaction tx, int tx_input_index, String base58PrivKey, BitcoinScript script, SigHash sigHash) {
Log.d("SharedCoin", "SharedCoin signInput tx.getInputs().size " + tx.getInputs().size());
Log.d("SharedCoin", "SharedCoin signInput tx_input_index " + tx_input_index);
Log.d("SharedCoin", "SharedCoin signInput base58PrivKey " + base58PrivKey);
try {
ECKey key = new ECKey(Base58.decode(base58PrivKey), null);
Log.d("SharedCoin", "SharedCoin signInput key.toAddress " + key.toAddress(params).toString());
TransactionSignature transactionSignature = tx.calculateSignature(tx_input_index, key, null, script.getProgram(), SigHash.ALL, false);
byte[] signedScript = Script.createInputScript(transactionSignature.encodeToBitcoin(), key.getPubKey());
//ArrayUtils.reverse(signedScript);
String signedScriptHex = new String(Hex.encode(signedScript));
Log.d("SharedCoin", "SharedCoin signInput signedScriptHex " + signedScriptHex);
Log.d("SharedCoin", "SharedCoin signInput script.program hex " + new String(Hex.encode(script.getProgram())));
return signedScript;
} catch (Exception e) {
Log.d("SharedCoin", "SharedCoin signInput e " + e.getLocalizedMessage());
e.printStackTrace();
}
return null;
}
示例7: testNonCanonicalSigs
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
@Test
public void testNonCanonicalSigs() throws Exception {
// Tests the noncanonical sigs from the reference client 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 (DecoderException e) {
// Expected for non-hex strings in the JSON that we should ignore
}
}
in.close();
}
示例8: provideRefundTransaction
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
/**
* 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);
checkState(state == 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 of zero.
if (refundTx.getInput(0).getSequenceNumber() != 0)
throw new VerificationException("Refund transaction's input's sequence number is non-0");
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 = new ECKey(null, 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);
state = State.WAITING_FOR_MULTISIG_CONTRACT;
return sig.encodeToBitcoin();
}
示例9: completeTxPartiallySigned
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
@SuppressWarnings("ConstantConditions")
@Test
public void completeTxPartiallySigned() throws Exception {
// Check the wallet will write dummy scriptSigs for inputs that we have only pubkeys for without the privkey.
ECKey priv = new ECKey();
ECKey pub = new ECKey(null, priv.getPubKey());
wallet.addKey(pub);
ECKey priv2 = new ECKey();
wallet.addKey(priv2);
// Send three transactions, with one being an address type and the other being a raw CHECKSIG type pubkey only,
// and the final one being a key we do have. We expect the first two inputs to be dummy values and the last
// to be signed correctly.
Transaction t1 = sendMoneyToWallet(wallet, Utils.CENT, pub.toAddress(params), AbstractBlockChain.NewBlockType.BEST_CHAIN);
Transaction t2 = sendMoneyToWallet(wallet, Utils.CENT, pub, AbstractBlockChain.NewBlockType.BEST_CHAIN);
Transaction t3 = sendMoneyToWallet(wallet, Utils.CENT, priv2, AbstractBlockChain.NewBlockType.BEST_CHAIN);
ECKey dest = new ECKey();
Wallet.SendRequest req = Wallet.SendRequest.emptyWallet(dest.toAddress(params));
wallet.completeTx(req);
byte[] dummySig = TransactionSignature.dummy().encodeToBitcoin();
// Selected inputs can be in any order.
for (int i = 0; i < req.tx.getInputs().size(); i++) {
TransactionInput input = req.tx.getInput(i);
if (input.getConnectedOutput().getParentTransaction().equals(t1)) {
assertArrayEquals(dummySig, input.getScriptSig().getChunks().get(0).data);
} else if (input.getConnectedOutput().getParentTransaction().equals(t2)) {
assertArrayEquals(dummySig, input.getScriptSig().getChunks().get(0).data);
} else if (input.getConnectedOutput().getParentTransaction().equals(t3)) {
input.getScriptSig().correctlySpends(req.tx, i, t3.getOutput(0).getScriptPubKey(), true);
}
}
assertTrue(TransactionSignature.isEncodingCanonical(dummySig));
}
示例10: sign
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
/**
* Signs the given hash and returns the R and S components as BigIntegers. In the Bitcoin protocol, they are
* usually encoded using DER format, so you want {@link com.google.bitcoin.core.ECKey.ECDSASignature#encodeToDER()}
* instead. However sometimes the independent components can be useful, for instance, if you're doing to do further
* EC maths on them.
*
* @param aesKey The AES key to use for decryption of the private key. If null then no decryption is required.
* @throws KeyCrypterException if this ECKey doesn't have a private part.
*/
public ECDSASignature sign(Sha256Hash input, @Nullable KeyParameter aesKey) throws KeyCrypterException {
if (FAKE_SIGNATURES)
return TransactionSignature.dummy();
// The private key bytes to use for signing.
BigInteger privateKeyForSigning;
if (isEncrypted()) {
// The private key needs decrypting before use.
if (aesKey == null) {
throw new KeyCrypterException("This ECKey is encrypted but no decryption key has been supplied.");
}
if (keyCrypter == null) {
throw new KeyCrypterException("There is no KeyCrypter to decrypt the private key for signing.");
}
privateKeyForSigning = new BigInteger(1, keyCrypter.decrypt(encryptedPrivateKey, aesKey));
// Check encryption was correct.
if (!Arrays.equals(pub, publicKeyFromPrivate(privateKeyForSigning, isCompressed())))
throw new KeyCrypterException("Could not decrypt bytes");
} else {
// No decryption of private key required.
if (priv == null) {
throw new KeyCrypterException("This ECKey does not have the private key necessary for signing.");
} else {
privateKeyForSigning = priv;
}
}
ECDSASigner signer = new ECDSASigner();
ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE);
signer.init(true, privKey);
BigInteger[] components = signer.generateSignature(input.getBytes());
final ECDSASignature signature = new ECDSASignature(components[0], components[1]);
signature.ensureCanonical();
return signature;
}
示例11: incrementPaymentBy
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
/**
* <p>Updates the outputs on the payment contract transaction and re-signs it. The state must be READY in order to
* call this method. The signature that is returned should be sent to the server so it has the ability to broadcast
* the best seen payment when the channel closes or times out.</p>
*
* <p>The returned signature is over the payment transaction, which we never have a valid copy of and thus there
* is no accessor for it on this object.</p>
*
* <p>To spend the whole channel increment by {@link PaymentChannelClientState#getTotalValue()} -
* {@link PaymentChannelClientState#getValueRefunded()}</p>
*
* @param size How many satoshis to increment the payment by (note: not the new total).
* @throws ValueOutOfRangeException If size is negative or the channel does not have sufficient money in it to
* complete this payment.
*/
public synchronized IncrementedPayment incrementPaymentBy(BigInteger size) throws ValueOutOfRangeException {
checkState(state == State.READY);
checkNotExpired();
checkNotNull(size); // Validity of size will be checked by makeUnsignedChannelContract.
if (size.compareTo(BigInteger.ZERO) < 0)
throw new ValueOutOfRangeException("Tried to decrement payment");
BigInteger newValueToMe = valueToMe.subtract(size);
if (newValueToMe.compareTo(Transaction.MIN_NONDUST_OUTPUT) < 0 && newValueToMe.compareTo(BigInteger.ZERO) > 0) {
log.info("New value being sent back as change was smaller than minimum nondust output, sending all");
size = valueToMe;
newValueToMe = BigInteger.ZERO;
}
if (newValueToMe.compareTo(BigInteger.ZERO) < 0)
throw new ValueOutOfRangeException("Channel has too little money to pay " + size + " satoshis");
Transaction tx = makeUnsignedChannelContract(newValueToMe);
log.info("Signing new payment tx {}", tx);
Transaction.SigHash mode;
// If we spent all the money we put into this channel, we (by definition) don't care what the outputs are, so
// we sign with SIGHASH_NONE to let the server do what it wants.
if (newValueToMe.equals(BigInteger.ZERO))
mode = Transaction.SigHash.NONE;
else
mode = Transaction.SigHash.SINGLE;
TransactionSignature sig = tx.calculateSignature(0, myKey, multisigScript, mode, true);
valueToMe = newValueToMe;
updateChannelInWallet();
IncrementedPayment payment = new IncrementedPayment();
payment.signature = sig;
payment.amount = size;
return payment;
}
示例12: incrementPaymentBy
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
/**
* <p>Updates the outputs on the payment contract transaction and re-signs it. The state must be READY in order to
* call this method. The signature that is returned should be sent to the server so it has the ability to broadcast
* the best seen payment when the channel closes or times out.</p>
*
* <p>The returned signature is over the payment transaction, which we never have a valid copy of and thus there
* is no accessor for it on this object.</p>
*
* <p>To spend the whole channel increment by {@link PaymentChannelClientState#getTotalValue()} -
* {@link PaymentChannelClientState#getValueRefunded()}</p>
*
* @param size How many satoshis to increment the payment by (note: not the new total).
* @throws ValueOutOfRangeException If size is negative or the channel does not have sufficient money in it to
* complete this payment.
*/
public synchronized IncrementedPayment incrementPaymentBy(BigInteger size) throws ValueOutOfRangeException {
checkState(state == State.READY);
checkNotExpired();
checkNotNull(size); // Validity of size will be checked by makeUnsignedChannelContract.
if (size.signum() < 0)
throw new ValueOutOfRangeException("Tried to decrement payment");
BigInteger newValueToMe = valueToMe.subtract(size);
if (newValueToMe.compareTo(Transaction.MIN_NONDUST_OUTPUT) < 0 && newValueToMe.signum() > 0) {
log.info("New value being sent back as change was smaller than minimum nondust output, sending all");
size = valueToMe;
newValueToMe = BigInteger.ZERO;
}
if (newValueToMe.signum() < 0)
throw new ValueOutOfRangeException("Channel has too little money to pay " + size + " satoshis");
Transaction tx = makeUnsignedChannelContract(newValueToMe);
log.info("Signing new payment tx {}", tx);
Transaction.SigHash mode;
// If we spent all the money we put into this channel, we (by definition) don't care what the outputs are, so
// we sign with SIGHASH_NONE to let the server do what it wants.
if (newValueToMe.equals(BigInteger.ZERO))
mode = Transaction.SigHash.NONE;
else
mode = Transaction.SigHash.SINGLE;
TransactionSignature sig = tx.calculateSignature(0, myKey, multisigScript, mode, true);
valueToMe = newValueToMe;
updateChannelInWallet();
IncrementedPayment payment = new IncrementedPayment();
payment.signature = sig;
payment.amount = size;
return payment;
}
示例13: createMultiSigInputScript
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
/** Create a program that satisfies an OP_CHECKMULTISIG program. */
public static Script createMultiSigInputScript(List<TransactionSignature> signatures) {
List<byte[]> sigs = new ArrayList<byte[]>(signatures.size());
for (TransactionSignature signature : signatures)
sigs.add(signature.encodeToBitcoin());
return createMultiSigInputScriptBytes(sigs);
}
示例14: createP2SHMultiSigInputScript
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
/** Create a program that satisfies a pay-to-script hashed OP_CHECKMULTISIG program. */
public static Script createP2SHMultiSigInputScript(List<TransactionSignature> signatures,
byte[] multisigProgramBytes) {
List<byte[]> sigs = new ArrayList<byte[]>(signatures.size());
for (TransactionSignature signature : signatures)
sigs.add(signature.encodeToBitcoin());
return createMultiSigInputScriptBytes(sigs, multisigProgramBytes);
}
示例15: executeCheckSig
import com.google.bitcoin.crypto.TransactionSignature; //导入依赖的package包/类
private static void executeCheckSig(Transaction txContainingThis, int index, Script script, LinkedList<byte[]> stack,
int lastCodeSepLocation, int opcode) throws ScriptException {
if (stack.size() < 2)
throw new ScriptException("Attempted OP_CHECKSIG(VERIFY) on a stack with size < 2");
byte[] pubKey = stack.pollLast();
byte[] sigBytes = stack.pollLast();
byte[] prog = script.getProgram();
byte[] connectedScript = Arrays.copyOfRange(prog, lastCodeSepLocation, prog.length);
UnsafeByteArrayOutputStream outStream = new UnsafeByteArrayOutputStream(sigBytes.length + 1);
try {
writeBytes(outStream, sigBytes);
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen
}
connectedScript = removeAllInstancesOf(connectedScript, outStream.toByteArray());
// TODO: Use int for indexes everywhere, we can't have that many inputs/outputs
boolean sigValid = false;
try {
TransactionSignature sig = TransactionSignature.decodeFromBitcoin(sigBytes, false);
Sha256Hash hash = txContainingThis.hashForSignature(index, connectedScript, (byte) sig.sighashFlags);
sigValid = ECKey.verify(hash.getBytes(), sig, pubKey);
} catch (Exception e1) {
// There is (at least) one exception that could be hit here (EOFException, if the sig is too short)
// Because I can't verify there aren't more, we use a very generic Exception catch
log.warn(e1.toString());
}
if (opcode == OP_CHECKSIG)
stack.add(sigValid ? new byte[] {1} : new byte[] {0});
else if (opcode == OP_CHECKSIGVERIFY)
if (!sigValid)
throw new ScriptException("Script failed OP_CHECKSIGVERIFY");
}