本文整理汇总了Golang中github.com/conformal/btcwire.NewOutPoint函数的典型用法代码示例。如果您正苦于以下问题:Golang NewOutPoint函数的具体用法?Golang NewOutPoint怎么用?Golang NewOutPoint使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewOutPoint函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: maybeAddOutpoint
// maybeAddOutpoint potentially adds the passed outpoint to the bloom filter
// depending on the bloom update flags and the type of the passed public key
// script.
//
// This function MUST be called with the filter lock held.
func (bf *Filter) maybeAddOutpoint(pkScript []byte, outHash *btcwire.ShaHash, outIdx uint32) {
switch bf.msgFilterLoad.Flags {
case btcwire.BloomUpdateAll:
outpoint := btcwire.NewOutPoint(outHash, outIdx)
bf.addOutPoint(outpoint)
case btcwire.BloomUpdateP2PubkeyOnly:
class := btcscript.GetScriptClass(pkScript)
if class == btcscript.PubKeyTy || class == btcscript.MultiSigTy {
outpoint := btcwire.NewOutPoint(outHash, outIdx)
bf.addOutPoint(outpoint)
}
}
}
开发者ID:kac-,项目名称:btcutil,代码行数:18,代码来源:filter.go
示例2: TestFilterInsertUpdateNone
func TestFilterInsertUpdateNone(t *testing.T) {
f := bloom.NewFilter(10, 0, 0.000001, btcwire.BloomUpdateNone)
// Add the generation pubkey
inputStr := "04eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c" +
"876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a" +
"2252247d97a46a91"
inputBytes, err := hex.DecodeString(inputStr)
if err != nil {
t.Errorf("TestFilterInsertUpdateNone DecodeString failed: %v", err)
return
}
f.Add(inputBytes)
// Add the output address for the 4th transaction
inputStr = "b6efd80d99179f4f4ff6f4dd0a007d018c385d21"
inputBytes, err = hex.DecodeString(inputStr)
if err != nil {
t.Errorf("TestFilterInsertUpdateNone DecodeString failed: %v", err)
return
}
f.Add(inputBytes)
inputStr = "147caa76786596590baa4e98f5d9f48b86c7765e489f7a6ff3360fe5c674360b"
sha, err := btcwire.NewShaHashFromStr(inputStr)
if err != nil {
t.Errorf("TestFilterInsertUpdateNone NewShaHashFromStr failed: %v", err)
return
}
outpoint := btcwire.NewOutPoint(sha, 0)
if f.MatchesOutPoint(outpoint) {
t.Errorf("TestFilterInsertUpdateNone matched outpoint %s", inputStr)
return
}
inputStr = "02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"
sha, err = btcwire.NewShaHashFromStr(inputStr)
if err != nil {
t.Errorf("TestFilterInsertUpdateNone NewShaHashFromStr failed: %v", err)
return
}
outpoint = btcwire.NewOutPoint(sha, 0)
if f.MatchesOutPoint(outpoint) {
t.Errorf("TestFilterInsertUpdateNone matched outpoint %s", inputStr)
return
}
}
开发者ID:jrick,项目名称:btcutil,代码行数:49,代码来源:filter_test.go
示例3: makeTx
func makeTx(outputs []output, amount, value int64, toAddr, changeAddr string) (*btcwire.MsgTx, error) {
msgTx := btcwire.NewMsgTx()
for _, op := range outputs {
hash, err := btcwire.NewShaHashFromStr(op.TxHash)
if err != nil {
return nil, err
}
b, err := hex.DecodeString(op.Script)
if err != nil {
return nil, err
}
txIn := btcwire.NewTxIn(btcwire.NewOutPoint(hash, op.TxN), b)
msgTx.AddTxIn(txIn)
}
script, err := makeScriptPubKey(toAddr)
if err != nil {
return nil, err
}
txOut := btcwire.NewTxOut(value, script)
msgTx.AddTxOut(txOut)
if amount > value {
script, err = makeScriptPubKey(changeAddr)
if err != nil {
return nil, err
}
txOut := btcwire.NewTxOut(amount-value, script)
msgTx.AddTxOut(txOut)
}
return msgTx, nil
}
开发者ID:shevilangle,项目名称:sports,代码行数:33,代码来源:sign.go
示例4: parseNotifySpentCmd
// parseNotifySpentCmd parses a NotifySpentCmd into a concrete type
// satisifying the btcjson.Cmd interface. This is used when registering
// the custom command with the btcjson parser.
func parseNotifySpentCmd(r *btcjson.RawCmd) (btcjson.Cmd, error) {
if len(r.Params) != 2 {
return nil, btcjson.ErrWrongNumberOfParams
}
hashStr, ok := r.Params[0].(string)
if !ok {
return nil, errors.New("first parameter must be a string")
}
hash, err := btcwire.NewShaHashFromStr(hashStr)
if err != nil {
return nil, errors.New("first parameter is not a valid " +
"hash string")
}
idx, ok := r.Params[1].(float64)
if !ok {
return nil, errors.New("second parameter is not a number")
}
if idx < 0 {
return nil, errors.New("second parameter cannot be negative")
}
cmd := NewNotifySpentCmd(r.Id, btcwire.NewOutPoint(hash, uint32(idx)))
return cmd, nil
}
开发者ID:hsk81,项目名称:btcws,代码行数:28,代码来源:cmds.go
示例5: 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)
}
}
开发者ID:kazcw,项目名称:btcd,代码行数:26,代码来源:mempool.go
示例6: createCoinbaseTx
// createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
// based on the passed block height to the provided address. When the address
// is nil, the coinbase transaction will instead be redeemable by anyone.
//
// See the comment for NewBlockTemplate for more information about why the nil
// address handling is useful.
func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int64, addr btcutil.Address) (*btcutil.Tx, error) {
// Create the script to pay to the provided payment address if one was
// specified. Otherwise create a script that allows the coinbase to be
// redeemable by anyone.
var pkScript []byte
if addr != nil {
var err error
pkScript, err = btcscript.PayToAddrScript(addr)
if err != nil {
return nil, err
}
} else {
scriptBuilder := btcscript.NewScriptBuilder()
pkScript = scriptBuilder.AddOp(btcscript.OP_TRUE).Script()
}
tx := btcwire.NewMsgTx()
tx.AddTxIn(&btcwire.TxIn{
// Coinbase transactions have no inputs, so previous outpoint is
// zero hash and max index.
PreviousOutPoint: *btcwire.NewOutPoint(&btcwire.ShaHash{},
btcwire.MaxPrevOutIndex),
SignatureScript: coinbaseScript,
Sequence: btcwire.MaxTxInSequenceNum,
})
tx.AddTxOut(&btcwire.TxOut{
Value: btcchain.CalcBlockSubsidy(nextBlockHeight,
activeNetParams.Params),
PkScript: pkScript,
})
return btcutil.NewTx(tx), nil
}
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:38,代码来源:mining.go
示例7: removeConflict
// removeConflict removes an unconfirmed transaction record and all spend chains
// deriving from it from the store. This is designed to remove transactions
// that would otherwise result in double spend conflicts if left in the store.
// All not-removed credits spent by removed transactions are set unspent.
func (s *Store) removeConflict(r *txRecord) error {
u := &s.unconfirmed
// If this transaction contains any spent credits (which must be spent by
// other unconfirmed transactions), recursively remove each spender.
for i, credit := range r.credits {
if credit == nil || credit.spentBy == nil {
continue
}
op := btcwire.NewOutPoint(r.Tx().Sha(), uint32(i))
nextSpender, ok := u.spentUnconfirmed[*op]
if !ok {
return ErrInconsistentStore
}
log.Debugf("Transaction %v is part of a removed double spend "+
"chain -- removing as well", nextSpender.tx.Sha())
if err := s.removeConflict(nextSpender); err != nil {
return err
}
}
// If this tx spends any previous credits, set each unspent.
for _, input := range r.Tx().MsgTx().TxIn {
delete(u.previousOutpoints, input.PreviousOutpoint)
// For all mined transactions with credits spent by this
// conflicting transaction, remove from the bookkeeping maps
// and set each previous record's credit as unspent.
prevKey, ok := u.spentBlockOutPointKeys[input.PreviousOutpoint]
if ok {
delete(u.spentBlockOutPointKeys, input.PreviousOutpoint)
delete(u.spentBlockOutPoints, prevKey)
prev, err := s.lookupBlockTx(prevKey.BlockTxKey)
if err != nil {
return err
}
prev.credits[prevKey.OutputIndex].spentBy = nil
continue
}
// For all unmined transactions with credits spent by this
// conflicting transaction, remove from the unspent store's
// spent tracking.
//
// Spend tracking is only handled by these maps, so there is
// no need to modify the record and unset a spent-by pointer.
if _, ok := u.spentUnconfirmed[input.PreviousOutpoint]; ok {
delete(u.spentUnconfirmed, input.PreviousOutpoint)
}
}
delete(u.txs, *r.Tx().Sha())
for _, input := range r.Tx().MsgTx().TxIn {
delete(u.previousOutpoints, input.PreviousOutpoint)
}
return nil
}
开发者ID:kingpro,项目名称:btcwallet,代码行数:62,代码来源:tx.go
示例8: TestFakeTxs
func TestFakeTxs(t *testing.T) {
// First we need a wallet.
w, err := wallet.NewWallet("banana wallet", "", []byte("banana"),
btcwire.MainNet, &wallet.BlockStamp{}, 100)
if err != nil {
t.Errorf("Can not create encrypted wallet: %s", err)
return
}
a := &Account{
Wallet: w,
lockedOutpoints: map[btcwire.OutPoint]struct{}{},
}
w.Unlock([]byte("banana"))
// Create and add a fake Utxo so we have some funds to spend.
//
// This will pass validation because btcscript is unaware of invalid
// tx inputs, however, this example would fail in btcd.
utxo := &tx.Utxo{}
addr, err := w.NextChainedAddress(&wallet.BlockStamp{}, 100)
if err != nil {
t.Errorf("Cannot get next address: %s", err)
return
}
copy(utxo.AddrHash[:], addr.ScriptAddress())
ophash := (btcwire.ShaHash)([...]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32})
out := btcwire.NewOutPoint(&ophash, 0)
utxo.Out = tx.OutPoint(*out)
ss, err := btcscript.PayToAddrScript(addr)
if err != nil {
t.Errorf("Could not create utxo PkScript: %s", err)
return
}
utxo.Subscript = tx.PkScript(ss)
utxo.Amt = 1000000
utxo.Height = 12345
a.UtxoStore = append(a.UtxoStore, utxo)
// Fake our current block height so btcd doesn't need to be queried.
curBlock.BlockStamp.Height = 12346
// Create the transaction.
pairs := map[string]int64{
"17XhEvq9Nahdj7Xe1nv6oRe1tEmaHUuynH": 5000,
}
_, err = a.txToPairs(pairs, 1)
if err != nil {
t.Errorf("Tx creation failed: %s", err)
return
}
}
开发者ID:kingpro,项目名称:btcwallet,代码行数:54,代码来源:createtx_test.go
示例9: TestFindingSpentCredits
func TestFindingSpentCredits(t *testing.T) {
s := New()
// Insert transaction and credit which will be spent.
r, err := s.InsertTx(TstRecvTx, TstRecvTxBlockDetails)
if err != nil {
t.Fatal(err)
}
_, err = r.AddCredit(0, false)
if err != nil {
t.Fatal(err)
}
// Insert confirmed transaction which spends the above credit.
TstSpendingTx.SetIndex(TstSignedTxIndex)
r2, err := s.InsertTx(TstSpendingTx, TstSignedTxBlockDetails)
if err != nil {
t.Fatal(err)
}
_, err = r2.AddCredit(0, false)
if err != nil {
t.Fatal(err)
}
_, err = r2.AddDebits(nil)
if err != nil {
t.Fatal(err)
}
bal, err := s.Balance(1, TstSignedTxBlockDetails.Height)
if err != nil {
t.Fatal(err)
}
if bal != btcutil.Amount(TstSpendingTx.MsgTx().TxOut[0].Value) {
t.Fatal("bad balance")
}
unspents, err := s.UnspentOutputs()
if err != nil {
t.Fatal(err)
}
op := btcwire.NewOutPoint(TstSpendingTx.Sha(), 0)
if *unspents[0].OutPoint() != *op {
t.Fatal("unspent outpoint doesn't match expected")
}
if len(unspents) > 1 {
t.Fatal("has more than one unspent credit")
}
}
开发者ID:kingpro,项目名称:btcwallet,代码行数:47,代码来源:tx_test.go
示例10: TestCheckSerializedHeight
// TestCheckSerializedHeight tests the checkSerializedHeight function with
// various serialized heights and also does negative tests to ensure errors
// and handled properly.
func TestCheckSerializedHeight(t *testing.T) {
// Create an empty coinbase template to be used in the tests below.
coinbaseOutpoint := btcwire.NewOutPoint(&btcwire.ShaHash{}, math.MaxUint32)
coinbaseTx := btcwire.NewMsgTx()
coinbaseTx.Version = 2
coinbaseTx.AddTxIn(btcwire.NewTxIn(coinbaseOutpoint, nil))
//
tests := []struct {
sigScript []byte // Serialized data
wantHeight int64 // Expected height
err error // Expected error type
}{
// No serialized height length.
{[]byte{}, 0, btcchain.RuleError("")},
// Serialized height length with no height bytes.
{[]byte{0x02}, 0, btcchain.RuleError("")},
// Serialized height length with too few height bytes.
{[]byte{0x02, 0x4a}, 0, btcchain.RuleError("")},
// Serialized height that needs 2 bytes to encode.
{[]byte{0x02, 0x4a, 0x52}, 21066, nil},
// Serialized height that needs 2 bytes to encode, but backwards
// endianness.
{[]byte{0x02, 0x4a, 0x52}, 19026, btcchain.RuleError("")},
// Serialized height that needs 3 bytes to encode.
{[]byte{0x03, 0x40, 0x0d, 0x03}, 200000, nil},
// Serialized height that needs 3 bytes to encode, but backwards
// endianness.
{[]byte{0x03, 0x40, 0x0d, 0x03}, 1074594560, btcchain.RuleError("")},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
msgTx := coinbaseTx.Copy()
msgTx.TxIn[0].SignatureScript = test.sigScript
tx := btcutil.NewTx(msgTx)
err := btcchain.TstCheckSerializedHeight(tx, test.wantHeight)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
t.Errorf("checkSerializedHeight #%d wrong error type "+
"got: %v <%T>, want: %T", i, err, err, test.err)
continue
}
}
}
开发者ID:hsk81,项目名称:btcchain,代码行数:48,代码来源:validate_test.go
示例11: rpcTxPick
func rpcTxPick(exact bool, targetAmnt int64, params BuilderParams) (*TxInParams, error) {
// selects an unspent outpoint that is funded over the minAmount
list, err := params.Client.ListUnspent()
if err != nil {
log.Println("list unpsent threw")
return nil, err
}
if len(list) < 1 {
return nil, errors.New("No unspent outputs at all.")
}
for _, prevJson := range list {
_amnt, _ := btcutil.NewAmount(prevJson.Amount)
amnt := int64(_amnt)
txid := prevJson.TxId
prevHash, _ := btcwire.NewShaHashFromStr(txid)
outPoint := btcwire.NewOutPoint(prevHash, prevJson.Vout)
_, contained := params.PendingSet[outPointStr(outPoint)]
// This unpsent is in the pending set and it either exactly equals the target or
// has a value above that target
if !contained && (exact && targetAmnt == amnt || !exact && targetAmnt <= amnt) {
// Found one, lets use it
script, _ := hex.DecodeString(prevJson.ScriptPubKey)
// None of the above ~should~ ever throw errors
txOut := btcwire.NewTxOut(amnt, script)
prevAddress, _ := btcutil.DecodeAddress(prevJson.Address, params.NetParams)
wifkey, err := params.Client.DumpPrivKey(prevAddress)
if err != nil {
return nil, err
}
inParams := TxInParams{
TxOut: txOut,
OutPoint: outPoint,
Wif: wifkey,
}
params.PendingSet[outPointStr(outPoint)] = struct{}{}
return &inParams, nil
}
}
// Never found a good outpoint
return nil, errors.New("No txout with the right funds")
}
开发者ID:bclermont,项目名称:btcbuilder,代码行数:44,代码来源:txutil.go
示例12: removeTransaction
// removeTransaction is the internal function which implements the public
// RemoveTransaction. See the comment for RemoveTransaction for more details.
//
// This function MUST be called with the mempool lock held (for writes).
func (mp *txMemPool) removeTransaction(tx *btcutil.Tx) {
// Remove any transactions which rely on this one.
txHash := tx.Sha()
for i := uint32(0); i < uint32(len(tx.MsgTx().TxOut)); i++ {
outpoint := btcwire.NewOutPoint(txHash, i)
if txRedeemer, exists := mp.outpoints[*outpoint]; exists {
mp.removeTransaction(txRedeemer)
}
}
// Remove the transaction and mark the referenced outpoints as unspent
// by the pool.
if txDesc, exists := mp.pool[*txHash]; exists {
for _, txIn := range txDesc.Tx.MsgTx().TxIn {
delete(mp.outpoints, txIn.PreviousOutpoint)
}
delete(mp.pool, *txHash)
}
}
开发者ID:Cryptoper,项目名称:btcd,代码行数:23,代码来源:mempool.go
示例13: createCoinbaseTx
// createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
// based on the passed block height to the passed public key. It also accepts
// an extra nonce value for the signature script. This extra nonce helps ensure
// the transaction is not a duplicate transaction (paying the same value to the
// same public key address would otherwise be an identical transaction for
// block version 1).
func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int64, addr btcutil.Address) (*btcutil.Tx, error) {
// Create a script to pay to the specific address.
pkScript, err := btcscript.PayToAddrScript(addr)
if err != nil {
return nil, err
}
tx := btcwire.NewMsgTx()
tx.AddTxIn(&btcwire.TxIn{
// Coinbase transactions have no inputs, so previous outpoint is
// zero hash and max index.
PreviousOutpoint: *btcwire.NewOutPoint(&btcwire.ShaHash{},
btcwire.MaxPrevOutIndex),
SignatureScript: coinbaseScript,
Sequence: btcwire.MaxTxInSequenceNum,
})
tx.AddTxOut(&btcwire.TxOut{
Value: btcchain.CalcBlockSubsidy(nextBlockHeight,
activeNetParams.Params),
PkScript: pkScript,
})
return btcutil.NewTx(tx), nil
}
开发者ID:nixoid,项目名称:btcd,代码行数:29,代码来源:mining.go
示例14: TestTx
// TestTx tests the MsgTx API.
func TestTx(t *testing.T) {
pver := btcwire.ProtocolVersion
// Block 100000 hash.
hashStr := "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
hash, err := btcwire.NewShaHashFromStr(hashStr)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
}
// Ensure the command is expected value.
wantCmd := "tx"
msg := btcwire.NewMsgTx()
if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgAddr: wrong command - got %v want %v",
cmd, wantCmd)
}
// Ensure max payload is expected value for latest protocol version.
// Num addresses (varInt) + max allowed addresses.
wantPayload := uint32(1000 * 1000)
maxPayload := msg.MaxPayloadLength(pver)
if maxPayload != wantPayload {
t.Errorf("MaxPayloadLength: wrong max payload length for "+
"protocol version %d - got %v, want %v", pver,
maxPayload, wantPayload)
}
// Ensure we get the same transaction output point data back out.
prevOutIndex := uint32(1)
prevOut := btcwire.NewOutPoint(hash, prevOutIndex)
if !prevOut.Hash.IsEqual(hash) {
t.Errorf("NewOutPoint: wrong hash - got %v, want %v",
spew.Sprint(&prevOut.Hash), spew.Sprint(hash))
}
if prevOut.Index != prevOutIndex {
t.Errorf("NewOutPoint: wrong index - got %v, want %v",
prevOut.Index, prevOutIndex)
}
// Ensure we get the same transaction input back out.
sigScript := []byte{0x04, 0x31, 0xdc, 0x00, 0x1b, 0x01, 0x62}
txIn := btcwire.NewTxIn(prevOut, sigScript)
if !reflect.DeepEqual(&txIn.PreviousOutpoint, prevOut) {
t.Errorf("NewTxIn: wrong prev outpoint - got %v, want %v",
spew.Sprint(&txIn.PreviousOutpoint),
spew.Sprint(prevOut))
}
if !bytes.Equal(txIn.SignatureScript, sigScript) {
t.Errorf("NewTxIn: wrong signature script - got %v, want %v",
spew.Sdump(txIn.SignatureScript),
spew.Sdump(sigScript))
}
// Ensure we get the same transaction output back out.
txValue := int64(5000000000)
pkScript := []byte{
0x41, // OP_DATA_65
0x04, 0xd6, 0x4b, 0xdf, 0xd0, 0x9e, 0xb1, 0xc5,
0xfe, 0x29, 0x5a, 0xbd, 0xeb, 0x1d, 0xca, 0x42,
0x81, 0xbe, 0x98, 0x8e, 0x2d, 0xa0, 0xb6, 0xc1,
0xc6, 0xa5, 0x9d, 0xc2, 0x26, 0xc2, 0x86, 0x24,
0xe1, 0x81, 0x75, 0xe8, 0x51, 0xc9, 0x6b, 0x97,
0x3d, 0x81, 0xb0, 0x1c, 0xc3, 0x1f, 0x04, 0x78,
0x34, 0xbc, 0x06, 0xd6, 0xd6, 0xed, 0xf6, 0x20,
0xd1, 0x84, 0x24, 0x1a, 0x6a, 0xed, 0x8b, 0x63,
0xa6, // 65-byte signature
0xac, // OP_CHECKSIG
}
txOut := btcwire.NewTxOut(txValue, pkScript)
if txOut.Value != txValue {
t.Errorf("NewTxOut: wrong pk script - got %v, want %v",
txOut.Value, txValue)
}
if !bytes.Equal(txOut.PkScript, pkScript) {
t.Errorf("NewTxOut: wrong pk script - got %v, want %v",
spew.Sdump(txOut.PkScript),
spew.Sdump(pkScript))
}
// Ensure transaction inputs are added properly.
msg.AddTxIn(txIn)
if !reflect.DeepEqual(msg.TxIn[0], txIn) {
t.Errorf("AddTxIn: wrong transaction input added - got %v, want %v",
spew.Sprint(msg.TxIn[0]), spew.Sprint(txIn))
}
// Ensure transaction outputs are added properly.
msg.AddTxOut(txOut)
if !reflect.DeepEqual(msg.TxOut[0], txOut) {
t.Errorf("AddTxIn: wrong transaction output added - got %v, want %v",
spew.Sprint(msg.TxOut[0]), spew.Sprint(txOut))
}
// Ensure the copy produced an identical transaction message.
newMsg := msg.Copy()
if !reflect.DeepEqual(newMsg, msg) {
t.Errorf("Copy: mismatched tx messages - got %v, want %v",
//.........这里部分代码省略.........
开发者ID:kac-,项目名称:btcwire,代码行数:101,代码来源:msgtx_test.go
示例15: handleCreateRawTransaction
// handleCreateRawTransaction handles createrawtransaction commands.
func handleCreateRawTransaction(s *rpcServer, cmd btcjson.Cmd) (interface{}, error) {
c := cmd.(*btcjson.CreateRawTransactionCmd)
// Add all transaction inputs to a new transaction after performing
// some validity checks.
mtx := btcwire.NewMsgTx()
for _, input := range c.Inputs {
txHash, err := btcwire.NewShaHashFromStr(input.Txid)
if err != nil {
return nil, btcjson.ErrDecodeHexString
}
if input.Vout < 0 {
return nil, btcjson.Error{
Code: btcjson.ErrInvalidParameter.Code,
Message: "Invalid parameter, vout must be positive",
}
}
prevOut := btcwire.NewOutPoint(txHash, uint32(input.Vout))
txIn := btcwire.NewTxIn(prevOut, []byte{})
mtx.AddTxIn(txIn)
}
// Add all transaction outputs to the transaction after performing
// some validity checks.
for encodedAddr, amount := range c.Amounts {
// Ensure amount is in the valid range for monetary amounts.
if amount <= 0 || amount > btcutil.MaxSatoshi {
return nil, btcjson.Error{
Code: btcjson.ErrType.Code,
Message: "Invalid amount",
}
}
// Decode the provided address.
addr, err := btcutil.DecodeAddress(encodedAddr,
activeNetParams.btcnet)
if err != nil {
return nil, btcjson.Error{
Code: btcjson.ErrInvalidAddressOrKey.Code,
Message: btcjson.ErrInvalidAddressOrKey.Message +
": " + err.Error(),
}
}
// Ensure the address is one of the supported types and that
// the network encoded with the address matches the network the
// server is currently on.
switch addr.(type) {
case *btcutil.AddressPubKeyHash:
case *btcutil.AddressScriptHash:
default:
return nil, btcjson.ErrInvalidAddressOrKey
}
if !addr.IsForNet(s.server.btcnet) {
return nil, btcjson.Error{
Code: btcjson.ErrInvalidAddressOrKey.Code,
Message: fmt.Sprintf("%s: %q",
btcjson.ErrInvalidAddressOrKey.Message,
encodedAddr),
}
}
// Create a new script which pays to the provided address.
pkScript, err := btcscript.PayToAddrScript(addr)
if err != nil {
return nil, btcjson.Error{
Code: btcjson.ErrInternal.Code,
Message: err.Error(),
}
}
txOut := btcwire.NewTxOut(amount, pkScript)
mtx.AddTxOut(txOut)
}
// Return the serialized and hex-encoded transaction.
mtxHex, err := messageToHex(mtx)
if err != nil {
return nil, err
}
return mtxHex, nil
}
开发者ID:Cryptoper,项目名称:btcd,代码行数:85,代码来源:rpcserver.go
示例16: TestFilterInsertP2PubKeyOnly
//.........这里部分代码省略.........
"a788a62f0db780022100d17b2d6fa84dcaf1c95d88d7e7c30385aecf415" +
"588d749afd3ec81f6022cecd701410462bb73f76ca0994fcb8b4271e6fb" +
"7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018" +
"ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff0100c817a8" +
"040000001976a914b6efd80d99179f4f4ff6f4dd0a007d018c385d2188a" +
"c000000000100000001834537b2f1ce8ef9373a258e10545ce5a50b758d" +
"f616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34" +
"fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243" +
"bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec" +
"20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442" +
"e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632" +
"d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10" +
"eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a91" +
"4a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000010000" +
"000143ac81c8e6f6ef307dfe17f3d906d999e23e0189fda838c5510d850" +
"927e03ae7000000008c4930460221009c87c344760a64cb8ae6685a3eec" +
"2c1ac1bed5b88c87de51acd0e124f266c16602210082d07c037359c3a25" +
"7b5c63ebd90f5a5edf97b2ac1c434b08ca998839f346dd40141040ba7e5" +
"21fa7946d12edbb1d1e95a15c34bd4398195e86433c92b431cd315f455f" +
"e30032ede69cad9d1e1ed6c3c4ec0dbfced53438c625462afb792dcb098" +
"544bffffffff0240420f00000000001976a9144676d1b820d63ec272f19" +
"00d59d43bc6463d96f888ac40420f00000000001976a914648d04341d00" +
"d7968b3405c034adc38d4d8fb9bd88ac00000000010000000248cc91750" +
"1ea5c55f4a8d2009c0567c40cfe037c2e71af017d0a452ff705e3f10000" +
"00008b483045022100bf5fdc86dc5f08a5d5c8e43a8c9d5b1ed8c65562e" +
"280007b52b133021acd9acc02205e325d613e555f772802bf413d36ba80" +
"7892ed1a690a77811d3033b3de226e0a01410429fa713b124484cb2bd7b" +
"5557b2c0b9df7b2b1fee61825eadc5ae6c37a9920d38bfccdc7dc3cb0c4" +
"7d7b173dbc9db8d37db0a33ae487982c59c6f8606e9d1791ffffffff41e" +
"d70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d0" +
"68000000008b4830450221008513ad65187b903aed1102d1d0c47688127" +
"658c51106753fed0151ce9c16b80902201432b9ebcb87bd04ceb2de6603" +
"5fbbaf4bf8b00d1cfe41f1a1f7338f9ad79d210141049d4cf80125bf50b" +
"e1709f718c07ad15d0fc612b7da1f5570dddc35f2a352f0f27c978b0682" +
"0edca9ef982c35fda2d255afba340068c5035552368bc7200c1488fffff" +
"fff0100093d00000000001976a9148edb68822f1ad580b043c7b3df2e40" +
"0f8699eb4888ac00000000"
blockBytes, err := hex.DecodeString(blockStr)
if err != nil {
t.Errorf("TestFilterInsertP2PubKeyOnly DecodeString failed: %v", err)
return
}
block, err := btcutil.NewBlockFromBytes(blockBytes)
if err != nil {
t.Errorf("TestFilterInsertP2PubKeyOnly NewBlockFromBytes failed: %v", err)
return
}
f := bloom.NewFilter(10, 0, 0.000001, btcwire.BloomUpdateP2PubkeyOnly)
// Generation pubkey
inputStr := "04eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c" +
"876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a" +
"2252247d97a46a91"
inputBytes, err := hex.DecodeString(inputStr)
if err != nil {
t.Errorf("TestFilterInsertP2PubKeyOnly DecodeString failed: %v", err)
return
}
f.Add(inputBytes)
// Output address of 4th transaction
inputStr = "b6efd80d99179f4f4ff6f4dd0a007d018c385d21"
inputBytes, err = hex.DecodeString(inputStr)
if err != nil {
t.Errorf("TestFilterInsertP2PubKeyOnly DecodeString failed: %v", err)
return
}
f.Add(inputBytes)
// Ignore return value -- this is just used to update the filter.
_, _ = bloom.NewMerkleBlock(block, f)
// We should match the generation pubkey
inputStr = "147caa76786596590baa4e98f5d9f48b86c7765e489f7a6ff3360fe5c674360b"
sha, err := btcwire.NewShaHashFromStr(inputStr)
if err != nil {
t.Errorf("TestMerkleBlockP2PubKeyOnly NewShaHashFromStr failed: %v", err)
return
}
outpoint := btcwire.NewOutPoint(sha, 0)
if !f.MatchesOutPoint(outpoint) {
t.Errorf("TestMerkleBlockP2PubKeyOnly didn't match the generation "+
"outpoint %s", inputStr)
return
}
// We should not match the 4th transaction, which is not p2pk
inputStr = "02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"
sha, err = btcwire.NewShaHashFromStr(inputStr)
if err != nil {
t.Errorf("TestMerkleBlockP2PubKeyOnly NewShaHashFromStr failed: %v", err)
return
}
outpoint = btcwire.NewOutPoint(sha, 0)
if f.MatchesOutPoint(outpoint) {
t.Errorf("TestMerkleBlockP2PubKeyOnly matched outpoint %s", inputStr)
return
}
}
开发者ID:jrick,项目名称:btcutil,代码行数:101,代码来源:filter_test.go
示例17: 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) {
// Previous transaction output point for coinbase to test.
prevOutIndex := uint32(0xffffffff)
prevOut := btcwire.NewOutPoint(&btcwire.ShaHash{}, prevOutIndex)
// Transaction input to test.
sigScript := []byte{0x04, 0x31, 0xdc, 0x00, 0x1b, 0x01, 0x62}
txIn := btcwire.NewTxIn(prevOut, sigScript)
txIn.Sequence = 0xffffffff
// Transaction output to test.
txValue := int64(5000000000)
pkScript := []byte{
0x41, // OP_DATA_65
0x04, 0xd6, 0x4b, 0xdf, 0xd0, 0x9e, 0xb1, 0xc5,
0xfe, 0x29, 0x5a, 0xbd, 0xeb, 0x1d, 0xca, 0x42,
0x81, 0xbe, 0x98, 0x8e, 0x2d, 0xa0, 0xb6, 0xc1,
0xc6, 0xa5, 0x9d, 0xc2, 0x26, 0xc2, 0x86, 0x24,
0xe1, 0x81, 0x75, 0xe8, 0x51, 0xc9, 0x6b, 0x97,
0x3d, 0x81, 0xb0, 0x1c, 0xc3, 0x1f, 0x04, 0x78,
0x34, 0xbc, 0x06, 0xd6, 0xd6, 0xed, 0xf6, 0x20,
0xd1, 0x84, 0x24, 0x1a, 0x6a, 0xed, 0x8b, 0x63,
0xa6, // 65-byte signature
0xac, // OP_CHECKSIG
}
txOut := btcwire.NewTxOut(txValue, pkScript)
// Empty tx message.
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
}
multiTx := btcwire.NewMsgTx()
multiTx.Version = 1
multiTx.AddTxIn(txIn)
multiTx.AddTxOut(txOut)
multiTx.LockTime = 0
multiTxEncoded := []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, 0x31, 0xdc, 0x00, 0x1b, 0x01, 0x62, // 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, 0xd6, 0x4b, 0xdf, 0xd0, 0x9e, 0xb1, 0xc5,
0xfe, 0x29, 0x5a, 0xbd, 0xeb, 0x1d, 0xca, 0x42,
0x81, 0xbe, 0x98, 0x8e, 0x2d, 0xa0, 0xb6, 0xc1,
0xc6, 0xa5, 0x9d, 0xc2, 0x26, 0xc2, 0x86, 0x24,
0xe1, 0x81, 0x75, 0xe8, 0x51, 0xc9, 0x6b, 0x97,
0x3d, 0x81, 0xb0, 0x1c, 0xc3, 0x1f, 0x04, 0x78,
0x34, 0xbc, 0x06, 0xd6, 0xd6, 0xed, 0xf6, 0x20,
0xd1, 0x84, 0x24, 0x1a, 0x6a, 0xed, 0x8b, 0x63,
0xa6, // 65-byte signature
0xac, // OP_CHECKSIG
0x00, 0x00, 0x00, 0x00, // Lock time
}
tests := []struct {
in *btcwire.MsgTx // Message to encode
out *btcwire.MsgTx // Expected decoded message
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version with no transactions.
{
noTx,
noTx,
noTxEncoded,
btcwire.ProtocolVersion,
},
// Latest protocol version with multiple transactions.
{
multiTx,
multiTx,
multiTxEncoded,
btcwire.ProtocolVersion,
},
// Protocol version BIP0035Version with no transactions.
{
noTx,
noTx,
noTxEncoded,
btcwire.BIP0035Version,
//.........这里部分代码省略.........
开发者ID:h00gs,项目名称:btcwire,代码行数:101,代码来源:msgtx_test.go
示例18: 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 *btcutil.Block) (height int64, rerr error) {
db.dbLock.Lock()
defer db.dbLock.Unlock()
defer func() {
if rerr == nil {
rerr = db.processBatches()
} else {
db.lBatch().Reset()
}
}()
blocksha, err := block.Sha()
if err != nil {
log.Warnf("Failed to compute block sha %v", blocksha)
return 0, err
}
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 := btcwire.NewShaHashFromStr("d5d27987d2a3dfc724e359870c6644b40e497bdc0589a033220fe15429d88599")
if err != nil {
panic("invalid sha string in source")
}
if txsha.IsEqual(dupsha) {
// marking TxOut[0] as spent
po := btcwire.NewOutPoint(dupsha, 0)
txI := btcwire.NewTxIn(po, []byte("garbage"))
var spendtx btcwire.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 := btcwire.NewShaHashFromStr("e3bf3d07d4b0375638d5f1db5255fe07ba2c4cb067cd81b84ee974b6585fb468")
if err != nil {
panic("invalid sha string in source")
}
if txsha.IsEqual(dupsha) {
// marking TxOut[0] as spent
po := btcwire.NewOutPoint(dupsha, 0)
txI := btcwire.NewTxIn(po, []byte("garbage"))
var spendtx btcwire.MsgTx
spendtx.AddTxIn(txI)
err = db.doSpend(&spendtx)
//.........这里部分代码省略.........
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:101,代码来源:leveldb.go
示例19: NtfnProcessedTx
// NtfnProcessedTx handles the btcws.ProcessedTxNtfn notification.
func NtfnProcessedTx(n btcjson.Cmd, marshaled []byte) {
ptn, ok := n.(*btcws.ProcessedTxNtfn)
if !ok {
log.Errorf("%v handler: unexpected type", n.Method())
return
}
// Create useful types from the JSON strings.
receiver, err := btcutil.DecodeAddr(ptn.Receiver)
if err != nil {
log.Errorf("%v handler: error parsing receiver: %v", n.Method(), err)
return
}
txID, err := btcwire.NewShaHashFromStr(ptn.TxID)
if err != nil {
log.Errorf("%v handler: error parsing txid: %v", n.Method(), err)
return
}
blockHash, err := btcwire.NewShaHashFromStr(ptn.BlockHash)
if err != nil {
log.Errorf("%v handler: error parsing block hash: %v", n.Method(), err)
return
}
pkscript, err := hex.DecodeString(ptn.PkScript)
if err != nil {
log.Errorf("%v handler: error parsing pkscript: %v", n.Method(), err)
return
}
// Lookup account for address in result.
aname, err := LookupAccountByAddress(ptn.Receiver)
if err == ErrNotFound {
log.Warnf("Received rescan result for unknown address %v", ptn.Receiver)
return
}
a, err := accountstore.Account(aname)
if err == ErrAcctNotExist {
log.Errorf("Missing account for rescaned address %v", ptn.Receiver)
}
// Create RecvTx to add to tx history.
t := &tx.RecvTx{
TxID: *txID,
TxOutIdx: ptn.TxOutIndex,
TimeReceived: time.Now().Unix(),
BlockHeight: ptn.BlockHeight,
BlockHash: *blockHash,
BlockIndex: int32(ptn.BlockIndex),
BlockTime: ptn.BlockTime,
Amount: ptn.Amount,
ReceiverHash: receiver.ScriptAddress(),
}
// For transactions originating from this wallet, the sent tx history should
// be recorded before the received history. If wallet created this tx, wait
// for the sent history to finish being recorded before continuing.
req := SendTxHistSyncRequest{
txid: *txID,
response: make(chan SendTxHistSyncResponse),
}
SendTxHistSyncChans.access <- req
resp := <-req.response
if resp.ok {
// Wait until send history has been recorded.
<-resp.c
SendTxHistSyncChans.remove <- *txID
}
// Record the tx history.
a.TxStore.Lock()
a.TxStore.s.InsertRecvTx(t)
a.TxStore.Unlock()
a.ScheduleTxStoreWrite()
// Notify frontends of tx. If the tx is unconfirmed, it is always
// notified and the outpoint is marked as notified. If the outpoint
// has already been notified and is now in a block, a txmined notifiction
// should be sent once to let frontends that all previous send/recvs
// for this unconfirmed tx are now confirmed.
recvTxOP := btcwire.NewOutPoint(txID, ptn.TxOutIndex)
previouslyNotifiedReq := NotifiedRecvTxRequest{
op: *recvTxOP,
response: make(chan NotifiedRecvTxResponse),
}
NotifiedRecvTxChans.access <- previouslyNotifiedReq
if <-previouslyNotifiedReq.response {
NotifyMinedTx <- t
NotifiedRecvTxChans.remove <- *recvTxOP
} else {
// Notify frontends of new recv tx and mark as notified.
NotifiedRecvTxChans.add <- *recvTxOP
NotifyNewTxDetails(frontendNotificationMaster, a.Name(), t.TxInfo(a.Name(),
ptn.BlockHeight, a.Wallet.Net())[0])
}
if !ptn.Spent {
u := &tx.Utxo{
Amt: uint64(ptn.Amount),
Height: ptn.BlockHeight,
//.........这里部分代码省略.........
|
请发表评论