• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang btcutil.Amount函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/conformal/btcutil.Amount函数的典型用法代码示例。如果您正苦于以下问题:Golang Amount函数的具体用法?Golang Amount怎么用?Golang Amount使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Amount函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: 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
}
开发者ID:GeertJohan,项目名称:btcwallet,代码行数:32,代码来源:createtx.go


示例2: OutputAmount

// OutputAmount returns the total amount of all outputs for a transaction.
func (t *TxRecord) OutputAmount(ignoreChange bool) btcutil.Amount {
	a := btcutil.Amount(0)
	for i, txOut := range t.Tx().MsgTx().TxOut {
		if ignoreChange {
			switch cs := t.credits; {
			case i < len(cs) && cs[i] != nil && cs[i].change:
				continue
			}
		}
		a += btcutil.Amount(txOut.Value)
	}
	return a
}
开发者ID:kingpro,项目名称:btcwallet,代码行数:14,代码来源:tx.go


示例3: CreateRawTx2

func CreateRawTx2(outputs []output, amount, value int64, toAddr, changeAddr string) (rawtx string, err error) {
	var inputs []btcjson.TransactionInput
	var rawInputs []btcjson.RawTxInput
	var amounts = make(map[btcutil.Address]btcutil.Amount)
	var privKeys []string

	for _, op := range outputs {
		inputs = append(inputs, btcjson.TransactionInput{Txid: op.TxHash, Vout: op.TxN})
		rawInputs = append(rawInputs, btcjson.RawTxInput{
			Txid:         op.TxHash,
			Vout:         op.TxN,
			ScriptPubKey: op.Script,
		})
		privKeys = append(privKeys, op.PrivKey)
	}

	addr, err := btcutil.DecodeAddress(toAddr, &btcnet.MainNetParams)
	if err != nil {
		return
	}
	amounts[addr] = btcutil.Amount(value)
	if amount > value {
		addr, err = btcutil.DecodeAddress(changeAddr, &btcnet.MainNetParams)
		if err != nil {
			return
		}
		amounts[addr] = btcutil.Amount(amount - value)
	}
	client, err := btcRpcClient()
	if err != nil {
		return
	}
	txMsg, err := client.CreateRawTransaction(inputs, amounts)
	if err != nil {
		return
	}

	txMsg, complete, err := client.SignRawTransaction3(txMsg, rawInputs, privKeys)
	if err != nil {
		return
	}
	if !complete {
		return "", errors.New("not complete")
	}

	buffer := &bytes.Buffer{}
	if err = txMsg.BtcEncode(buffer, 1); err != nil {
		return
	}
	return hex.EncodeToString(buffer.Bytes()), nil
}
开发者ID:shevilangle,项目名称:sports,代码行数:51,代码来源:sign2.go


示例4: markOutputsSpent

// markOutputsSpent marks each previous credit spent by t as spent.  The total
// input of all spent previous outputs is returned.
func (s *Store) markOutputsSpent(spent []*Credit, t *TxRecord) (btcutil.Amount, error) {
	var a btcutil.Amount
	for _, prev := range spent {
		switch prev.BlockHeight {
		case -1: // unconfirmed
			op := prev.OutPoint()
			s.unconfirmed.spentUnconfirmed[*op] = t.txRecord

		default:
			b, err := s.lookupBlock(prev.BlockHeight)
			if err != nil {
				return 0, err
			}
			r, _, err := b.lookupTxRecord(prev.BlockIndex)
			if err != nil {
				return 0, err
			}

			// Update spent info.  If this transaction (and possibly
			// block) no longer contains any unspent transactions,
			// remove from bookkeeping maps.
			credit := prev.txRecord.credits[prev.OutputIndex]
			if credit.spentBy != nil {
				if *credit.spentBy == t.BlockTxKey {
					continue
				}
				return 0, ErrInconsistentStore
			}
			credit.spentBy = &t.BlockTxKey
			if !r.hasUnspents() {
				delete(b.unspent, prev.BlockIndex)
				if len(b.unspent) == 0 {
					delete(s.unspent, b.Height)
				}
			}
			if t.BlockHeight == -1 { // unconfirmed
				op := prev.OutPoint()
				key := prev.outputKey()
				s.unconfirmed.spentBlockOutPointKeys[*op] = *key
				s.unconfirmed.spentBlockOutPoints[*key] = t.txRecord
			}

			// Increment total debited amount.
			v := r.Tx().MsgTx().TxOut[prev.OutputIndex].Value
			a += btcutil.Amount(v)
		}
	}

	// If t refers to a mined transaction, update its block's amount deltas
	// by the total debited amount.
	if t.BlockHeight != -1 {
		b, err := s.lookupBlock(t.BlockHeight)
		if err != nil {
			return 0, err
		}
		b.amountDeltas.Spendable -= a
	}

	return a, nil
}
开发者ID:GeertJohan,项目名称:btcwallet,代码行数:62,代码来源:tx.go


