// transaction must be called within a job transaction.
//
// It pops pending triggers/events, producing invocations or other events along
// the way.
//
// This method may be called multiple times (when the transaction is retried).
777695
func (op *triageOp) transaction(c context.Context, job *Job) error {
	op.txnAttempt++
	if op.txnAttempt == 1 {
		op.debugInfoLog(c, "Started the transaction")
	} else {
		op.debugInfoLog(c, "Retrying the transaction, attempt %d", op.txnAttempt)
	}

	// Reset state collected in the transaction in case this is a retry.
	op.garbage = nil
	op.lastTriage = time.Time{}

	// Tidy ActiveInvocations list by moving all recently finished invocations to
	// FinishedInvocations list.
	tidyOp, err := op.tidyActiveInvocations(c, job)
	if err != nil {
		return err // the error is logged inside already
	}

	// Process pending triggers set by emitting new invocations. Note that this
	// modifies ActiveInvocations list when emitting invocations.
	triggersOp, err := op.processTriggers(c, job)
	if err != nil {
		return err // the error is logged inside already
	}

	// If nothing is running anymore, make sure the cron is ticking again. This is
	// useful for schedules like "with 10min interval" that initiate an invocation
	// after some time after the previous one finishes. This call submits at most
	// one task to TQ. Note that there's no harm in calling this multiple times,
	// only the first call will actually do something.
	if len(job.ActiveInvocations) == 0 {
		op.debugInfoLog(c, "Poking the cron")
		err := pokeCron(c, job, op.dispatcher, func(m *cron.Machine) error {
			m.RewindIfNecessary()
			return nil
		})
		if err != nil {
			op.debugErrLog(c, err, "Failed to rewind the cron machine")
			return err
		}
	}

	// Submit set modifications. This may produce more garbage that we need to
	// cleanup later (outside the transaction).
	popOps := []*dsset.PopOp{}
	if tidyOp != nil {
		popOps = append(popOps, tidyOp)
	}
	if triggersOp != nil {
		popOps = append(popOps, triggersOp)
	}
	op.debugInfoLog(c, "Removing consumed dsset items")
	if op.garbage, err = dsset.FinishPop(c, popOps...); err != nil {
		op.debugErrLog(c, err, "Failed to pop consumed dsset items")
		return err
	}

	op.lastTriage = clock.Now(c).UTC()
	job.LastTriage = op.lastTriage

	op.debugInfoLog(c, "Landing the transaction")
	return nil
}
143150
func (_Chequebook *ChequebookRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
	return _Chequebook.Contract.ChequebookTransactor.contract.Transfer(opts)
}
645070
func (tx *SQLiteTx) Commit() error {
	_, err := tx.c.exec(context.Background(), "COMMIT", nil)
	if err != nil && err.(Error).Code == C.SQLITE_BUSY {
		// sqlite3 will leave the transaction open in this scenario.
		// However, database/sql considers the transaction complete once we
		// return from Commit() - we must clean up to honour its semantics.
		tx.c.exec(context.Background(), "ROLLBACK", nil)
	}
	return err
}
1270690
func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
	b.mu.Lock()
	defer b.mu.Unlock()

	sender, err := types.Sender(types.HomesteadSigner{}, tx)
	if err != nil {
		panic(fmt.Errorf("invalid transaction: %v", err))
	}
	nonce := b.pendingState.GetNonce(sender)
	if tx.Nonce() != nonce {
		panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
	}

	blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
		for _, tx := range b.pendingBlock.Transactions() {
			block.AddTxWithChain(b.blockchain, tx)
		}
		block.AddTxWithChain(b.blockchain, tx)
	})
	statedb, _ := b.blockchain.State()

	b.pendingBlock = blocks[0]
	b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database())
	return nil
}
754764
func (l *TransactionalLatencyInjector) Transaction(ctx context.Context, txns []*TxnEntry) error {
	l.addLatency()
	return l.Transactional.Transaction(ctx, txns)
}
308054
func (w *WalletKit) PublishTransaction(ctx context.Context,
	req *Transaction) (*PublishResponse, error) {

	switch {
	// If the client doesn't specify a transaction, then there's nothing to
	// publish.
	case len(req.TxHex) == 0:
		return nil, fmt.Errorf("must provide a transaction to " +
			"publish")
	}

	tx := &wire.MsgTx{}
	txReader := bytes.NewReader(req.TxHex)
	if err := tx.Deserialize(txReader); err != nil {
		return nil, err
	}

	err := w.cfg.Wallet.PublishTransaction(tx)
	if err != nil {
		return nil, err
	}

	return &PublishResponse{}, nil
}
514322
func (_PublicResolver *PublicResolverRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
	return _PublicResolver.Contract.PublicResolverTransactor.contract.Transact(opts, method, params...)
}
20395
func Transactional(db DB, todo func(f Application) error) error {
	var tx Transaction
	var err error
	if tx, err = db.BeginTransaction(); err != nil {
		log.Error(nil, map[string]interface{}{
			"err": err,
		}, "database BeginTransaction failed!")

		return errors.WithStack(err)
	}

	return func() error {
		errorChan := make(chan error, 1)
		txTimeout := time.After(databaseTransactionTimeout)

		go func(tx Transaction) {
			defer func() {
				if err := recover(); err != nil {
					errorChan <- errors.Errorf("recovered %v. stack: %s", err, debug.Stack())
				}
			}()
			errorChan <- todo(tx)
		}(tx)

		select {
		case err := <-errorChan:
			if err != nil {
				log.Debug(nil, map[string]interface{}{"error": err}, "Rolling back the transaction...")
				tx.Rollback()
				log.Error(nil, map[string]interface{}{
					"err": err,
				}, "database transaction failed!")
				return errors.WithStack(err)
			}

			tx.Commit()
			log.Debug(nil, nil, "Commit the transaction!")
			return nil
		case <-txTimeout:
			log.Debug(nil, nil, "Rolling back the transaction...")
			tx.Rollback()
			log.Error(nil, nil, "database transaction timeout!")
			return errors.New("database transaction timeout")
		}
	}()
}
160531
func (r *DB) Transaction(callback func() error) (err error) {
	var tries int

	// Perform transaction statements
	tries = 0
	for {
		// Start transaction
		if err = r.Begin(); err != nil {
			return
		}

		if err = callback(); err == nil {
			break
		}

		tries++
		if tries > 3 {
			log.Printf("Retried transaction %d times, aborting", tries-1)
			break
		}

		// Break out if the causer is not a MySQL error
		cause, ok := (errors.Cause(err)).(*mysql.MySQLError)
		if !ok {
			log.Printf("Returned error cause is not a MySQLError, %#v", err)
			break
		}

		// restart transaction:
		//   - 1205: lock within transaction (unit tested),
		//   - 1213: deadlock found
		if cause.Number == 1205 || cause.Number == 1213 {
			log.Printf("Restarting transaction (try=%d): %s", tries, cause)
			r.Rollback()
			time.Sleep(50 * time.Millisecond)
			continue
		}
		log.Println("Can't handle transaction error")
		break
	}

	if err != nil {
		r.Rollback()
		return err
	}
	return r.Commit()
}
553637
func (p *peer) SendTransactions(txs types.Transactions) error {
	for _, tx := range txs {
		p.knownTxs.Add(tx.Hash())
	}
	return p2p.Send(p.rw, TxMsg, txs)
}
194688
func GenericTransactionHandler(ctx context.Context, t PseudoTransactional, txns []*TxnEntry) (retErr error) {
	rollbackStack := make([]*TxnEntry, 0, len(txns))
	var dirty bool

	// We walk the transactions in order; each successful operation goes into a
	// LIFO for rollback if we hit an error along the way
TxnWalk:
	for _, txn := range txns {
		switch txn.Operation {
		case DeleteOperation:
			entry, err := t.GetInternal(ctx, txn.Entry.Key)
			if err != nil {
				retErr = multierror.Append(retErr, err)
				dirty = true
				break TxnWalk
			}
			if entry == nil {
				// Nothing to delete or roll back
				continue
			}
			rollbackEntry := &TxnEntry{
				Operation: PutOperation,
				Entry: &Entry{
					Key:   entry.Key,
					Value: entry.Value,
				},
			}
			err = t.DeleteInternal(ctx, txn.Entry.Key)
			if err != nil {
				retErr = multierror.Append(retErr, err)
				dirty = true
				break TxnWalk
			}
			rollbackStack = append([]*TxnEntry{rollbackEntry}, rollbackStack...)

		case PutOperation:
			entry, err := t.GetInternal(ctx, txn.Entry.Key)
			if err != nil {
				retErr = multierror.Append(retErr, err)
				dirty = true
				break TxnWalk
			}
			// Nothing existed so in fact rolling back requires a delete
			var rollbackEntry *TxnEntry
			if entry == nil {
				rollbackEntry = &TxnEntry{
					Operation: DeleteOperation,
					Entry: &Entry{
						Key: txn.Entry.Key,
					},
				}
			} else {
				rollbackEntry = &TxnEntry{
					Operation: PutOperation,
					Entry: &Entry{
						Key:   entry.Key,
						Value: entry.Value,
					},
				}
			}

			err = t.PutInternal(ctx, txn.Entry)
			if err != nil {
				retErr = multierror.Append(retErr, err)
				dirty = true
				break TxnWalk
			}
			rollbackStack = append([]*TxnEntry{rollbackEntry}, rollbackStack...)
		}
	}

	// Need to roll back because we hit an error along the way
	if dirty {
		// While traversing this, if we get an error, we continue anyways in
		// best-effort fashion
		for _, txn := range rollbackStack {
			switch txn.Operation {
			case DeleteOperation:
				err := t.DeleteInternal(ctx, txn.Entry.Key)
				if err != nil {
					retErr = multierror.Append(retErr, err)
				}
			case PutOperation:
				err := t.PutInternal(ctx, txn.Entry)
				if err != nil {
					retErr = multierror.Append(retErr, err)
				}
			}
		}
	}

	return
}
109327
func (pool *TxPool) GetTransactions() (txs types.Transactions, err error) {
	pool.mu.RLock()
	defer pool.mu.RUnlock()

	txs = make(types.Transactions, len(pool.pending))
	i := 0
	for _, tx := range pool.pending {
		txs[i] = tx
		i++
	}
	return txs, nil
}
614679
func finishTransaction(ctx context.Context, exec sqlexec.SQLExecutor, err error) error {
	if err == nil {
		_, err = exec.Execute(ctx, "commit")
	} else {
		_, err1 := exec.Execute(ctx, "rollback")
		terror.Log(errors.Trace(err1))
	}
	return errors.Trace(err)
}
803023
func (self *Bill) transaction(evt *Event) error {
	log.Infof("Event:BILL:transaction")
	result := &bills.BillOpts{}
	_ = result.FillStruct(evt.EventData.M) //we will manage error later
	for k, bp := range bills.BillProviders {
		if !self.skip(k) {
			err := bp.Transaction(result, self.M)
			if err != nil {
				return err
			}
		}
	}
	return nil
}
841011
func (transaction *Transaction) Commit() error {
	var (
		cErr *C.char
	)
	C.rocksdb_transaction_commit(transaction.c, &cErr)
	if cErr != nil {
		defer C.free(unsafe.Pointer(cErr))
		return errors.New(C.GoString(cErr))
	}
	return nil
}
965570
func (t *Transaction) Script(script *redis.Script, args redis.Args, handler ReplyHandler) {
	t.actions = append(t.actions, &Action{
		kind:    scriptAction,
		script:  script,
		args:    args,
		handler: handler,
	})
}
344560
func (w *Wallet) publishTransaction(tx *wire.MsgTx) (*chainhash.Hash, error) {
	chainClient, err := w.requireChainClient()
	if err != nil {
		return nil, err
	}

	txid, err := chainClient.SendRawTransaction(tx, false)
	switch {
	case err == nil:
		return txid, nil

	// Since we have different backends that can be used with the wallet,
	// we'll need to check specific errors for each one.
	//
	// If the transaction is already in the mempool, we can just return now.
	//
	// This error is returned when broadcasting/sending a transaction to a
	// btcd node that already has it in their mempool.
	case strings.Contains(err.Error(), "already have transaction"):
		fallthrough

	// This error is returned when broadcasting a transaction to a bitcoind
	// node that already has it in their mempool.
	case strings.Contains(err.Error(), "txn-already-in-mempool"):
		return txid, nil

	// If the transaction has already confirmed, we can safely remove it
	// from the unconfirmed store as it should already exist within the
	// confirmed store. We'll avoid returning an error as the broadcast was
	// in a sense successful.
	//
	// This error is returned when broadcasting/sending a transaction that
	// has already confirmed to a btcd node.
	case strings.Contains(err.Error(), "transaction already exists"):
		fallthrough

	// This error is returned when broadcasting a transaction that has
	// already confirmed to a bitcoind node.
	case strings.Contains(err.Error(), "txn-already-known"):
		fallthrough

	// This error is returned when sending a transaction that has already
	// confirmed to a bitcoind node over RPC.
	case strings.Contains(err.Error(), "transaction already in block chain"):
		dbErr := walletdb.Update(w.db, func(dbTx walletdb.ReadWriteTx) error {
			txmgrNs := dbTx.ReadWriteBucket(wtxmgrNamespaceKey)
			txRec, err := wtxmgr.NewTxRecordFromMsgTx(tx, time.Now())
			if err != nil {
				return err
			}
			return w.TxStore.RemoveUnminedTx(txmgrNs, txRec)
		})
		if dbErr != nil {
			log.Warnf("Unable to remove confirmed transaction %v "+
				"from unconfirmed store: %v", tx.TxHash(), dbErr)
		}

		return txid, nil

	// If the transaction was rejected for whatever other reason, then we'll
	// remove it from the transaction store, as otherwise, we'll attempt to
	// continually re-broadcast it, and the UTXO state of the wallet won't
	// be accurate.
	default:
		dbErr := walletdb.Update(w.db, func(dbTx walletdb.ReadWriteTx) error {
			txmgrNs := dbTx.ReadWriteBucket(wtxmgrNamespaceKey)
			txRec, err := wtxmgr.NewTxRecordFromMsgTx(tx, time.Now())
			if err != nil {
				return err
			}
			return w.TxStore.RemoveUnminedTx(txmgrNs, txRec)
		})
		if dbErr != nil {
			log.Warnf("Unable to remove invalid transaction %v: %v",
				tx.TxHash(), dbErr)
		} else {
			log.Infof("Removed invalid transaction: %v",
				spew.Sdump(tx))
		}

		return nil, err
	}
}