static void exchangeNXTForCurrency(
      Transaction transaction,
      Account account,
      final long currencyId,
      final long rateNQT,
      long units) {
    long extraUnits = 0;
    long remainingAmountNQT = Math.multiplyExact(units, rateNQT);

    List<CurrencySellOffer> currencySellOffers = new ArrayList<>();
    try (DbIterator<CurrencySellOffer> offers =
        CurrencySellOffer.getOffers(
            new ValidOffersDbClause(currencyId, rateNQT, false),
            0,
            -1,
            " ORDER BY rate ASC, creation_height ASC, transaction_height ASC, transaction_index ASC ")) {
      for (CurrencySellOffer offer : offers) {
        currencySellOffers.add(offer);
      }
    }

    for (CurrencySellOffer offer : currencySellOffers) {
      if (remainingAmountNQT == 0) {
        break;
      }
      long curUnits =
          Math.min(
              Math.min(remainingAmountNQT / offer.getRateNQT(), offer.getSupply()),
              offer.getLimit());
      if (curUnits == 0) {
        continue;
      }
      long curAmountNQT = Math.multiplyExact(curUnits, offer.getRateNQT());

      extraUnits = Math.addExact(extraUnits, curUnits);
      remainingAmountNQT = Math.subtractExact(remainingAmountNQT, curAmountNQT);

      offer.decreaseLimitAndSupply(curUnits);
      long excess = offer.getCounterOffer().increaseSupply(curUnits);

      Account counterAccount = Account.getAccount(offer.getAccountId());
      counterAccount.addToBalanceNQT(curAmountNQT);
      counterAccount.addToUnconfirmedBalanceNQT(
          Math.addExact(
              Math.multiplyExact(
                  curUnits - excess, offer.getRateNQT() - offer.getCounterOffer().getRateNQT()),
              Math.multiplyExact(excess, offer.getRateNQT())));
      counterAccount.addToCurrencyUnits(currencyId, -curUnits);
      Exchange.addExchange(
          transaction, currencyId, offer, offer.getAccountId(), account.getId(), curUnits);
    }

    account.addToCurrencyAndUnconfirmedCurrencyUnits(currencyId, extraUnits);
    account.addToBalanceNQT(-(Math.multiplyExact(units, rateNQT) - remainingAmountNQT));
    account.addToUnconfirmedBalanceNQT(remainingAmountNQT);
  }
