本文整理汇总了Golang中github.com/decred/dcrd/wire.MsgTx类的典型用法代码示例。如果您正苦于以下问题:Golang MsgTx类的具体用法?Golang MsgTx怎么用?Golang MsgTx使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MsgTx类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: 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 in the txindex", 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
}
开发者ID:decred,项目名称:dcrd,代码行数:27,代码来源:manager.go
示例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 int64) 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)
}
开发者ID:decred,项目名称:dcrd,代码行数:39,代码来源:policy.go
示例3: Receive
// Receive waits for the response promised by the future and returns a
// transaction given its hash.
func (r FutureGetRawTransactionResult) Receive() (*dcrutil.Tx, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a string.
var txHex string
err = json.Unmarshal(res, &txHex)
if err != nil {
return nil, err
}
// Decode the serialized transaction hex to raw bytes.
serializedTx, err := hex.DecodeString(txHex)
if err != nil {
return nil, err
}
// Deserialize the transaction and return it.
var msgTx wire.MsgTx
if err := msgTx.Deserialize(bytes.NewReader(serializedTx)); err != nil {
return nil, err
}
return dcrutil.NewTx(&msgTx), nil
}
开发者ID:Action-Committee,项目名称:dcrrpcclient,代码行数:28,代码来源:rawtransactions.go
示例4: fetchTxDataByLoc
// fetchTxDataByLoc returns several pieces of data regarding the given tx
// located by the block/offset/size location
func (db *LevelDb) fetchTxDataByLoc(blkHeight int64, txOff int, txLen int, txspent []byte) (rtx *wire.MsgTx, rblksha *chainhash.Hash, rheight int64, rtxspent []byte, err error) {
var blksha *chainhash.Hash
var blkbuf []byte
blksha, blkbuf, err = db.getBlkByHeight(blkHeight)
if err != nil {
if err == leveldb.ErrNotFound {
err = database.ErrTxShaMissing
}
return
}
if len(blkbuf) < txOff+txLen {
log.Warnf("block buffer overrun while looking for tx: "+
"block %v %v txoff %v txlen %v", blkHeight, blksha, txOff, txLen)
err = database.ErrDbInconsistency
return
}
rbuf := bytes.NewReader(blkbuf[txOff : txOff+txLen])
var tx wire.MsgTx
err = tx.Deserialize(rbuf)
if err != nil {
log.Warnf("unable to decode tx block %v %v txoff %v txlen %v",
blkHeight, blksha, txOff, txLen)
err = database.ErrDbInconsistency
return
}
return &tx, blksha, blkHeight, txspent, nil
}
开发者ID:zebbra2014,项目名称:dcrd,代码行数:33,代码来源:tx.go
示例5: TestForVMFailure
// TestForVMFailure feeds random scripts to the VMs to check and see if it
// crashes. Try increasing the number of iterations or the length of the
// byte string to sample a greater space.
func TestForVMFailure(t *testing.T) {
numTests := 2
bsLength := 11
for i := 0; i < numTests; i++ {
tests := randByteSliceSlice(65536, bsLength, i)
for j := range tests {
if j == 0 {
continue
}
msgTx := new(wire.MsgTx)
msgTx.AddTxIn(&wire.TxIn{
PreviousOutPoint: wire.OutPoint{},
SignatureScript: tests[j-1],
Sequence: 0xFFFFFFFF,
})
msgTx.AddTxOut(&wire.TxOut{
Value: 0x00FFFFFF00000000,
PkScript: []byte{0x01},
})
flags := StandardVerifyFlags
engine, err := NewEngine(tests[j], msgTx, 0, flags, 0,
nil)
if err == nil {
engine.Execute()
}
}
}
}
开发者ID:decred,项目名称:dcrd,代码行数:35,代码来源:opcode_test.go
示例6: deserializeSStxRecord
// deserializeSStxRecord deserializes the passed serialized tx record information.
func deserializeSStxRecord(serializedSStxRecord []byte) (*sstxRecord, error) {
record := new(sstxRecord)
curPos := 0
// Read MsgTx size (as a uint64).
msgTxLen := int(byteOrder.Uint64(
serializedSStxRecord[curPos : curPos+int64Size]))
curPos += int64Size
// Pretend to read the pkScrLoc for the 0th output pkScript.
curPos += int32Size
// Read the intended voteBits and extended voteBits length (uint8).
record.voteBitsSet = false
voteBitsLen := uint8(serializedSStxRecord[curPos])
if voteBitsLen != 0 {
record.voteBitsSet = true
}
curPos += int8Size
// Read the assumed 2 byte VoteBits as well as the extended
// votebits (75 bytes max).
record.voteBits = byteOrder.Uint16(
serializedSStxRecord[curPos : curPos+int16Size])
curPos += int16Size
record.voteBitsExt = make([]byte, int(voteBitsLen)-int16Size)
copy(record.voteBitsExt[:],
serializedSStxRecord[curPos:curPos+int(voteBitsLen)-int16Size])
curPos += stake.MaxSingleBytePushLength - int16Size
// Prepare a buffer for the msgTx.
buf := bytes.NewBuffer(serializedSStxRecord[curPos : curPos+msgTxLen])
curPos += msgTxLen
// Deserialize transaction.
msgTx := new(wire.MsgTx)
err := msgTx.Deserialize(buf)
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
// Create and save the dcrutil.Tx of the read MsgTx and set its index.
tx := dcrutil.NewTx((*wire.MsgTx)(msgTx))
tx.SetIndex(dcrutil.TxIndexUnknown)
tx.SetTree(dcrutil.TxTreeStake)
record.tx = tx
// Read received unix time (int64).
received := int64(byteOrder.Uint64(
serializedSStxRecord[curPos : curPos+int64Size]))
curPos += int64Size
record.ts = time.Unix(received, 0)
return record, nil
}
开发者ID:jcvernaleo,项目名称:btcwallet,代码行数:60,代码来源:db.go
示例7: NewTx
// NewTx returns a new instance of a transaction given an underlying
// wire.MsgTx. See Tx.
func NewTx(msgTx *wire.MsgTx) *Tx {
return &Tx{
hash: msgTx.TxHash(),
msgTx: msgTx,
txTree: wire.TxTreeUnknown,
txIndex: TxIndexUnknown,
}
}
开发者ID:decred,项目名称:dcrutil,代码行数:10,代码来源:tx.go
示例8: 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
}
开发者ID:frankbraun,项目名称:dcrwallet,代码行数:13,代码来源:tx_test.go
示例9: spendOutput
func spendOutput(txHash *chainhash.Hash, 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
}
开发者ID:frankbraun,项目名称:dcrwallet,代码行数:13,代码来源:tx_test.go
示例10: SendRawTransactionAsync
// SendRawTransactionAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function on
// the returned instance.
//
// See SendRawTransaction for the blocking version and more details.
func (c *Client) SendRawTransactionAsync(tx *wire.MsgTx, allowHighFees bool) FutureSendRawTransactionResult {
txHex := ""
if tx != nil {
// Serialize the transaction and convert to hex string.
buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize()))
if err := tx.Serialize(buf); err != nil {
return newFutureError(err)
}
txHex = hex.EncodeToString(buf.Bytes())
}
cmd := dcrjson.NewSendRawTransactionCmd(txHex, &allowHighFees)
return c.sendCmd(cmd)
}
开发者ID:Action-Committee,项目名称:dcrrpcclient,代码行数:19,代码来源:rawtransactions.go
示例11: SignRawTransaction2Async
// SignRawTransaction2Async returns an instance of a type that can be used to
// get the result of the RPC at some future time by invoking the Receive
// function on the returned instance.
//
// See SignRawTransaction2 for the blocking version and more details.
func (c *Client) SignRawTransaction2Async(tx *wire.MsgTx, inputs []dcrjson.RawTxInput) FutureSignRawTransactionResult {
txHex := ""
if tx != nil {
// Serialize the transaction and convert to hex string.
buf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize()))
if err := tx.Serialize(buf); err != nil {
return newFutureError(err)
}
txHex = hex.EncodeToString(buf.Bytes())
}
cmd := dcrjson.NewSignRawTransactionCmd(txHex, &inputs, nil, nil)
return c.sendCmd(cmd)
}
开发者ID:Action-Committee,项目名称:dcrrpcclient,代码行数:19,代码来源:rawtransactions.go
示例12: 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: %x", bufGot.Bytes())
t.Errorf("Expected: %x", bufExp.Bytes())
}
}
开发者ID:decred,项目名称:dcrwallet,代码行数:16,代码来源:query_test.go
示例13: PublishTransaction
// BUGS:
// - The transaction is not inspected to be relevant before publishing using
// sendrawtransaction, so connection errors to dcrd 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)
}
txHash, err := s.wallet.PublishTransaction(&msgTx)
if err != nil {
return nil, translateError(err)
}
return &pb.PublishTransactionResponse{TransactionHash: txHash[:]}, nil
}
开发者ID:decred,项目名称:dcrwallet,代码行数:24,代码来源:server.go
示例14: NewTxFromReader
// NewTxFromReader returns a new instance of a transaction given a
// Reader to deserialize the transaction. See Tx.
func NewTxFromReader(r io.Reader) (*Tx, error) {
// Deserialize the bytes into a MsgTx.
var msgTx wire.MsgTx
err := msgTx.Deserialize(r)
if err != nil {
return nil, err
}
t := Tx{
hash: msgTx.TxHash(),
msgTx: &msgTx,
txTree: wire.TxTreeUnknown,
txIndex: TxIndexUnknown,
}
return &t, nil
}
开发者ID:decred,项目名称:dcrutil,代码行数:19,代码来源:tx.go
示例15: NewTxDeepTxIns
// NewTxDeepTxIns is used to deep copy a transaction, maintaining the old
// pointers to the TxOuts while replacing the old pointers to the TxIns with
// deep copies. This is to prevent races when the fraud proofs for the
// transactions are set by the miner.
func NewTxDeepTxIns(msgTx *wire.MsgTx) *Tx {
if msgTx == nil {
return nil
}
newMsgTx := new(wire.MsgTx)
// Copy the fixed fields.
newMsgTx.Version = msgTx.Version
newMsgTx.LockTime = msgTx.LockTime
newMsgTx.Expiry = msgTx.Expiry
// Copy the TxIns deeply.
for _, txIn := range msgTx.TxIn {
sigScrLen := len(txIn.SignatureScript)
sigScrCopy := make([]byte, sigScrLen, sigScrLen)
txInCopy := new(wire.TxIn)
txInCopy.PreviousOutPoint.Hash = txIn.PreviousOutPoint.Hash
txInCopy.PreviousOutPoint.Index = txIn.PreviousOutPoint.Index
txInCopy.PreviousOutPoint.Tree = txIn.PreviousOutPoint.Tree
txInCopy.Sequence = txIn.Sequence
txInCopy.ValueIn = txIn.ValueIn
txInCopy.BlockHeight = txIn.BlockHeight
txInCopy.BlockIndex = txIn.BlockIndex
txInCopy.SignatureScript = sigScrCopy
newMsgTx.AddTxIn(txIn)
}
// Shallow copy the TxOuts.
for _, txOut := range msgTx.TxOut {
newMsgTx.AddTxOut(txOut)
}
return &Tx{
hash: msgTx.TxHash(),
msgTx: msgTx,
txTree: wire.TxTreeUnknown,
txIndex: TxIndexUnknown,
}
}
开发者ID:decred,项目名称:dcrutil,代码行数:48,代码来源:tx.go
示例16: SignTransaction
// BUGS:
// - InputIndexes request field is ignored.
func (s *walletServer) SignTransaction(ctx context.Context, req *pb.SignTransactionRequest) (
*pb.SignTransactionResponse, error) {
defer zero.Bytes(req.Passphrase)
var tx wire.MsgTx
err := tx.Deserialize(bytes.NewReader(req.SerializedTransaction))
if err != nil {
return nil, grpc.Errorf(codes.InvalidArgument,
"Bytes do not represent a valid raw transaction: %v", err)
}
lock := make(chan time.Time, 1)
defer func() {
lock <- time.Time{} // send matters, not the value
}()
err = s.wallet.Unlock(req.Passphrase, lock)
if err != nil {
return nil, translateError(err)
}
invalidSigs, err := s.wallet.SignTransaction(&tx, txscript.SigHashAll, nil, nil, nil)
if err != nil {
return nil, translateError(err)
}
invalidInputIndexes := make([]uint32, len(invalidSigs))
for i, e := range invalidSigs {
invalidInputIndexes[i] = e.InputIndex
}
var serializedTransaction bytes.Buffer
serializedTransaction.Grow(tx.SerializeSize())
err = tx.Serialize(&serializedTransaction)
if err != nil {
return nil, translateError(err)
}
resp := &pb.SignTransactionResponse{
Transaction: serializedTransaction.Bytes(),
UnsignedInputIndexes: invalidInputIndexes,
}
return resp, nil
}
开发者ID:decred,项目名称:dcrwallet,代码行数:46,代码来源:server.go
示例17: TestStakeInvalidationOfTip
func TestStakeInvalidationOfTip(t *testing.T) {
db, s, teardown, err := setup()
defer teardown()
if err != nil {
t.Fatal(err)
}
g := makeBlockGenerator()
block1Header := g.generate(dcrutil.BlockValid)
block2Header := g.generate(dcrutil.BlockValid)
block3Header := g.generate(0)
block1Tx := wire.MsgTx{
TxOut: []*wire.TxOut{{Value: 2e8}},
}
block2Tx := wire.MsgTx{
TxIn: []*wire.TxIn{
{PreviousOutPoint: wire.OutPoint{Hash: block1Tx.TxSha(), Index: 0, Tree: 0}},
},
TxOut: []*wire.TxOut{{Value: 1e8}},
}
block1TxRec, err := NewTxRecordFromMsgTx(&block1Tx, time.Time{})
if err != nil {
t.Fatal(err)
}
block2TxRec, err := NewTxRecordFromMsgTx(&block2Tx, time.Time{})
if err != nil {
t.Fatal(err)
}
const balanceFlag = BFBalanceSpendable
err = walletdb.Update(db, func(tx walletdb.ReadWriteTx) error {
ns := tx.ReadWriteBucket(wtxmgrNamespaceKey)
addrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)
err := s.InsertMemPoolTx(ns, block1TxRec)
if err != nil {
return err
}
err = s.AddCredit(ns, block1TxRec, nil, 0, false, 0)
if err != nil {
return err
}
err = s.InsertMemPoolTx(ns, block2TxRec)
if err != nil {
return err
}
err = s.AddCredit(ns, block2TxRec, nil, 0, false, 0)
if err != nil {
return err
}
bal, err := s.Balance(ns, addrmgrNs, 0, balanceFlag, false, 0)
if err != nil {
return err
}
if bal != 1e8 {
t.Errorf("Wrong balance before mining either transaction: %v", bal)
}
headerData := makeHeaderDataSlice(block1Header, block2Header)
err = s.InsertMainChainHeaders(ns, addrmgrNs, headerData)
if err != nil {
return err
}
err = s.InsertMinedTx(ns, addrmgrNs, block1TxRec, &headerData[0].BlockHash)
if err != nil {
return err
}
err = s.InsertMinedTx(ns, addrmgrNs, block2TxRec, &headerData[1].BlockHash)
if err != nil {
return err
}
// At this point there should only be one credit for the tx in block 2.
bal, err = s.Balance(ns, addrmgrNs, 1, balanceFlag, false, 0)
if err != nil {
return err
}
if bal != dcrutil.Amount(block2Tx.TxOut[0].Value) {
t.Errorf("Wrong balance: expected %v got %v", dcrutil.Amount(block2Tx.TxOut[0].Value), bal)
}
credits, err := s.UnspentOutputs(ns)
if err != nil {
return err
}
if len(credits) != 1 {
t.Errorf("Expected only 1 credit, got %v", len(credits))
return nil
}
if credits[0].Hash != block2Tx.TxSha() {
t.Errorf("Credit hash does match tx from block 2")
return nil
}
if credits[0].Amount != dcrutil.Amount(block2Tx.TxOut[0].Value) {
t.Errorf("Credit value does not match tx output 0 from block 2")
return nil
}
//.........这里部分代码省略.........
开发者ID:decred,项目名称:dcrwallet,代码行数:101,代码来源:stakevalidation_test.go
示例18: TestTxWireErrors
// TestTxWireErrors performs negative tests against wire encode and decode
// of MsgTx to confirm error paths work correctly.
func TestTxWireErrors(t *testing.T) {
// Use protocol version 60002 specifically here instead of the latest
// because the test data is using bytes encoded with that protocol
// version.
pver := uint32(60002)
tests := []struct {
in *wire.MsgTx // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Force error in version.
{multiTx, multiTxEncoded, pver, 0, io.ErrShortWrite, io.EOF}, // 0
// Force error in number of transaction inputs.
{multiTx, multiTxEncoded, pver, 4, io.ErrShortWrite, io.EOF}, // 1
// Force error in transaction input previous block hash.
{multiTx, multiTxEncoded, pver, 5, io.ErrShortWrite, io.EOF}, // 2
// Force error in transaction input previous block output index.
{multiTx, multiTxEncoded, pver, 37, io.ErrShortWrite, io.EOF}, // 3
// Force error in transaction input previous block output tree.
{multiTx, multiTxEncoded, pver, 41, io.ErrShortWrite, io.EOF}, // 4
// Force error in transaction input sequence.
{multiTx, multiTxEncoded, pver, 42, io.ErrShortWrite, io.EOF}, // 5
// Force error in number of transaction outputs.
{multiTx, multiTxEncoded, pver, 46, io.ErrShortWrite, io.EOF}, // 6
// Force error in transaction output value.
{multiTx, multiTxEncoded, pver, 47, io.ErrShortWrite, io.EOF}, // 7
// Force error in transaction output script version.
{multiTx, multiTxEncoded, pver, 55, io.ErrShortWrite, io.EOF}, // 8
// Force error in transaction output pk script length.
{multiTx, multiTxEncoded, pver, 57, io.ErrShortWrite, io.EOF}, // 9
// Force error in transaction output pk script.
{multiTx, multiTxEncoded, pver, 58, io.ErrShortWrite, io.EOF}, // 10
// Force error in transaction output lock time.
{multiTx, multiTxEncoded, pver, 203, io.ErrShortWrite, io.EOF}, // 11
// Force error in transaction output expiry.
{multiTx, multiTxEncoded, pver, 207, io.ErrShortWrite, io.EOF}, // 12
// Force error in transaction num sig varint.
{multiTx, multiTxEncoded, pver, 211, io.ErrShortWrite, io.EOF}, // 13
// Force error in transaction sig 0 AmountIn.
{multiTx, multiTxEncoded, pver, 212, io.ErrShortWrite, io.EOF}, // 14
// Force error in transaction sig 0 BlockHeight.
{multiTx, multiTxEncoded, pver, 220, io.ErrShortWrite, io.EOF}, // 15
// Force error in transaction sig 0 BlockIndex.
{multiTx, multiTxEncoded, pver, 224, io.ErrShortWrite, io.EOF}, // 16
// Force error in transaction sig 0 length.
{multiTx, multiTxEncoded, pver, 228, io.ErrShortWrite, io.EOF}, // 17
// Force error in transaction sig 0 signature script.
{multiTx, multiTxEncoded, pver, 229, io.ErrShortWrite, io.EOF}, // 18
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver)
if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
continue
}
// Decode from wire format.
var msg wire.MsgTx
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver)
if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)
continue
}
}
}
开发者ID:ironbits,项目名称:dcrd,代码行数:78,代码来源:msgtx_test.go
示例19: TestTxSerializeWitnessValueSigning
// TestTxSerializeWitnessValueSigning tests MsgTx serialize and deserialize.
func TestTxSerializeWitnessValueSigning(t *testing.T) {
noTx := wire.NewMsgTx()
noTx.Version = 262145
noTxEncoded := []byte{
0x01, 0x00, 0x04, 0x00, // Version
0x00, // Varint for number of input signatures
}
tests := []struct {
in *wire.MsgTx // Message to encode
out *wire.MsgTx // Expected decoded message
buf []byte // Serialized data
pkScriptLocs []int // Expected output script locations
}{
// No transactions.
{
noTx,
noTx,
noTxEncoded,
nil,
},
// Multiple transactions.
{
multiTxWitnessValueSigning,
multiTxWitnessValueSigning,
multiTxWitnessValueSigningEncoded,
nil,
},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Serialize the transaction.
var buf bytes.Buffer
err := test.in.Serialize(&buf)
if err != nil {
t.Errorf("Serialize #%d error %v", i, err)
continue
}
if !bytes.Equal(buf.Bytes(), test.buf) {
t.Errorf("Serialize #%d\n got: %s want: %s", i,
spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
continue
}
// Test SerializeSize.
sz := test.in.SerializeSize()
actualSz := len(buf.Bytes())
if sz != actualSz {
t.Errorf("Wrong serialize size #%d\n got: %s want: %s", i,
sz, actualSz)
}
// Deserialize the transaction.
var tx wire.MsgTx
rbuf := bytes.NewReader(test.buf)
err = tx.Deserialize(rbuf)
if err != nil {
t.Errorf("Deserialize #%d error %v", i, err)
continue
}
if !reflect.DeepEqual(&tx, test.out) {
t.Errorf("Deserialize #%d\n got: %s want: %s", i,
spew.Sdump(&tx), spew.Sdump(test.out))
continue
}
// Ensure the public key script locations are accurate.
pkScriptLocs := test.in.PkScriptLocs()
if !reflect.DeepEqual(pkScriptLocs, test.pkScriptLocs) {
t.Errorf("PkScriptLocs #%d\n got: %s want: %s", i,
spew.Sdump(pkScriptLocs),
spew.Sdump(test.pkScriptLocs))
continue
}
for j, loc := range pkScriptLocs {
wantPkScript := test.in.TxOut[j].PkScript
gotPkScript := test.buf[loc : loc+len(wantPkScript)]
if !bytes.Equal(gotPkScript, wantPkScript) {
t.Errorf("PkScriptLocs #%d:%d\n unexpected "+
"script got: %s want: %s", i, j,
spew.Sdump(gotPkScript),
spew.Sdump(wantPkScript))
}
}
}
}
开发者ID:ironbits,项目名称:dcrd,代码行数:89,代码来源:msgtx_test.go
示例20: TestTxSerializeErrors
// TestTxSerializeErrors performs negative tests against wire encode and decode
// of MsgTx to confirm error paths work correctly.
func TestTxSerializeErrors(t *testing.T) {
tests := []struct {
in *wire.MsgTx // Value to encode
buf []byte // Serialized data
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
// Force error in version.
{multiTx, multiTxEncoded, 0, io.ErrShortWrite, io.EOF},
// Force error in number of transaction inputs.
{multiTx, multiTxEncoded, 4, io.ErrShortWrite, io.EOF},
// Force error in transaction input previous block hash.
{multiTx, multiTxEncoded, 5, io.ErrShortWrite, io.EOF},
// Force error in transaction input previous block output index.
{multiTx, multiTxEncoded, 37, io.ErrShortWrite, io.EOF},
// Force error in transaction input previous block output tree.
{multiTx, multiTxEncoded, 41, io.ErrShortWrite, io.EOF},
// Force error in transaction input sequence.
{multiTx, multiTxEncoded, 42, io.ErrShortWrite, io.EOF},
// Force error in number of transaction outputs.
{multiTx, multiTxEncoded, 46, io.ErrShortWrite, io.EOF},
// Force error in transaction output value.
{multiTx, multiTxEncoded, 47, io.ErrShortWrite, io.EOF},
// Force error in transaction output version.
{multiTx, multiTxEncoded, 55, io.ErrShortWrite, io.EOF},
// Force error in transaction output pk script length.
{multiTx, multiTxEncoded, 57, io.ErrShortWrite, io.EOF},
// Force error in transaction output pk script.
{multiTx, multiTxEncoded, 58, io.ErrShortWrite, io.EOF},
// Force error in transaction lock time.
{multiTx, multiTxEncoded, 203, io.ErrShortWrite, io.EOF},
// Force error in transaction expiry.
{multiTx, multiTxEncoded, 207, io.ErrShortWrite, io.EOF},
// Force error in transaction num sig varint.
{multiTx, multiTxEncoded, 211, io.ErrShortWrite, io.EOF},
// Force error in transaction sig 0 ValueIn.
{multiTx, multiTxEncoded, 212, io.ErrShortWrite, io.EOF},
// Force error in transaction sig 0 BlockHeight.
{multiTx, multiTxEncoded, 220, io.ErrShortWrite, io.EOF},
// Force error in transaction sig 0 BlockIndex.
{multiTx, multiTxEncoded, 224, io.ErrShortWrite, io.EOF},
// Force error in transaction sig 0 length.
{multiTx, multiTxEncoded, 228, io.ErrShortWrite, io.EOF},
// Force error in transaction sig 0 signature script.
{multiTx, multiTxEncoded, 229, io.ErrShortWrite, io.EOF},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Serialize the transaction.
w := newFixedWriter(test.max)
err := test.in.Serialize(w)
if err != test.writeErr {
t.Errorf("Serialize #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
continue
}
// Deserialize the transaction.
var tx wire.MsgTx
r := newFixedReader(test.max, test.buf)
err = tx.Deserialize(r)
if err != test.readErr {
t.Errorf("Deserialize #%d wrong error got: %v, want: %v",
i, err, test.readErr)
continue
}
}
}
开发者ID:ironbits,项目名称:dcrd,代码行数:72,代码来源:msgtx_test.go
注:本文中的github.com/decred/dcrd/wire.MsgTx类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论