本文整理匯總了Golang中github.com/decred/dcrutil.Tx類的典型用法代碼示例。如果您正苦於以下問題:Golang Tx類的具體用法?Golang Tx怎麽用?Golang Tx使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Tx類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: AddUnconfirmedTx
// AddUnconfirmedTx adds all addresses related to the transaction to the
// unconfirmed (memory-only) address index.
//
// NOTE: This transaction MUST have already been validated by the memory pool
// before calling this function with it and have all of the inputs available in
// the provided utxo view. Failure to do so could result in some or all
// addresses not being indexed.
//
// This function is safe for concurrent access.
func (idx *AddrIndex) AddUnconfirmedTx(tx *dcrutil.Tx, utxoView *blockchain.UtxoViewpoint) {
// Index addresses of all referenced previous transaction outputs.
//
// The existence checks are elided since this is only called after the
// transaction has already been validated and thus all inputs are
// already known to exist.
msgTx := tx.MsgTx()
isSSGen, _ := stake.IsSSGen(msgTx)
for i, txIn := range msgTx.TxIn {
// Skip stakebase.
if i == 0 && isSSGen {
continue
}
entry := utxoView.LookupEntry(&txIn.PreviousOutPoint.Hash)
if entry == nil {
// Ignore missing entries. This should never happen
// in practice since the function comments specifically
// call out all inputs must be available.
continue
}
version := entry.ScriptVersionByIndex(txIn.PreviousOutPoint.Index)
pkScript := entry.PkScriptByIndex(txIn.PreviousOutPoint.Index)
txType := entry.TransactionType()
idx.indexUnconfirmedAddresses(version, pkScript, tx,
txType == stake.TxTypeSStx)
}
// Index addresses of all created outputs.
isSStx, _ := stake.IsSStx(msgTx)
for _, txOut := range msgTx.TxOut {
idx.indexUnconfirmedAddresses(txOut.Version, txOut.PkScript, tx,
isSStx)
}
}
示例2: GetSSGenVoteBits
// GetSSGenVoteBits takes an SSGen tx as input and scans through its
// outputs, returning the VoteBits of the index 1 output.
func GetSSGenVoteBits(tx *dcrutil.Tx) uint16 {
msgTx := tx.MsgTx()
votebits := binary.LittleEndian.Uint16(msgTx.TxOut[1].PkScript[2:4])
return votebits
}
示例3: ValidateTransactionScripts
// ValidateTransactionScripts validates the scripts for the passed transaction
// using multiple goroutines.
func ValidateTransactionScripts(tx *dcrutil.Tx, utxoView *UtxoViewpoint, flags txscript.ScriptFlags, sigCache *txscript.SigCache) error {
// Collect all of the transaction inputs and required information for
// validation.
txIns := tx.MsgTx().TxIn
txValItems := make([]*txValidateItem, 0, len(txIns))
for txInIdx, txIn := range txIns {
// Skip coinbases.
if txIn.PreviousOutPoint.Index == math.MaxUint32 {
continue
}
txVI := &txValidateItem{
txInIndex: txInIdx,
txIn: txIn,
tx: tx,
}
txValItems = append(txValItems, txVI)
}
// Validate all of the inputs.
validator := newTxValidator(utxoView, flags, sigCache)
if err := validator.Validate(txValItems); err != nil {
return err
}
return nil
}
示例4: IsFinalizedTransaction
// IsFinalizedTransaction determines whether or not a transaction is finalized.
func IsFinalizedTransaction(tx *dcrutil.Tx, blockHeight int64,
blockTime time.Time) bool {
msgTx := tx.MsgTx()
// Lock time of zero means the transaction is finalized.
lockTime := msgTx.LockTime
if lockTime == 0 {
return true
}
// The lock time field of a transaction is either a block height at
// which the transaction is finalized or a timestamp depending on if the
// value is before the txscript.LockTimeThreshold. When it is under the
// threshold it is a block height.
blockTimeOrHeight := int64(0)
if lockTime < txscript.LockTimeThreshold {
blockTimeOrHeight = blockHeight
} else {
blockTimeOrHeight = blockTime.Unix()
}
if int64(lockTime) < blockTimeOrHeight {
return true
}
// At this point, the transaction's lock time hasn't occurred yet, but
// the transaction might still be finalized if the sequence number
// for all transaction inputs is maxed out.
for _, txIn := range msgTx.TxIn {
if txIn.Sequence != math.MaxUint32 {
return false
}
}
return true
}
示例5: FetchTransactionStore
// FetchTransactionStore fetches the input transactions referenced by the
// passed transaction from the point of view of the end of the main chain. It
// also attempts to fetch the transaction itself so the returned TxStore can be
// examined for duplicate transactions.
// IsValid indicates if the current block on head has had its TxTreeRegular
// validated by the stake voters.
func (b *BlockChain) FetchTransactionStore(tx *dcrutil.Tx,
isValid bool) (TxStore, error) {
isSSGen, _ := stake.IsSSGen(tx)
// Create a set of needed transactions from the transactions referenced
// by the inputs of the passed transaction. Also, add the passed
// transaction itself as a way for the caller to detect duplicates.
txNeededSet := make(map[chainhash.Hash]struct{})
txNeededSet[*tx.Sha()] = struct{}{}
for i, txIn := range tx.MsgTx().TxIn {
// Skip all stakebase inputs.
if isSSGen && (i == 0) {
continue
}
txNeededSet[txIn.PreviousOutPoint.Hash] = struct{}{}
}
// Request the input transactions from the point of view of the end of
// the main chain without including fully spent transactions in the
// results. Fully spent transactions are only needed for chain
// reorganization which does not apply here.
txStore := fetchTxStoreMain(b.db, txNeededSet, false)
topBlock, err := b.getBlockFromHash(b.bestChain.hash)
if err != nil {
return nil, err
}
if isValid {
connectTxTree(txStore, topBlock, true)
}
return txStore, nil
}
示例6: calcPriority
// calcPriority returns a transaction priority given a transaction and the sum
// of each of its input values multiplied by their age (# of confirmations).
// Thus, the final formula for the priority is:
// sum(inputValue * inputAge) / adjustedTxSize
func calcPriority(tx *dcrutil.Tx, inputValueAge float64) float64 {
// In order to encourage spending multiple old unspent transaction
// outputs thereby reducing the total set, don't count the constant
// overhead for each input as well as enough bytes of the signature
// script to cover a pay-to-script-hash redemption with a compressed
// pubkey. This makes additional inputs free by boosting the priority
// of the transaction accordingly. No more incentive is given to avoid
// encouraging gaming future transactions through the use of junk
// outputs. This is the same logic used in the reference
// implementation.
//
// The constant overhead for a txin is 41 bytes since the previous
// outpoint is 36 bytes + 4 bytes for the sequence + 1 byte the
// signature script length.
//
// A compressed pubkey pay-to-script-hash redemption with a maximum len
// signature is of the form:
// [OP_DATA_73 <73-byte sig> + OP_DATA_35 + {OP_DATA_33
// <33 byte compresed pubkey> + OP_CHECKSIG}]
//
// Thus 1 + 73 + 1 + 1 + 33 + 1 = 110
overhead := 0
for _, txIn := range tx.MsgTx().TxIn {
// Max inputs + size can't possibly overflow here.
overhead += 41 + minInt(110, len(txIn.SignatureScript))
}
serializedTxSize := tx.MsgTx().SerializeSize()
if overhead >= serializedTxSize {
return 0.0
}
return inputValueAge / float64(serializedTxSize-overhead)
}
示例7: GetSStxStakeOutputInfo
// GetSStxStakeOutputsInfo takes an SStx as input and scans through its outputs,
// returning the pubkeyhashs and amounts for any NullDataTy's (future commitments
// to stake generation rewards).
func GetSStxStakeOutputInfo(tx *dcrutil.Tx) ([]bool, [][]byte, []int64, []int64,
[][]bool, [][]uint16) {
msgTx := tx.MsgTx()
isP2SH := make([]bool, len(msgTx.TxIn))
addresses := make([][]byte, len(msgTx.TxIn))
amounts := make([]int64, len(msgTx.TxIn))
changeAmounts := make([]int64, len(msgTx.TxIn))
allSpendRules := make([][]bool, len(msgTx.TxIn))
allSpendLimits := make([][]uint16, len(msgTx.TxIn))
// Cycle through the inputs and pull the proportional amounts
// and commit to PKHs/SHs.
for idx, out := range msgTx.TxOut {
// We only care about the outputs where we get proportional
// amounts and the PKHs/SHs to send rewards to, which is all
// the odd numbered output indexes.
if (idx > 0) && (idx%2 != 0) {
// The MSB (sign), not used ever normally, encodes whether
// or not it is a P2PKH or P2SH for the input.
amtEncoded := make([]byte, 8, 8)
copy(amtEncoded, out.PkScript[22:30])
isP2SH[idx/2] = !(amtEncoded[7]&(1<<7) == 0) // MSB set?
amtEncoded[7] &= ^uint8(1 << 7) // Clear bit
addresses[idx/2] = out.PkScript[2:22]
amounts[idx/2] = int64(binary.LittleEndian.Uint64(amtEncoded))
// Get flags and restrictions for the outputs to be
// make in either a vote or revocation.
spendRules := make([]bool, 2, 2)
spendLimits := make([]uint16, 2, 2)
// This bitflag is true/false.
feeLimitUint16 := binary.LittleEndian.Uint16(out.PkScript[30:32])
spendRules[0] = (feeLimitUint16 & SStxVoteFractionFlag) ==
SStxVoteFractionFlag
spendRules[1] = (feeLimitUint16 & SStxRevFractionFlag) ==
SStxRevFractionFlag
allSpendRules[idx/2] = spendRules
// This is the fraction to use out of 64.
spendLimits[0] = feeLimitUint16 & SStxVoteReturnFractionMask
spendLimits[1] = feeLimitUint16 & SStxRevReturnFractionMask
spendLimits[1] >>= 8
allSpendLimits[idx/2] = spendLimits
}
// Here we only care about the change amounts, so scan
// the change outputs (even indices) and save their
// amounts.
if (idx > 0) && (idx%2 == 0) {
changeAmounts[(idx/2)-1] = out.Value
}
}
return isP2SH, addresses, amounts, changeAmounts, allSpendRules,
allSpendLimits
}
示例8: matchTxAndUpdate
// matchTxAndUpdate returns true if the bloom filter matches data within the
// passed transaction, otherwise false is returned. If the filter does match
// the passed transaction, it will also update the filter depending on the bloom
// update flags set via the loaded filter if needed.
//
// This function MUST be called with the filter lock held.
func (bf *Filter) matchTxAndUpdate(tx *dcrutil.Tx) bool {
// Check if the filter matches the hash of the transaction.
// This is useful for finding transactions when they appear in a block.
matched := bf.matches(tx.Sha().Bytes())
// Check if the filter matches any data elements in the public key
// scripts of any of the outputs. When it does, add the outpoint that
// matched so transactions which spend from the matched transaction are
// also included in the filter. This removes the burden of updating the
// filter for this scenario from the client. It is also more efficient
// on the network since it avoids the need for another filteradd message
// from the client and avoids some potential races that could otherwise
// occur.
for i, txOut := range tx.MsgTx().TxOut {
pushedData, err := txscript.PushedData(txOut.PkScript)
if err != nil {
continue
}
for _, data := range pushedData {
if !bf.matches(data) {
continue
}
matched = true
bf.maybeAddOutpoint(txOut.Version, txOut.PkScript, tx.Sha(),
uint32(i), tx.Tree())
break
}
}
// Nothing more to do if a match has already been made.
if matched {
return true
}
// At this point, the transaction and none of the data elements in the
// public key scripts of its outputs matched.
// Check if the filter matches any outpoints this transaction spends or
// any any data elements in the signature scripts of any of the inputs.
for _, txin := range tx.MsgTx().TxIn {
if bf.matchesOutPoint(&txin.PreviousOutPoint) {
return true
}
pushedData, err := txscript.PushedData(txin.SignatureScript)
if err != nil {
continue
}
for _, data := range pushedData {
if bf.matches(data) {
return true
}
}
}
return false
}
示例9: isNullOutpoint
// isNullOutpoint determines whether or not a previous transaction output point
// is set.
func isNullOutpoint(tx *dcrutil.Tx) bool {
nullInOP := tx.MsgTx().TxIn[0].PreviousOutPoint
if nullInOP.Index == math.MaxUint32 && nullInOP.Hash.IsEqual(zeroHash) &&
nullInOP.Tree == dcrutil.TxTreeRegular {
return true
}
return false
}
示例10: serializeTx
func serializeTx(tx *dcrutil.Tx) []byte {
var buf bytes.Buffer
err := tx.MsgTx().Serialize(&buf)
if err != nil {
panic(err)
}
return buf.Bytes()
}
示例11: isNonstandardTransaction
// isNonstandardTransaction determines whether a transaction contains any
// scripts which are not one of the standard types.
func isNonstandardTransaction(tx *dcrutil.Tx) bool {
// Check all of the output public key scripts for non-standard scripts.
for _, txOut := range tx.MsgTx().TxOut {
scriptClass := txscript.GetScriptClass(txOut.Version, txOut.PkScript)
if scriptClass == txscript.NonStandardTy {
return true
}
}
return false
}
示例12: SetTxTree
// SetTxTree analyzes the embedded MsgTx and sets the transaction tree
// accordingly.
func SetTxTree(tx *dcrutil.Tx) {
txType := DetermineTxType(tx.MsgTx())
indicatedTree := wire.TxTreeRegular
if txType != TxTypeRegular {
indicatedTree = wire.TxTreeStake
}
tx.SetTree(indicatedTree)
}
示例13: isNullFraudProof
// isNullFraudProof determines whether or not a previous transaction fraud proof
// is set.
func isNullFraudProof(tx *dcrutil.Tx) bool {
txIn := tx.MsgTx().TxIn[0]
switch {
case txIn.BlockHeight != wire.NullBlockHeight:
return false
case txIn.BlockIndex != wire.NullBlockIndex:
return false
}
return true
}
示例14: FetchUtxoView
// FetchUtxoView loads utxo details about the input transactions referenced by
// the passed transaction from the point of view of the end of the main chain.
// It also attempts to fetch the utxo details for the transaction itself so the
// returned view can be examined for duplicate unspent transaction outputs.
//
// This function is safe for concurrent access however the returned view is NOT.
func (b *BlockChain) FetchUtxoView(tx *dcrutil.Tx, treeValid bool) (*UtxoViewpoint,
error) {
b.chainLock.RLock()
defer b.chainLock.RUnlock()
// Request the utxos from the point of view of the end of the main
// chain.
view := NewUtxoViewpoint()
if treeValid {
view.SetStakeViewpoint(ViewpointPrevValidRegular)
block, err := b.fetchBlockFromHash(&b.bestNode.hash)
if err != nil {
return nil, err
}
parent, err := b.fetchBlockFromHash(&b.bestNode.header.PrevBlock)
if err != nil {
return nil, err
}
err = view.fetchInputUtxos(b.db, block, parent)
if err != nil {
return nil, err
}
for i, blockTx := range block.Transactions() {
err := view.connectTransaction(blockTx, b.bestNode.height,
uint32(i), nil)
if err != nil {
return nil, err
}
}
}
view.SetBestHash(&b.bestNode.hash)
// Create a set of needed transactions based on those referenced by the
// inputs of the passed transaction. Also, add the passed transaction
// itself as a way for the caller to detect duplicates that are not
// fully spent.
txNeededSet := make(map[chainhash.Hash]struct{})
txNeededSet[*tx.Sha()] = struct{}{}
msgTx := tx.MsgTx()
isSSGen, _ := stake.IsSSGen(msgTx)
if !IsCoinBaseTx(msgTx) {
for i, txIn := range msgTx.TxIn {
if isSSGen && i == 0 {
continue
}
txNeededSet[txIn.PreviousOutPoint.Hash] = struct{}{}
}
}
err := view.fetchUtxosMain(b.db, txNeededSet)
return view, err
}
示例15: GetSSGenBlockVotedOn
// GetSSGenBlockVotedOn takes an SSGen tx and returns the block voted on in the
// first OP_RETURN by hash and height.
func GetSSGenBlockVotedOn(tx *dcrutil.Tx) (chainhash.Hash, uint32, error) {
msgTx := tx.MsgTx()
// Get the block header hash.
blockSha, err := chainhash.NewHash(msgTx.TxOut[0].PkScript[2:34])
if err != nil {
return chainhash.Hash{}, 0, err
}
// Get the block height.
height := binary.LittleEndian.Uint32(msgTx.TxOut[0].PkScript[34:38])
return *blockSha, height, nil
}