Пример #1
0
  /**
   * Broadcast outgoing transactions.
   *
   * <p>This method should only be called from the wallet manager
   *
   * @return false if synchronization failed due to failed blockchain connection
   */
  public synchronized boolean broadcastOutgoingTransactions() {
    checkNotArchived();
    List<Sha256Hash> broadcastedIds = new LinkedList<Sha256Hash>();
    Map<Sha256Hash, byte[]> transactions = _backing.getOutgoingTransactions();

    for (byte[] rawTransaction : transactions.values()) {
      TransactionEx tex = TransactionEx.fromUnconfirmedTransaction(rawTransaction);

      BroadcastResult result = broadcastTransaction(TransactionEx.toTransaction(tex));
      if (result == BroadcastResult.SUCCESS) {
        broadcastedIds.add(tex.txid);
        _backing.removeOutgoingTransaction(tex.txid);
      } else {
        if (result == BroadcastResult.REJECTED) {
          // invalid tx
          _backing.deleteTransaction(tex.txid);
          _backing.removeOutgoingTransaction(tex.txid);
        } else {
          // No connection --> retry next sync
        }
      }
    }
    if (!broadcastedIds.isEmpty()) {
      onTransactionsBroadcasted(broadcastedIds);
    }
    return true;
  }
Пример #2
0
 @Override
 public synchronized boolean deleteTransaction(Sha256Hash transactionId) {
   TransactionEx tex = _backing.getTransaction(transactionId);
   if (tex == null) return false;
   Transaction tx = TransactionEx.toTransaction(tex);
   _backing.beginTransaction();
   try {
     // See if any of the outputs are stored locally and remove them
     for (int i = 0; i < tx.outputs.length; i++) {
       TransactionOutput output = tx.outputs[i];
       OutPoint outPoint = new OutPoint(tx.getHash(), i);
       TransactionOutputEx utxo = _backing.getUnspentOutput(outPoint);
       if (utxo != null) {
         _backing.deleteUnspentOutput(outPoint);
       }
     }
     // remove it from the backing
     _backing.deleteTransaction(transactionId);
     _backing.setTransactionSuccessful();
   } finally {
     _backing.endTransaction();
   }
   updateLocalBalance(); // will still need a new sync besides re-calculating
   return true;
 }
Пример #3
0
 /**
  * Determine whether a transaction was sent from one of our own addresses.
  *
  * <p>This is a costly operation as we first have to lookup the transaction and then it's funding
  * outputs
  *
  * @param txid the ID of the transaction to investigate
  * @return true if one of the funding outputs were sent from one of our own addresses
  */
 protected boolean isFromMe(Sha256Hash txid) {
   Transaction t = TransactionEx.toTransaction(_backing.getTransaction(txid));
   if (t == null) {
     return false;
   }
   return isFromMe(t);
 }
Пример #4
0
  private void markTransactionAsSpent(Transaction transaction) {
    _backing.beginTransaction();
    try {
      // Remove inputs from unspent, marking them as spent
      for (TransactionInput input : transaction.inputs) {
        TransactionOutputEx parentOutput = _backing.getUnspentOutput(input.outPoint);
        if (parentOutput != null) {
          _backing.deleteUnspentOutput(input.outPoint);
          _backing.putParentTransactionOutput(parentOutput);
        }
      }

      // See if any of the outputs are for ourselves and store them as
      // unspent
      for (int i = 0; i < transaction.outputs.length; i++) {
        TransactionOutput output = transaction.outputs[i];
        if (isMine(output.script)) {
          _backing.putUnspentOutput(
              new TransactionOutputEx(
                  new OutPoint(transaction.getHash(), i),
                  -1,
                  output.value,
                  output.script.getScriptBytes(),
                  false));
        }
      }

      // Store transaction locally, so we have it in our history and don't
      // need to fetch it in a minute
      _backing.putTransaction(TransactionEx.fromUnconfirmedTransaction(transaction));
      _backing.setTransactionSuccessful();
    } finally {
      _backing.endTransaction();
    }

    // Tell account that we have a new transaction
    onNewTransaction(TransactionEx.fromUnconfirmedTransaction(transaction), transaction);

    // Calculate local balance cache. It has changed because we have done
    // some spending
    updateLocalBalance();
    persistContextIfNecessary();
  }
Пример #5
0
  protected boolean monitorYoungTransactions() {
    Collection<TransactionEx> list = _backing.getYoungTransactions(5, getBlockChainHeight());
    if (list.isEmpty()) {
      return true;
    }
    List<Sha256Hash> txids = new ArrayList<Sha256Hash>(list.size());
    for (TransactionEx tex : list) {
      txids.add(tex.txid);
    }
    CheckTransactionsResponse result;
    try {
      result = _wapi.checkTransactions(new CheckTransactionsRequest(txids)).getResult();
    } catch (WapiException e) {
      postEvent(Event.SERVER_CONNECTION_ERROR);
      _logger.logError("Server connection failed with error code: " + e.errorCode, e);
      // We failed to check transactions
      return false;
    }
    for (TransactionStatus t : result.transactions) {
      if (!t.found) {
        // We have a transaction locally that does not exist in the
        // blockchain. Must be a residue due to double-spend or malleability

        _backing.deleteTransaction(t.txid);
        continue;
      }
      TransactionEx tex = _backing.getTransaction(t.txid);
      Preconditions.checkNotNull(tex);
      if (tex.height != t.height || tex.time != t.time) {
        // The transaction got a new height or timestamp. There could be
        // several reasons for that. It got a new timestamp from the server,
        // it confirmed, or might also be a reorg.
        TransactionEx newTex = new TransactionEx(tex.txid, t.height, t.time, tex.binary);
        System.out.println("Replacing:\n" + tex.toString() + "\nWith:\n" + newTex.toString());
        postEvent(Event.TRANSACTION_HISTORY_CHANGED);
        _backing.deleteTransaction(tex.txid);
        _backing.putTransaction(newTex);
      }
    }
    return true;
  }
Пример #6
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);
  }
Пример #7
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);
    }
  }