示例5: parseAccountBalanceNtfnParams

// parseAccountBalanceNtfnParams parses out the account name, total balance,
// and whether or not the balance is confirmed or unconfirmed from the
// parameters of an accountbalance notification.
func parseAccountBalanceNtfnParams(params []json.RawMessage) (account string,
	balance btcutil.Amount, confirmed bool, err error) {

	if len(params) != 3 {
		return "", 0, false, wrongNumParams(len(params))
	}

	// Unmarshal first parameter as a string.
	err = json.Unmarshal(params[0], &account)
	if err != nil {
		return "", 0, false, err
	}

	// Unmarshal second parameter as a floating point number.
	var fbal float64
	err = json.Unmarshal(params[1], &fbal)
	if err != nil {
		return "", 0, false, err
	}

	// Unmarshal third parameter as a boolean.
	err = json.Unmarshal(params[2], &confirmed)
	if err != nil {
		return "", 0, false, err
	}

	// Bounds check amount.
	bal, err := btcjson.JSONToAmount(fbal)
	if err != nil {
		return "", 0, false, err
	}

	return account, btcutil.Amount(bal), confirmed, nil
}
开发者ID:awt,项目名称:btcrpcclient,代码行数:37,代码来源:notify.go


示例6: parseTxAcceptedNtfnParams

// parseTxAcceptedNtfnParams parses out the transaction hash and total amount
// from the parameters of a txaccepted notification.
func parseTxAcceptedNtfnParams(params []json.RawMessage) (*btcwire.ShaHash,
	btcutil.Amount, error) {

	if len(params) != 2 {
		return nil, 0, wrongNumParams(len(params))
	}

	// Unmarshal first parameter as a string.
	var txShaStr string
	err := json.Unmarshal(params[0], &txShaStr)
	if err != nil {
		return nil, 0, err
	}

	// Unmarshal second parameter as an integer.
	var amt int64
	err = json.Unmarshal(params[1], &amt)
	if err != nil {
		return nil, 0, err
	}

	// Decode string encoding of transaction sha.
	txSha, err := btcwire.NewShaHashFromStr(txShaStr)
	if err != nil {
		return nil, 0, err
	}

	return txSha, btcutil.Amount(amt), nil
}
开发者ID:awt,项目名称:btcrpcclient,代码行数:31,代码来源:notify.go


示例7: AddCredit

// AddCredit marks the transaction record as containing a transaction output
// spendable by wallet.  The output is added unspent, and is marked spent
// when a new transaction spending the output is inserted into the store.
func (t *TxRecord) AddCredit(index uint32, change bool) (*Credit, error) {
	if len(t.tx.MsgTx().TxOut) <= int(index) {
		return nil, errors.New("transaction output does not exist")
	}

	c := &credit{change: change}
	if err := t.txRecord.setCredit(c, index, t.tx); err != nil {
		if err == ErrDuplicateInsert {
			return &Credit{t, index}, nil
		}
		return nil, err
	}

	switch t.BlockHeight {
	case -1: // unconfirmed
	default:
		b, err := t.s.lookupBlock(t.BlockHeight)
		if err != nil {
			return nil, err
		}
		_, txsIndex, err := b.lookupTxRecord(t.Tx().Index())
		if err != nil {
			return nil, err
		}

		// New outputs are added unspent.
		t.s.unspent[t.BlockTxKey.BlockHeight] = struct{}{}
		b.unspent[t.Tx().Index()] = txsIndex
		switch a := t.tx.MsgTx().TxOut[index].Value; t.tx.Index() {
		case 0: // Coinbase
			b.amountDeltas.Reward += btcutil.Amount(a)
		default:
			b.amountDeltas.Spendable += btcutil.Amount(a)
		}
	}

	return &Credit{t, index}, nil
}
开发者ID:GeertJohan,项目名称:btcwallet,代码行数:41,代码来源:tx.go


示例8: ToJSON

// ToJSON returns a slice of objects that may be marshaled as a JSON array
// of JSON objects for a listtransactions RPC reply.
func (c *Credit) ToJSON(account string, chainHeight int32,
	net btcwire.BitcoinNet) (btcjson.ListTransactionsResult, error) {

	msgTx := c.Tx().MsgTx()
	txout := msgTx.TxOut[c.OutputIndex]

	var address string
	_, addrs, _, _ := btcscript.ExtractPkScriptAddrs(txout.PkScript, net)
	if len(addrs) == 1 {
		address = addrs[0].EncodeAddress()
	}

	var category string
	switch {
	case c.IsCoinbase():
		if c.Confirmed(btcchain.CoinbaseMaturity, chainHeight) {
			category = "generate"
		} else {
			category = "immature"
		}
	default:
		category = "receive"
	}

	result := btcjson.ListTransactionsResult{
		Account:         account,
		Category:        category,
		Address:         address,
		Amount:          btcutil.Amount(txout.Value).ToUnit(btcutil.AmountBTC),
		TxID:            c.Tx().Sha().String(),
		Time:            c.received.Unix(),
		TimeReceived:    c.received.Unix(),
		WalletConflicts: []string{},
	}
	if c.BlockHeight != -1 {
		b, err := c.s.lookupBlock(c.BlockHeight)
		if err != nil {
			return btcjson.ListTransactionsResult{}, err
		}

		result.BlockHash = b.Hash.String()
		result.BlockIndex = int64(c.Tx().Index())
		result.BlockTime = b.Time.Unix()
		result.Confirmations = int64(c.Confirmations(chainHeight))
	}

	return result, nil
}
开发者ID:GeertJohan,项目名称:btcwallet,代码行数:50,代码来源:json.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: submitBlock

