本文整理匯總了Golang中github.com/btcsuite/btcd/txscript.ExtractPkScriptAddrs函數的典型用法代碼示例。如果您正苦於以下問題:Golang ExtractPkScriptAddrs函數的具體用法?Golang ExtractPkScriptAddrs怎麽用?Golang ExtractPkScriptAddrs使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了ExtractPkScriptAddrs函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: indexUnconfirmedAddresses
// indexUnconfirmedAddresses modifies the unconfirmed (memory-only) address
// index to include mappings for the addresses encoded by the passed public key
// script to the transaction.
//
// This function is safe for concurrent access.
func (idx *AddrIndex) indexUnconfirmedAddresses(pkScript []byte, tx *btcutil.Tx) {
// The error is ignored here since the only reason it can fail is if the
// script fails to parse and it was already validated before being
// admitted to the mempool.
_, addresses, _, _ := txscript.ExtractPkScriptAddrs(pkScript,
idx.chainParams)
for _, addr := range addresses {
// Ignore unsupported address types.
addrKey, err := addrToKey(addr)
if err != nil {
continue
}
// Add a mapping from the address to the transaction.
idx.unconfirmedLock.Lock()
addrIndexEntry := idx.txnsByAddr[addrKey]
if addrIndexEntry == nil {
addrIndexEntry = make(map[chainhash.Hash]*btcutil.Tx)
idx.txnsByAddr[addrKey] = addrIndexEntry
}
addrIndexEntry[*tx.Hash()] = tx
// Add a mapping from the transaction to the address.
addrsByTxEntry := idx.addrsByTx[*tx.Hash()]
if addrsByTxEntry == nil {
addrsByTxEntry = make(map[[addrKeySize]byte]struct{})
idx.addrsByTx[*tx.Hash()] = addrsByTxEntry
}
addrsByTxEntry[addrKey] = struct{}{}
idx.unconfirmedLock.Unlock()
}
}
示例2: getActor
// getActor returns the actor to which this vout belongs to
func (com *Communication) getActor(actors []*Actor,
vout *wire.TxOut) (*Actor, error) {
// get addrs which own this utxo
_, addrs, _, err := txscript.ExtractPkScriptAddrs(vout.PkScript,
&chaincfg.SimNetParams)
if err != nil {
return nil, err
}
// we're expecting only 1 addr since we created a standard p2pkh tx
addr := addrs[0].String()
// find which actor this addr belongs to
// TODO: could probably be optimized by creating
// a global addr -> actor index rather than looking
// up each actor addrs
for _, actor := range actors {
for _, actorAddr := range actor.ownedAddresses {
if addr == actorAddr.String() {
return actor, nil
}
}
}
err = errors.New("cannot find any actor who owns this tx output")
return nil, err
}
示例3: lookupInputAccount
func lookupInputAccount(w *Wallet, details *wtxmgr.TxDetails, deb wtxmgr.DebitRecord) uint32 {
// TODO: Debits should record which account(s?) they
// debit from so this doesn't need to be looked up.
prevOP := &details.MsgTx.TxIn[deb.Index].PreviousOutPoint
prev, err := w.TxStore.TxDetails(&prevOP.Hash)
if err != nil {
log.Errorf("Cannot query previous transaction details for %v: %v", prevOP.Hash, err)
return 0
}
if prev == nil {
log.Errorf("Missing previous transaction %v", prevOP.Hash)
return 0
}
prevOut := prev.MsgTx.TxOut[prevOP.Index]
_, addrs, _, err := txscript.ExtractPkScriptAddrs(prevOut.PkScript, w.chainParams)
var inputAcct uint32
if err == nil && len(addrs) > 0 {
inputAcct, err = w.Manager.AddrAccount(addrs[0])
}
if err != nil {
log.Errorf("Cannot fetch account for previous output %v: %v", prevOP, err)
inputAcct = 0
}
return inputAcct
}
示例4: indexPkScript
// indexPkScript extracts all standard addresses from the passed public key
// script and maps each of them to the associated transaction using the passed
// map.
func (idx *AddrIndex) indexPkScript(data writeIndexData, pkScript []byte, txIdx int) {
// Nothing to index if the script is non-standard or otherwise doesn't
// contain any addresses.
_, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript,
idx.chainParams)
if err != nil || len(addrs) == 0 {
return
}
for _, addr := range addrs {
addrKey, err := addrToKey(addr)
if err != nil {
// Ignore unsupported address types.
continue
}
// Avoid inserting the transaction more than once. Since the
// transactions are indexed serially any duplicates will be
// indexed in a row, so checking the most recent entry for the
// address is enough to detect duplicates.
indexedTxns := data[addrKey]
numTxns := len(indexedTxns)
if numTxns > 0 && indexedTxns[numTxns-1] == txIdx {
continue
}
indexedTxns = append(indexedTxns, txIdx)
data[addrKey] = indexedTxns
}
}
示例5: ExampleExtractPkScriptAddrs
// This example demonstrates extracting information from a standard public key
// script.
func ExampleExtractPkScriptAddrs() {
// Start with a standard pay-to-pubkey-hash script.
scriptHex := "76a914128004ff2fcaf13b2b91eb654b1dc2b674f7ec6188ac"
script, err := hex.DecodeString(scriptHex)
if err != nil {
fmt.Println(err)
return
}
// Extract and print details from the script.
scriptClass, addresses, reqSigs, err := txscript.ExtractPkScriptAddrs(
script, &chaincfg.MainNetParams)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Script Class:", scriptClass)
fmt.Println("Addresses:", addresses)
fmt.Println("Required Signatures:", reqSigs)
// Output:
// Script Class: pubkeyhash
// Addresses: [12gpXQVcCL2qhTNQgyLVdCFG2Qs2px98nV]
// Required Signatures: 1
}
示例6: signMultiSigUTXO
// signMultiSigUTXO signs the P2SH UTXO with the given index by constructing a
// script containing all given signatures plus the redeem (multi-sig) script. The
// redeem script is obtained by looking up the address of the given P2SH pkScript
// on the address manager.
// The order of the signatures must match that of the public keys in the multi-sig
// script as OP_CHECKMULTISIG expects that.
// This function must be called with the manager unlocked.
func signMultiSigUTXO(mgr *waddrmgr.Manager, tx *wire.MsgTx, idx int, pkScript []byte, sigs []RawSig) error {
class, addresses, _, err := txscript.ExtractPkScriptAddrs(pkScript, mgr.ChainParams())
if err != nil {
return newError(ErrTxSigning, "unparseable pkScript", err)
}
if class != txscript.ScriptHashTy {
return newError(ErrTxSigning, fmt.Sprintf("pkScript is not P2SH: %s", class), nil)
}
redeemScript, err := getRedeemScript(mgr, addresses[0].(*btcutil.AddressScriptHash))
if err != nil {
return newError(ErrTxSigning, "unable to retrieve redeem script", err)
}
class, _, nRequired, err := txscript.ExtractPkScriptAddrs(redeemScript, mgr.ChainParams())
if err != nil {
return newError(ErrTxSigning, "unparseable redeem script", err)
}
if class != txscript.MultiSigTy {
return newError(ErrTxSigning, fmt.Sprintf("redeem script is not multi-sig: %v", class), nil)
}
if len(sigs) < nRequired {
errStr := fmt.Sprintf("not enough signatures; need %d but got only %d", nRequired,
len(sigs))
return newError(ErrTxSigning, errStr, nil)
}
// Construct the unlocking script.
// Start with an OP_0 because of the bug in bitcoind, then add nRequired signatures.
unlockingScript := txscript.NewScriptBuilder().AddOp(txscript.OP_FALSE)
for _, sig := range sigs[:nRequired] {
unlockingScript.AddData(sig)
}
// Combine the redeem script and the unlocking script to get the actual signature script.
sigScript := unlockingScript.AddData(redeemScript)
script, err := sigScript.Script()
if err != nil {
return newError(ErrTxSigning, "error building sigscript", err)
}
tx.TxIn[idx].SignatureScript = script
if err := validateSigScript(tx, idx, pkScript); err != nil {
return err
}
return nil
}
示例7: get_tx_info
//this is a debug func
func get_tx_info(tx *wire.MsgTx, block_index uint64) (source,
destination string, btc_amount, fee uint64, data []string) {
var bFound bool = false
for _, value := range tx.TxOut {
nettype := &chaincfg.MainNetParams
if conf.MainNet {
nettype = &chaincfg.MainNetParams
} else {
nettype = &chaincfg.RegressionNetParams
}
_, Address, _, _ := txscript.ExtractPkScriptAddrs(value.PkScript, nettype)
if len(Address) != 0 {
if Address[0].String() == conf.WISHINGWALLADDRESS {
bFound = true
continue
}
}
if bFound == true {
tempasm, _ := txscript.DisasmString(value.PkScript)
message := strings.Split(tempasm, " ")
merge := message[1] + message[2]
data = append(data, merge)
}
}
if bFound == true {
destination = conf.WISHINGWALLADDRESS
} else {
var temp []string
return "", "", 0, 0, temp
}
//get source address
if tx.TxIn[0].PreviousOutPoint.Index == 0 {
source = string(block_index)
} else {
SourceTx, _ := bitcoinchain.GetRawTransaction(tx.TxIn[0].PreviousOutPoint.Hash.String())
if SourceTx == nil {
source = "Unkonw"
} else {
for _, prevalue := range SourceTx.Vout {
if prevalue.N == tx.TxIn[0].PreviousOutPoint.Index {
source = prevalue.ScriptPubKey.Addresses[0]
}
}
}
}
return source, destination, 0, 0, data
}
示例8: findEligibleOutputs
func (w *Wallet) findEligibleOutputs(account uint32, minconf int32, bs *waddrmgr.BlockStamp) ([]wtxmgr.Credit, error) {
unspent, err := w.TxStore.UnspentOutputs()
if err != nil {
return nil, err
}
// TODO: Eventually all of these filters (except perhaps output locking)
// should be handled by the call to UnspentOutputs (or similar).
// Because one of these filters requires matching the output script to
// the desired account, this change depends on making wtxmgr a waddrmgr
// dependancy and requesting unspent outputs for a single account.
eligible := make([]wtxmgr.Credit, 0, len(unspent))
for i := range unspent {
output := &unspent[i]
// Only include this output if it meets the required number of
// confirmations. Coinbase transactions must have have reached
// maturity before their outputs may be spent.
if !confirmed(minconf, output.Height, bs.Height) {
continue
}
if output.FromCoinBase {
const target = blockchain.CoinbaseMaturity
if !confirmed(target, output.Height, bs.Height) {
continue
}
}
// Locked unspent outputs are skipped.
if w.LockedOutpoint(output.OutPoint) {
continue
}
// 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).
class, addrs, _, err := txscript.ExtractPkScriptAddrs(
output.PkScript, w.chainParams)
if err != nil || class != txscript.PubKeyHashTy {
continue
}
// Only include the output if it is associated with the passed
// account. There should only be one address since this is a
// P2PKH script.
addrAcct, err := w.Manager.AddrAccount(addrs[0])
if err != nil || addrAcct != account {
continue
}
eligible = append(eligible, *output)
}
return eligible, nil
}
示例9: NewOutputRecord
func NewOutputRecord(txout *wire.TxOut) *OutputRecord {
class, addrs, sigs, _ := txscript.ExtractPkScriptAddrs(txout.PkScript,
&chaincfg.MainNetParams)
record := &OutputRecord{
value: txout.Value,
class: uint8(class),
sigs: uint8(sigs),
addrs: addrs,
}
return record
}
示例10: removeScriptFromAddrIndex
// removeScriptFromAddrIndex dissociates the address encoded by the
// passed pkScript from the passed tx in our address based tx index.
//
// This function MUST be called with the mempool lock held (for writes).
func (mp *txMemPool) removeScriptFromAddrIndex(pkScript []byte, tx *btcutil.Tx) error {
_, addresses, _, err := txscript.ExtractPkScriptAddrs(pkScript,
activeNetParams.Params)
if err != nil {
txmpLog.Errorf("Unable to extract encoded addresses from script "+
"for addrindex (addrindex): %v", err)
return err
}
for _, addr := range addresses {
delete(mp.addrindex[addr.EncodeAddress()], *tx.Sha())
}
return nil
}
示例11: lookupOutputChain
func lookupOutputChain(w *Wallet, details *wtxmgr.TxDetails, cred wtxmgr.CreditRecord) (account uint32, internal bool) {
output := details.MsgTx.TxOut[cred.Index]
_, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript, w.chainParams)
var ma waddrmgr.ManagedAddress
if err == nil && len(addrs) > 0 {
ma, err = w.Manager.Address(addrs[0])
}
if err != nil {
log.Errorf("Cannot fetch account for wallet output: %v", err)
} else {
account = ma.Account()
internal = ma.Internal()
}
return
}
示例12: indexScriptAddressToTx
// indexScriptByAddress alters our address index by indexing the payment address
// encoded by the passed scriptPubKey to the passed transaction.
//
// This function MUST be called with the mempool lock held (for writes).
func (mp *txMemPool) indexScriptAddressToTx(pkScript []byte, tx *btcutil.Tx) error {
_, addresses, _, err := txscript.ExtractPkScriptAddrs(pkScript,
activeNetParams.Params)
if err != nil {
txmpLog.Errorf("Unable to extract encoded addresses from script "+
"for addrindex: %v", err)
return err
}
for _, addr := range addresses {
if mp.addrindex[addr.EncodeAddress()] == nil {
mp.addrindex[addr.EncodeAddress()] = make(map[wire.ShaHash]struct{})
}
mp.addrindex[addr.EncodeAddress()][*tx.Sha()] = struct{}{}
}
return nil
}
示例13: ListAddressTransactions
// ListAddressTransactions returns a slice of objects with details about
// recorded transactions to or from any address belonging to a set. This is
// intended to be used for listaddresstransactions RPC replies.
func (w *Wallet) ListAddressTransactions(pkHashes map[string]struct{}) (
[]btcjson.ListTransactionsResult, error) {
txList := []btcjson.ListTransactionsResult{}
// Get current block. The block height used for calculating
// the number of tx confirmations.
syncBlock := w.Manager.SyncedTo()
err := w.TxStore.RangeTransactions(0, -1, func(details []wtxmgr.TxDetails) (bool, error) {
loopDetails:
for i := range details {
detail := &details[i]
for _, cred := range detail.Credits {
pkScript := detail.MsgTx.TxOut[cred.Index].PkScript
_, addrs, _, err := txscript.ExtractPkScriptAddrs(
pkScript, w.chainParams)
if err != nil || len(addrs) != 1 {
continue
}
apkh, ok := addrs[0].(*btcutil.AddressPubKeyHash)
if !ok {
continue
}
_, ok = pkHashes[string(apkh.ScriptAddress())]
if !ok {
continue
}
jsonResults := ListTransactions(detail,
syncBlock.Height, w.chainParams)
if err != nil {
return false, err
}
txList = append(txList, jsonResults...)
continue loopDetails
}
}
return false, nil
})
return txList, err
}
示例14: signMsgTx
// signMsgTx sets the SignatureScript for every item in msgtx.TxIn.
// It must be called every time a msgtx is changed.
// Only P2PKH outputs are supported at this point.
func signMsgTx(msgtx *wire.MsgTx, prevOutputs []wtxmgr.Credit, mgr *waddrmgr.Manager, chainParams *chaincfg.Params) error {
if len(prevOutputs) != len(msgtx.TxIn) {
return fmt.Errorf(
"Number of prevOutputs (%d) does not match number of tx inputs (%d)",
len(prevOutputs), len(msgtx.TxIn))
}
for i, output := range prevOutputs {
// Errors don't matter here, as we only consider the
// case where len(addrs) == 1.
_, addrs, _, _ := txscript.ExtractPkScriptAddrs(output.PkScript,
chainParams)
if len(addrs) != 1 {
continue
}
apkh, ok := addrs[0].(*btcutil.AddressPubKeyHash)
if !ok {
return ErrUnsupportedTransactionType
}
ai, err := mgr.Address(apkh)
if err != nil {
return fmt.Errorf("cannot get address info: %v", err)
}
pka := ai.(waddrmgr.ManagedPubKeyAddress)
privkey, err := pka.PrivKey()
if err != nil {
return fmt.Errorf("cannot get private key: %v", err)
}
sigscript, err := txscript.SignatureScript(msgtx, i,
output.PkScript, txscript.SigHashAll, privkey,
ai.Compressed())
if err != nil {
return fmt.Errorf("cannot create sigscript: %s", err)
}
msgtx.TxIn[i].SignatureScript = sigscript
}
return nil
}
示例15: addTestTx
// addTestTx adds an output spendable by our test wallet, marked as included in
// 'block'.
func addTestTx(w *LightningWallet, rec *wtxmgr.TxRecord, block *wtxmgr.BlockMeta) error {
err := w.TxStore.InsertTx(rec, block)
if err != nil {
return err
}
// Check every output to determine whether it is controlled by a wallet
// key. If so, mark the output as a credit.
for i, output := range rec.MsgTx.TxOut {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(output.PkScript,
ActiveNetParams)
if err != nil {
// Non-standard outputs are skipped.
continue
}
for _, addr := range addrs {
ma, err := w.Manager.Address(addr)
if err == nil {
err = w.TxStore.AddCredit(rec, block, uint32(i),
ma.Internal())
if err != nil {
return err
}
err = w.Manager.MarkUsed(addr)
if err != nil {
return err
}
continue
}
// Missing addresses are skipped. Other errors should
// be propagated.
if !waddrmgr.IsError(err, waddrmgr.ErrAddressNotFound) {
return err
}
}
}
return nil
}