本文整理汇总了Golang中github.com/roasbeef/btcd/wire.MsgTx类的典型用法代码示例。如果您正苦于以下问题:Golang MsgTx类的具体用法?Golang MsgTx怎么用?Golang MsgTx使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MsgTx类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: CheckDoubleSpends
// GetDoubleSpends takes a transaction and compares it with
// all transactions in the db. It returns a slice of all txids in the db
// which are double spent by the received tx.
func CheckDoubleSpends(
argTx *wire.MsgTx, txs []*wire.MsgTx) ([]*wire.ShaHash, error) {
var dubs []*wire.ShaHash // slice of all double-spent txs
argTxid := argTx.TxSha()
for _, compTx := range txs {
compTxid := compTx.TxSha()
// check if entire tx is dup
if argTxid.IsEqual(&compTxid) {
return nil, fmt.Errorf("tx %s is dup", argTxid.String())
}
// not dup, iterate through inputs of argTx
for _, argIn := range argTx.TxIn {
// iterate through inputs of compTx
for _, compIn := range compTx.TxIn {
if OutPointsEqual(
argIn.PreviousOutPoint, compIn.PreviousOutPoint) {
// found double spend
dubs = append(dubs, &compTxid)
break // back to argIn loop
}
}
}
}
return dubs, nil
}
示例2: 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 *wire.MsgTx, utxoView *blockchain.UtxoViewpoint, nextBlockHeight int32) 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.TxIn {
// Max inputs + size can't possibly overflow here.
overhead += 41 + minInt(110, len(txIn.SignatureScript))
}
serializedTxSize := tx.SerializeSize()
if overhead >= serializedTxSize {
return 0.0
}
inputValueAge := calcInputValueAge(tx, utxoView, nextBlockHeight)
return inputValueAge / float64(serializedTxSize-overhead)
}
示例3: dbFetchTx
// dbFetchTx looks up the passed transaction hash in the transaction index and
// loads it from the database.
func dbFetchTx(dbTx database.Tx, hash *chainhash.Hash) (*wire.MsgTx, error) {
// Look up the location of the transaction.
blockRegion, err := dbFetchTxIndexEntry(dbTx, hash)
if err != nil {
return nil, err
}
if blockRegion == nil {
return nil, fmt.Errorf("transaction %v not found", hash)
}
// Load the raw transaction bytes from the database.
txBytes, err := dbTx.FetchBlockRegion(blockRegion)
if err != nil {
return nil, err
}
// Deserialize the transaction.
var msgTx wire.MsgTx
err = msgTx.Deserialize(bytes.NewReader(txBytes))
if err != nil {
return nil, err
}
return &msgTx, nil
}
示例4: AddSigHashes
// AddSigHashes computes, then adds the partial sighashes for the passed
// transaction.
func (h *HashCache) AddSigHashes(tx *wire.MsgTx) {
h.Lock()
defer h.Unlock()
sigHashes := NewTxSigHashes(tx)
txid := tx.TxHash()
h.sigHashes[txid] = sigHashes
return
}
示例5: TestCalcSignatureHash
// TestCalcSignatureHash runs the Bitcoin Core signature hash calculation tests
// in sighash.json.
// https://github.com/bitcoin/bitcoin/blob/master/src/test/data/sighash.json
func TestCalcSignatureHash(t *testing.T) {
file, err := ioutil.ReadFile("data/sighash.json")
if err != nil {
t.Errorf("TestCalcSignatureHash: %v\n", err)
return
}
var tests [][]interface{}
err = json.Unmarshal(file, &tests)
if err != nil {
t.Errorf("TestCalcSignatureHash couldn't Unmarshal: %v\n",
err)
return
}
for i, test := range tests {
if i == 0 {
// Skip first line -- contains comments only.
continue
}
if len(test) != 5 {
t.Fatalf("TestCalcSignatureHash: Test #%d has "+
"wrong length.", i)
}
var tx wire.MsgTx
rawTx, _ := hex.DecodeString(test[0].(string))
err := tx.Deserialize(bytes.NewReader(rawTx))
if err != nil {
t.Errorf("TestCalcSignatureHash failed test #%d: "+
"Failed to parse transaction: %v", i, err)
continue
}
subScript, _ := hex.DecodeString(test[1].(string))
parsedScript, err := parseScript(subScript)
if err != nil {
t.Errorf("TestCalcSignatureHash failed test #%d: "+
"Failed to parse sub-script: %v", i, err)
continue
}
hashType := SigHashType(testVecF64ToUint32(test[3].(float64)))
hash := calcSignatureHash(parsedScript, hashType, &tx,
int(test[2].(float64)))
expectedHash, _ := chainhash.NewHashFromStr(test[4].(string))
if !bytes.Equal(hash, expectedHash[:]) {
t.Errorf("TestCalcSignatureHash failed test #%d: "+
"Signature hash mismatch.", i)
}
}
}
示例6: spendOutput
func spendOutput(txHash *wire.ShaHash, index uint32, outputValues ...int64) *wire.MsgTx {
tx := wire.MsgTx{
TxIn: []*wire.TxIn{
&wire.TxIn{
PreviousOutPoint: wire.OutPoint{Hash: *txHash, Index: index},
},
},
}
for _, val := range outputValues {
tx.TxOut = append(tx.TxOut, &wire.TxOut{Value: val})
}
return &tx
}
示例7: newCoinBase
func newCoinBase(outputValues ...int64) *wire.MsgTx {
tx := wire.MsgTx{
TxIn: []*wire.TxIn{
&wire.TxIn{
PreviousOutPoint: wire.OutPoint{Index: ^uint32(0)},
},
},
}
for _, val := range outputValues {
tx.TxOut = append(tx.TxOut, &wire.TxOut{Value: val})
}
return &tx
}
示例8: receiverHtlcSpendRedeem
// receiverHtlcSpendRedeem constructs a valid witness allowing the receiver of
// an HTLC to redeem the conditional payment in the event that their commitment
// transaction is broadcast. Since this is a pay out to the receiving party as
// an output on their commitment transaction, a relative time delay is required
// before the output can be spent.
func receiverHtlcSpendRedeem(commitScript []byte, outputAmt btcutil.Amount,
reciverKey *btcec.PrivateKey, sweepTx *wire.MsgTx,
paymentPreimage []byte, relativeTimeout uint32) (wire.TxWitness, error) {
// In order to properly spend the transaction, we need to set the
// sequence number. We do this by convering the relative block delay
// into a sequence number value able to be interpeted by
// OP_CHECKSEQUENCEVERIFY.
sweepTx.TxIn[0].Sequence = lockTimeToSequence(false, relativeTimeout)
// Additionally, OP_CSV requires that the version of the transaction
// spending a pkscript with OP_CSV within it *must* be >= 2.
sweepTx.Version = 2
hashCache := txscript.NewTxSigHashes(sweepTx)
sweepSig, err := txscript.RawTxInWitnessSignature(
sweepTx, hashCache, 0, int64(outputAmt), commitScript,
txscript.SigHashAll, reciverKey)
if err != nil {
return nil, err
}
// Place a one as the first item in the evaluated witness stack to
// force script execution to the HTLC redemption clause.
witnessStack := wire.TxWitness(make([][]byte, 4))
witnessStack[0] = sweepSig
witnessStack[1] = paymentPreimage
witnessStack[2] = []byte{1}
witnessStack[3] = commitScript
return witnessStack, nil
}
示例9: receiverHtlcSpendTimeout
// receiverHtlcSpendTimeout constructs a valid witness allowing the sender of
// an HTLC to recover the pending funds after an absolute timeout in the
// scenario that the receiver of the HTLC broadcasts their version of the
// commitment transaction.
func receiverHtlcSpendTimeout(commitScript []byte, outputAmt btcutil.Amount,
senderKey *btcec.PrivateKey, sweepTx *wire.MsgTx,
absoluteTimeout uint32) (wire.TxWitness, error) {
// The HTLC output has an absolute time period before we are permitted
// to recover the pending funds. Therefore we need to set the locktime
// on this sweeping transaction in order to pass Script verification.
sweepTx.LockTime = absoluteTimeout
hashCache := txscript.NewTxSigHashes(sweepTx)
sweepSig, err := txscript.RawTxInWitnessSignature(
sweepTx, hashCache, 0, int64(outputAmt), commitScript,
txscript.SigHashAll, senderKey)
if err != nil {
return nil, err
}
witnessStack := wire.TxWitness(make([][]byte, 4))
witnessStack[0] = sweepSig
witnessStack[1] = []byte{0}
witnessStack[2] = []byte{0}
witnessStack[3] = commitScript
return witnessStack, nil
}
示例10: equalTxs
func equalTxs(t *testing.T, got, exp *wire.MsgTx) {
var bufGot, bufExp bytes.Buffer
err := got.Serialize(&bufGot)
if err != nil {
t.Fatal(err)
}
err = exp.Serialize(&bufExp)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(bufGot.Bytes(), bufExp.Bytes()) {
t.Errorf("Found unexpected wire.MsgTx:")
t.Errorf("Got: %v", got)
t.Errorf("Expected: %v", exp)
}
}
示例11: PublishTransaction
// BUGS:
// - The transaction is not inspected to be relevant before publishing using
// sendrawtransaction, so connection errors to btcd could result in the tx
// never being added to the wallet database.
// - Once the above bug is fixed, wallet will require a way to purge invalid
// transactions from the database when they are rejected by the network, other
// than double spending them.
func (s *walletServer) PublishTransaction(ctx context.Context, req *pb.PublishTransactionRequest) (
*pb.PublishTransactionResponse, error) {
var msgTx wire.MsgTx
err := msgTx.Deserialize(bytes.NewReader(req.SignedTransaction))
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"Bytes do not represent a valid raw transaction: %v", err)
}
err = s.wallet.PublishTransaction(&msgTx)
if err != nil {
return nil, translateError(err)
}
return &pb.PublishTransactionResponse{}, nil
}
示例12: TxToString
// TxToString prints out some info about a transaction. for testing / debugging
func TxToString(tx *wire.MsgTx) string {
str := fmt.Sprintf("size %d vsize %d wsize %d locktime %d txid %s\n",
tx.SerializeSize(), blockchain.GetTxVirtualSize(btcutil.NewTx(tx)),
tx.SerializeSize(), tx.LockTime, tx.TxSha().String())
for i, in := range tx.TxIn {
str += fmt.Sprintf("Input %d spends %s\n", i, in.PreviousOutPoint.String())
str += fmt.Sprintf("\tSigScript: %x\n", in.SignatureScript)
for j, wit := range in.Witness {
str += fmt.Sprintf("\twitness %d: %x\n", j, wit)
}
}
for i, out := range tx.TxOut {
if out != nil {
str += fmt.Sprintf("output %d script: %x amt: %d\n",
i, out.PkScript, out.Value)
} else {
str += fmt.Sprintf("output %d nil (WARNING)\n", i)
}
}
return str
}
示例13: NewOutgoingTx
func (s *SPVCon) NewOutgoingTx(tx *wire.MsgTx) error {
txid := tx.TxSha()
// assign height of zero for txs we create
err := s.TS.AddTxid(&txid, 0)
if err != nil {
return err
}
_, err = s.TS.Ingest(tx, 0) // our own tx; don't keep track of false positives
if err != nil {
return err
}
// make an inv message instead of a tx message to be polite
iv1 := wire.NewInvVect(wire.InvTypeWitnessTx, &txid)
invMsg := wire.NewMsgInv()
err = invMsg.AddInvVect(iv1)
if err != nil {
return err
}
s.outMsgQueue <- invMsg
return nil
}
示例14: senderHtlcSpendTimeout
// htlcSpendTimeout constructs a valid witness allowing the sender of an HTLC
// to recover the pending funds after an absolute, then relative locktime
// period.
func senderHtlcSpendTimeout(commitScript []byte, outputAmt btcutil.Amount,
senderKey *btcec.PrivateKey, sweepTx *wire.MsgTx,
absoluteTimeout, relativeTimeout uint32) (wire.TxWitness, error) {
// Since the HTLC output has an absolute timeout before we're permitted
// to sweep the output, we need to set the locktime of this sweepign
// transaction to that aboslute value in order to pass Script
// verification.
sweepTx.LockTime = absoluteTimeout
// Additionally, we're required to wait a relative period of time
// before we can sweep the output in order to allow the other party to
// contest our claim of validity to this version of the commitment
// transaction.
sweepTx.TxIn[0].Sequence = lockTimeToSequence(false, relativeTimeout)
// Finally, OP_CSV requires that the version of the transaction
// spending a pkscript with OP_CSV within it *must* be >= 2.
sweepTx.Version = 2
hashCache := txscript.NewTxSigHashes(sweepTx)
sweepSig, err := txscript.RawTxInWitnessSignature(
sweepTx, hashCache, 0, int64(outputAmt), commitScript,
txscript.SigHashAll, senderKey)
if err != nil {
return nil, err
}
// We place a zero as the first item of the evaluated witness stack in
// order to force Script execution to the HTLC timeout clause.
witnessStack := wire.TxWitness(make([][]byte, 3))
witnessStack[0] = sweepSig
witnessStack[1] = []byte{0}
witnessStack[2] = commitScript
return witnessStack, nil
}
示例15: EstFee
// EstFee gives a fee estimate based on a tx and a sat/Byte target.
// The TX should have all outputs, including the change address already
// populated (with potentially 0 amount. Also it should have all inputs
// populated, but inputs don't need to have sigscripts or witnesses
// (it'll guess the sizes of sigs/wits that arent' filled in).
func EstFee(otx *wire.MsgTx, spB int64) int64 {
mtsig := make([]byte, 72)
mtpub := make([]byte, 33)
tx := otx.Copy()
// iterate through txins, replacing subscript sigscripts with noise
// sigs or witnesses
for _, txin := range tx.TxIn {
// check wpkh
if len(txin.SignatureScript) == 22 &&
txin.SignatureScript[0] == 0x00 && txin.SignatureScript[1] == 0x14 {
txin.SignatureScript = nil
txin.Witness = make([][]byte, 2)
txin.Witness[0] = mtsig
txin.Witness[1] = mtpub
} else if len(txin.SignatureScript) == 34 &&
txin.SignatureScript[0] == 0x00 && txin.SignatureScript[1] == 0x20 {
// p2wsh -- sig lenght is a total guess!
txin.SignatureScript = nil
txin.Witness = make([][]byte, 3)
// 3 sigs? totally guessing here
txin.Witness[0] = mtsig
txin.Witness[1] = mtsig
txin.Witness[2] = mtsig
} else {
// assume everything else is p2pkh. Even though it's not
txin.Witness = nil
txin.SignatureScript = make([]byte, 105) // len of p2pkh sigscript
}
}
fmt.Printf(TxToString(tx))
size := int64(blockchain.GetTxVirtualSize(btcutil.NewTx(tx)))
fmt.Printf("%d spB, est vsize %d, fee %d\n", spB, size, size*spB)
return size * spB
}