// submitBlock submits the passed block to network after ensuring it passes all
// of the consensus validation rules.
func (m *CPUMiner) submitBlock(block *btcutil.Block) bool {
	m.submitBlockLock.Lock()
	defer m.submitBlockLock.Unlock()

	// Ensure the block is not stale since a new block could have shown up
	// while the solution was being found.  Typically that condition is
	// detected and all work on the stale block is halted to start work on
	// a new block, but the check only happens periodically, so it is
	// possible a block was found and submitted in between.
	latestHash, _ := m.server.blockManager.chainState.Best()
	msgBlock := block.MsgBlock()
	if !msgBlock.Header.PrevBlock.IsEqual(latestHash) {
		minrLog.Debugf("Block submitted via CPU miner with previous "+
			"block %s is stale", msgBlock.Header.PrevBlock)
		return false
	}

	// Process this block using the same rules as blocks coming from other
	// nodes.  This will in turn relay it to the network like normal.
	isOrphan, err := m.server.blockManager.ProcessBlock(block)
	if err != nil {
		// Anything other than a rule violation is an unexpected error,
		// so log that error as an internal error.
		if _, ok := err.(btcchain.RuleError); !ok {
			minrLog.Errorf("Unexpected error while processing "+
				"block submitted via CPU miner: %v", err)
			return false
		}

		minrLog.Debugf("Block submitted via CPU miner rejected: %v", err)
		return false
	}
	if isOrphan {
		minrLog.Debugf("Block submitted via CPU miner is an orphan")
		return false
	}

	// The block was accepted.
	blockSha, _ := block.Sha()
	coinbaseTx := block.MsgBlock().Transactions[0].TxOut[0]
	minrLog.Infof("Block submitted via CPU miner accepted (hash %s, "+
		"amount %v)", blockSha, btcutil.Amount(coinbaseTx.Value))
	return true
}
开发者ID:nixoid,项目名称:btcd,代码行数:46,代码来源:cpuminer.go


示例11: AddCredit

// AddCredit marks the transaction record as containing a transaction output
// spendable by wallet.  The output is added unspent, and is marked spent
// when a new transaction spending the output is inserted into the store.
func (t *TxRecord) AddCredit(index uint32, change bool) (Credit, error) {
	if len(t.tx.MsgTx().TxOut) <= int(index) {
		return Credit{}, errors.New("transaction output does not exist")
	}

	if err := t.txRecord.setCredit(index, change, t.tx); err != nil {
		if err == ErrDuplicateInsert {
			return Credit{t, index}, nil
		}
		return Credit{}, err
	}

	txOutAmt := btcutil.Amount(t.tx.MsgTx().TxOut[index].Value)
	log.Debugf("Marking transaction %v output %d (%v) spendable",
		t.tx.Sha(), index, txOutAmt)

	switch t.BlockHeight {
	case -1: // unconfirmed
	default:
		b, err := t.s.lookupBlock(t.BlockHeight)
		if err != nil {
			return Credit{}, err
		}

		// New outputs are added unspent.
		op := btcwire.OutPoint{Hash: *t.tx.Sha(), Index: index}
		t.s.unspent[op] = t.BlockTxKey
		switch t.tx.Index() {
		case 0: // Coinbase
			b.amountDeltas.Reward += txOutAmt
		default:
			b.amountDeltas.Spendable += txOutAmt
		}
	}

	return Credit{t, index}, nil
}
开发者ID:kingpro,项目名称:btcwallet,代码行数:40,代码来源:tx.go


示例12: ToJSON