示例#2
1
  static {
    if (userServer != null) {
      Account.addListener(
          account -> {
            JSONObject response = new JSONObject();
            response.put("response", "setBalance");
            response.put("balanceNQT", account.getUnconfirmedBalanceNQT());
            byte[] accountPublicKey = account.getPublicKey();
            Users.users
                .values()
                .forEach(
                    user -> {
                      if (user.getSecretPhrase() != null
                          && Arrays.equals(user.getPublicKey(), accountPublicKey)) {
                        user.send(response);
                      }
                    });
          },
          Account.Event.UNCONFIRMED_BALANCE);

      Peers.addListener(
          peer -> {
            JSONObject response = new JSONObject();
            JSONArray removedActivePeers = new JSONArray();
            JSONObject removedActivePeer = new JSONObject();
            removedActivePeer.put("index", Users.getIndex(peer));
            removedActivePeers.add(removedActivePeer);
            response.put("removedActivePeers", removedActivePeers);
            JSONArray removedKnownPeers = new JSONArray();
            JSONObject removedKnownPeer = new JSONObject();
            removedKnownPeer.put("index", Users.getIndex(peer));
            removedKnownPeers.add(removedKnownPeer);
            response.put("removedKnownPeers", removedKnownPeers);
            JSONArray addedBlacklistedPeers = new JSONArray();
            JSONObject addedBlacklistedPeer = new JSONObject();
            addedBlacklistedPeer.put("index", Users.getIndex(peer));
            addedBlacklistedPeer.put("address", peer.getHost());
            addedBlacklistedPeer.put(
                "announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true));
            addedBlacklistedPeer.put("software", peer.getSoftware());
            addedBlacklistedPeers.add(addedBlacklistedPeer);
            response.put("addedBlacklistedPeers", addedBlacklistedPeers);
            Users.sendNewDataToAll(response);
          },
          Peers.Event.BLACKLIST);

      Peers.addListener(
          peer -> {
            JSONObject response = new JSONObject();
            JSONArray removedActivePeers = new JSONArray();
            JSONObject removedActivePeer = new JSONObject();
            removedActivePeer.put("index", Users.getIndex(peer));
            removedActivePeers.add(removedActivePeer);
            response.put("removedActivePeers", removedActivePeers);
            JSONArray addedKnownPeers = new JSONArray();
            JSONObject addedKnownPeer = new JSONObject();
            addedKnownPeer.put("index", Users.getIndex(peer));
            addedKnownPeer.put("address", peer.getHost());
            addedKnownPeer.put(
                "announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true));
            addedKnownPeer.put("software", peer.getSoftware());
            addedKnownPeers.add(addedKnownPeer);
            response.put("addedKnownPeers", addedKnownPeers);
            Users.sendNewDataToAll(response);
          },
          Peers.Event.DEACTIVATE);

      Peers.addListener(
          peer -> {
            JSONObject response = new JSONObject();
            JSONArray removedBlacklistedPeers = new JSONArray();
            JSONObject removedBlacklistedPeer = new JSONObject();
            removedBlacklistedPeer.put("index", Users.getIndex(peer));
            removedBlacklistedPeers.add(removedBlacklistedPeer);
            response.put("removedBlacklistedPeers", removedBlacklistedPeers);
            JSONArray addedKnownPeers = new JSONArray();
            JSONObject addedKnownPeer = new JSONObject();
            addedKnownPeer.put("index", Users.getIndex(peer));
            addedKnownPeer.put("address", peer.getHost());
            addedKnownPeer.put(
                "announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true));
            addedKnownPeer.put("software", peer.getSoftware());
            addedKnownPeers.add(addedKnownPeer);
            response.put("addedKnownPeers", addedKnownPeers);
            Users.sendNewDataToAll(response);
          },
          Peers.Event.UNBLACKLIST);

      Peers.addListener(
          peer -> {
            JSONObject response = new JSONObject();
            JSONArray removedKnownPeers = new JSONArray();
            JSONObject removedKnownPeer = new JSONObject();
            removedKnownPeer.put("index", Users.getIndex(peer));
            removedKnownPeers.add(removedKnownPeer);
            response.put("removedKnownPeers", removedKnownPeers);
            Users.sendNewDataToAll(response);
          },
          Peers.Event.REMOVE);

      Peers.addListener(
          peer -> {
            JSONObject response = new JSONObject();
            JSONArray changedActivePeers = new JSONArray();
            JSONObject changedActivePeer = new JSONObject();
            changedActivePeer.put("index", Users.getIndex(peer));
            changedActivePeer.put("downloaded", peer.getDownloadedVolume());
            changedActivePeers.add(changedActivePeer);
            response.put("changedActivePeers", changedActivePeers);
            Users.sendNewDataToAll(response);
          },
          Peers.Event.DOWNLOADED_VOLUME);

      Peers.addListener(
          peer -> {
            JSONObject response = new JSONObject();
            JSONArray changedActivePeers = new JSONArray();
            JSONObject changedActivePeer = new JSONObject();
            changedActivePeer.put("index", Users.getIndex(peer));
            changedActivePeer.put("uploaded", peer.getUploadedVolume());
            changedActivePeers.add(changedActivePeer);
            response.put("changedActivePeers", changedActivePeers);
            Users.sendNewDataToAll(response);
          },
          Peers.Event.UPLOADED_VOLUME);

      Peers.addListener(
          peer -> {
            JSONObject response = new JSONObject();
            JSONArray changedActivePeers = new JSONArray();
            JSONObject changedActivePeer = new JSONObject();
            changedActivePeer.put("index", Users.getIndex(peer));
            changedActivePeer.put("weight", peer.getWeight());
            changedActivePeers.add(changedActivePeer);
            response.put("changedActivePeers", changedActivePeers);
            Users.sendNewDataToAll(response);
          },
          Peers.Event.WEIGHT);

      Peers.addListener(
          peer -> {
            JSONObject response = new JSONObject();
            JSONArray removedKnownPeers = new JSONArray();
            JSONObject removedKnownPeer = new JSONObject();
            removedKnownPeer.put("index", Users.getIndex(peer));
            removedKnownPeers.add(removedKnownPeer);
            response.put("removedKnownPeers", removedKnownPeers);
            JSONArray addedActivePeers = new JSONArray();
            JSONObject addedActivePeer = new JSONObject();
            addedActivePeer.put("index", Users.getIndex(peer));
            if (peer.getState() != Peer.State.CONNECTED) {
              addedActivePeer.put("disconnected", true);
            }
            addedActivePeer.put("address", peer.getHost());
            addedActivePeer.put(
                "announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true));
            addedActivePeer.put("weight", peer.getWeight());
            addedActivePeer.put("downloaded", peer.getDownloadedVolume());
            addedActivePeer.put("uploaded", peer.getUploadedVolume());
            addedActivePeer.put("software", peer.getSoftware());
            addedActivePeers.add(addedActivePeer);
            response.put("addedActivePeers", addedActivePeers);
            Users.sendNewDataToAll(response);
          },
          Peers.Event.ADDED_ACTIVE_PEER);

      Peers.addListener(
          peer -> {
            JSONObject response = new JSONObject();
            JSONArray changedActivePeers = new JSONArray();
            JSONObject changedActivePeer = new JSONObject();
            changedActivePeer.put("index", Users.getIndex(peer));
            changedActivePeer.put(
                peer.getState() == Peer.State.CONNECTED ? "connected" : "disconnected", true);
            changedActivePeer.put(
                "announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true));
            changedActivePeers.add(changedActivePeer);
            response.put("changedActivePeers", changedActivePeers);
            Users.sendNewDataToAll(response);
          },
          Peers.Event.CHANGED_ACTIVE_PEER);

      Peers.addListener(
          peer -> {
            JSONObject response = new JSONObject();
            JSONArray addedKnownPeers = new JSONArray();
            JSONObject addedKnownPeer = new JSONObject();
            addedKnownPeer.put("index", Users.getIndex(peer));
            addedKnownPeer.put("address", peer.getHost());
            addedKnownPeer.put(
                "announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true));
            addedKnownPeer.put("software", peer.getSoftware());
            addedKnownPeers.add(addedKnownPeer);
            response.put("addedKnownPeers", addedKnownPeers);
            Users.sendNewDataToAll(response);
          },
          Peers.Event.NEW_PEER);

      Nxt.getTransactionProcessor()
          .addListener(
              transactions -> {
                JSONObject response = new JSONObject();
                JSONArray removedUnconfirmedTransactions = new JSONArray();
                for (Transaction transaction : transactions) {
                  JSONObject removedUnconfirmedTransaction = new JSONObject();
                  removedUnconfirmedTransaction.put("index", Users.getIndex(transaction));
                  removedUnconfirmedTransactions.add(removedUnconfirmedTransaction);
                }
                response.put("removedUnconfirmedTransactions", removedUnconfirmedTransactions);
                Users.sendNewDataToAll(response);
              },
              TransactionProcessor.Event.REMOVED_UNCONFIRMED_TRANSACTIONS);

      Nxt.getTransactionProcessor()
          .addListener(
              transactions -> {
                JSONObject response = new JSONObject();
                JSONArray addedUnconfirmedTransactions = new JSONArray();
                for (Transaction transaction : transactions) {
                  JSONObject addedUnconfirmedTransaction = new JSONObject();
                  addedUnconfirmedTransaction.put("index", Users.getIndex(transaction));
                  addedUnconfirmedTransaction.put("timestamp", transaction.getTimestamp());
                  addedUnconfirmedTransaction.put("deadline", transaction.getDeadline());
                  addedUnconfirmedTransaction.put(
                      "recipient", Long.toUnsignedString(transaction.getRecipientId()));
                  addedUnconfirmedTransaction.put("amountNQT", transaction.getAmountNQT());
                  addedUnconfirmedTransaction.put("feeNQT", transaction.getFeeNQT());
                  addedUnconfirmedTransaction.put(
                      "sender", Long.toUnsignedString(transaction.getSenderId()));
                  addedUnconfirmedTransaction.put("id", transaction.getStringId());
                  addedUnconfirmedTransactions.add(addedUnconfirmedTransaction);
                }
                response.put("addedUnconfirmedTransactions", addedUnconfirmedTransactions);
                Users.sendNewDataToAll(response);
              },
              TransactionProcessor.Event.ADDED_UNCONFIRMED_TRANSACTIONS);

      Nxt.getTransactionProcessor()
          .addListener(
              transactions -> {
                JSONObject response = new JSONObject();
                JSONArray addedConfirmedTransactions = new JSONArray();
                for (Transaction transaction : transactions) {
                  JSONObject addedConfirmedTransaction = new JSONObject();
                  addedConfirmedTransaction.put("index", Users.getIndex(transaction));
                  addedConfirmedTransaction.put("blockTimestamp", transaction.getBlockTimestamp());
                  addedConfirmedTransaction.put("transactionTimestamp", transaction.getTimestamp());
                  addedConfirmedTransaction.put(
                      "sender", Long.toUnsignedString(transaction.getSenderId()));
                  addedConfirmedTransaction.put(
                      "recipient", Long.toUnsignedString(transaction.getRecipientId()));
                  addedConfirmedTransaction.put("amountNQT", transaction.getAmountNQT());
                  addedConfirmedTransaction.put("feeNQT", transaction.getFeeNQT());
                  addedConfirmedTransaction.put("id", transaction.getStringId());
                  addedConfirmedTransactions.add(addedConfirmedTransaction);
                }
                response.put("addedConfirmedTransactions", addedConfirmedTransactions);
                Users.sendNewDataToAll(response);
              },
              TransactionProcessor.Event.ADDED_CONFIRMED_TRANSACTIONS);

      Nxt.getBlockchainProcessor()
          .addListener(
              block -> {
                JSONObject response = new JSONObject();
                JSONArray addedOrphanedBlocks = new JSONArray();
                JSONObject addedOrphanedBlock = new JSONObject();
                addedOrphanedBlock.put("index", Users.getIndex(block));
                addedOrphanedBlock.put("timestamp", block.getTimestamp());
                addedOrphanedBlock.put("numberOfTransactions", block.getTransactions().size());
                addedOrphanedBlock.put("totalAmountNQT", block.getTotalAmountNQT());
                addedOrphanedBlock.put("totalFeeNQT", block.getTotalFeeNQT());
                addedOrphanedBlock.put("payloadLength", block.getPayloadLength());
                addedOrphanedBlock.put("generator", Long.toUnsignedString(block.getGeneratorId()));
                addedOrphanedBlock.put("height", block.getHeight());
                addedOrphanedBlock.put("version", block.getVersion());
                addedOrphanedBlock.put("block", block.getStringId());
                addedOrphanedBlock.put(
                    "baseTarget",
                    BigInteger.valueOf(block.getBaseTarget())
                        .multiply(BigInteger.valueOf(100000))
                        .divide(BigInteger.valueOf(Constants.INITIAL_BASE_TARGET)));
                addedOrphanedBlocks.add(addedOrphanedBlock);
                response.put("addedOrphanedBlocks", addedOrphanedBlocks);
                Users.sendNewDataToAll(response);
              },
              BlockchainProcessor.Event.BLOCK_POPPED);

      Nxt.getBlockchainProcessor()
          .addListener(
              block -> {
                JSONObject response = new JSONObject();
                JSONArray addedRecentBlocks = new JSONArray();
                JSONObject addedRecentBlock = new JSONObject();
                addedRecentBlock.put("index", Users.getIndex(block));
                addedRecentBlock.put("timestamp", block.getTimestamp());
                addedRecentBlock.put("numberOfTransactions", block.getTransactions().size());
                addedRecentBlock.put("totalAmountNQT", block.getTotalAmountNQT());
                addedRecentBlock.put("totalFeeNQT", block.getTotalFeeNQT());
                addedRecentBlock.put("payloadLength", block.getPayloadLength());
                addedRecentBlock.put("generator", Long.toUnsignedString(block.getGeneratorId()));
                addedRecentBlock.put("height", block.getHeight());
                addedRecentBlock.put("version", block.getVersion());
                addedRecentBlock.put("block", block.getStringId());
                addedRecentBlock.put(
                    "baseTarget",
                    BigInteger.valueOf(block.getBaseTarget())
                        .multiply(BigInteger.valueOf(100000))
                        .divide(BigInteger.valueOf(Constants.INITIAL_BASE_TARGET)));
                addedRecentBlocks.add(addedRecentBlock);
                response.put("addedRecentBlocks", addedRecentBlocks);
                Users.sendNewDataToAll(response);
              },
              BlockchainProcessor.Event.BLOCK_PUSHED);

      Generator.addListener(
          generator -> {
            JSONObject response = new JSONObject();
            response.put("response", "setBlockGenerationDeadline");
            response.put("deadline", generator.getDeadline());
            users
                .values()
                .forEach(
                    user -> {
                      if (Arrays.equals(generator.getPublicKey(), user.getPublicKey())) {
                        user.send(response);
                      }
                    });
          },
          Generator.Event.GENERATION_DEADLINE);
    }
  }
示例#3
0
 void leaseEffectiveBalance(long lesseeId, short period) {
   Account lessee = Account.getAccount(lesseeId);
   if (lessee != null && lessee.getPublicKey() != null) {
     int height = Nxt.getBlockchain().getHeight();
     if (currentLeasingHeightFrom == Integer.MAX_VALUE) {
       currentLeasingHeightFrom = height + 1440;
       currentLeasingHeightTo = currentLeasingHeightFrom + period;
       currentLesseeId = lesseeId;
       nextLeasingHeightFrom = Integer.MAX_VALUE;
       accountTable.insert(this);
       leaseListeners.notify(
           new AccountLease(
               this.getId(), lesseeId, currentLeasingHeightFrom, currentLeasingHeightTo),
           Event.LEASE_SCHEDULED);
     } else {
       nextLeasingHeightFrom = height + 1440;
       if (nextLeasingHeightFrom < currentLeasingHeightTo) {
         nextLeasingHeightFrom = currentLeasingHeightTo;
       }
       nextLeasingHeightTo = nextLeasingHeightFrom + period;
       nextLesseeId = lesseeId;
       accountTable.insert(this);
       leaseListeners.notify(
           new AccountLease(this.getId(), lesseeId, nextLeasingHeightFrom, nextLeasingHeightTo),
           Event.LEASE_SCHEDULED);
     }
   }
 }
  static void removeOffer(CurrencyBuyOffer buyOffer) {
    CurrencySellOffer sellOffer = buyOffer.getCounterOffer();

    CurrencyBuyOffer.remove(buyOffer);
    CurrencySellOffer.remove(sellOffer);

    Account account = Account.getAccount(buyOffer.getAccountId());
    account.addToUnconfirmedBalanceNQT(
        Math.multiplyExact(buyOffer.getSupply(), buyOffer.getRateNQT()));
    account.addToUnconfirmedCurrencyUnits(buyOffer.getCurrencyId(), sellOffer.getSupply());
  }
示例#5
0
 @Override
 JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {
   long orderId = ParameterParser.getUnsignedLong(req, "order", true);
   Account account = ParameterParser.getSenderAccount(req);
   Order.Ask orderData = Order.Ask.getAskOrder(orderId);
   if (orderData == null || orderData.getAccountId() != account.getId()) {
     return UNKNOWN_ORDER;
   }
   Attachment attachment = new Attachment.ColoredCoinsAskOrderCancellation(orderId);
   return createTransaction(req, account, attachment);
 }
示例#6
0
  @Override
  JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {

    long recipientId = ParameterParser.getRecipientId(req);
    Account recipientAccount = Account.getAccount(recipientId);
    if (recipientAccount == null || recipientAccount.getPublicKey() == null) {
      return INCORRECT_RECIPIENT;
    }

    EncryptedData encryptedData = ParameterParser.getEncryptedMessage(req, recipientAccount);
    return JSONData.encryptedData(encryptedData);
  }
示例#7
0
 @Override
 boolean applyAttachmentUnconfirmed(Transaction transaction, Account senderAccount) {
   Attachment.MonetarySystemExchangeSell attachment =
       (Attachment.MonetarySystemExchangeSell) transaction.getAttachment();
   if (senderAccount.getUnconfirmedCurrencyUnits(attachment.getCurrencyId())
       >= attachment.getUnits()) {
     senderAccount.addToUnconfirmedCurrencyUnits(
         attachment.getCurrencyId(), -attachment.getUnits());
     return true;
   }
   return false;
 }
示例#8
0
 @Override
 boolean applyAttachmentUnconfirmed(Transaction transaction, Account senderAccount) {
   Attachment.MonetarySystemExchangeBuy attachment =
       (Attachment.MonetarySystemExchangeBuy) transaction.getAttachment();
   if (senderAccount.getUnconfirmedBalanceNQT()
       >= Math.multiplyExact(attachment.getUnits(), attachment.getRateNQT())) {
     senderAccount.addToUnconfirmedBalanceNQT(
         -Math.multiplyExact(attachment.getUnits(), attachment.getRateNQT()));
     return true;
   }
   return false;
 }
示例#9
0
 @Override
 void undoAttachmentUnconfirmed(Transaction transaction, Account senderAccount) {
   Attachment.MonetarySystemPublishExchangeOffer attachment =
       (Attachment.MonetarySystemPublishExchangeOffer) transaction.getAttachment();
   senderAccount.addToUnconfirmedBalanceNQT(
       Math.multiplyExact(attachment.getInitialBuySupply(), attachment.getBuyRateNQT()));
   Currency currency = Currency.getCurrency(attachment.getCurrencyId());
   if (currency != null) {
     senderAccount.addToUnconfirmedCurrencyUnits(
         attachment.getCurrencyId(), attachment.getInitialSellSupply());
   }
 }
示例#10
0
 @Override
 boolean applyAttachmentUnconfirmed(Transaction transaction, Account senderAccount) {
   Attachment.MonetarySystemCurrencyTransfer attachment =
       (Attachment.MonetarySystemCurrencyTransfer) transaction.getAttachment();
   if (attachment.getUnits()
       > senderAccount.getUnconfirmedCurrencyUnits(attachment.getCurrencyId())) {
     return false;
   }
   senderAccount.addToUnconfirmedCurrencyUnits(
       attachment.getCurrencyId(), -attachment.getUnits());
   return true;
 }
示例#11
0
 @Override
 boolean applyAttachmentUnconfirmed(Transaction transaction, Account senderAccount) {
   Attachment.MonetarySystemReserveIncrease attachment =
       (Attachment.MonetarySystemReserveIncrease) transaction.getAttachment();
   Currency currency = Currency.getCurrency(attachment.getCurrencyId());
   if (senderAccount.getUnconfirmedBalanceNQT()
       >= Math.multiplyExact(
           currency.getReserveSupply(), attachment.getAmountPerUnitNQT())) {
     senderAccount.addToUnconfirmedBalanceNQT(
         -Math.multiplyExact(currency.getReserveSupply(), attachment.getAmountPerUnitNQT()));
     return true;
   }
   return false;
 }
示例#12
0
 @Override
 boolean applyAttachmentUnconfirmed(Transaction transaction, Account senderAccount) {
   Attachment.MonetarySystemReserveClaim attachment =
       (Attachment.MonetarySystemReserveClaim) transaction.getAttachment();
   if (senderAccount.getUnconfirmedCurrencyUnits(attachment.getCurrencyId())
       >= attachment.getUnits()) {
     senderAccount.addToUnconfirmedCurrencyUnits(
         getLedgerEvent(),
         transaction.getId(),
         attachment.getCurrencyId(),
         -attachment.getUnits());
     return true;
   }
   return false;
 }
示例#13
0
 public static Account getAccount(byte[] publicKey) {
   Account account = accountTable.get(accountDbKeyFactory.newKey(getId(publicKey)));
   if (account == null) {
     return null;
   }
   if (account.getPublicKey() == null || Arrays.equals(account.getPublicKey(), publicKey)) {
     return account;
   }
   throw new RuntimeException(
       "DUPLICATE KEY for account "
           + Convert.toUnsignedLong(account.getId())
           + " existing key "
           + Convert.toHexString(account.getPublicKey())
           + " new key "
           + Convert.toHexString(publicKey));
 }
示例#14
0
 @Override
 void undoAttachmentUnconfirmed(Transaction transaction, Account senderAccount) {
   Attachment.MonetarySystemExchangeBuy attachment =
       (Attachment.MonetarySystemExchangeBuy) transaction.getAttachment();
   senderAccount.addToUnconfirmedBalanceNQT(
       Math.multiplyExact(attachment.getUnits(), attachment.getRateNQT()));
 }
示例#15
0
 @Override
 boolean applyAttachmentUnconfirmed(Transaction transaction, Account senderAccount) {
   Attachment.MonetarySystemPublishExchangeOffer attachment =
       (Attachment.MonetarySystemPublishExchangeOffer) transaction.getAttachment();
   if (senderAccount.getUnconfirmedBalanceNQT()
           >= Math.multiplyExact(
               attachment.getInitialBuySupply(), attachment.getBuyRateNQT())
       && senderAccount.getUnconfirmedCurrencyUnits(attachment.getCurrencyId())
           >= attachment.getInitialSellSupply()) {
     senderAccount.addToUnconfirmedBalanceNQT(
         -Math.multiplyExact(attachment.getInitialBuySupply(), attachment.getBuyRateNQT()));
     senderAccount.addToUnconfirmedCurrencyUnits(
         attachment.getCurrencyId(), -attachment.getInitialSellSupply());
     return true;
   }
   return false;
 }
示例#16
0
 @Override
 void applyAttachment(
     Transaction transaction, Account senderAccount, Account recipientAccount) {
   Attachment.MonetarySystemCurrencyIssuance attachment =
       (Attachment.MonetarySystemCurrencyIssuance) transaction.getAttachment();
   Currency.addCurrency(transaction, senderAccount, attachment);
   senderAccount.addToCurrencyAndUnconfirmedCurrencyUnits(
       transaction.getId(), attachment.getInitialSupply());
 }
示例#17
0
  @Override
  protected JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {

    DigitalGoodsStore.Goods goods = ParameterParser.getGoods(req);
    if (goods.isDelisted()) {
      return UNKNOWN_GOODS;
    }

    int quantity = ParameterParser.getGoodsQuantity(req);
    if (quantity > goods.getQuantity()) {
      return INCORRECT_PURCHASE_QUANTITY;
    }

    long priceNQT = ParameterParser.getPriceNQT(req);
    if (priceNQT != goods.getPriceNQT()) {
      return INCORRECT_PURCHASE_PRICE;
    }

    String deliveryDeadlineString =
        Convert.emptyToNull(req.getParameter("deliveryDeadlineTimestamp"));
    if (deliveryDeadlineString == null) {
      return MISSING_DELIVERY_DEADLINE_TIMESTAMP;
    }
    int deliveryDeadline;
    try {
      deliveryDeadline = Integer.parseInt(deliveryDeadlineString);
      if (deliveryDeadline <= Nxt.getEpochTime()) {
        return INCORRECT_DELIVERY_DEADLINE_TIMESTAMP;
      }
    } catch (NumberFormatException e) {
      return INCORRECT_DELIVERY_DEADLINE_TIMESTAMP;
    }

    Account buyerAccount = ParameterParser.getSenderAccount(req);
    Account sellerAccount = Account.getAccount(goods.getSellerId());

    Attachment attachment =
        new Attachment.DigitalGoodsPurchase(goods.getId(), quantity, priceNQT, deliveryDeadline);
    try {
      return createTransaction(req, buyerAccount, sellerAccount.getId(), 0, attachment);
    } catch (NxtException.InsufficientBalanceException e) {
      return JSONResponses.NOT_ENOUGH_FUNDS;
    }
  }
示例#18
0
 @Override
 void undoAttachmentUnconfirmed(Transaction transaction, Account senderAccount) {
   Attachment.MonetarySystemExchangeSell attachment =
       (Attachment.MonetarySystemExchangeSell) transaction.getAttachment();
   Currency currency = Currency.getCurrency(attachment.getCurrencyId());
   if (currency != null) {
     senderAccount.addToUnconfirmedCurrencyUnits(
         attachment.getCurrencyId(), attachment.getUnits());
   }
 }
示例#19
0
  @Override
  JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {

    long assetId = ParameterParser.getUnsignedLong(req, "asset", true);
    int height = ParameterParser.getHeight(req);

    JSONObject response = new JSONObject();
    response.put("numberOfAccounts", Account.getAssetAccountCount(assetId, height));
    return response;
  }
示例#20
0
 @Override
 void undoAttachmentUnconfirmed(Transaction transaction, Account senderAccount) {
   Attachment.MonetarySystemCurrencyTransfer attachment =
       (Attachment.MonetarySystemCurrencyTransfer) transaction.getAttachment();
   Currency currency = Currency.getCurrency(attachment.getCurrencyId());
   if (currency != null) {
     senderAccount.addToUnconfirmedCurrencyUnits(
         getLedgerEvent(),
         transaction.getId(),
         attachment.getCurrencyId(),
         attachment.getUnits());
   }
 }
示例#21
0
 @Override
 public int getBlockCount(Account account) {
   try (Connection con = Db.db.getConnection();
       PreparedStatement pstmt =
           con.prepareStatement("SELECT COUNT(*) FROM block WHERE generator_id = ?")) {
     pstmt.setLong(1, account.getId());
     try (ResultSet rs = pstmt.executeQuery()) {
       rs.next();
       return rs.getInt(1);
     }
   } catch (SQLException e) {
     throw new RuntimeException(e.toString(), e);
   }
 }
  public static Transaction create(
      IAccount sender,
      Long order,
      short deadline,
      int fee,
      Long referencedTransaction,
      NXTService nxt)
      throws TransactionException, ValidationException {

    String secretPhrase = sender.getPrivateKey();
    byte[] publicKey = Crypto.getPublicKey(secretPhrase);

    if ((fee <= 0) || (fee >= 1000000000L))
      throw new TransactionException(TransactionException.INCORRECT_FEE);

    if ((deadline < 1) || (deadline > 1440))
      throw new TransactionException(TransactionException.INCORRECT_DEADLINE);

    Account account = Account.getAccount(publicKey);
    if (account == null) throw new TransactionException(TransactionException.INTERNAL_ERROR);

    Order.Ask orderData = Order.Ask.getAskOrder(order);
    if (orderData == null || !orderData.getAccount().getId().equals(account.getId()))
      throw new TransactionException(TransactionException.UNKNOWN_ORDER);

    Attachment attachment = new Attachment.ColoredCoinsAskOrderCancellation(order);

    Transaction transaction =
        Nxt.getTransactionProcessor()
            .newTransaction(
                deadline, publicKey, Genesis.CREATOR_ID, 0, fee, referencedTransaction, attachment);
    transaction.sign(secretPhrase);

    nxt.broacastTransaction(transaction);

    return transaction;
  }
示例#23
0
 @Override
 void undoAttachmentUnconfirmed(Transaction transaction, Account senderAccount) {
   Attachment.MonetarySystemReserveIncrease attachment =
       (Attachment.MonetarySystemReserveIncrease) transaction.getAttachment();
   long reserveSupply;
   Currency currency = Currency.getCurrency(attachment.getCurrencyId());
   if (currency != null) {
     reserveSupply = currency.getReserveSupply();
   } else { // currency must have been deleted, get reserve supply from the original issuance
            // transaction
     Transaction currencyIssuance =
         Nxt.getBlockchain().getTransaction(attachment.getCurrencyId());
     Attachment.MonetarySystemCurrencyIssuance currencyIssuanceAttachment =
         (Attachment.MonetarySystemCurrencyIssuance) currencyIssuance.getAttachment();
     reserveSupply = currencyIssuanceAttachment.getReserveSupply();
   }
   senderAccount.addToUnconfirmedBalanceNQT(
       Math.multiplyExact(reserveSupply, attachment.getAmountPerUnitNQT()));
 }
示例#24
0
 private Hallmark(
     String hallmarkString,
     byte[] publicKey,
     byte[] signature,
     String host,
     int weight,
     int date,
     boolean isValid)
     throws URISyntaxException {
   this.hallmarkString = hallmarkString;
   URI uri = new URI("http://" + host);
   this.host = uri.getHost();
   this.port = uri.getPort() == -1 ? Peers.getDefaultPeerPort() : uri.getPort();
   this.publicKey = publicKey;
   this.accountId = Account.getId(publicKey);
   this.signature = signature;
   this.weight = weight;
   this.date = date;
   this.isValid = isValid;
 }
示例#25
0
 @Override
 public DbIterator<BlockImpl> getBlocks(Account account, int timestamp, int from, int to) {
   Connection con = null;
   try {
     con = Db.db.getConnection();
     PreparedStatement pstmt =
         con.prepareStatement(
             "SELECT * FROM block WHERE generator_id = ? "
                 + (timestamp > 0 ? " AND timestamp >= ? " : " ")
                 + "ORDER BY height DESC"
                 + DbUtils.limitsClause(from, to));
     int i = 0;
     pstmt.setLong(++i, account.getId());
     if (timestamp > 0) {
       pstmt.setInt(++i, timestamp);
     }
     DbUtils.setLimits(++i, pstmt, from, to);
     return getBlocks(con, pstmt);
   } catch (SQLException e) {
     DbUtils.close(con);
     throw new RuntimeException(e.toString(), e);
   }
 }
示例#26
0
 public DbIterator<Account.AccountAsset> getAccounts(int height, int from, int to) {
   if (height < 0) {
     return getAccounts(from, to);
   }
   return Account.getAssetAccounts(this.assetId, height, from, to);
 }
示例#27
0
  @Override
  public DbIterator<TransactionImpl> getTransactions(
      Account account,
      int numberOfConfirmations,
      byte type,
      byte subtype,
      int blockTimestamp,
      boolean withMessage,
      boolean phasedOnly,
      boolean nonPhasedOnly,
      int from,
      int to) {
    if (phasedOnly && nonPhasedOnly) {
      throw new IllegalArgumentException(
          "At least one of phasedOnly or nonPhasedOnly must be false");
    }
    int height =
        numberOfConfirmations > 0 ? getHeight() - numberOfConfirmations : Integer.MAX_VALUE;
    if (height < 0) {
      throw new IllegalArgumentException(
          "Number of confirmations required "
              + numberOfConfirmations
              + " exceeds current blockchain height "
              + getHeight());
    }
    Connection con = null;
    try {
      StringBuilder buf = new StringBuilder();
      buf.append("SELECT * FROM transaction WHERE recipient_id = ? AND sender_id <> ? ");
      if (blockTimestamp > 0) {
        buf.append("AND block_timestamp >= ? ");
      }
      if (type >= 0) {
        buf.append("AND type = ? ");
        if (subtype >= 0) {
          buf.append("AND subtype = ? ");
        }
      }
      if (height < Integer.MAX_VALUE) {
        buf.append("AND height <= ? ");
      }
      if (withMessage) {
        buf.append("AND (has_message = TRUE OR has_encrypted_message = TRUE ");
        buf.append(
            "OR ((has_prunable_message = TRUE OR has_prunable_encrypted_message = TRUE) AND timestamp > ?)) ");
      }
      if (phasedOnly) {
        buf.append("AND phased = TRUE ");
      } else if (nonPhasedOnly) {
        buf.append("AND phased = FALSE ");
      }

      buf.append("UNION ALL SELECT * FROM transaction WHERE sender_id = ? ");
      if (blockTimestamp > 0) {
        buf.append("AND block_timestamp >= ? ");
      }
      if (type >= 0) {
        buf.append("AND type = ? ");
        if (subtype >= 0) {
          buf.append("AND subtype = ? ");
        }
      }
      if (height < Integer.MAX_VALUE) {
        buf.append("AND height <= ? ");
      }
      if (withMessage) {
        buf.append(
            "AND (has_message = TRUE OR has_encrypted_message = TRUE OR has_encrypttoself_message = TRUE ");
        buf.append(
            "OR ((has_prunable_message = TRUE OR has_prunable_encrypted_message = TRUE) AND timestamp > ?)) ");
      }
      if (phasedOnly) {
        buf.append("AND phased = TRUE ");
      } else if (nonPhasedOnly) {
        buf.append("AND phased = FALSE ");
      }

      buf.append("ORDER BY block_timestamp DESC, transaction_index DESC");
      buf.append(DbUtils.limitsClause(from, to));
      con = Db.db.getConnection();
      PreparedStatement pstmt;
      int i = 0;
      pstmt = con.prepareStatement(buf.toString());
      pstmt.setLong(++i, account.getId());
      pstmt.setLong(++i, account.getId());
      if (blockTimestamp > 0) {
        pstmt.setInt(++i, blockTimestamp);
      }
      if (type >= 0) {
        pstmt.setByte(++i, type);
        if (subtype >= 0) {
          pstmt.setByte(++i, subtype);
        }
      }
      if (height < Integer.MAX_VALUE) {
        pstmt.setInt(++i, height);
      }
      int prunableExpiration =
          Constants.INCLUDE_EXPIRED_PRUNABLE
              ? 0
              : Nxt.getEpochTime() - Constants.MAX_PRUNABLE_LIFETIME;
      if (withMessage) {
        pstmt.setInt(++i, prunableExpiration);
      }
      pstmt.setLong(++i, account.getId());
      if (blockTimestamp > 0) {
        pstmt.setInt(++i, blockTimestamp);
      }
      if (type >= 0) {
        pstmt.setByte(++i, type);
        if (subtype >= 0) {
          pstmt.setByte(++i, subtype);
        }
      }
      if (height < Integer.MAX_VALUE) {
        pstmt.setInt(++i, height);
      }
      if (withMessage) {
        pstmt.setInt(++i, prunableExpiration);
      }
      DbUtils.setLimits(++i, pstmt, from, to);
      return getTransactions(con, pstmt);
    } catch (SQLException e) {
      DbUtils.close(con);
      throw new RuntimeException(e.toString(), e);
    }
  }
示例#28
0
 @Override
 protected void save(Connection con, Account account) throws SQLException {
   account.save(con);
 }
示例#29
0
 public DbIterator<Account.AccountAsset> getAccounts(int from, int to) {
   return Account.getAssetAccounts(this.assetId, from, to);
 }