本文整理汇总了Golang中github.com/btcsuite/btcd/txscript.PayToAddrScript函数的典型用法代码示例。如果您正苦于以下问题:Golang PayToAddrScript函数的具体用法?Golang PayToAddrScript怎么用?Golang PayToAddrScript使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PayToAddrScript函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: ExamplePayToAddrScript
// This example demonstrates creating a script which pays to a bitcoin address.
// It also prints the created script hex and uses the DisasmString function to
// display the disassembled script.
func ExamplePayToAddrScript() {
// Parse the address to send the coins to into a btcutil.Address
// which is useful to ensure the accuracy of the address and determine
// the address type. It is also required for the upcoming call to
// PayToAddrScript.
addressStr := "12gpXQVcCL2qhTNQgyLVdCFG2Qs2px98nV"
address, err := btcutil.DecodeAddress(addressStr, &chaincfg.MainNetParams)
if err != nil {
fmt.Println(err)
return
}
// Create a public key script that pays to the address.
script, err := txscript.PayToAddrScript(address)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Script Hex: %x\n", script)
disasm, err := txscript.DisasmString(script)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Script Disassembly:", disasm)
// Output:
// Script Hex: 76a914128004ff2fcaf13b2b91eb654b1dc2b674f7ec6188ac
// Script Disassembly: OP_DUP OP_HASH160 128004ff2fcaf13b2b91eb654b1dc2b674f7ec61 OP_EQUALVERIFY OP_CHECKSIG
}
开发者ID:jimmysong,项目名称:btcd,代码行数:34,代码来源:example_test.go
示例2: 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(params *chaincfg.Params, coinbaseScript []byte, nextBlockHeight int32, 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 = txscript.PayToAddrScript(addr)
if err != nil {
return nil, err
}
} else {
var err error
scriptBuilder := txscript.NewScriptBuilder()
pkScript, err = scriptBuilder.AddOp(txscript.OP_TRUE).Script()
if err != nil {
return nil, err
}
}
tx := wire.NewMsgTx(wire.TxVersion)
tx.AddTxIn(&wire.TxIn{
// Coinbase transactions have no inputs, so previous outpoint is
// zero hash and max index.
PreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},
wire.MaxPrevOutIndex),
SignatureScript: coinbaseScript,
Sequence: wire.MaxTxInSequenceNum,
})
tx.AddTxOut(&wire.TxOut{
Value: blockchain.CalcBlockSubsidy(nextBlockHeight, params),
PkScript: pkScript,
})
return btcutil.NewTx(tx), nil
}
开发者ID:jongillham,项目名称:btcd,代码行数:41,代码来源:mining.go
示例3: TstCreateSeriesCredits
// TstCreateSeriesCredits creates a new credit for every item in the amounts
// slice, locked to the given series' address with branch==1 and index==0.
func TstCreateSeriesCredits(t *testing.T, pool *Pool, seriesID uint32, amounts []int64) []credit {
addr := TstNewWithdrawalAddress(t, pool, seriesID, Branch(1), Index(0))
pkScript, err := txscript.PayToAddrScript(addr.addr)
if err != nil {
t.Fatal(err)
}
msgTx := createMsgTx(pkScript, amounts)
txHash := msgTx.TxHash()
credits := make([]credit, len(amounts))
for i := range msgTx.TxOut {
c := wtxmgr.Credit{
OutPoint: wire.OutPoint{
Hash: txHash,
Index: uint32(i),
},
BlockMeta: wtxmgr.BlockMeta{
Block: wtxmgr.Block{Height: TstInputsBlock},
},
Amount: btcutil.Amount(msgTx.TxOut[i].Value),
PkScript: msgTx.TxOut[i].PkScript,
}
credits[i] = newCredit(c, *addr)
}
return credits
}
开发者ID:justusranvier,项目名称:btcwallet,代码行数:27,代码来源:factory_test.go
示例4: makeDestinationScriptSource
// makeDestinationScriptSource creates a ChangeSource which is used to receive
// all correlated previous input value. A non-change address is created by this
// function.
func makeDestinationScriptSource(rpcClient *btcrpcclient.Client, accountName string) txauthor.ChangeSource {
return func() ([]byte, error) {
destinationAddress, err := rpcClient.GetNewAddress(accountName)
if err != nil {
return nil, err
}
return txscript.PayToAddrScript(destinationAddress)
}
}
开发者ID:justusranvier,项目名称:btcwallet,代码行数:12,代码来源:main.go
示例5: createTxOut
// createTxOut generates a TxOut that can be added to a transaction.
func createTxOut(outCoins uint64, addr btcutil.Address) *wire.TxOut {
// Take the address and generate a PubKeyScript out of it
script, err := txscript.PayToAddrScript(addr)
if err != nil {
log.Fatal(err)
}
txout := wire.NewTxOut(int64(outCoins), script)
return txout
}
开发者ID:skycoin,项目名称:skycoin-exchange,代码行数:10,代码来源:transaction.go
示例6: createTxOut
// createTxOut generates a TxOut that can be added to a transaction.
func createTxOut(inCoin int64, addr btcutil.Address) *wire.TxOut {
// Pay the minimum network fee so that nodes will broadcast the tx.
outCoin := inCoin - TX_FEE
// Take the address and generate a PubKeyScript out of it
script, err := txscript.PayToAddrScript(addr)
if err != nil {
log.Fatal(err)
}
txout := wire.NewTxOut(outCoin, script)
return txout
}
开发者ID:2014mchidamb,项目名称:ps1,代码行数:12,代码来源:spend.go
示例7: TestFakeTxs
func TestFakeTxs(t *testing.T) {
// First we need a wallet.
w, err := keystore.NewStore("banana wallet", "", []byte("banana"),
wire.MainNet, &keystore.BlockStamp{}, 100)
if err != nil {
t.Errorf("Can not create encrypted wallet: %s", err)
return
}
a := &Wallet{
Wallet: w,
lockedOutpoints: map[wire.OutPoint]struct{}{},
}
w.Unlock([]byte("banana"))
// Create and add a fake Utxo so we have some funds to spend.
//
// This will pass validation because txcscript is unaware of invalid
// tx inputs, however, this example would fail in btcd.
utxo := &tx.Utxo{}
addr, err := w.NextChainedAddress(&keystore.BlockStamp{}, 100)
if err != nil {
t.Errorf("Cannot get next address: %s", err)
return
}
copy(utxo.AddrHash[:], addr.ScriptAddress())
ophash := (wire.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 := wire.NewOutPoint(&ophash, 0)
utxo.Out = tx.OutPoint(*out)
ss, err := txscript.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:D-bank,项目名称:btcwallet,代码行数:54,代码来源:createtx_test_disabled.go
示例8: TstCreatePkScript
func TstCreatePkScript(t *testing.T, p *Pool, seriesID uint32, branch Branch, idx Index) []byte {
script := TstEnsureUsedAddr(t, p, seriesID, branch, idx)
addr, err := p.addressFor(script)
if err != nil {
t.Fatal(err)
}
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
t.Fatal(err)
}
return pkScript
}
开发者ID:justusranvier,项目名称:btcwallet,代码行数:12,代码来源:factory_test.go
示例9: addChange
// addChange adds a new output with the given amount and address, and
// randomizes the index (and returns it) of the newly added output.
func addChange(msgtx *wire.MsgTx, change btcutil.Amount, changeAddr btcutil.Address) (int, error) {
pkScript, err := txscript.PayToAddrScript(changeAddr)
if err != nil {
return 0, fmt.Errorf("cannot create txout script: %s", err)
}
msgtx.AddTxOut(wire.NewTxOut(int64(change), pkScript))
// Randomize index of the change output.
rng := badrand.New(badrand.NewSource(time.Now().UnixNano()))
r := rng.Int31n(int32(len(msgtx.TxOut))) // random index
c := len(msgtx.TxOut) - 1 // change index
msgtx.TxOut[r], msgtx.TxOut[c] = msgtx.TxOut[c], msgtx.TxOut[r]
return int(r), nil
}
开发者ID:D-bank,项目名称:btcwallet,代码行数:16,代码来源:createtx.go
示例10: finalizeCurrentTx
// finalizeCurrentTx finalizes the transaction in w.current, moves it to the
// list of finalized transactions and replaces w.current with a new empty
// transaction.
func (w *withdrawal) finalizeCurrentTx() error {
log.Debug("Finalizing current transaction")
tx := w.current
if len(tx.outputs) == 0 {
log.Debug("Current transaction has no outputs, doing nothing")
return nil
}
pkScript, err := txscript.PayToAddrScript(w.status.nextChangeAddr.addr)
if err != nil {
return newError(ErrWithdrawalProcessing, "failed to generate pkScript for change address", err)
}
if tx.addChange(pkScript) {
var err error
w.status.nextChangeAddr, err = nextChangeAddress(w.status.nextChangeAddr)
if err != nil {
return newError(ErrWithdrawalProcessing, "failed to get next change address", err)
}
}
ntxid := tx.ntxid()
for i, txOut := range tx.outputs {
outputStatus := w.status.outputs[txOut.request.outBailmentID()]
outputStatus.addOutpoint(
OutBailmentOutpoint{ntxid: ntxid, index: uint32(i), amount: txOut.amount})
}
// Check that WithdrawalOutput entries with status==success have the sum of
// their outpoint amounts matching the requested amount.
for _, txOut := range tx.outputs {
// Look up the original request we received because txOut.request may
// represent a split request and thus have a different amount from the
// original one.
outputStatus := w.status.outputs[txOut.request.outBailmentID()]
origRequest := outputStatus.request
amtFulfilled := btcutil.Amount(0)
for _, outpoint := range outputStatus.outpoints {
amtFulfilled += outpoint.amount
}
if outputStatus.status == statusSuccess && amtFulfilled != origRequest.Amount {
msg := fmt.Sprintf("%s was not completely fulfilled; only %v fulfilled", origRequest,
amtFulfilled)
return newError(ErrWithdrawalProcessing, msg, nil)
}
}
w.transactions = append(w.transactions, tx)
w.current = newWithdrawalTx(w.txOptions)
return nil
}
开发者ID:justusranvier,项目名称:btcwallet,代码行数:53,代码来源:withdrawal.go
示例11: TestSignMultiSigUTXOPkScriptNotP2SH
func TestSignMultiSigUTXOPkScriptNotP2SH(t *testing.T) {
tearDown, pool, _ := TstCreatePoolAndTxStore(t)
defer tearDown()
mgr := pool.Manager()
tx := createWithdrawalTx(t, pool, []int64{4e6}, []int64{})
addr, _ := btcutil.DecodeAddress("1MirQ9bwyQcGVJPwKUgapu5ouK2E2Ey4gX", mgr.ChainParams())
pubKeyHashPkScript, _ := txscript.PayToAddrScript(addr.(*btcutil.AddressPubKeyHash))
msgtx := tx.toMsgTx()
err := signMultiSigUTXO(mgr, msgtx, 0, pubKeyHashPkScript, []RawSig{RawSig{}})
TstCheckError(t, "", err, ErrTxSigning)
}
开发者ID:D-bank,项目名称:btcwallet,代码行数:14,代码来源:withdrawal_wb_test.go
示例12: TstNewOutputRequest
func TstNewOutputRequest(t *testing.T, transaction uint32, address string, amount btcutil.Amount,
net *chaincfg.Params) OutputRequest {
addr, err := btcutil.DecodeAddress(address, net)
if err != nil {
t.Fatalf("Unable to decode address %s", address)
}
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
t.Fatalf("Unable to generate pkScript for %v", addr)
}
return OutputRequest{
PkScript: pkScript,
Address: addr,
Amount: amount,
Server: "server",
Transaction: transaction,
}
}
开发者ID:justusranvier,项目名称:btcwallet,代码行数:18,代码来源:factory_test.go
示例13: createTxOut
// createTxOut generates a TxOut that can be added to a transaction.
func createTxOut(inCoin int64, addr btcutil.Address) *wire.TxOut {
// Pay the minimum network fee so that nodes will broadcast the tx.
outCoin := *amount
if outCoin == 0 {
log.Fatal("You probably don't want to transfer 0 satoshis")
}
if outCoin > inCoin-TX_FEE {
log.Fatal("Can't complete transaction--the request amount" +
" is larger than available funds after transaction fee")
}
// Take the address and generate a PubKeyScript out of it
script, err := txscript.PayToAddrScript(addr)
if err != nil {
log.Fatal(err)
}
txout := wire.NewTxOut(outCoin, script)
return txout
}
开发者ID:lgessler,项目名称:cs4501-001-ps1,代码行数:19,代码来源:spend.go
示例14: SignThis
func (t *TxStore) SignThis(tx *wire.MsgTx) error {
fmt.Printf("-= SignThis =-\n")
// sort tx before signing.
txsort.InPlaceSort(tx)
sigs := make([][]byte, len(tx.TxIn))
// first iterate over each input
for j, in := range tx.TxIn {
for k := uint32(0); k < uint32(len(t.Adrs)); k++ {
child, err := t.rootPrivKey.Child(k + hdkeychain.HardenedKeyStart)
if err != nil {
return err
}
myadr, err := child.Address(t.Param)
if err != nil {
return err
}
adrScript, err := txscript.PayToAddrScript(myadr)
if err != nil {
return err
}
if bytes.Equal(adrScript, in.SignatureScript) {
fmt.Printf("Hit; key %d matches input %d. Signing.\n", k, j)
priv, err := child.ECPrivKey()
if err != nil {
return err
}
sigs[j], err = txscript.SignatureScript(
tx, j, in.SignatureScript, txscript.SigHashAll, priv, true)
if err != nil {
return err
}
break
}
}
}
for i, s := range sigs {
if s != nil {
tx.TxIn[i].SignatureScript = s
}
}
return nil
}
开发者ID:conseweb,项目名称:lnd,代码行数:44,代码来源:sortsignsend.go
示例15: newBobNode
// newBobNode generates a test "ln node" to interact with Alice (us). For the
// funding transaction, bob has a single output totaling 7BTC. For our basic
// test, he'll fund the channel with 5BTC, leaving 2BTC to the change output.
// TODO(roasbeef): proper handling of change etc.
func newBobNode() (*bobNode, error) {
// First, parse Bob's priv key in order to obtain a key he'll use for the
// multi-sig funding transaction.
privKey, pubKey := btcec.PrivKeyFromBytes(btcec.S256(), bobsPrivKey)
// Next, generate an output redeemable by bob.
bobAddr, err := btcutil.NewAddressPubKey(privKey.PubKey().SerializeCompressed(),
ActiveNetParams)
if err != nil {
return nil, err
}
bobAddrScript, err := txscript.PayToAddrScript(bobAddr.AddressPubKeyHash())
if err != nil {
return nil, err
}
prevOut := wire.NewOutPoint(&wire.ShaHash{}, ^uint32(0))
// TODO(roasbeef): When the chain rpc is hooked in, assert bob's output
// actually exists and it unspent in the chain.
bobTxIn := wire.NewTxIn(prevOut, nil)
// Using bobs priv key above, create a change address he can spend.
bobChangeOutput := wire.NewTxOut(2*1e8, bobAddrScript)
// Bob's initial revocation hash is just his private key with the first
// byte changed...
var revocation [20]byte
copy(revocation[:], bobsPrivKey)
revocation[0] = 0xff
// His ID is just as creative...
var id [wire.HashSize]byte
id[0] = 0xff
return &bobNode{
id: id,
privKey: privKey,
channelKey: pubKey,
deliveryAddress: bobAddr,
revocation: revocation,
delay: 5,
availableOutputs: []*wire.TxIn{bobTxIn},
changeOutputs: []*wire.TxOut{bobChangeOutput},
}, nil
}
开发者ID:martindale,项目名称:lnd,代码行数:48,代码来源:wallet_test.go
示例16: TestSignMultiSigUTXORedeemScriptNotFound
func TestSignMultiSigUTXORedeemScriptNotFound(t *testing.T) {
tearDown, pool, _ := TstCreatePoolAndTxStore(t)
defer tearDown()
mgr := pool.Manager()
tx := createWithdrawalTx(t, pool, []int64{4e6}, []int64{})
// This is a P2SH address for which the addr manager doesn't have the redeem
// script.
addr, _ := btcutil.DecodeAddress("3Hb4xcebcKg4DiETJfwjh8sF4uDw9rqtVC", mgr.ChainParams())
if _, err := mgr.Address(addr); err == nil {
t.Fatalf("Address %s found in manager when it shouldn't", addr)
}
msgtx := tx.toMsgTx()
pkScript, _ := txscript.PayToAddrScript(addr.(*btcutil.AddressScriptHash))
err := signMultiSigUTXO(mgr, msgtx, 0, pkScript, []RawSig{RawSig{}})
TstCheckError(t, "", err, ErrTxSigning)
}
开发者ID:D-bank,项目名称:btcwallet,代码行数:19,代码来源:withdrawal_wb_test.go
示例17: createTxRemainder
func createTxRemainder(inCoin int64) *wire.TxOut {
remainder := inCoin - *amount - TX_FEE
// Put the remainder back in our wallet
pkBytes, err := hex.DecodeString(*privkey)
if err != nil {
log.Fatal(err)
}
// Get pubkey object
_, pubkey := btcec.PrivKeyFromBytes(btcec.S256(), pkBytes)
// Get an address object from WIF string
changeAddress := generateAddr(pubkey)
script, err := txscript.PayToAddrScript(changeAddress)
if err != nil {
log.Fatal(err)
}
remtx := wire.NewTxOut(remainder, script)
return remtx
}
开发者ID:lgessler,项目名称:cs4501-001-ps1,代码行数:21,代码来源:spend.go
示例18: addOutputs
// addOutputs adds the given address/amount pairs as outputs to msgtx,
// returning their total amount.
func addOutputs(msgtx *wire.MsgTx, pairs map[string]btcutil.Amount, chainParams *chaincfg.Params) (btcutil.Amount, error) {
var minAmount btcutil.Amount
for addrStr, amt := range pairs {
if amt <= 0 {
return minAmount, ErrNonPositiveAmount
}
minAmount += amt
addr, err := btcutil.DecodeAddress(addrStr, chainParams)
if err != nil {
return minAmount, fmt.Errorf("cannot decode address: %s", err)
}
// Add output to spend amt to addr.
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
return minAmount, fmt.Errorf("cannot create txout script: %s", err)
}
txout := wire.NewTxOut(int64(amt), pkScript)
msgtx.AddTxOut(txout)
}
return minAmount, nil
}
开发者ID:D-bank,项目名称:btcwallet,代码行数:24,代码来源:createtx.go
示例19: testMemWalletLockedOutputs
func testMemWalletLockedOutputs(r *Harness, t *testing.T) {
// Obtain the initial balance of the wallet at this point.
startingBalance := r.ConfirmedBalance()
// First, create a signed transaction spending some outputs.
addr, err := r.NewAddress()
if err != nil {
t.Fatalf("unable to generate new address: %v", err)
}
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
t.Fatalf("unable to create script: %v", err)
}
outputAmt := btcutil.Amount(50 * btcutil.SatoshiPerBitcoin)
output := wire.NewTxOut(int64(outputAmt), pkScript)
tx, err := r.CreateTransaction([]*wire.TxOut{output}, 10)
if err != nil {
t.Fatalf("unable to create transaction: %v", err)
}
// The current wallet balance should now be at least 50 BTC less
// (accounting for fees) than the period balance
currentBalance := r.ConfirmedBalance()
if !(currentBalance <= startingBalance-outputAmt) {
t.Fatalf("spent outputs not locked: previous balance %v, "+
"current balance %v", startingBalance, currentBalance)
}
// Now unlocked all the spent inputs within the unbroadcast signed
// transaction. The current balance should now be exactly that of the
// starting balance.
r.UnlockOutputs(tx.TxIn)
currentBalance = r.ConfirmedBalance()
if currentBalance != startingBalance {
t.Fatalf("current and starting balance should now match: "+
"expected %v, got %v", startingBalance, currentBalance)
}
}
开发者ID:jongillham,项目名称:btcd,代码行数:38,代码来源:rpc_harness_test.go
示例20: createCoinbaseTx
// createCoinbaseTx returns a coinbase transaction paying an appropriate
// subsidy based on the passed block height to the provided address.
func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int32,
addr btcutil.Address, net *chaincfg.Params) (*btcutil.Tx, error) {
// Create the script to pay to the provided payment address.
pkScript, err := txscript.PayToAddrScript(addr)
if err != nil {
return nil, err
}
tx := wire.NewMsgTx()
tx.AddTxIn(&wire.TxIn{
// Coinbase transactions have no inputs, so previous outpoint is
// zero hash and max index.
PreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},
wire.MaxPrevOutIndex),
SignatureScript: coinbaseScript,
Sequence: wire.MaxTxInSequenceNum,
})
tx.AddTxOut(&wire.TxOut{
Value: blockchain.CalcBlockSubsidy(nextBlockHeight, net),
PkScript: pkScript,
})
return btcutil.NewTx(tx), nil
}
开发者ID:skycoin,项目名称:skycoin-exchange,代码行数:26,代码来源:blockgen.go
注:本文中的github.com/btcsuite/btcd/txscript.PayToAddrScript函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论