// ToJSON returns a slice of objects that may be marshaled as a JSON array
// of JSON objects for a listtransactions RPC reply.
func (c *Credit) ToJSON(account string, chainHeight int32,
	net *btcnet.Params) (btcjson.ListTransactionsResult, error) {

	msgTx := c.Tx().MsgTx()
	txout := msgTx.TxOut[c.OutputIndex]

	var address string
	_, addrs, _, _ := btcscript.ExtractPkScriptAddrs(txout.PkScript, net)
	if len(addrs) == 1 {
		address = addrs[0].EncodeAddress()
	}

	result := btcjson.ListTransactionsResult{
		Account:         account,
		Category:        c.Category(chainHeight).String(),
		Address:         address,
		Amount:          btcutil.Amount(txout.Value).ToUnit(btcutil.AmountBTC),
		TxID:            c.Tx().Sha().String(),
		Time:            c.received.Unix(),
		TimeReceived:    c.received.Unix(),
		WalletConflicts: []string{},
	}
	if c.BlockHeight != -1 {
		b, err := c.s.lookupBlock(c.BlockHeight)
		if err != nil {
			return btcjson.ListTransactionsResult{}, err
		}

		result.BlockHash = b.Hash.String()
		result.BlockIndex = int64(c.Tx().Index())
		result.BlockTime = b.Time.Unix()
		result.Confirmations = int64(c.Confirmations(chainHeight))
	}

	return result, nil
}
开发者ID:kingpro,项目名称:btcwallet,代码行数:38,代码来源:json.go


示例13: Value

// Value returns the value of the Coin
func (c *SimpleCoin) Value() btcutil.Amount {
	return btcutil.Amount(c.txOut().Value)
}
开发者ID:stoiclabs,项目名称:blockchainr,代码行数:4,代码来源:coins.go


示例14: txToPairs

// txToPairs creates a raw transaction sending the amounts for each
// address/amount pair and fee to each address and the miner.  minconf
// specifies the minimum number of confirmations required before an
// unspent output is eligible for spending. Leftover input funds not sent
// to addr or as a fee for the miner are sent to a newly generated
// address. If change is needed to return funds back to an owned
// address, changeUtxo will point to a unconfirmed (height = -1, zeroed
// block hash) Utxo.  ErrInsufficientFunds is returned if there are not
// enough eligible unspent outputs to create the transaction.
func (a *Account) txToPairs(pairs map[string]btcutil.Amount,
	minconf int) (*CreatedTx, error) {

	// Wallet must be unlocked to compose transaction.
	if a.IsLocked() {
		return nil, wallet.ErrWalletLocked
	}

	// Create a new transaction which will include all input scripts.
	msgtx := btcwire.NewMsgTx()

	// Calculate minimum amount needed for inputs.
	var amt btcutil.Amount
	for _, v := range pairs {
		// Error out if any amount is negative.
		if v <= 0 {
			return nil, ErrNonPositiveAmount
		}
		amt += v
	}

	// Add outputs to new tx.
	for addrStr, amt := range pairs {
		addr, err := btcutil.DecodeAddress(addrStr, cfg.Net())
		if err != nil {
			return nil, fmt.Errorf("cannot decode address: %s", err)
		}

		// Add output to spend amt to addr.
		pkScript, err := btcscript.PayToAddrScript(addr)
		if err != nil {
			return nil, fmt.Errorf("cannot create txout script: %s", err)
		}
		txout := btcwire.NewTxOut(int64(amt), pkScript)
		msgtx.AddTxOut(txout)
	}

	// Get current block's height and hash.
	bs, err := GetCurBlock()
	if err != nil {
		return nil, err
	}

	// Make a copy of msgtx before any inputs are added.  This will be
	// used as a starting point when trying a fee and starting over with
	// a higher fee if not enough was originally chosen.
	txNoInputs := msgtx.Copy()

	unspent, err := a.TxStore.UnspentOutputs()
	if err != nil {
		return nil, err
	}

	var selectedInputs []*txstore.Credit
	// These are nil/zeroed until a change address is needed, and reused
	// again in case a change utxo has already been chosen.
	var changeAddr btcutil.Address

	// Get the number of satoshis to increment fee by when searching for
	// the minimum tx fee needed.
	fee := btcutil.Amount(0)
	for {
		msgtx = txNoInputs.Copy()

		// Select unspent outputs to be used in transaction based on the amount
		// neededing to sent, and the current fee estimation.
		inputs, btcin, err := selectInputs(unspent, amt+fee, minconf)
		if err != nil {
			return nil, err
		}

		// Check if there are leftover unspent outputs, and return coins back to
		// a new address we own.
		//
		// TODO: change needs to be inserted into a random txout index, or else
		// this is a privacy risk.
		change := btcin - amt - fee
		if change > 0 {
			// Get a new change address if one has not already been found.
			if changeAddr == nil {
				changeAddr, err = a.ChangeAddress(&bs, cfg.KeypoolSize)
				if err != nil {
					return nil, fmt.Errorf("failed to get next address: %s", err)
				}

				// Mark change address as belonging to this account.
				AcctMgr.MarkAddressForAccount(changeAddr, a)
			}

			// Spend change.
			pkScript, err := btcscript.PayToAddrScript(changeAddr)
//.........这里部分代码省略.........
开发者ID:GeertJohan,项目名称:btcwallet,代码行数:101,代码来源:createtx.go


示例15: handleNotification


//.........这里部分代码省略.........
				"invalid transaction hex '%q': %v", ntfn.HexTx,
				err)
		}

		// Deserialize the transaction.
		var msgTx btcwire.MsgTx
		err = msgTx.Deserialize(bytes.NewReader(serializedTx))
		if err != nil {
			log.Warnf("Received redeemingtx notification with "+
				"transaction that failed to deserialize: %v",
				err)
		}

		c.ntfnHandlers.OnRedeemingTx(btcutil.NewTx(&msgTx), ntfn.Block)

	// OnRescanProgress
	case *btcws.RescanProgressNtfn:
		// Ignore the notification is the client is not interested in
		// it.
		if c.ntfnHandlers.OnRescanProgress == nil {
			return
		}

		c.ntfnHandlers.OnRescanProgress(ntfn.LastProcessed)

	// OnTxAccepted
	case *btcws.TxAcceptedNtfn:
		// Ignore the notification is the client is not interested in
		// it.
		if c.ntfnHandlers.OnTxAccepted == nil {
			return
		}

		hash, err := btcwire.NewShaHashFromStr(ntfn.TxID)
		if err != nil {
			log.Warnf("Received tx accepted notification with "+
				"invalid hash string: %q", ntfn.TxID)
			return
		}

		c.ntfnHandlers.OnTxAccepted(hash, btcutil.Amount(ntfn.Amount))

	// OnTxAcceptedVerbose
	case *btcws.TxAcceptedVerboseNtfn:
		// Ignore the notification is the client is not interested in
		// it.
		if c.ntfnHandlers.OnTxAcceptedVerbose == nil {
			return
		}

		c.ntfnHandlers.OnTxAcceptedVerbose(ntfn.RawTx)

	// OnBtcdConnected
	case *btcws.BtcdConnectedNtfn:
		// Ignore the notification is the client is not interested in
		// it.
		if c.ntfnHandlers.OnBtcdConnected == nil {
			return
		}

		c.ntfnHandlers.OnBtcdConnected(ntfn.Connected)

	// OnAccountBalance
	case *btcws.AccountBalanceNtfn:
		// Ignore the notification is the client is not interested in
		// it.
		if c.ntfnHandlers.OnAccountBalance == nil {
			return
		}

		balance, err := btcjson.JSONToAmount(ntfn.Balance)
		if err != nil {
			log.Warnf("Received account balance notification with "+
				"an amount that does not parse: %v",
				ntfn.Balance)
			return
		}

		c.ntfnHandlers.OnAccountBalance(ntfn.Account,
			btcutil.Amount(balance), ntfn.Confirmed)

	// OnWalletLockState
	case *btcws.WalletLockStateNtfn:
		// Ignore the notification is the client is not interested in
		// it.
		if c.ntfnHandlers.OnWalletLockState == nil {
			return
		}

		c.ntfnHandlers.OnWalletLockState(ntfn.Locked)

	// OnUnknownNotification
	default:
		if c.ntfnHandlers.OnUnknownNotification == nil {
			return
		}

		c.ntfnHandlers.OnUnknownNotification(ntfn)
	}
}
开发者ID:GeertJohan,项目名称:btcrpcclient,代码行数:101,代码来源:notify.go


