本文整理汇总了Golang中github.com/conformal/btcutil.Amount函数的典型用法代码示例。如果您正苦于以下问题:Golang Amount函数的具体用法?Golang Amount怎么用?Golang Amount使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Amount函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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")
}
}
示例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
}
示例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
}
示例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
}
示例13: Value
// Value returns the value of the Coin
func (c *SimpleCoin) Value() btcutil.Amount {
return btcutil.Amount(c.txOut().Value)
}
示例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)
//.........这里部分代码省略.........
示例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)
}
}