示例#1
0
  @Override
  public TransactionDetails getTransactionDetails(Sha256Hash txid) {
    // Note that this method is not synchronized, and we might fetch the transaction history while
    // synchronizing
    // accounts. That should be ok as we write to the DB in a sane order.

    TransactionEx tex = _backing.getTransaction(txid);
    Transaction tx = TransactionEx.toTransaction(tex);
    if (tx == null) {
      throw new RuntimeException();
    }

    List<TransactionDetails.Item> inputs = new ArrayList<TransactionDetails.Item>(tx.inputs.length);
    if (tx.isCoinbase()) {
      // We have a coinbase transaction. Create one input with the sum of the outputs as its value,
      // and make the address the null address
      long value = 0;
      for (TransactionOutput out : tx.outputs) {
        value += out.value;
      }
      inputs.add(new TransactionDetails.Item(Address.getNullAddress(_network), value, true));
    } else {
      // Populate the inputs
      for (TransactionInput input : tx.inputs) {
        Sha256Hash parentHash = input.outPoint.hash;
        // Get the parent transaction
        TransactionOutputEx parentOutput = _backing.getParentTransactionOutput(input.outPoint);
        if (parentOutput == null) {
          // We never heard about the parent, skip
          continue;
        }
        // Determine the parent address
        Address parentAddress;
        ScriptOutput parentScript = ScriptOutput.fromScriptBytes(parentOutput.script);
        if (parentScript == null) {
          // Null address means we couldn't figure out the address, strange script
          parentAddress = Address.getNullAddress(_network);
        } else {
          parentAddress = parentScript.getAddress(_network);
        }
        inputs.add(new TransactionDetails.Item(parentAddress, parentOutput.value, false));
      }
    }
    // Populate the outputs
    TransactionDetails.Item[] outputs = new TransactionDetails.Item[tx.outputs.length];
    for (int i = 0; i < tx.outputs.length; i++) {
      Address address = tx.outputs[i].script.getAddress(_network);
      outputs[i] = new TransactionDetails.Item(address, tx.outputs[i].value, false);
    }

    return new TransactionDetails(
        txid, tex.height, tex.time, inputs.toArray(new TransactionDetails.Item[] {}), outputs);
  }
示例#2
0
  protected TransactionSummary transform(
      Transaction tx, int time, int height, int blockChainHeight) {
    long value = 0;
    Address destAddress = null;
    for (TransactionOutput output : tx.outputs) {
      if (isMine(output.script)) {
        value += output.value;
      } else {
        destAddress = output.script.getAddress(_network);
      }
    }

    if (tx.isCoinbase()) {
      // For coinbase transactions there is nothing to subtract
    } else {
      for (TransactionInput input : tx.inputs) {
        // find parent output
        TransactionOutputEx funding = _backing.getParentTransactionOutput(input.outPoint);
        if (funding == null) {
          _logger.logError("Unable to find parent output for: " + input.outPoint);
          continue;
        }
        if (isMine(funding)) {
          value -= funding.value;
        }
      }
    }

    int confirmations;
    if (height == -1) {
      confirmations = 0;
    } else {
      confirmations = Math.max(0, blockChainHeight - height + 1);
    }

    // only track a destinationAddress if it is an outgoing transaction (i.e. send money to someone)
    // to prevent the user that he tries to return money to an address he got bitcoin from.
    if (value >= 0) {
      destAddress = null;
    }

    boolean isQueuedOutgoing = _backing.isOutgoingTransaction(tx.getHash());

    return new TransactionSummary(
        tx.getHash(),
        value,
        time,
        height,
        confirmations,
        isQueuedOutgoing,
        com.google.common.base.Optional.fromNullable(destAddress));
  }
示例#3
0
 /**
  * Determine whether a transaction was sent from one of our own addresses.
  *
  * <p>This is a costly operation as we have to lookup funding outputs of the transaction
  *
  * @param t the transaction to investigate
  * @return true iff one of the funding outputs were sent from one of our own addresses
  */
 protected boolean isFromMe(Transaction t) {
   for (TransactionInput input : t.inputs) {
     TransactionOutputEx funding = _backing.getParentTransactionOutput(input.outPoint);
     if (funding == null || funding.isCoinBase) {
       continue;
     }
     ScriptOutput fundingScript = ScriptOutput.fromScriptBytes(funding.script);
     Address fundingAddress = fundingScript.getAddress(_network);
     if (isMine(fundingAddress)) {
       return true;
     }
   }
   return false;
 }