示例16: txToPairs

// txToPairs creates a raw transaction sending the amounts for each
// address/amount pair and fee to each address and the miner.  minconf
// specifies the minimum number of confirmations required before an
// unspent output is eligible for spending. Leftover input funds not sent
// to addr or as a fee for the miner are sent to a newly generated
// address. If change is needed to return funds back to an owned
// address, changeUtxo will point to a unconfirmed (height = -1, zeroed
// block hash) Utxo.  ErrInsufficientFunds is returned if there are not
// enough eligible unspent outputs to create the transaction.
func (a *Account) txToPairs(pairs map[string]btcutil.Amount,
	minconf int) (*CreatedTx, error) {

	// Wallet must be unlocked to compose transaction.
	if a.IsLocked() {
		return nil, wallet.ErrWalletLocked
	}

	// Create a new transaction which will include all input scripts.
	msgtx := btcwire.NewMsgTx()

	// Calculate minimum amount needed for inputs.
	var amt btcutil.Amount
	for _, v := range pairs {
		// Error out if any amount is negative.
		if v <= 0 {
			return nil, ErrNonPositiveAmount
		}
		amt += v
	}

	// Add outputs to new tx.
	for addrStr, amt := range pairs {
		addr, err := btcutil.DecodeAddress(addrStr, activeNet.Params)
		if err != nil {
			return nil, fmt.Errorf("cannot decode address: %s", err)
		}

		// Add output to spend amt to addr.
		pkScript, err := btcscript.PayToAddrScript(addr)
		if err != nil {
			return nil, fmt.Errorf("cannot create txout script: %s", err)
		}
		txout := btcwire.NewTxOut(int64(amt), pkScript)
		msgtx.AddTxOut(txout)
	}

	// Get current block's height and hash.
	bs, err := GetCurBlock()
	if err != nil {
		return nil, err
	}

	// Make a copy of msgtx before any inputs are added.  This will be
	// used as a starting point when trying a fee and starting over with
	// a higher fee if not enough was originally chosen.
	txNoInputs := msgtx.Copy()

	unspent, err := a.TxStore.UnspentOutputs()
	if err != nil {
		return nil, err
	}

	// Filter out unspendable outputs, that is, remove those that (at this
	// time) are not P2PKH outputs.  Other inputs must be manually included
	// in transactions and sent (for example, using createrawtransaction,
	// signrawtransaction, and sendrawtransaction).
	eligible := make([]txstore.Credit, 0, len(unspent))
	for i := range unspent {
		switch btcscript.GetScriptClass(unspent[i].TxOut().PkScript) {
		case btcscript.PubKeyHashTy:
			if !unspent[i].Confirmed(minconf, bs.Height) {
				continue
			}
			// Coinbase transactions must have have reached maturity
			// before their outputs may be spent.
			if unspent[i].IsCoinbase() {
				target := btcchain.CoinbaseMaturity
				if !unspent[i].Confirmed(target, bs.Height) {
					continue
				}
			}

			// Locked unspent outputs are skipped.
			if a.LockedOutpoint(*unspent[i].OutPoint()) {
				continue
			}

			eligible = append(eligible, unspent[i])
		}
	}

	// Sort eligible inputs, as selectInputs expects these to be sorted
	// by amount in reverse order.
	sort.Sort(sort.Reverse(ByAmount(eligible)))

	var selectedInputs []txstore.Credit
	// changeAddr is nil/zeroed until a change address is needed, and reused
	// again in case a change utxo has already been chosen.
	var changeAddr btcutil.Address

//.........这里部分代码省略.........
开发者ID:kingpro,项目名称:btcwallet,代码行数:101,代码来源:createtx.go


示例17: TestMinPrioritySelector

	{minPrioritySelectors[3], []coinset.Coin{coins[1], coins[2]}, 10000000, []coinset.Coin{coins[1]}, nil},
	{minPrioritySelectors[4], connectedCoins, 1, nil, coinset.ErrCoinsNoSelectionAvailable},
	{minPrioritySelectors[5], connectedCoins, 20000000, []coinset.Coin{coins[1], coins[3]}, nil},
	{minPrioritySelectors[6], connectedCoins, 25000000, []coinset.Coin{coins[3], coins[0]}, nil},
}

