本文整理汇总了Java中org.bitcoinj.core.Transaction类的典型用法代码示例。如果您正苦于以下问题:Java Transaction类的具体用法?Java Transaction怎么用?Java Transaction使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Transaction类属于org.bitcoinj.core包,在下文中一共展示了Transaction类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getWalletAddressOfReceived
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
@Nullable
public static Address getWalletAddressOfReceived(final Transaction tx, final Wallet wallet) {
for (final TransactionOutput output : tx.getOutputs()) {
try {
if (output.isMine(wallet)) {
final Script script = output.getScriptPubKey();
return script.getToAddress(Constants.NETWORK_PARAMETERS, true);
}
} catch (final ScriptException x) {
// swallow
}
}
return null;
}
示例2: maybeMovePool
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
/**
* If the transactions outputs are all marked as spent, and it's in the unspent map, move it.
* If the owned transactions outputs are not all marked as spent, and it's in the spent map, move it.
*/
private void maybeMovePool(Transaction tx, String context) {
checkState(lock.isHeldByCurrentThread());
if (tx.isEveryOwnedOutputSpent(this)) {
// There's nothing left I can spend in this transaction.
if (unspent.remove(tx.getHash()) != null) {
if (log.isInfoEnabled()) {
log.info(" {} {} <-unspent ->spent", tx.getHashAsString(), context);
}
spent.put(tx.getHash(), tx);
}
} else {
if (spent.remove(tx.getHash()) != null) {
if (log.isInfoEnabled()) {
log.info(" {} {} <-spent ->unspent", tx.getHashAsString(), context);
}
unspent.put(tx.getHash(), tx);
}
}
}
示例3: onCoinsReceived
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
@Override
public void onCoinsReceived(final Wallet wallet, final Transaction tx, final Coin prevBalance,
final Coin newBalance) {
transactionsReceived.incrementAndGet();
final int bestChainHeight = blockChain.getBestChainHeight();
final Address address = WalletUtils.getWalletAddressOfReceived(tx, wallet);
final Coin amount = tx.getValue(wallet);
final ConfidenceType confidenceType = tx.getConfidence().getConfidenceType();
final Sha256Hash hash = tx.getHash();
handler.post(new Runnable() {
@Override
public void run() {
final boolean isReceived = amount.signum() > 0;
final boolean replaying = bestChainHeight < config.getBestChainHeightEver();
final boolean isReplayedTx = confidenceType == ConfidenceType.BUILDING && replaying;
if (isReceived && !isReplayedTx)
notifyCoinsReceived(address, amount, hash);
}
});
}
示例4: onBindViewHolder
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTvTitle.setText("");
synchronized (mDataset) {
try {
final Transaction tx = mDataset.get(position);
holder.mTvTitle.setText(String.valueOf(tx.getOutputSum().getValue()/100000000) + " BTC"+((tx.isPending())?" (U)":""));
holder.mTvHash.setText(tx.getHashAsString());
holder.key = tx.getHashAsString().toString();
}catch (Exception e){
e.printStackTrace();
}
}
}
示例5: isPendingTransactionRelevant
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
/**
* This method is used by a {@link Peer} to find out if a transaction that has been announced is interesting,
* that is, whether we should bother downloading its dependencies and exploring the transaction to decide how
* risky it is. If this method returns true then {@link Wallet#receivePending(Transaction, java.util.List)}
* will soon be called with the transactions dependencies as well.
*/
public boolean isPendingTransactionRelevant(Transaction tx) throws ScriptException {
lock.lock();
try {
// Ignore it if we already know about this transaction. Receiving a pending transaction never moves it
// between pools.
EnumSet<Pool> containingPools = getContainingPools(tx);
if (!containingPools.equals(EnumSet.noneOf(Pool.class))) {
log.debug("Received tx we already saw in a block or created ourselves: " + tx.getHashAsString());
return false;
}
// We only care about transactions that:
// - Send us coins
// - Spend our coins
// - Double spend a tx in our wallet
if (!isTransactionRelevant(tx)) {
log.debug("Received tx that isn't relevant to this wallet, discarding.");
return false;
}
return true;
} finally {
lock.unlock();
}
}
示例6: isValidImprintingTransaction
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
/**
* Return true if the transaction in input is a valid imprinting transaction and contains the specified address in
* one of its output, otherwise false.
* @param tx the transaction to check if is valid imprinting
* @param networkParameters the {@link NetworkParameters}
* @param imprintingAddress the address to check for
* @return true if it's an imprinting transaction otherwise false
*/
public static boolean isValidImprintingTransaction(Transaction tx, NetworkParameters networkParameters, Address imprintingAddress) {
// Retrieve sender
String sender = tx.getInput(0).getFromAddress().toBase58();
// Check output
List<TransactionOutput> transactionOutputs = tx.getOutputs();
for (TransactionOutput to : transactionOutputs) {
Address address = to.getAddressFromP2PKHScript(networkParameters);
if (address != null && address.equals(imprintingAddress)) {
return true;
}
}
return false;
}
示例7: loadInBackground
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
@Override
public List<Transaction> loadInBackground() {
org.bitcoinj.core.Context.propagate(Constants.CONTEXT);
final Set<Transaction> transactions = wallet.getTransactions(true);
final List<Transaction> filteredTransactions = new ArrayList<Transaction>(transactions.size());
for (final Transaction tx : transactions) {
final boolean sent = tx.getValue(wallet).signum() < 0;
final boolean isInternal = tx.getPurpose() == Purpose.KEY_ROTATION;
if ((direction == Direction.RECEIVED && !sent && !isInternal) || direction == null
|| (direction == Direction.SENT && sent && !isInternal))
filteredTransactions.add(tx);
}
Collections.sort(filteredTransactions, TRANSACTION_COMPARATOR);
return filteredTransactions;
}
示例8: analyzeIsStandard
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
private Result analyzeIsStandard() {
// The IsStandard rules don't apply on testnet, because they're just a safety mechanism and we don't want to
// crush innovation with valueless test coins.
if (wallet != null && !wallet.getNetworkParameters().getId().equals(NetworkParameters.ID_MAINNET))
return Result.OK;
RuleViolation ruleViolation = isStandard(tx);
if (ruleViolation != RuleViolation.NONE) {
nonStandard = tx;
return Result.NON_STANDARD;
}
for (Transaction dep : dependencies) {
ruleViolation = isStandard(dep);
if (ruleViolation != RuleViolation.NONE) {
nonStandard = dep;
return Result.NON_STANDARD;
}
}
return Result.OK;
}
示例9: getContainingPools
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
EnumSet<Pool> getContainingPools(Transaction tx) {
lock.lock();
try {
EnumSet<Pool> result = EnumSet.noneOf(Pool.class);
Sha256Hash txHash = tx.getHash();
if (unspent.containsKey(txHash)) {
result.add(Pool.UNSPENT);
}
if (spent.containsKey(txHash)) {
result.add(Pool.SPENT);
}
if (pending.containsKey(txHash)) {
result.add(Pool.PENDING);
}
if (dead.containsKey(txHash)) {
result.add(Pool.DEAD);
}
return result;
} finally {
lock.unlock();
}
}
示例10: notifyTransactionIsInBlock
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
/**
* Called by the {@link BlockChain} when we receive a new filtered block that contains a transactions previously
* received by a call to {@link #receivePending}.<p>
*
* This is necessary for the internal book-keeping Wallet does. When a transaction is received that sends us
* coins it is added to a pool so we can use it later to create spends. When a transaction is received that
* consumes outputs they are marked as spent so they won't be used in future.<p>
*
* A transaction that spends our own coins can be received either because a spend we created was accepted by the
* network and thus made it into a block, or because our keys are being shared between multiple instances and
* some other node spent the coins instead. We still have to know about that to avoid accidentally trying to
* double spend.<p>
*
* A transaction may be received multiple times if is included into blocks in parallel chains. The blockType
* parameter describes whether the containing block is on the main/best chain or whether it's on a presently
* inactive side chain. We must still record these transactions and the blocks they appear in because a future
* block might change which chain is best causing a reorganize. A re-org can totally change our balance!
*/
@Override
public boolean notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block,
BlockChain.NewBlockType blockType,
int relativityOffset) throws VerificationException {
lock.lock();
try {
Transaction tx = transactions.get(txHash);
if (tx == null) {
tx = riskDropped.get(txHash);
if (tx != null) {
// If this happens our risk analysis is probably wrong and should be improved.
log.info("Risk analysis dropped tx {} but was included in block anyway", tx.getHash());
} else {
// False positive that was broadcast to us and ignored by us because it was irrelevant to our keys.
return false;
}
}
receive(tx, block, blockType, relativityOffset);
return true;
} finally {
lock.unlock();
}
}
示例11: getRecentTransactions
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
/**
* Returns an list of N transactions, ordered by increasing age. Transactions on side chains are not included.
* Dead transactions (overridden by double spends) are optionally included. <p>
* <p/>
* Note: the current implementation is O(num transactions in wallet). Regardless of how many transactions are
* requested, the cost is always the same. In future, requesting smaller numbers of transactions may be faster
* depending on how the wallet is implemented (eg if backed by a database).
*/
public List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead) {
lock.lock();
try {
checkArgument(numTransactions >= 0);
// Firstly, put all transactions into an array.
int size = unspent.size() + spent.size() + pending.size();
if (numTransactions > size || numTransactions == 0) {
numTransactions = size;
}
ArrayList<Transaction> all = new ArrayList<>(getTransactions(includeDead));
// Order by update time.
Collections.sort(all, Transaction.SORT_TX_BY_UPDATE_TIME);
if (numTransactions == all.size()) {
return all;
} else {
all.subList(numTransactions, all.size()).clear();
return all;
}
} finally {
lock.unlock();
}
}
示例12: generateGenesisTransaction
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
public void generateGenesisTransaction(int lockTime) {
Transaction genesisTx;
try {
//generate genesis transaction if our proof is empty
if(pm.getValidationPath().size() == 0 && wallet.getBalance(BalanceType.AVAILABLE).isGreaterThan(PSNYMVALUE)) {
genesisTx = tg.generateGenesisTransaction(pm, walletFile, lockTime);
//TODO register listener before sending tx out, to avoid missing a confidence change
genesisTx.getConfidence().addEventListener(new Listener() {
@Override
public void onConfidenceChanged(TransactionConfidence arg0,
ChangeReason arg1) {
if (arg0.getConfidenceType() != TransactionConfidence.ConfidenceType.BUILDING) {
return;
}
if(arg0.getDepthInBlocks() == 1) {
//enough confidence, write proof message to the file system
System.out.println("depth of genesis tx is now 1, consider ready for usage");
}
}
});
}
} catch (InsufficientMoneyException e) {
e.printStackTrace();
}
}
示例13: markKeysAsUsed
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
/**
* Marks all keys used in the transaction output as used in the wallet.
* See {@link org.bitcoinj.wallet.DeterministicKeyChain#markKeyAsUsed(DeterministicKey)} for more info on this.
*/
private void markKeysAsUsed(Transaction tx) {
keyChainGroupLock.lock();
try {
for (TransactionOutput o : tx.getOutputs()) {
try {
Script script = o.getScriptPubKey();
if (script.isSentToRawPubKey()) {
byte[] pubkey = script.getPubKey();
keyChainGroup.markPubKeyAsUsed(pubkey);
} else if (script.isSentToAddress()) {
byte[] pubkeyHash = script.getPubKeyHash();
keyChainGroup.markPubKeyHashAsUsed(pubkeyHash);
} else if (script.isPayToScriptHash()) {
Address a = Address.fromP2SHScript(tx.getParams(), script);
keyChainGroup.markP2SHAddressAsUsed(a);
}
} catch (ScriptException e) {
// Just means we didn't understand the output of this transaction: ignore it.
log.warn("Could not parse tx output script: {}", e.toString());
}
}
} finally {
keyChainGroupLock.unlock();
}
}
示例14: onBlocksDownloaded
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
@Override
public void onBlocksDownloaded(Peer arg0, Block arg1,
@Nullable FilteredBlock arg2, int arg3) {
System.out.println("received block");
boolean receivedBcastAnnouncmnt = false;
Map<Sha256Hash, Transaction> assocTxs = arg2.getAssociatedTransactions();
for(Transaction tx : assocTxs.values()) {
System.out.println("from within mixpartner discovery " + tx);
if(tx.getOutputs().size() > 1 &&
BroadcastAnnouncement.isBroadcastAnnouncementScript(tx.getOutput(1).getScriptBytes()))
//&& !wallet.isTransactionRelevant(tx)) {
//tx.getInput(0).getScriptSig().getChunks().get(0)
{
if(!this.broadcasts.contains(tx) && wallet.getTransaction(tx.getHash()) == null) {
this.broadcasts.add(tx);
receivedBcastAnnouncmnt = true;
}
}
}
if(receivedBcastAnnouncmnt) {
for(BroadcastAnnouncementChangeEventListener l : listeners) {
l.onBroadcastAnnouncementChanged();
}
}
}
示例15: initStateFromBitcoinUri
import org.bitcoinj.core.Transaction; //导入依赖的package包/类
private void initStateFromBitcoinUri(final Uri bitcoinUri) {
final String input = bitcoinUri.toString();
new StringInputParser(input) {
@Override
protected void handlePaymentIntent(final PaymentIntent paymentIntent) {
updateStateFrom(paymentIntent);
}
@Override
protected void handlePrivateKey(final VersionedChecksummedBytes key) {
throw new UnsupportedOperationException();
}
@Override
protected void handleDirectTransaction(final Transaction transaction) throws VerificationException {
throw new UnsupportedOperationException();
}
@Override
protected void error(final int messageResId, final Object... messageArgs) {
dialog(activity, activityDismissListener, 0, messageResId, messageArgs);
}
}.parse();
}