/** * Prepare a transaction. * * @param transactionId the transaction id */ void prepare(Transaction t) { storeTransaction(t); Object[] old = openTransactions.get(t.getId()); Object[] v = {Transaction.STATUS_PREPARED, old[1]}; openTransactions.put(t.getId(), v); store.commit(); }
/* abort a transaction, return true if success, false if not */ public boolean abort(Transaction t) { if (!transactionTable.keySet().contains(t)) { System.out.println("Oops where does this transaction come from. " + t.toString()); return false; } System.out.println("ABORTING: " + t.toString()); List<RMmeta> rms = middleware.resourceManagers; synchronized (rms) { for (RMmeta rm : rms) { Socket s = rm.getSocket(); synchronized (s) { try { BufferedReader inFromServer = new BufferedReader(new InputStreamReader(s.getInputStream())); DataOutputStream outToServer = new DataOutputStream(s.getOutputStream()); outToServer.writeBytes("abort," + t.getId() + '\n'); System.out.println(inFromServer.readLine()); } catch (Exception e) { e.printStackTrace(); } } } } this.middleware.lockManager.UnlockAll(t.getId()); t.addCommand("abort", "abort"); transactionTable.remove(t); return true; }
public void testRollback() { Transaction txn = createWorkers(true); printTxStatus(txn); if (txn.isCommited()) { fail("TX Committed. Expected TX rollbacked " + txn.getId()); } else { System.out.println("TX Rollbacked " + txn.getId()); } }
private Vote(Transaction transaction, Attachment.MessagingVoteCasting attachment) { this.id = transaction.getId(); this.dbKey = voteDbKeyFactory.newKey(this.id); this.pollId = attachment.getPollId(); this.voterId = transaction.getSenderId(); this.voteBytes = attachment.getPollVote(); }
/** * Send trace messages to the java.util.logger. Don't rely on the logger alone to conditionalize * whether we send this message, we don't even want to construct the message if the level is not * enabled. */ void trace( Level level, String methodName, Transaction txn, DatabaseEntry key, DatabaseEntry data, LockMode lockMode) throws DatabaseException { if (logger.isLoggable(level)) { StringBuffer sb = new StringBuffer(); sb.append(methodName); if (txn != null) { sb.append(" txnId=").append(txn.getId()); } sb.append(" key=").append(key.dumpData()); if (data != null) { sb.append(" data=").append(data.dumpData()); } if (lockMode != null) { sb.append(" lockMode=").append(lockMode); } logger.log(level, sb.toString()); } }
/* start a transaction and add to transaction table */ public Transaction start() { Transaction t = new Transaction(random.nextInt(Integer.MAX_VALUE)); t.addCommand("start", "start"); ArrayList<RMmeta.RMtype> types = new ArrayList<RMmeta.RMtype>(); transactionTable.put(t, types); types.add(null); List<RMmeta> rms = middleware.resourceManagers; synchronized (rms) { for (RMmeta rm : rms) { Socket s = rm.getSocket(); synchronized (s) { try { BufferedReader inFromServer = new BufferedReader(new InputStreamReader(s.getInputStream())); DataOutputStream outToServer = new DataOutputStream(s.getOutputStream()); outToServer.writeBytes("start," + t.getId() + '\n'); System.out.println(inFromServer.readLine()); } catch (Exception e) { e.printStackTrace(); } } } } return t; }
@Override void applyAttachment( Transaction transaction, Account senderAccount, Account recipientAccount) { Attachment.MonetarySystemCurrencyDeletion attachment = (Attachment.MonetarySystemCurrencyDeletion) transaction.getAttachment(); Currency currency = Currency.getCurrency(attachment.getCurrencyId()); currency.delete(getLedgerEvent(), transaction.getId(), senderAccount); }
@Override void applyAttachment( Transaction transaction, Account senderAccount, Account recipientAccount) { Attachment.MonetarySystemCurrencyMinting attachment = (Attachment.MonetarySystemCurrencyMinting) transaction.getAttachment(); CurrencyMint.mintCurrency( getLedgerEvent(), transaction.getId(), senderAccount, attachment); }
@Override void undoAttachmentUnconfirmed(Transaction transaction, Account senderAccount) { Attachment.MonetarySystemPublishExchangeOffer attachment = (Attachment.MonetarySystemPublishExchangeOffer) transaction.getAttachment(); senderAccount.addToUnconfirmedBalanceNQT( getLedgerEvent(), transaction.getId(), Math.multiplyExact(attachment.getInitialBuySupply(), attachment.getBuyRateNQT())); Currency currency = Currency.getCurrency(attachment.getCurrencyId()); if (currency != null) { senderAccount.addToUnconfirmedCurrencyUnits( getLedgerEvent(), transaction.getId(), attachment.getCurrencyId(), attachment.getInitialSellSupply()); } }
@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()); }
@Override void undoAttachmentUnconfirmed(Transaction transaction, Account senderAccount) { Attachment.MonetarySystemExchangeBuy attachment = (Attachment.MonetarySystemExchangeBuy) transaction.getAttachment(); senderAccount.addToUnconfirmedBalanceNQT( getLedgerEvent(), transaction.getId(), Math.multiplyExact(attachment.getUnits(), attachment.getRateNQT())); }
private Asset(Transaction transaction, Attachment.ColoredCoinsAssetIssuance attachment) { this.assetId = transaction.getId(); this.dbKey = assetDbKeyFactory.newKey(this.assetId); this.accountId = transaction.getSenderId(); this.name = attachment.getName(); this.description = attachment.getDescription(); this.quantityQNT = attachment.getQuantityQNT(); this.decimals = attachment.getDecimals(); }
@Override void applyAttachment( Transaction transaction, Account senderAccount, Account recipientAccount) { Attachment.MonetarySystemReserveClaim attachment = (Attachment.MonetarySystemReserveClaim) transaction.getAttachment(); Currency.claimReserve( getLedgerEvent(), transaction.getId(), senderAccount, attachment.getCurrencyId(), attachment.getUnits()); }
@Override void applyAttachment( Transaction transaction, Account senderAccount, Account recipientAccount) { Attachment.MonetarySystemReserveIncrease attachment = (Attachment.MonetarySystemReserveIncrease) transaction.getAttachment(); Currency.increaseReserve( getLedgerEvent(), transaction.getId(), senderAccount, attachment.getCurrencyId(), attachment.getAmountPerUnitNQT()); }
@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( getLedgerEvent(), transaction.getId(), -Math.multiplyExact(attachment.getInitialBuySupply(), attachment.getBuyRateNQT())); senderAccount.addToUnconfirmedCurrencyUnits( getLedgerEvent(), transaction.getId(), attachment.getCurrencyId(), -attachment.getInitialSellSupply()); return true; } return false; }
@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( getLedgerEvent(), transaction.getId(), attachment.getCurrencyId(), attachment.getUnits()); } }
@Override void applyAttachment( Transaction transaction, Account senderAccount, Account recipientAccount) { Attachment.MonetarySystemCurrencyTransfer attachment = (Attachment.MonetarySystemCurrencyTransfer) transaction.getAttachment(); Currency.transferCurrency( getLedgerEvent(), transaction.getId(), senderAccount, recipientAccount, attachment.getCurrencyId(), attachment.getUnits()); CurrencyTransfer.addTransfer(transaction, attachment); }
@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( getLedgerEvent(), transaction.getId(), -Math.multiplyExact(attachment.getUnits(), attachment.getRateNQT())); return true; } return false; }
/** * @deprecated It has not been possible to implement this method with correct transactional * semantics without incurring a performance penalty on all Database operations. Truncate * functionality has been moved to Environment.truncateDatabase(), which requires that all * Database handles on the database are closed before the truncate operation can execute. */ public int truncate(Transaction txn, boolean countRecords) throws DatabaseException { checkEnv(); checkRequiredDbState(OPEN, "Can't call Database.truncate"); checkWritable("truncate"); Tracer.trace( Level.FINEST, envHandle.getEnvironmentImpl(), "Database.truncate" + ": txnId=" + ((txn == null) ? "null" : Long.toString(txn.getId()))); Locker locker = null; boolean triggerLock = false; boolean operationOk = false; try { locker = LockerFactory.getWritableLocker( envHandle, txn, isTransactional(), true /*retainLocks*/, null); /* * Pass true to always get a read lock on the triggers, so we are * sure that no secondaries are added during truncation. */ acquireTriggerListReadLock(); triggerLock = true; /* Truncate primary. */ int count = truncateInternal(locker, countRecords); /* Truncate secondaries. */ for (int i = 0; i < triggerList.size(); i += 1) { Object obj = triggerList.get(i); if (obj instanceof SecondaryTrigger) { SecondaryDatabase secDb = ((SecondaryTrigger) obj).getDb(); secDb.truncateInternal(locker, false); } } operationOk = true; return count; } finally { if (locker != null) { locker.operationEnd(operationOk); } if (triggerLock) { releaseTriggerListReadLock(); } } }
@Override public void broadcast(Transaction transaction) throws NxtException.ValidationException { if (!transaction.verify()) { throw new NxtException.ValidationException("Transaction signature verification failed"); } List<Transaction> validTransactions = processTransactions(Collections.singletonList((TransactionImpl) transaction), true); if (validTransactions.contains(transaction)) { nonBroadcastedTransactions.put(transaction.getId(), (TransactionImpl) transaction); Logger.logDebugMessage("Accepted new transaction " + transaction.getStringId()); } else { Logger.logDebugMessage("Rejecting double spending transaction " + transaction.getStringId()); throw new NxtException.ValidationException("Double spending transaction"); } }
@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( getLedgerEvent(), transaction.getId(), attachment.getCurrencyId(), -attachment.getUnits()); return true; }
@Override boolean applyAttachmentUnconfirmed(Transaction transaction, Account senderAccount) { Attachment.MonetarySystemExchangeSell attachment = (Attachment.MonetarySystemExchangeSell) transaction.getAttachment(); if (senderAccount.getUnconfirmedCurrencyUnits(attachment.getCurrencyId()) >= attachment.getUnits()) { senderAccount.addToUnconfirmedCurrencyUnits( getLedgerEvent(), transaction.getId(), attachment.getCurrencyId(), -attachment.getUnits()); return true; } return false; }
/** * Send trace messages to the java.util.logger. Don't rely on the logger alone to conditionalize * whether we send this message, we don't even want to construct the message if the level is not * enabled. */ void trace(Level level, String methodName, Transaction txn, CursorConfig config) throws DatabaseException { if (logger.isLoggable(level)) { StringBuffer sb = new StringBuffer(); sb.append(methodName); sb.append(" name=" + getDebugName()); if (txn != null) { sb.append(" txnId=").append(txn.getId()); } if (config != null) { sb.append(" config=").append(config); } logger.log(level, sb.toString()); } }
@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( getLedgerEvent(), transaction.getId(), -Math.multiplyExact(currency.getReserveSupply(), attachment.getAmountPerUnitNQT())); return true; } return false; }
private void storeTransaction(Transaction t) { if (store.getUnsavedPageCount() > MAX_UNSAVED_PAGES) { store.commit(); } if (t.isStored()) { return; } t.setStored(true); long transactionId = t.getId(); Object[] v = {t.getStatus(), null}; openTransactions.put(transactionId, v); openTransactionMap.put(transactionId, t); if (lastTransactionId > lastTransactionIdStored) { lastTransactionIdStored += 32; settings.put(LAST_TRANSACTION_ID, "" + lastTransactionIdStored); } }
public static void createTransaction(Transaction transaction) throws ParseException { try { String query = "insert into transaction_table(business_id, transaction_id, type, category, description, amount, transaction_date, account_balance) values (?,?,?,?,?,?,?,?)"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, 1); preparedStatement.setInt(2, transaction.getId()); preparedStatement.setBoolean(3, transaction.getType()); preparedStatement.setString(4, transaction.getCategory()); preparedStatement.setString(5, transaction.getDescription()); preparedStatement.setFloat(6, transaction.getAmount()); preparedStatement.setString(7, transaction.getTransactionDate()); preparedStatement.setFloat(8, transaction.getAccountBalance()); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }
private static int getTotalTuples(int tableid) { int count = 0; try { Transaction t = new Transaction(); t.start(); SeqScan s = new SeqScan(t.getId(), tableid, null); s.open(); while (s.hasNext()) { s.next(); count++; } t.commit(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } return count; }
public static void updateTransaction(Transaction transaction) throws ParseException { try { String query = "update transaction_table set type=?, category=?, description=?, amount=?, transaction_date=?, account_balance=? where transaction_id=?"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, 1); preparedStatement.setInt(2, transaction.getId()); preparedStatement.setBoolean(3, transaction.getType()); preparedStatement.setString(4, transaction.getCategory()); preparedStatement.setString(5, transaction.getDescription()); preparedStatement.setFloat(6, transaction.getAmount()); preparedStatement.setString(7, transaction.getTransactionDate()); preparedStatement.setFloat(8, transaction.getAccountBalance()); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }
/** * Rollback to an old savepoint. * * @param t the transaction * @param maxLogId the last log id * @param toLogId the log id to roll back to */ void rollbackTo(Transaction t, long maxLogId, long toLogId) { for (long logId = maxLogId - 1; logId >= toLogId; logId--) { Object[] op = undoLog.get(new long[] {t.getId(), logId}); int mapId = ((Integer) op[1]).intValue(); Map<String, String> meta = store.getMetaMap(); String m = meta.get("map." + mapId); String mapName = DataUtils.parseMap(m).get("name"); MVMap<Object, Object[]> map = store.openMap(mapName); Object key = op[2]; Object[] oldValue = (Object[]) op[3]; if (oldValue == null) { // this transaction added the value map.remove(key); } else { // this transaction updated the value map.put(key, oldValue); } undoLog.remove(op); } }
@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( getLedgerEvent(), transaction.getId(), Math.multiplyExact(reserveSupply, attachment.getAmountPerUnitNQT())); }