func TestMinPrioritySelector(t *testing.T) {
	testCoinSelector(minPriorityTests, t)
}

var (
	// should be two outpoints, with 1st one having 0.035BTC value.
	testSimpleCoinNumConfs            = int64(1)
	testSimpleCoinTxHash              = "9b5965c86de51d5dc824e179a05cf232db78c80ae86ca9d7cb2a655b5e19c1e2"
	testSimpleCoinTxHex               = "0100000001a214a110f79e4abe073865ea5b3745c6e82c913bad44be70652804a5e4003b0a010000008c493046022100edd18a69664efa57264be207100c203e6cade1888cbb88a0ad748548256bb2f0022100f1027dc2e6c7f248d78af1dd90027b5b7d8ec563bb62aa85d4e74d6376f3868c0141048f3757b65ed301abd1b0e8942d1ab5b50594d3314cff0299f300c696376a0a9bf72e74710a8af7a5372d4af4bb519e2701a094ef48c8e48e3b65b28502452dceffffffff02e0673500000000001976a914686dd149a79b4a559d561fbc396d3e3c6628b98d88ace86ef102000000001976a914ac3f995655e81b875b38b64351d6f896ddbfc68588ac00000000"
	testSimpleCoinTxValue0            = btcutil.Amount(3500000)
	testSimpleCoinTxValueAge0         = int64(testSimpleCoinTxValue0) * testSimpleCoinNumConfs
	testSimpleCoinTxPkScript0Hex      = "76a914686dd149a79b4a559d561fbc396d3e3c6628b98d88ac"
	testSimpleCoinTxPkScript0Bytes, _ = hex.DecodeString(testSimpleCoinTxPkScript0Hex)
	testSimpleCoinTxBytes, _          = hex.DecodeString(testSimpleCoinTxHex)
	testSimpleCoinTx, _               = btcutil.NewTxFromBytes(testSimpleCoinTxBytes)
	testSimpleCoin                    = &coinset.SimpleCoin{
		Tx:         testSimpleCoinTx,
		TxIndex:    0,
		TxNumConfs: testSimpleCoinNumConfs,
	}
)

