// PrepareTransfers prepares the transaction trytes by generating a bundle, filling in transfers and inputs,
// adding remainder and signing all input transactions.
973612
func (api *API) PrepareTransfers(seed Trytes, transfers bundle.Transfers, opts PrepareTransfersOptions) ([]Trytes, error) {
	opts = getPrepareTransfersDefaultOptions(opts)

	if err := Validate(ValidateSeed(seed), ValidateSecurityLevel(opts.Security)); err != nil {
		return nil, err
	}

	for i := range transfers {
		if err := Validate(ValidateAddresses(transfers[i].Value != 0, transfers[i].Address)); err != nil {
			return nil, err
		}
	}

	var timestamp uint64
	txs := transaction.Transactions{}

	if opts.Timestamp != nil {
		timestamp = *opts.Timestamp
	} else {
		timestamp = uint64(time.Now().UnixNano() / int64(time.Second))
	}

	var totalOutput uint64
	for i := range transfers {
		totalOutput += transfers[i].Value
	}

	// add transfers
	outEntries, err := bundle.TransfersToBundleEntries(timestamp, transfers...)
	if err != nil {
		return nil, err
	}
	for i := range outEntries {
		txs = bundle.AddEntry(txs, outEntries[i])
	}

	// gather inputs if we have api value transfer but no inputs were given.
	// this would error out if the gathered inputs don't fulfill the threshold value
	if totalOutput != 0 && len(opts.Inputs) == 0 {
		inputs, err := api.GetInputs(seed, GetInputsOptions{Security: opts.Security, Threshold: &totalOutput})
		if err != nil {
			return nil, err
		}

		// filter out inputs which are already spent
		inputAddresses := make(Hashes, len(opts.Inputs))
		for i := range opts.Inputs {
			inputAddresses[i] = inputs.Inputs[i].Address
		}

		states, err := api.WereAddressesSpentFrom(inputAddresses...)
		if err != nil {
			return nil, err
		}
		for i, state := range states {
			if state {
				inputs.Inputs = append(inputs.Inputs[:i], inputs.Inputs[i+1:]...)
			}
		}

		opts.Inputs = inputs.Inputs
	}

	// add input transactions
	var totalInput uint64
	for i := range opts.Inputs {
		if err := Validate(ValidateAddresses(opts.Inputs[i].Balance != 0, opts.Inputs[i].Address)); err != nil {
			return nil, err
		}
		totalInput += opts.Inputs[i].Balance
		input := &opts.Inputs[i]
		bndlEntry := bundle.BundleEntry{
			Address:   input.Address[:HashTrytesSize],
			Value:     -int64(input.Balance),
			Length:    uint64(input.Security),
			Timestamp: timestamp,
		}
		txs = bundle.AddEntry(txs, bndlEntry)
	}

	// verify whether provided inputs fulfill threshold value
	if totalInput < totalOutput {
		return nil, ErrInsufficientBalance
	}

	// compute remainder
	remainder := totalInput - totalOutput

	// add remainder transaction if there's a remainder
	if remainder > 0 {
		// compute new remainder address if non supplied
		if opts.RemainderAddress == nil {
			remainderAddressKeyIndex := opts.Inputs[0].KeyIndex
			for i := range opts.Inputs {
				keyIndex := opts.Inputs[i].KeyIndex
				if keyIndex > remainderAddressKeyIndex {
					remainderAddressKeyIndex = keyIndex
				}
			}
			remainderAddressKeyIndex++
			addrs, err := api.GetNewAddress(seed, GetNewAddressOptions{Security: opts.Security, Index: remainderAddressKeyIndex})
			if err != nil {
				return nil, err
			}
			opts.RemainderAddress = &addrs[0]
		} else {
			if err := Validate(ValidateAddresses(true, *opts.RemainderAddress)); err != nil {
				return nil, ErrInvalidRemainderAddress
			}
			// make sure to remove checksum from remainder address
			cleanedAddr, err := checksum.RemoveChecksum(*opts.RemainderAddress)
			if err != nil {
				return nil, err
			}
			opts.RemainderAddress = &cleanedAddr
		}

		// add remainder transaction
		txs = bundle.AddEntry(txs, bundle.BundleEntry{
			Address: (*opts.RemainderAddress)[:HashTrytesSize],
			Length:  1, Timestamp: timestamp,
			Value: int64(remainder),
		})
	}

	// verify that input txs don't send to the same address
	for i := range txs {
		tx := &txs[i]
		// only check output txs
		if tx.Value <= 0 {
			continue
		}
		// check whether any input uses the same address as the output tx
		for j := range opts.Inputs {
			if opts.Inputs[j].Address == tx.Address {
				return nil, ErrSendingBackToInputs
			}
		}
	}

	// finalize bundle by adding the bundle hash
	finalizedBundle, err := bundle.Finalize(txs)
	if err != nil {
		return nil, err
	}

	// compute signatures for all input txs
	normalizedBundleHash := signing.NormalizedBundleHash(finalizedBundle[0].Bundle)

	signedFrags := []Trytes{}
	for i := range opts.Inputs {
		input := &opts.Inputs[i]
		subseed, err := signing.Subseed(seed, input.KeyIndex)
		if err != nil {
			return nil, err
		}
		var sec SecurityLevel
		if input.Security == 0 {
			sec = SecurityLevelMedium
		} else {
			sec = input.Security
		}

		prvKey, err := signing.Key(subseed, sec)
		if err != nil {
			return nil, err
		}

		frags := make([]Trytes, input.Security)
		for i := 0; i < int(input.Security); i++ {
			signedFragTrits, err := signing.SignatureFragment(
				normalizedBundleHash[i*HashTrytesSize/3:(i+1)*HashTrytesSize/3],
				prvKey[i*KeyFragmentLength:(i+1)*KeyFragmentLength],
			)
			if err != nil {
				return nil, err
			}
			frags[i] = MustTritsToTrytes(signedFragTrits)
		}

		signedFrags = append(signedFrags, frags...)
	}

	// add signed fragments to txs
	var indexFirstInputTx int
	for i := range txs {
		if txs[i].Value < 0 {
			indexFirstInputTx = i
			break
		}
	}

	txs = bundle.AddTrytes(txs, signedFrags, indexFirstInputTx)

	// finally return built up txs as raw trytes
	return transaction.MustFinalTransactionTrytes(txs), nil
}
1326401
func (w *GCWorker) prepare() (bool, uint64, error) {
	// Add a transaction here is to prevent following situations:
	// 1. GC check gcEnable is true, continue to do GC
	// 2. The user sets gcEnable to false
	// 3. The user gets `tikv_gc_safe_point` value is t1, then the user thinks the data after time t1 won't be clean by GC.
	// 4. GC update `tikv_gc_safe_point` value to t2, continue do GC in this round.
	// Then the data record that has been dropped between time t1 and t2, will be cleaned by GC, but the user thinks the data after t1 won't be clean by GC.
	ctx := context.Background()
	_, err := w.session.Execute(ctx, "BEGIN")
	if err != nil {
		return false, 0, errors.Trace(err)
	}
	doGC, safePoint, err := w.checkPrepare(ctx)
	if doGC {
		_, err = w.session.Execute(ctx, "COMMIT")
		if err != nil {
			return false, 0, errors.Trace(err)
		}
	} else {
		_, err1 := w.session.Execute(ctx, "ROLLBACK")
		terror.Log(errors.Trace(err1))
	}
	return doGC, safePoint, errors.Trace(err)
}
370253
func (dc *CDA) AsTransfer() bundle.Transfer {
	return bundle.Transfer{
		Address: dc.Address,
		Value: func() uint64 {
			if dc.ExpectedAmount == nil {
				return 0
			}
			return *dc.ExpectedAmount
		}(),
	}
}
1132010
func (el *ChannelEventListener) RegPreparingTransfer() *ChannelEventListener {
	el.PreparingTransfers = make(chan struct{})
	el.ids = append(el.ids, el.em.RegisterListener(func(data interface{}) {
		el.PreparingTransfers <- struct{}{}
	}, event.EventPreparingTransfer))
	return el
}
1105433
func (c *authenticatedConnection) prepare(ctx context.Context) error {
	c.prepareMutex.Lock()
	defer c.prepareMutex.Unlock()
	if c.prepared == 0 {
		// We need to prepare first
		if err := c.auth.Prepare(ctx, c.conn); err != nil {
			// Authentication failed
			return driver.WithStack(err)
		}
		// We're now prepared
		atomic.StoreInt32(&c.prepared, 1)
	} else {
		// We're already prepared, do nothing
	}
	return nil
}
102166
func (_Chequebook *ChequebookTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
	return _Chequebook.Contract.contract.Transfer(opts)
}
1100717
func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
	// Otherwise pack up the parameters and invoke the contract
	input, err := c.abi.Pack(method, params...)
	if err != nil {
		return nil, err
	}
	return c.transact(opts, &c.address, input)
}
1266508
func (v *Verifier) commitTransferAction(transferAction *token.PlainTransfer, txID string, simulator ledger.LedgerWriter) error {
	var outputID string
	var err error
	for i, output := range transferAction.GetOutputs() {
		if output.Owner != nil {
			outputID, err = createOutputKey(txID, i)
		} else {
			outputID, err = createRedeemKey(txID, i)
		}
		if err != nil {
			return &customtx.InvalidTxError{Msg: fmt.Sprintf("error creating output ID: %s", err)}
		}

		err = v.addOutput(outputID, output, simulator)
		if err != nil {
			return err
		}
	}
	return v.markInputsSpent(txID, transferAction.GetInputs(), simulator)
}
860534
func (tc *TransCache) BeginTransaction() (transID string) {
	transID = GenUUID()
	tc.transBufMux.Lock()
	tc.transactionBuffer[transID] = make([]*transactionItem, 0)
	tc.transBufMux.Unlock()
	return transID
}
1126924
func (api *API) GetTransfers(seed Trytes, options GetTransfersOptions) (bundle.Bundles, error) {
	options = getTransfersDefaultOptions(options)
	if err := Validate(
		ValidateSeed(seed), ValidateSecurityLevel(options.Security),
		ValidateStartEndOptions(options.Start, options.End),
	); err != nil {
		return nil, err
	}
	addresses, err := api.GetNewAddress(seed, options.ToGetNewAddressOptions())
	if err != nil {
		return nil, err
	}
	return api.GetBundlesFromAddresses(addresses, options.InclusionStates)
}
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)
}
362327
func (_FIFSRegistrar *FIFSRegistrarRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
	return _FIFSRegistrar.Contract.FIFSRegistrarTransactor.contract.Transfer(opts)
}
482351
func (m *contentChangeMap) handleBundles(b *bundleDirs) {
	for _, bd := range b.bundles {
		m.add(bd.fi.Path(), bd.tp)
	}
}
326716
func PrepareBatchPayments(mctx libkb.MetaContext, walletState *WalletState, senderSeed stellarnet.SeedStr, payments []stellar1.BatchPaymentArg) ([]*MiniPrepared, func(), error) {
	mctx.Debug("preparing %d batch payments", len(payments))

	baseFee := walletState.BaseFee(mctx)

	prepared := make(chan *MiniPrepared)

	sp, unlock := NewSeqnoProvider(mctx, walletState)
	for _, payment := range payments {
		go func(p stellar1.BatchPaymentArg) {
			prepared <- prepareBatchPayment(mctx, walletState, sp, senderSeed, p, baseFee)
		}(payment)
	}

	// prepared chan could be out of order, so sort by seqno
	preparedList := make([]*MiniPrepared, len(payments))
	for i := 0; i < len(payments); i++ {
		preparedList[i] = <-prepared
	}
	sort.Slice(preparedList, func(a, b int) bool { return preparedList[a].Seqno < preparedList[b].Seqno })

	return preparedList, unlock, nil
}
331330
func (m *ServeMux) Prepare() {
	for _, plugin := range m.plugins {
		used := false
		if sc := plugin.HandlersScanner(); sc != nil {
			err := sc.HandlersScannerProcess(m, m.router.handlers)
			if err != nil {
				panic(err)
			}
			used = true
		}
		if !used {
			panic(fmt.Sprintf("unused plugin: %#v", plugin))
		}
	}
}
145889
func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
	var err error

	// Ensure a valid value field and resolve the account nonce
	value := opts.Value
	if value == nil {
		value = new(big.Int)
	}
	var nonce uint64
	if opts.Nonce == nil {
		nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
		if err != nil {
			return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
		}
	} else {
		nonce = opts.Nonce.Uint64()
	}
	// Figure out the gas allowance and gas price values
	gasPrice := opts.GasPrice
	if gasPrice == nil {
		gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context))
		if err != nil {
			return nil, fmt.Errorf("failed to suggest gas price: %v", err)
		}
	}
	gasLimit := opts.GasLimit
	if gasLimit == 0 {
		// Gas estimation cannot succeed without code for method invocations
		if contract != nil {
			if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
				return nil, err
			} else if len(code) == 0 {
				return nil, ErrNoCode
			}
		}
		// If the contract surely has code (or code is not needed), estimate the transaction
		msg := ethereum.CallMsg{From: opts.From, To: contract, Value: value, Data: input}
		gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg)
		if err != nil {
			return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
		}
	}
	// Create the transaction, sign it and schedule it for execution
	var rawTx *types.Transaction
	if contract == nil {
		rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input)
	} else {
		rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
	}
	if opts.Signer == nil {
		return nil, errors.New("no signer to authorize the transaction with")
	}
	signedTx, err := opts.Signer(types.HomesteadSigner{}, opts.From, rawTx)
	if err != nil {
		return nil, err
	}
	if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
		return nil, err
	}
	return signedTx, nil
}
57987
func (tx *Tx) Preparex(query string) (*Stmt, error) {
	return Preparex(tx, query)
}