示例#4
0
  protected Balance calculateLocalBalance() {

    Collection<TransactionOutputEx> unspentOutputs =
        new HashSet<TransactionOutputEx>(_backing.getAllUnspentOutputs());
    long confirmed = 0;
    long pendingChange = 0;
    long pendingSending = 0;
    long pendingReceiving = 0;

    //
    // Determine the value we are receiving and create a set of outpoints for fast lookup
    //
    Set<OutPoint> unspentOutPoints = new HashSet<OutPoint>();
    for (TransactionOutputEx output : unspentOutputs) {
      if (output.height == -1) {
        if (isFromMe(output.outPoint.hash)) {
          pendingChange += output.value;
        } else {
          pendingReceiving += output.value;
        }
      } else {
        confirmed += output.value;
      }
      unspentOutPoints.add(output.outPoint);
    }

    //
    // Determine the value we are sending
    //

    // Get the current set of unconfirmed transactions
    List<Transaction> unconfirmed = new ArrayList<Transaction>();
    for (TransactionEx tex : _backing.getUnconfirmedTransactions()) {
      try {
        Transaction t = Transaction.fromByteReader(new ByteReader(tex.binary));
        unconfirmed.add(t);
      } catch (TransactionParsingException e) {
        // never happens, we have parsed it before
      }
    }

    for (Transaction t : unconfirmed) {
      // For each input figure out if WE are sending it by fetching the
      // parent transaction and looking at the address
      boolean weSend = false;
      for (TransactionInput input : t.inputs) {
        // Find the parent transaction
        if (input.outPoint.hash.equals(Sha256Hash.ZERO_HASH)) {
          continue;
        }
        TransactionOutputEx parent = _backing.getParentTransactionOutput(input.outPoint);
        if (parent == null) {
          _logger.logError("Unable to find parent transaction output: " + input.outPoint);
          continue;
        }
        TransactionOutput parentOutput = transform(parent);
        Address fundingAddress = parentOutput.script.getAddress(_network);
        if (isMine(fundingAddress)) {
          // One of our addresses are sending coins
          pendingSending += parentOutput.value;
          weSend = true;
        }
      }

      // Now look at the outputs and if it contains change for us, then subtract that from the
      // sending amount
      // if it is already spent in another transaction
      for (int i = 0; i < t.outputs.length; i++) {
        TransactionOutput output = t.outputs[i];
        Address destination = output.script.getAddress(_network);
        if (weSend && isMine(destination)) {
          // The funds are sent from us to us
          OutPoint outPoint = new OutPoint(t.getHash(), i);
          if (!unspentOutPoints.contains(outPoint)) {
            // This output has been spent, subtract it from the amount sent
            pendingSending -= output.value;
          }
        }
      }
    }

    int blockHeight = getBlockChainHeight();
    return new Balance(
        confirmed,
        pendingReceiving,
        pendingSending,
        pendingChange,
        System.currentTimeMillis(),
        blockHeight,
        true,
        _allowZeroConfSpending);
  }
示例#5
0
  private void fetchStoreAndValidateParentOutputs(ArrayList<Transaction> transactions)
      throws WapiException {
    Map<Sha256Hash, TransactionEx> parentTransactions = new HashMap<Sha256Hash, TransactionEx>();
    Map<OutPoint, TransactionOutputEx> parentOutputs = new HashMap<OutPoint, TransactionOutputEx>();

    // Find list of parent outputs to fetch
    Collection<Sha256Hash> toFetch = new HashSet<Sha256Hash>();
    for (Transaction t : transactions) {
      for (TransactionInput in : t.inputs) {
        if (in.outPoint.hash.equals(OutPoint.COINBASE_OUTPOINT.hash)) {
          // Coinbase input, so no parent
          continue;
        }
        TransactionOutputEx parentOutput = _backing.getParentTransactionOutput(in.outPoint);
        if (parentOutput != null) {
          // We already have the parent output, no need to fetch the entire
          // parent transaction
          parentOutputs.put(parentOutput.outPoint, parentOutput);
          continue;
        }
        TransactionEx parentTransaction = _backing.getTransaction(in.outPoint.hash);
        if (parentTransaction != null) {
          // We had the parent transaction in our own transactions, no need to
          // fetch it remotely
          parentTransactions.put(parentTransaction.txid, parentTransaction);
        } else {
          // Need to fetch it
          toFetch.add(in.outPoint.hash);
        }
      }
    }

    // Fetch missing parent transactions
    if (toFetch.size() > 0) {
      GetTransactionsResponse result =
          _wapi.getTransactions(new GetTransactionsRequest(Wapi.VERSION, toFetch)).getResult();
      for (TransactionEx tx : result.transactions) {
        // Verify transaction hash. This is important as we don't want to
        // have a transaction output associated with an outpoint that
        // doesn't match.
        // This is the end users protection against a rogue server that lies
        // about the value of an output and makes you pay a large fee.
        Sha256Hash hash = HashUtils.doubleSha256(tx.binary).reverse();
        if (hash.equals(tx.txid)) {
          parentTransactions.put(tx.txid, tx);
        } else {
          _logger.logError(
              "Failed to validate transaction hash from server. Expected: "
                  + tx.txid
                  + " Calculated: "
                  + hash);
          throw new RuntimeException(
              "Failed to validate transaction hash from server. Expected: "
                  + tx.txid
                  + " Calculated: "
                  + hash);
        }
      }
    }

    // We should now have all parent transactions or parent outputs. There is
    // a slight probability that one of them was not found due to double
    // spends and/or malleability and network latency etc.

    // Now figure out which parent outputs we need to persist
    List<TransactionOutputEx> toPersist = new LinkedList<TransactionOutputEx>();
    for (Transaction t : transactions) {
      for (TransactionInput in : t.inputs) {
        if (in.outPoint.hash.equals(OutPoint.COINBASE_OUTPOINT.hash)) {
          // coinbase input, so no parent
          continue;
        }
        TransactionOutputEx parentOutput = parentOutputs.get(in.outPoint);
        if (parentOutput != null) {
          // We had it all along
          continue;
        }
        TransactionEx parentTex = parentTransactions.get(in.outPoint.hash);
        if (parentTex != null) {
          // Parent output not found, maybe we already have it
          parentOutput = TransactionEx.getTransactionOutput(parentTex, in.outPoint.index);
          toPersist.add(parentOutput);
          continue;
        }
        _logger.logError("Parent transaction not found: " + in.outPoint.hash);
      }
    }

    // Persist
    for (TransactionOutputEx output : toPersist) {
      _backing.putParentTransactionOutput(output);
    }
  }