func TestSimpleCoin(t *testing.T) {
	if testSimpleCoin.Hash().String() != testSimpleCoinTxHash {
		t.Error("Different value for tx hash than expected")
开发者ID:kac-,项目名称:btcutil,代码行数:31,代码来源:coins_test.go


示例18: ReadFrom

func (t *txRecord) ReadFrom(r io.Reader) (int64, error) {
	var buf [8]byte
	uint64Bytes := buf[:8]
	uint32Bytes := buf[:4]
	singleByte := buf[:1]

	// Read transaction index (as a uint32).
	n, err := io.ReadFull(r, uint32Bytes)
	n64 := int64(n)
	if err != nil {
		return n64, err
	}
	txIndex := int(byteOrder.Uint32(uint32Bytes))

	// Deserialize transaction.
	msgTx := new(msgTx)
	tmpn64, err := msgTx.ReadFrom(r)
	n64 += tmpn64
	if err != nil {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
		return n64, err
	}

	// Create and save the btcutil.Tx of the read MsgTx and set its index.
	tx := btcutil.NewTx((*btcwire.MsgTx)(msgTx))
	tx.SetIndex(txIndex)
	t.tx = tx

	// Read identifier for existance of debits.
	n, err = io.ReadFull(r, singleByte)
	n64 += int64(n)
	if err != nil {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
		return n64, err
	}
	hasDebits, err := byteMarksValidPointer(singleByte[0])
	if err != nil {
		return n64, err
	}

	// If debits have been set, read them.  Otherwise, set to nil.
	if hasDebits {
		// Read debited amount (int64).
		n, err := io.ReadFull(r, uint64Bytes)
		n64 += int64(n)
		if err != nil {
			if err == io.EOF {
				err = io.ErrUnexpectedEOF
			}
			return n64, err
		}
		amount := btcutil.Amount(byteOrder.Uint64(uint64Bytes))

		// Read number of written outputs (as a uint32) this record
		// debits from.
		n, err = io.ReadFull(r, uint32Bytes)
		n64 += int64(n)
		if err != nil {
			if err == io.EOF {
				err = io.ErrUnexpectedEOF
			}
			return n64, err
		}
		spendsCount := byteOrder.Uint32(uint32Bytes)

		// For each expected output key, allocate and read the key,
		// appending the result to the spends slice.  This slice is
		// originally set to nil (*not* preallocated to spendsCount
		// size) to prevent accidentally allocating so much memory that
		// the process dies.
		var spends []*BlockOutputKey
		for i := uint32(0); i < spendsCount; i++ {
			k := &BlockOutputKey{}
			tmpn64, err := k.ReadFrom(r)
			n64 += tmpn64
			if err != nil {
				if err == io.EOF {
					err = io.ErrUnexpectedEOF
				}
				return n64, err
			}
			spends = append(spends, k)
		}

		t.debits = &debits{amount, spends}
	} else {
		t.debits = nil
	}

	// Read number of pointers (as a uint32) written to be read into the
	// credits slice (although some may be nil).
	n, err = io.ReadFull(r, uint32Bytes)
	n64 += int64(n)
	if err != nil {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
//.........这里部分代码省略.........
开发者ID:GeertJohan,项目名称:btcwallet,代码行数:101,代码来源:serialization.go


示例19: TestInsertsCreditsDebitsRollbacks

func TestInsertsCreditsDebitsRollbacks(t *testing.T) {
	// Create a double spend of the received blockchain transaction.
	dupRecvTx, _ := btcutil.NewTxFromBytes(TstRecvSerializedTx)
	// Switch txout amount to 1 BTC.  Transaction store doesn't
	// validate txs, so this is fine for testing a double spend
	// removal.
	TstDupRecvAmount := int64(1e8)
	newDupMsgTx := dupRecvTx.MsgTx()
	newDupMsgTx.TxOut[0].Value = TstDupRecvAmount
	TstDoubleSpendTx := btcutil.NewTx(newDupMsgTx)

	// Create a "signed" (with invalid sigs) tx that spends output 0 of
	// the double spend.
	spendingTx := btcwire.NewMsgTx()
	spendingTxIn := btcwire.NewTxIn(btcwire.NewOutPoint(TstDoubleSpendTx.Sha(), 0), []byte{0, 1, 2, 3, 4})
	spendingTx.AddTxIn(spendingTxIn)
	spendingTxOut1 := btcwire.NewTxOut(1e7, []byte{5, 6, 7, 8, 9})
	spendingTxOut2 := btcwire.NewTxOut(9e7, []byte{10, 11, 12, 13, 14})
	spendingTx.AddTxOut(spendingTxOut1)
	spendingTx.AddTxOut(spendingTxOut2)
	TstSpendingTx := btcutil.NewTx(spendingTx)
	var _ = TstSpendingTx

	tests := []struct {
		name     string
		f        func(*Store) (*Store, error)
		bal, unc btcutil.Amount
		unspents map[btcwire.OutPoint]struct{}
		unmined  map[btcwire.ShaHash]struct{}
	}{
		{
			name: "new store",
			f: func(_ *Store) (*Store, error) {
				return New(), nil
			},
			bal:      0,
			unc:      0,
			unspents: map[btcwire.OutPoint]struct{}{},
			unmined:  map[btcwire.ShaHash]struct{}{},
		},
		{
			name: "txout insert",
			f: func(s *Store) (*Store, error) {
				r, err := s.InsertTx(TstRecvTx, nil)
				if err != nil {
					return nil, err
				}

				_, err = r.AddCredit(0, false)
				if err != nil {
					return nil, err
				}
				// Verify that we can create the JSON output without any
				// errors.
				_, err = r.ToJSON("", 100, &btcnet.MainNetParams)
				if err != nil {
					return nil, err
				}
				return s, nil
			},
			bal: 0,
			unc: btcutil.Amount(TstRecvTx.MsgTx().TxOut[0].Value),
			unspents: map[btcwire.OutPoint]struct{}{
				*btcwire.NewOutPoint(TstRecvTx.Sha(), 0): {},
			},
			unmined: map[btcwire.ShaHash]struct{}{},
		},
		{
			name: "insert duplicate unconfirmed",
			f: func(s *Store) (*Store, error) {
				r, err := s.InsertTx(TstRecvTx, nil)
				if err != nil {
					return nil, err
				}

				_, err = r.AddCredit(0, false)
				if err != nil {
					return nil, err
				}

				_, err = r.ToJSON("", 100, &btcnet.MainNetParams)
				if err != nil {
					return nil, err
				}
				return s, nil
			},
			bal: 0,
			unc: btcutil.Amount(TstRecvTx.MsgTx().TxOut[0].Value),
			unspents: map[btcwire.OutPoint]struct{}{
				*btcwire.NewOutPoint(TstRecvTx.Sha(), 0): {},
			},
			unmined: map[btcwire.ShaHash]struct{}{},
		},
		{
			name: "confirmed txout insert",
			f: func(s *Store) (*Store, error) {
				TstRecvTx.SetIndex(TstRecvIndex)
				r, err := s.InsertTx(TstRecvTx, TstRecvTxBlockDetails)
				if err != nil {
					return nil, err
//.........这里部分代码省略.........
开发者ID:kingpro,项目名称:btcwallet,代码行数:101,代码来源:tx_test.go


示例20: Balance

// Balance returns the spendable wallet balance (total value of all unspent
// transaction outputs) given a minimum of minConf confirmations, calculated
// at a current chain height of curHeight.  Coinbase outputs are only included
// in the balance if maturity has been reached.
func (s *Store) Balance(minConf int, chainHeight int32) (btcutil.Amount, error) {
	var bal btcutil.Amount

	// Shadow these functions to avoid repeating arguments unnecesarily.
	confirms := func(height int32) int32 {
		return confirms(height, chainHeight)
	}
	confirmed := func(height int32) bool {
		return confirmed(minConf, height, chainHeight)
	}

	for _, b := range s.blocks {
		if confirmed(b.Height) {
			bal += b.amountDeltas.Spendable
			if confirms(b.Height) >= btcchain.CoinbaseMaturity {
				bal += b.amountDeltas.Reward
			}
			continue
		}
		// If there are still blocks that contain debiting transactions,
		// decrement the balance if they spend credits meeting minConf
		// confirmations.
		for _, r := range b.txs {
			if r.debits == nil {
				continue
			}
			for _, prev := range r.debits.spends {
				if !confirmed(prev.BlockHeight) {
					continue
				}
				r, err := s.lookupBlockTx(prev.BlockTxKey)
				if err != nil {
					return 0, err
				}
				v := r.Tx().MsgTx().TxOut[prev.OutputIndex].Value
				bal -= btcutil.Amount(v)
			}
		}
	}

	// Unconfirmed transactions which spend previous credits debit from
	// the returned balance, even with minConf > 0.
	for prev := range s.unconfirmed.spentBlockOutPoints {
		if confirmed(prev.BlockHeight) {
			r, err := s.lookupBlockTx(prev.BlockTxKey)
			if err != nil {
				return 0, err
			}
			v := r.Tx().MsgTx().TxOut[prev.OutputIndex].Value
			bal -= btcutil.Amount(v)
		}
	}

	// If unconfirmed credits are included, tally them as well.
	if minConf == 0 {
		for _, r := range s.unconfirmed.txs {
			for i, c := range r.credits {
				if c == nil {
					continue
				}
				if c.spentBy == nil {
					v := r.Tx().MsgTx().TxOut[i].Value
					bal += btcutil.Amount(v)
				}
			}
		}
	}

	return bal, nil
}
开发者ID:kingpro,项目名称:btcwallet,代码行数:74,代码来源:tx.go



注:本文中的github.com/conformal/btcutil.Amount函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang btcutil.AppDataDir函数代码示例发布时间:2022-05-23
下一篇:
Golang btcscript.PayToAddrScript函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap