本文整理汇总了Golang中github.com/conseweb/stcd/wire.MsgTx类的典型用法代码示例。如果您正苦于以下问题:Golang MsgTx类的具体用法?Golang MsgTx怎么用?Golang MsgTx使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MsgTx类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: fetchTxDataByLoc
// fetchTxDataByLoc returns several pieces of data regarding the given tx
// located by the block/offset/size location
func (db *LevelDb) fetchTxDataByLoc(blkHeight int32, txOff int, txLen int, txspent []byte) (rtx *wire.MsgTx, rblksha *wire.ShaHash, rheight int32, rtxspent []byte, err error) {
var blksha *wire.ShaHash
var blkbuf []byte
blksha, blkbuf, err = db.getBlkByHeight(blkHeight)
if err != nil {
if err == leveldb.ErrNotFound {
err = database.ErrTxShaMissing
}
return
}
//log.Trace("transaction %v is at block %v %v txoff %v, txlen %v\n",
// txsha, blksha, blkHeight, txOff, txLen)
if len(blkbuf) < txOff+txLen {
err = database.ErrTxShaMissing
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)
return
}
return &tx, blksha, blkHeight, txspent, 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, txStore blockchain.TxStore, 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, txStore, nextBlockHeight)
return inputValueAge / float64(serializedTxSize-overhead)
}
示例3: 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 signature script length.
{multiTx, multiTxEncoded, 41, io.ErrShortWrite, io.EOF},
// Force error in transaction input signature script.
{multiTx, multiTxEncoded, 42, io.ErrShortWrite, io.EOF},
// Force error in transaction input sequence.
{multiTx, multiTxEncoded, 49, io.ErrShortWrite, io.EOF},
// Force error in number of transaction outputs.
{multiTx, multiTxEncoded, 53, io.ErrShortWrite, io.EOF},
// Force error in transaction output value.
{multiTx, multiTxEncoded, 54, io.ErrShortWrite, io.EOF},
// Force error in transaction output pk script length.
{multiTx, multiTxEncoded, 62, io.ErrShortWrite, io.EOF},
// Force error in transaction output pk script.
{multiTx, multiTxEncoded, 63, io.ErrShortWrite, io.EOF},
// Force error in transaction output lock time.
{multiTx, multiTxEncoded, 206, 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
}
}
}
示例4: 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
}
示例5: 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
}
示例6: addChange
// addChange adds a new output with the given amount and address, and
// randomizes the index (and returns it) of the newly added output.
func addChange(msgtx *wire.MsgTx, change coinutil.Amount, changeAddr coinutil.Address) (int, error) {
pkScript, err := txscript.PayToAddrScript(changeAddr)
if err != nil {
return 0, fmt.Errorf("cannot create txout script: %s", err)
}
msgtx.AddTxOut(wire.NewTxOut(int64(change), pkScript))
// Randomize index of the change output.
rng := badrand.New(badrand.NewSource(time.Now().UnixNano()))
r := rng.Int31n(int32(len(msgtx.TxOut))) // random index
c := len(msgtx.TxOut) - 1 // change index
msgtx.TxOut[r], msgtx.TxOut[c] = msgtx.TxOut[c], msgtx.TxOut[r]
return int(r), nil
}
示例7: NewTxFromReader
// NewTxFromReader returns a new instance of a bitcoin 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{
msgTx: &msgTx,
txIndex: TxIndexUnknown,
}
return &t, nil
}
示例8: NewTxRecordFromMsgTx
// NewTxRecordFromMsgTx creates a new transaction record that may be inserted
// into the store.
func NewTxRecordFromMsgTx(msgTx *wire.MsgTx, received time.Time) (*TxRecord, error) {
buf := bytes.NewBuffer(make([]byte, 0, msgTx.SerializeSize()))
err := msgTx.Serialize(buf)
if err != nil {
str := "failed to serialize transaction"
return nil, storeError(ErrInput, str, err)
}
rec := &TxRecord{
MsgTx: *msgTx,
Received: received,
SerializedTx: buf.Bytes(),
}
copy(rec.Hash[:], wire.DoubleSha256(rec.SerializedTx))
return rec, nil
}
示例9: 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)
}
}
示例10: addOutputs
// addOutputs adds the given address/amount pairs as outputs to msgtx,
// returning their total amount.
func addOutputs(msgtx *wire.MsgTx, pairs map[string]coinutil.Amount, chainParams *chaincfg.Params) (coinutil.Amount, error) {
var minAmount coinutil.Amount
for addrStr, amt := range pairs {
if amt <= 0 {
return minAmount, ErrNonPositiveAmount
}
minAmount += amt
addr, err := coinutil.DecodeAddress(addrStr, chainParams)
if err != nil {
return minAmount, fmt.Errorf("cannot decode address: %s", err)
}
// Add output to spend amt to addr.
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
return minAmount, fmt.Errorf("cannot create txout script: %s", err)
}
txout := wire.NewTxOut(int64(amt), pkScript)
msgtx.AddTxOut(txout)
}
return minAmount, nil
}
示例11: TestTxSerialize
// TestTxSerialize tests MsgTx serialize and deserialize.
func TestTxSerialize(t *testing.T) {
noTx := wire.NewMsgTx()
noTx.Version = 1
noTxEncoded := []byte{
0x01, 0x00, 0x00, 0x00, // Version
0x00, // Varint for number of input transactions
0x00, // Varint for number of output transactions
0x00, 0x00, 0x00, 0x00, // Lock time
}
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.
{
multiTx,
multiTx,
multiTxEncoded,
multiTxPkScriptLocs,
},
}
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
}
// 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))
}
}
}
}
示例12: 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},
// Force error in number of transaction inputs.
{multiTx, multiTxEncoded, pver, 4, io.ErrShortWrite, io.EOF},
// Force error in transaction input previous block hash.
{multiTx, multiTxEncoded, pver, 5, io.ErrShortWrite, io.EOF},
// Force error in transaction input previous block output index.
{multiTx, multiTxEncoded, pver, 37, io.ErrShortWrite, io.EOF},
// Force error in transaction input signature script length.
{multiTx, multiTxEncoded, pver, 41, io.ErrShortWrite, io.EOF},
// Force error in transaction input signature script.
{multiTx, multiTxEncoded, pver, 42, io.ErrShortWrite, io.EOF},
// Force error in transaction input sequence.
{multiTx, multiTxEncoded, pver, 49, io.ErrShortWrite, io.EOF},
// Force error in number of transaction outputs.
{multiTx, multiTxEncoded, pver, 53, io.ErrShortWrite, io.EOF},
// Force error in transaction output value.
{multiTx, multiTxEncoded, pver, 54, io.ErrShortWrite, io.EOF},
// Force error in transaction output pk script length.
{multiTx, multiTxEncoded, pver, 62, io.ErrShortWrite, io.EOF},
// Force error in transaction output pk script.
{multiTx, multiTxEncoded, pver, 63, io.ErrShortWrite, io.EOF},
// Force error in transaction output lock time.
{multiTx, multiTxEncoded, pver, 206, io.ErrShortWrite, io.EOF},
}
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
}
}
}
示例13: TestTxWire
// TestTxWire tests the MsgTx wire encode and decode for various numbers
// of transaction inputs and outputs and protocol versions.
func TestTxWire(t *testing.T) {
// Empty tx message.
noTx := wire.NewMsgTx()
noTx.Version = 1
noTxEncoded := []byte{
0x01, 0x00, 0x00, 0x00, // Version
0x00, // Varint for number of input transactions
0x00, // Varint for number of output transactions
0x00, 0x00, 0x00, 0x00, // Lock time
}
tests := []struct {
in *wire.MsgTx // Message to encode
out *wire.MsgTx // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version with no transactions.
{
noTx,
noTx,
noTxEncoded,
wire.ProtocolVersion,
},
// Latest protocol version with multiple transactions.
{
multiTx,
multiTx,
multiTxEncoded,
wire.ProtocolVersion,
},
// Protocol version BIP0035Version with no transactions.
{
noTx,
noTx,
noTxEncoded,
wire.BIP0035Version,
},
// Protocol version BIP0035Version with multiple transactions.
{
multiTx,
multiTx,
multiTxEncoded,
wire.BIP0035Version,
},
// Protocol version BIP0031Version with no transactions.
{
noTx,
noTx,
noTxEncoded,
wire.BIP0031Version,
},
// Protocol version BIP0031Version with multiple transactions.
{
multiTx,
multiTx,
multiTxEncoded,
wire.BIP0031Version,
},
// Protocol version NetAddressTimeVersion with no transactions.
{
noTx,
noTx,
noTxEncoded,
wire.NetAddressTimeVersion,
},
// Protocol version NetAddressTimeVersion with multiple transactions.
{
multiTx,
multiTx,
multiTxEncoded,
wire.NetAddressTimeVersion,
},
// Protocol version MultipleAddressVersion with no transactions.
{
noTx,
noTx,
noTxEncoded,
wire.MultipleAddressVersion,
},
// Protocol version MultipleAddressVersion with multiple transactions.
{
multiTx,
multiTx,
multiTxEncoded,
wire.MultipleAddressVersion,
},
}
//.........这里部分代码省略.........
示例14: InsertBlock
// InsertBlock inserts raw block and transaction data from a block into the
// database. The first block inserted into the database will be treated as the
// genesis block. Every subsequent block insert requires the referenced parent
// block to already exist.
func (db *LevelDb) InsertBlock(block *coinutil.Block) (height int32, rerr error) {
db.dbLock.Lock()
defer db.dbLock.Unlock()
defer func() {
if rerr == nil {
rerr = db.processBatches()
} else {
db.lBatch().Reset()
}
}()
blocksha := block.Sha()
mblock := block.MsgBlock()
rawMsg, err := block.Bytes()
if err != nil {
log.Warnf("Failed to obtain raw block sha %v", blocksha)
return 0, err
}
txloc, err := block.TxLoc()
if err != nil {
log.Warnf("Failed to obtain raw block sha %v", blocksha)
return 0, err
}
// Insert block into database
newheight, err := db.insertBlockData(blocksha, &mblock.Header.PrevBlock,
rawMsg)
if err != nil {
log.Warnf("Failed to insert block %v %v %v", blocksha,
&mblock.Header.PrevBlock, err)
return 0, err
}
// At least two blocks in the long past were generated by faulty
// miners, the sha of the transaction exists in a previous block,
// detect this condition and 'accept' the block.
for txidx, tx := range mblock.Transactions {
txsha, err := block.TxSha(txidx)
if err != nil {
log.Warnf("failed to compute tx name block %v idx %v err %v", blocksha, txidx, err)
return 0, err
}
spentbuflen := (len(tx.TxOut) + 7) / 8
spentbuf := make([]byte, spentbuflen, spentbuflen)
if len(tx.TxOut)%8 != 0 {
for i := uint(len(tx.TxOut) % 8); i < 8; i++ {
spentbuf[spentbuflen-1] |= (byte(1) << i)
}
}
err = db.insertTx(txsha, newheight, txloc[txidx].TxStart, txloc[txidx].TxLen, spentbuf)
if err != nil {
log.Warnf("block %v idx %v failed to insert tx %v %v err %v", blocksha, newheight, &txsha, txidx, err)
return 0, err
}
// Some old blocks contain duplicate transactions
// Attempt to cleanly bypass this problem by marking the
// first as fully spent.
// http://blockexplorer.com/b/91812 dup in 91842
// http://blockexplorer.com/b/91722 dup in 91880
if newheight == 91812 {
dupsha, err := wire.NewShaHashFromStr("d5d27987d2a3dfc724e359870c6644b40e497bdc0589a033220fe15429d88599")
if err != nil {
panic("invalid sha string in source")
}
if txsha.IsEqual(dupsha) {
// marking TxOut[0] as spent
po := wire.NewOutPoint(dupsha, 0)
txI := wire.NewTxIn(po, []byte("garbage"))
var spendtx wire.MsgTx
spendtx.AddTxIn(txI)
err = db.doSpend(&spendtx)
if err != nil {
log.Warnf("block %v idx %v failed to spend tx %v %v err %v", blocksha, newheight, &txsha, txidx, err)
}
}
}
if newheight == 91722 {
dupsha, err := wire.NewShaHashFromStr("e3bf3d07d4b0375638d5f1db5255fe07ba2c4cb067cd81b84ee974b6585fb468")
if err != nil {
panic("invalid sha string in source")
}
if txsha.IsEqual(dupsha) {
// marking TxOut[0] as spent
po := wire.NewOutPoint(dupsha, 0)
txI := wire.NewTxIn(po, []byte("garbage"))
var spendtx wire.MsgTx
spendtx.AddTxIn(txI)
err = db.doSpend(&spendtx)
if err != nil {
log.Warnf("block %v idx %v failed to spend tx %v %v err %v", blocksha, newheight, &txsha, txidx, err)
}
}
//.........这里部分代码省略.........
示例15: loadTxStore
// loadTxStore returns a transaction store loaded from a file.
func loadTxStore(filename string) (blockchain.TxStore, error) {
// The txstore file format is:
// <num tx data entries> <tx length> <serialized tx> <blk height>
// <num spent bits> <spent bits>
//
// All num and length fields are little-endian uint32s. The spent bits
// field is padded to a byte boundary.
filename = filepath.Join("testdata/", filename)
fi, err := os.Open(filename)
if err != nil {
return nil, err
}
// Choose read based on whether the file is compressed or not.
var r io.Reader
if strings.HasSuffix(filename, ".bz2") {
r = bzip2.NewReader(fi)
} else {
r = fi
}
defer fi.Close()
// Num of transaction store objects.
var numItems uint32
if err := binary.Read(r, binary.LittleEndian, &numItems); err != nil {
return nil, err
}
txStore := make(blockchain.TxStore)
var uintBuf uint32
for height := uint32(0); height < numItems; height++ {
txD := blockchain.TxData{}
// Serialized transaction length.
err = binary.Read(r, binary.LittleEndian, &uintBuf)
if err != nil {
return nil, err
}
serializedTxLen := uintBuf
if serializedTxLen > wire.MaxBlockPayload {
return nil, fmt.Errorf("Read serialized transaction "+
"length of %d is larger max allowed %d",
serializedTxLen, wire.MaxBlockPayload)
}
// Transaction.
var msgTx wire.MsgTx
err = msgTx.Deserialize(r)
if err != nil {
return nil, err
}
txD.Tx = coinutil.NewTx(&msgTx)
// Transaction hash.
txHash := msgTx.TxSha()
txD.Hash = &txHash
// Block height the transaction came from.
err = binary.Read(r, binary.LittleEndian, &uintBuf)
if err != nil {
return nil, err
}
txD.BlockHeight = int32(uintBuf)
// Num spent bits.
err = binary.Read(r, binary.LittleEndian, &uintBuf)
if err != nil {
return nil, err
}
numSpentBits := uintBuf
numSpentBytes := numSpentBits / 8
if numSpentBits%8 != 0 {
numSpentBytes++
}
// Packed spent bytes.
spentBytes := make([]byte, numSpentBytes)
_, err = io.ReadFull(r, spentBytes)
if err != nil {
return nil, err
}
// Populate spent data based on spent bits.
txD.Spent = make([]bool, numSpentBits)
for byteNum, spentByte := range spentBytes {
for bit := 0; bit < 8; bit++ {
if uint32((byteNum*8)+bit) < numSpentBits {
if spentByte&(1<<uint(bit)) != 0 {
txD.Spent[(byteNum*8)+bit] = true
}
}
}
}
txStore[*txD.Hash] = &txD
}
return txStore, nil
//.........这里部分代码省略.........