本文整理汇总了Golang中github.com/conformal/btcwire.MsgTx类的典型用法代码示例。如果您正苦于以下问题:Golang MsgTx类的具体用法?Golang MsgTx怎么用?Golang MsgTx使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MsgTx类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Receive
// Receive waits for the response promised by the future and returns a
// transaction given its hash.
func (r FutureGetRawTransactionResult) Receive() (*btcutil.Tx, error) {
reply, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Ensure the returned data is the expected type.
txHex, ok := reply.(string)
if !ok {
return nil, fmt.Errorf("unexpected response type for "+
"getrawtransaction (verbose=0): %T\n", reply)
}
// 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 btcwire.MsgTx
if err := msgTx.Deserialize(bytes.NewReader(serializedTx)); err != nil {
return nil, err
}
return btcutil.NewTx(&msgTx), nil
}
示例2: ProcessTransaction
// ProcessTransaction is the main workhorse for handling insertion of new
// free-standing transactions into a memory pool. It includes functionality
// such as rejecting duplicate transactions, ensuring transactions follow all
// rules, orphan transaction handling, and insertion into the memory pool.
func (mp *txMemPool) ProcessTransaction(tx *btcwire.MsgTx) error {
txHash, err := tx.TxSha()
if err != nil {
return err
}
log.Tracef("[TXMP] Processing transaction %v", txHash)
// Potentially accept the transaction to the memory pool.
var isOrphan bool
err = mp.maybeAcceptTransaction(tx, &isOrphan)
if err != nil {
return err
}
if !isOrphan {
// Accept any orphan transactions that depend on this
// transaction (they are no longer orphans) and repeat for those
// accepted transactions until there are no more.
err = mp.processOrphans(&txHash)
if err != nil {
return err
}
} else {
// When the transaction is an orphan (has inputs missing),
// potentially add it to the orphan pool.
err := mp.maybeAddOrphan(tx, &txHash)
if err != nil {
return err
}
}
return nil
}
示例3: minimumFee
// minimumFee calculates the minimum fee required for a transaction.
// If allowFree is true, a fee may be zero so long as the entire
// transaction has a serialized length less than 1 kilobyte
// and none of the outputs contain a value less than 1 bitcent.
// Otherwise, the fee will be calculated using TxFeeIncrement,
// incrementing the fee for each kilobyte of transaction.
func minimumFee(tx *btcwire.MsgTx, allowFree bool) btcutil.Amount {
txLen := tx.SerializeSize()
TxFeeIncrement.Lock()
incr := TxFeeIncrement.i
TxFeeIncrement.Unlock()
fee := btcutil.Amount(int64(1+txLen/1000) * int64(incr))
if allowFree && txLen < 1000 {
fee = 0
}
if fee < incr {
for _, txOut := range tx.TxOut {
if txOut.Value < btcutil.SatoshiPerBitcent {
return incr
}
}
}
max := btcutil.Amount(btcutil.MaxSatoshi)
if fee < 0 || fee > max {
fee = max
}
return fee
}
示例4: Receive
// Receive waits for the response promised by the future and returns the
// signed transaction as well as whether or not all inputs are now signed.
func (r FutureSignRawTransactionResult) Receive() (*btcwire.MsgTx, bool, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, false, err
}
// Unmarshal as a signrawtransaction result.
var signRawTxResult btcjson.SignRawTransactionResult
err = json.Unmarshal(res, &signRawTxResult)
if err != nil {
return nil, false, err
}
// Decode the serialized transaction hex to raw bytes.
serializedTx, err := hex.DecodeString(signRawTxResult.Hex)
if err != nil {
return nil, false, err
}
// Deserialize the transaction and return it.
var msgTx btcwire.MsgTx
if err := msgTx.Deserialize(bytes.NewReader(serializedTx)); err != nil {
return nil, false, err
}
return &msgTx, signRawTxResult.Complete, nil
}
示例5: maybeAddOrphan
// maybeAddOrphan potentially adds an orphan to the orphan pool.
func (mp *txMemPool) maybeAddOrphan(tx *btcwire.MsgTx, txHash *btcwire.ShaHash) error {
// Ignore orphan transactions that are too large. This helps avoid
// a memory exhaustion attack based on sending a lot of really large
// orphans. In the case there is a valid transaction larger than this,
// it will ultimtely be rebroadcast after the parent transactions
// have been mined or otherwise received.
//
// Note that the number of orphan transactions in the orphan pool is
// also limited, so this equates to a maximum memory used of
// maxOrphanTxSize * maxOrphanTransactions (which is 500MB as of the
// time this comment was written).
var serializedTxBuf bytes.Buffer
err := tx.Serialize(&serializedTxBuf)
if err != nil {
return err
}
serializedLen := serializedTxBuf.Len()
if serializedLen > maxOrphanTxSize {
str := fmt.Sprintf("orphan transaction size of %d bytes is "+
"larger than max allowed size of %d bytes",
serializedLen, maxOrphanTxSize)
return TxRuleError(str)
}
// Add the orphan if the none of the above disqualified it.
mp.addOrphan(tx, txHash)
return nil
}
示例6: removeTransaction
// removeTransaction removes the passed transaction from the memory pool.
func (mp *txMemPool) removeTransaction(tx *btcwire.MsgTx) {
mp.lock.Lock()
defer mp.lock.Unlock()
// Remove any transactions which rely on this one.
txHash, _ := tx.TxSha()
for i := uint32(0); i < uint32(len(tx.TxOut)); i++ {
outpoint := btcwire.NewOutPoint(&txHash, i)
if txRedeemer, exists := mp.outpoints[*outpoint]; exists {
mp.lock.Unlock()
mp.removeTransaction(txRedeemer)
mp.lock.Lock()
}
}
// Remove the transaction and mark the referenced outpoints as unspent
// by the pool.
if tx, exists := mp.pool[txHash]; exists {
for _, txIn := range tx.TxIn {
delete(mp.outpoints, txIn.PreviousOutpoint)
}
delete(mp.pool, txHash)
}
}
示例7: TestTxSerialize
// TestTxSerialize tests MsgTx serialize and deserialize.
func TestTxSerialize(t *testing.T) {
noTx := btcwire.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 *btcwire.MsgTx // Message to encode
out *btcwire.MsgTx // Expected decoded message
buf []byte // Serialized data
}{
// No transactions.
{
noTx,
noTx,
noTxEncoded,
},
// Multiple transactions.
{
multiTx,
multiTx,
multiTxEncoded,
},
}
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 btcwire.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
}
}
}
示例8: BenchmarkDeserializeTx
// BenchmarkDeserializeTx performs a benchmark on how long it takes to
// deserialize a transaction.
func BenchmarkDeserializeTx(b *testing.B) {
buf := []byte{
0x01, 0x00, 0x00, 0x00, // Version
0x01, // Varint for number of input transactions
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // // Previous output hash
0xff, 0xff, 0xff, 0xff, // Prevous output index
0x07, // Varint for length of signature script
0x04, 0xff, 0xff, 0x00, 0x1d, 0x01, 0x04, // Signature script
0xff, 0xff, 0xff, 0xff, // Sequence
0x01, // Varint for number of output transactions
0x00, 0xf2, 0x05, 0x2a, 0x01, 0x00, 0x00, 0x00, // Transaction amount
0x43, // Varint for length of pk script
0x41, // OP_DATA_65
0x04, 0x96, 0xb5, 0x38, 0xe8, 0x53, 0x51, 0x9c,
0x72, 0x6a, 0x2c, 0x91, 0xe6, 0x1e, 0xc1, 0x16,
0x00, 0xae, 0x13, 0x90, 0x81, 0x3a, 0x62, 0x7c,
0x66, 0xfb, 0x8b, 0xe7, 0x94, 0x7b, 0xe6, 0x3c,
0x52, 0xda, 0x75, 0x89, 0x37, 0x95, 0x15, 0xd4,
0xe0, 0xa6, 0x04, 0xf8, 0x14, 0x17, 0x81, 0xe6,
0x22, 0x94, 0x72, 0x11, 0x66, 0xbf, 0x62, 0x1e,
0x73, 0xa8, 0x2c, 0xbf, 0x23, 0x42, 0xc8, 0x58,
0xee, // 65-byte signature
0xac, // OP_CHECKSIG
0x00, 0x00, 0x00, 0x00, // Lock time
}
var tx btcwire.MsgTx
for i := 0; i < b.N; i++ {
tx.Deserialize(bytes.NewBuffer(buf))
}
}
示例9: handleTxMsg
// handleTxMsg is invoked when a peer receives a tx bitcoin message. It blocks
// until the bitcoin transaction has been fully processed. Unlock the block
// handler this does not serialize all transactions through a single thread
// transactions don't rely on the previous one in a linear fashion like blocks.
func (p *peer) handleTxMsg(msg *btcwire.MsgTx) {
// Add the transaction to the known inventory for the peer.
hash, err := msg.TxSha()
if err != nil {
log.Errorf("Unable to get transaction hash: %v", err)
return
}
iv := btcwire.NewInvVect(btcwire.InvVect_Tx, &hash)
p.addKnownInventory(iv)
// Process the transaction.
err = p.server.txMemPool.ProcessTransaction(msg)
if err != nil {
// When the error is a rule error, it means the transaction was
// simply rejected as opposed to something actually going wrong,
// so log it as such. Otherwise, something really did go wrong,
// so log it as an actual error.
if _, ok := err.(TxRuleError); ok {
log.Infof("Rejected transaction %v: %v", hash, err)
} else {
log.Errorf("Failed to process transaction %v: %v", hash, err)
}
return
}
}
示例10: 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 *btcwire.MsgTx, rblksha *btcwire.ShaHash, rheight int64, rtxspent []byte, err error) {
var blksha *btcwire.ShaHash
var blkbuf []byte
blksha, blkbuf, err = db.getBlkByHeight(blkHeight)
if err != nil {
if err == leveldb.ErrNotFound {
err = btcdb.TxShaMissing
}
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 = btcdb.TxShaMissing
return
}
rbuf := bytes.NewBuffer(blkbuf[txOff : txOff+txLen])
var tx btcwire.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
}
示例11: FetchTxAllBySha
// FetchTxAllBySha returns several pieces of data regarding the given sha.
func (db *SqliteDb) FetchTxAllBySha(txsha *btcwire.ShaHash) (rtx *btcwire.MsgTx, rtxbuf []byte, rpver uint32, rblksha *btcwire.ShaHash, err error) {
// Check Tx cache
if txc, ok := db.fetchTxCache(txsha); ok {
return txc.tx, txc.txbuf, txc.pver, &txc.blksha, nil
}
// If not cached load it
bidx, toff, tlen, err := db.FetchLocationBySha(txsha)
if err != nil {
log.Warnf("unable to find location of origin tx %v", txsha)
return
}
blksha, err := db.FetchBlockShaByHeight(bidx)
if err != nil {
log.Warnf("block idx lookup %v to %v", bidx, err)
return
}
log.Tracef("transaction %v is at block %v %v tx %v",
txsha, blksha, bidx, toff)
blk, err := db.FetchBlockBySha(blksha)
if err != nil {
log.Warnf("unable to fetch block %v %v ",
bidx, &blksha)
return
}
blkbuf, pver, err := blk.Bytes()
if err != nil {
log.Warnf("unable to decode block %v %v", bidx, &blksha)
return
}
txbuf := make([]byte, tlen)
copy(txbuf[:], blkbuf[toff:toff+tlen])
rbuf := bytes.NewBuffer(txbuf)
var tx btcwire.MsgTx
err = tx.BtcDecode(rbuf, pver)
if err != nil {
log.Warnf("unable to decode tx block %v %v txoff %v txlen %v",
bidx, &blksha, toff, tlen)
return
}
// Shove data into TxCache
// XXX -
var txc txCacheObj
txc.sha = *txsha
txc.tx = &tx
txc.txbuf = txbuf
txc.pver = pver
txc.blksha = *blksha
db.insertTxCache(&txc)
return &tx, txbuf, pver, blksha, nil
}
示例12: 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 *btcwire.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 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, 130, 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 btcwire.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
}
}
}
示例13: NewBulletin
// Creates a new bulletin from the containing Tx, supplied author and optional blockhash
// by unpacking txOuts that are considered data. It ignores extra junk behind the protobuffer.
// NewBulletin also asserts aspects of valid bulletins by throwing errors when msg len
// is zero or board len is greater than MaxBoardLen.
func NewBulletin(tx *btcwire.MsgTx, blkhash *btcwire.ShaHash, net *btcnet.Params) (*Bulletin, error) {
wireBltn := &wirebulletin.WireBulletin{}
author, err := getAuthor(tx, net)
if err != nil {
return nil, err
}
// TODO. scrutinize.
// Bootleg solution, but if unmarshal fails slice txout and try again until we can try no more or it fails
for j := len(tx.TxOut); j > 1; j-- {
rel_txouts := tx.TxOut[:j] // slice off change txouts
bytes, err := extractData(rel_txouts)
if err != nil {
continue
}
err = proto.Unmarshal(bytes, wireBltn)
if err != nil {
continue
} else {
// No errors, we found a good decode
break
}
}
if err != nil {
return nil, err
}
board := wireBltn.GetBoard()
// assert that the length of the board is within its max size!
if len(board) > MaxBoardLen {
return nil, ErrMaxBoardLen
}
msg := wireBltn.GetMessage()
// assert that the bulletin has a non zero message length.
if len(msg) < 1 {
return nil, ErrNoMsg
}
// TODO assert that msg and board are valid UTF-8 strings.
hash, _ := tx.TxSha()
bltn := &Bulletin{
Txid: &hash,
Block: blkhash,
Author: author,
Board: board,
Message: msg,
Timestamp: time.Unix(wireBltn.GetTimestamp(), 0),
}
return bltn, nil
}
示例14: 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 btcwire.MsgTx
err := msgTx.Deserialize(r)
if err != nil {
return nil, err
}
t := Tx{
msgTx: &msgTx,
txIndex: TxIndexUnknown,
}
return &t, nil
}
示例15: NewTxFromBytes
// NewTxFromBytes returns a new instance of a bitcoin transaction given the
// serialized bytes. See Tx.
func NewTxFromBytes(serializedTx []byte) (*Tx, error) {
// Deserialize the bytes into a MsgTx.
var msgTx btcwire.MsgTx
br := bytes.NewBuffer(serializedTx)
err := msgTx.Deserialize(br)
if err != nil {
return nil, err
}
t := Tx{
msgTx: &msgTx,
serializedTx: serializedTx,
txIndex: TxIndexUnknown,
}
return &t, nil
}