Some transactions need to be transformed before they can be stored in the
        ledger, eg. storing certain payload in another data store and only its
        hash in the ledger
497615
def transform_txn_for_ledger(txn):
        
        if get_type(txn) == ATTRIB:
            txn = DomainReqHandler.transform_attrib_for_ledger(txn)
        return txn
1182745
public void put(@NotNull final PersistentStoreTransaction txn,
                    final long localId,
                    @NotNull final ByteIterable value,
                    @Nullable final ByteIterable oldValue,
                    final int propertyId,
                    @NotNull final ComparableValueType type) {
        final Store valueIdx = getOrCreateValueIndex(txn, propertyId);
        final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId));
        final Transaction envTxn = txn.getEnvironmentTransaction();
        primaryStore.put(envTxn, key, value);
        final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId);
        boolean success;
        if (oldValue == null) {
            success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue);
        } else {
            success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type));
        }
        if (success) {
            for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) {
                valueIdx.put(envTxn, secondaryKey, secondaryValue);
            }
        }
        checkStatus(success, "Failed to put");
    }
1031161
def transaction_include_any_action?(actions)
        actions.any? do |action|
          case action
          when :create
            persisted? && @_new_record_before_last_commit
          when :update
            !(@_new_record_before_last_commit || destroyed?) && _trigger_update_callback
          when :destroy
            _trigger_destroy_callback
          end
        end
      end
910505
def serialize_transaction(inputs, outputs, lock_time=0, version=1):
    

    # add in the inputs
    serialized_inputs = ''.join([serialize_input(input) for input in inputs])

    # add in the outputs
    serialized_outputs = ''.join([serialize_output(output) for output in outputs])

    return ''.join([
        # add in the version number
        hexlify(struct.pack('<I', version)),
        # add in the number of inputs
        hexlify(variable_length_int(len(inputs))),
        # add in the inputs
        serialized_inputs,
        # add in the number of outputs
        hexlify(variable_length_int(len(outputs))),
        # add in the outputs
        serialized_outputs,
        # add in the lock time
        hexlify(struct.pack('<I', lock_time)),
    ])
463685
def deliver_tx(self, raw_transaction):
        

        self.abort_if_abci_chain_is_not_synced()

        logger.debug('deliver_tx: %s', raw_transaction)
        transaction = self.bigchaindb.is_valid_transaction(
            decode_transaction(raw_transaction), self.block_transactions)

        if not transaction:
            logger.debug('deliver_tx: INVALID')
            return ResponseDeliverTx(code=CodeTypeError)
        else:
            logger.debug('storing tx')
            self.block_txn_ids.append(transaction.id)
            self.block_transactions.append(transaction)
            return ResponseDeliverTx(code=CodeTypeOk)
929440
def make_raw_transaction(
    network: str,
    inputs: list,
    outputs: list,
    locktime: Locktime,
    timestamp: int=int(time()),
    version: int=1,
) -> MutableTransaction:
    ''''''

    network_params = net_query(network)

    if network_params.name.startswith("peercoin"):
        return MutableTransaction(
            version=version,
            ins=inputs,
            outs=outputs,
            locktime=locktime,
            network=network_params,
            timestamp=timestamp,
        )

    return MutableTransaction(
        version=version,
        ins=inputs,
        outs=outputs,
        locktime=locktime,
        network=network_params,
    )
401199
def ledger(self):
        """"""
        self.balance()  # make sure the transaction balances

        s = "{0}/{1:02}/{2:02}  {3}\n".format(
            self.date.year,
            self.date.month,
            self.date.day,
            self.desc.replace('\n', ' ')
        )
        for src in self.src:
            s += "  {0.account}  ${0.amount}\n".format(src)
        for dst in self.dst:
            s += "  {0.account}  ${0.amount}\n".format(dst)
        return s
575262
def create_3pc_batch(self, ledger_id):
        pp_seq_no = self.lastPrePrepareSeqNo + 1
        pool_state_root_hash = self.stateRootHash(POOL_LEDGER_ID)
        self.logger.debug("{} creating batch {} for ledger {} with state root {}".format(
            self, pp_seq_no, ledger_id,
            self.stateRootHash(ledger_id, to_str=False)))

        if self.last_accepted_pre_prepare_time is None:
            last_ordered_ts = self._get_last_timestamp_from_state(ledger_id)
            if last_ordered_ts:
                self.last_accepted_pre_prepare_time = last_ordered_ts

        # DO NOT REMOVE `view_no` argument, used while replay
        # tm = self.utc_epoch
        tm = self.get_utc_epoch_for_preprepare(self.instId, self.viewNo,
                                               pp_seq_no)

        reqs, invalid_indices, rejects = self.consume_req_queue_for_pre_prepare(
            ledger_id, tm, self.viewNo, pp_seq_no)
        if self.isMaster:
            three_pc_batch = ThreePcBatch(ledger_id=ledger_id,
                                          inst_id=self.instId,
                                          view_no=self.viewNo,
                                          pp_seq_no=pp_seq_no,
                                          pp_time=tm,
                                          state_root=self.stateRootHash(ledger_id, to_str=False),
                                          txn_root=self.txnRootHash(ledger_id, to_str=False),
                                          primaries=[],
                                          valid_digests=self.get_valid_req_ids_from_all_requests(
                                              reqs, invalid_indices))
            self.node.onBatchCreated(three_pc_batch)

        digest = self.batchDigest(reqs)
        state_root_hash = self.stateRootHash(ledger_id)
        audit_txn_root_hash = self.txnRootHash(AUDIT_LEDGER_ID)

        """"""
        params = [
            self.instId,
            self.viewNo,
            pp_seq_no,
            tm,
            [req.digest for req in reqs],
            invalid_index_serializer.serialize(invalid_indices, toBytes=False),
            digest,
            ledger_id,
            state_root_hash,
            self.txnRootHash(ledger_id),
            0,
            True,
            pool_state_root_hash,
            audit_txn_root_hash
        ]

        # BLS multi-sig:
        params = self._bls_bft_replica.update_pre_prepare(params, ledger_id)

        pre_prepare = PrePrepare(*params)
        if self.isMaster:
            rv = self.execute_hook(ReplicaHooks.CREATE_PPR, pre_prepare)
            pre_prepare = rv if rv is not None else pre_prepare

        self.logger.trace('{} created a PRE-PREPARE with {} requests for ledger {}'.format(
            self, len(reqs), ledger_id))
        self.lastPrePrepareSeqNo = pp_seq_no
        self.last_accepted_pre_prepare_time = tm
        if self.isMaster:
            self.outBox.extend(rejects)
        return pre_prepare
843374
void prepareTransaction(HotRodHeader header, Subject subject, XidImpl xid, boolean onePhaseCommit,
         List<TransactionWrite> writes, boolean recoverable, long timeout) {
      HotRodServer.CacheInfo cacheInfo = server.getCacheInfo(header);
      AdvancedCache<byte[], byte[]> cache = server.cache(cacheInfo, header, subject);
      validateConfiguration(cache);
      executor.execute(() -> prepareTransactionInternal(header, cache, cacheInfo.versionGenerator, xid, onePhaseCommit,
                                                        writes, recoverable, timeout));
   }
41108
def RemoveTransaction(self, tx):
        
        if BC.Default() is None:
            return False

        if not BC.Default().ContainsTransaction(tx.Hash):
            return False

        if tx.Hash.ToBytes() in self.MemPool:
            del self.MemPool[tx.Hash.ToBytes()]
            return True

        return False
1078392
def AddTransaction(self, tx):
        
        if BC.Default() is None:
            return False

        if tx.Hash.ToBytes() in self.MemPool.keys():
            return False

        if BC.Default().ContainsTransaction(tx.Hash):
            return False

        if not tx.Verify(self.MemPool.values()):
            logger.error("Verifying tx result... failed")
            return False

        self.MemPool[tx.Hash.ToBytes()] = tx

        return True
1091317
public boolean provideTransaction(Transaction tx) throws VerificationException {
        Sha256Hash hash = tx.getTxId();
        if (getTransactionHashes().contains(hash)) {
            associatedTransactions.put(hash, tx);
            return true;
        }
        return false;
    }
794742
private void completePreparingTransaction(TransactionId transactionId) {
    // Change ownership of the transaction to the local node and set its state to ROLLING_BACK and then roll it back.
    completeTransaction(
        transactionId,
        TransactionState.PREPARING,
        info -> new TransactionInfo(localMemberId, TransactionState.ROLLING_BACK, info.participants),
        info -> info.state == TransactionState.ROLLING_BACK,
        (id, transactional) -> transactional.rollback(id))
        .whenComplete((result, error) -> {
          if (error != null) {
            error = Throwables.getRootCause(error);
            if (error instanceof TransactionException) {
              LOGGER.warn("Failed to complete transaction", error);
            } else {
              LOGGER.warn("Failed to roll back transaction " + transactionId);
            }
          }
        });
  }
1270032
def sanitize_tx_data(unspents, outputs, fee, leftover, combine=True,
                     message=None, compressed=True, absolute_fee=False,
                     min_change=0, version='main'):
    

    outputs = outputs.copy()

    for i, output in enumerate(outputs):
        dest, amount, currency = output
        outputs[i] = (dest, currency_to_satoshi_cached(amount, currency))

    if not unspents:
        raise ValueError('Transactions must have at least one unspent.')

    # Temporary storage so all outputs precede messages.
    messages = []

    if message:
        message_chunks = chunk_data(message.encode('utf-8'), MESSAGE_LIMIT)

        for message in message_chunks:
            messages.append((message, 0))

    # Include return address in output count.
    # Calculate output size as a list (including return address).
    output_size = [len(address_to_scriptpubkey(o[0])) + 9 for o in outputs]
    output_size.append(len(messages) * (MESSAGE_LIMIT + 9))
    output_size.append(len(address_to_scriptpubkey(leftover)) + 9)
    sum_outputs = sum(out[1] for out in outputs)

    # Use Branch-and-Bound for coin selection:
    unspents[:], remaining = select_coins(
        sum_outputs, fee, output_size, min_change=min_change,
        absolute_fee=absolute_fee, consolidate=combine, unspents=unspents
    )

    if remaining > 0:
        outputs.append((leftover, remaining))

    # Sanity check: If spending from main-/testnet, then all output addresses must also be for main-/testnet.
    for output in outputs:
        dest, amount = output
        vs = get_version(dest)
        if vs and vs != version:
            raise ValueError('Cannot send to ' + vs + 'net address when '
                             'spending from a ' + version + 'net address.')

    outputs.extend(messages)

    return unspents, outputs
863461
def init_state_from_ledger(self, state: State, ledger: Ledger, reqHandler):
        
        if state.isEmpty:
            logger.info('{} found state to be empty, recreating from '
                        'ledger'.format(self))
            for seq_no, txn in ledger.getAllTxn():
                txn = self.update_txn_with_extra_data(txn)
                reqHandler.updateState([txn, ], isCommitted=True)
                state.commit(rootHash=state.headHash)
1313889
def apply_transaction(self,
                          transaction: BaseTransaction
                          ) -> Tuple[BaseBlock, Receipt, BaseComputation]:
        
        vm = self.get_vm(self.header)
        base_block = vm.block

        receipt, computation = vm.apply_transaction(base_block.header, transaction)
        header_with_receipt = vm.add_receipt_to_header(base_block.header, receipt)

        # since we are building the block locally, we have to persist all the incremental state
        vm.state.persist()
        new_header = header_with_receipt.copy(state_root=vm.state.state_root)

        transactions = base_block.transactions + (transaction, )
        receipts = base_block.get_receipts(self.chaindb) + (receipt, )

        new_block = vm.set_block_transactions(base_block, new_header, transactions, receipts)

        self.header = new_block.header

        return new_block, receipt, computation
1300436
private void recoverTransaction(TransactionId transactionId, TransactionInfo transactionInfo) {
    switch (transactionInfo.state) {
      case PREPARING:
        completePreparingTransaction(transactionId);
        break;
      case COMMITTING:
        completeCommittingTransaction(transactionId);
        break;
      case ROLLING_BACK:
        completeRollingBackTransaction(transactionId);
        break;
      default:
        break;
    }
  }