本文整理汇总了Golang中github.com/btcsuite/btcutil.DecodeAddress函数的典型用法代码示例。如果您正苦于以下问题:Golang DecodeAddress函数的具体用法?Golang DecodeAddress怎么用?Golang DecodeAddress使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了DecodeAddress函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
flag.Parse()
// Connect to local btcd RPC server
btcdHomeDir := btcutil.AppDataDir("btcd", false)
certs, err := ioutil.ReadFile(filepath.Join(btcdHomeDir, "rpc.cert"))
if err != nil {
log.Fatal(err)
}
connCfg := &btcrpcclient.ConnConfig{
Host: *host,
Endpoint: *protocol,
User: *user,
Pass: *pass,
Certificates: certs,
}
client, err := btcrpcclient.New(connCfg, nil)
if err != nil {
log.Fatal(err)
}
addr, err := btcutil.DecodeAddress("1JZJaDDC44DCKLnezDsbW43Zf8LspCKBYP", nil)
if err != nil {
log.Fatal(err)
}
log.Println(btcinterned.LookupAddress(client, addr, btcinterned.SixMonths))
}
示例2: CheckAddress
func CheckAddress(address string) bool {
_, err := btcutil.DecodeAddress(address, &FloParams)
if err != nil {
return false
}
return true
}
示例3: getArgs
// getArgs parses command line args and asserts that a private key and an
// address are present and correctly formatted.
func getArgs() requiredArgs {
flag.Parse()
if *a == "" || *k == "" || *t == "" || *v == -1 {
fmt.Println("\nThis tool generates a bitcoin transaction that moves coins from an input to an output.\n" +
"You must provide a key, an address, a transaction id (the hash\n" +
"of a tx) and the index into the outputs of that tx that fund your\n" +
"address! Use http://blockchain.info/pushtx to send the raw transaction.\n")
flag.PrintDefaults()
fmt.Println("")
os.Exit(0)
}
pkBytes, err := hex.DecodeString(*k)
if err != nil {
log.Fatal(err)
}
privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), pkBytes)
addr, err := btcutil.DecodeAddress(*a, &btcnet.MainNetParams)
if err != nil {
log.Fatal(err)
}
txid, err := btcwire.NewShaHashFromStr(*t)
args := requiredArgs{
txid: txid,
vout: uint32(*v),
toAddress: addr,
privKey: privKey,
}
return args
}
示例4: 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
}
示例5: NewTransaction
// NewTransaction create transaction,
// utxos is an interface which need to be a slice type, and each item
// of the slice is an UtxoWithPrivkey interface.
// outAddrs is the output address array.
// using the api of blockchain.info to get the raw trasaction info of txid.
func NewTransaction(utxos interface{}, outAddrs []TxOut) (*Transaction, error) {
s := reflect.ValueOf(utxos)
if s.Kind() != reflect.Slice {
return nil, errors.New("error utxo type")
}
ret := make([]interface{}, s.Len())
for i := 0; i < s.Len(); i++ {
ret[i] = s.Index(i).Interface()
}
tx := wire.NewMsgTx()
oldTxOuts := make([]*wire.TxOut, len(ret))
for i, r := range ret {
utxo := r.(UtxoWithkey)
txid, err := chainhash.NewHashFromStr(utxo.GetTxid())
if err != nil {
return nil, err
}
rawFundingTx, err := lookupTxid(txid)
if err != nil {
return nil, err
}
oldTxOut, outpoint, err := getFundingParams(rawFundingTx, utxo.GetVout())
if err != nil {
return nil, err
}
oldTxOuts[i] = oldTxOut
txin := createTxIn(outpoint)
tx.AddTxIn(txin)
}
if len(outAddrs) > 2 {
return nil, errors.New("out address more than 2")
}
for _, out := range outAddrs {
addr, err := btcutil.DecodeAddress(out.Addr, &chaincfg.MainNetParams)
if err != nil {
return nil, fmt.Errorf("decode address %s, faild, %s", out.Addr, err)
}
txout := createTxOut(out.Value, addr)
tx.AddTxOut(txout)
}
// sign the transaction
for i, r := range ret {
utxo := r.(UtxoWithkey)
sig, err := signRawTx(&Transaction{*tx}, i, utxo.GetPrivKey(), oldTxOuts[i].PkScript)
if err != nil {
return nil, err
}
tx.TxIn[i].SignatureScript = sig
}
return &Transaction{*tx}, nil
}
示例6: newLnAddr
// newLnAddr...
func newLnAddr(encodedAddr string) (*lnAddr, error) {
// The format of an lnaddr is "<pubkey or pkh>@host"
idHost := strings.Split(encodedAddr, "@")
if len(idHost) != 2 {
return nil, fmt.Errorf("invalid format for lnaddr string: %v", encodedAddr)
}
// Attempt to resolve the IP address, this handles parsing IPv6 zones,
// and such.
fmt.Println("host: ", idHost[1])
ipAddr, err := net.ResolveTCPAddr("tcp", idHost[1])
if err != nil {
return nil, err
}
addr := &lnAddr{netAddr: ipAddr}
idLen := len(idHost[0])
switch {
// Is the ID a hex-encoded compressed public key?
case idLen > 65 && idLen < 69:
pubkeyBytes, err := hex.DecodeString(idHost[0])
if err != nil {
return nil, err
}
addr.pubKey, err = btcec.ParsePubKey(pubkeyBytes, btcec.S256())
if err != nil {
return nil, err
}
// got pubey, populate address from pubkey
pkh := btcutil.Hash160(addr.pubKey.SerializeCompressed())
addr.bitcoinAddr, err = btcutil.NewAddressPubKeyHash(pkh,
&chaincfg.TestNet3Params)
if err != nil {
return nil, err
}
// Is the ID a string encoded bitcoin address?
case idLen > 33 && idLen < 37:
addr.bitcoinAddr, err = btcutil.DecodeAddress(idHost[0],
&chaincfg.TestNet3Params)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("invalid address %s", idHost[0])
}
// Finally, populate the lnid from the address.
copy(addr.lnId[:], addr.bitcoinAddr.ScriptAddress())
return addr, nil
}
示例7: CreateRawTx
// CreateRawTx create bitcoin raw transaction.
func (btc Bitcoin) CreateRawTx(txIns []coin.TxIn, txOuts interface{}) (string, error) {
tx := wire.NewMsgTx()
oldTxOuts := make([]*wire.TxOut, len(txIns))
for i, in := range txIns {
txid, err := chainhash.NewHashFromStr(in.Txid)
// txid, err := chainhash.NewShaHashFromStr(in.Txid)
if err != nil {
return "", err
}
rawFundingTx, err := lookupTxid(txid)
if err != nil {
return "", err
}
oldTxOut, outpoint, err := getFundingParams(rawFundingTx, in.Vout)
if err != nil {
return "", err
}
oldTxOuts[i] = oldTxOut
txin := createTxIn(outpoint)
tx.AddTxIn(txin)
}
s := reflect.ValueOf(txOuts)
if s.Kind() != reflect.Slice {
return "", errors.New("error tx out type")
}
outs := make([]interface{}, s.Len())
for i := 0; i < s.Len(); i++ {
outs[i] = s.Index(i).Interface()
}
if len(outs) > 2 {
return "", errors.New("out address more than 2")
}
for _, o := range outs {
out := o.(TxOut)
addr, err := btcutil.DecodeAddress(out.Addr, &chaincfg.MainNetParams)
if err != nil {
return "", err
}
txout := createTxOut(out.Value, addr)
tx.AddTxOut(txout)
}
t := Transaction{*tx}
d, err := t.Serialize()
if err != nil {
return "", err
}
return hex.EncodeToString(d), nil
}
示例8: 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)
}
示例9: 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,
}
}
示例10: Send
// Send sends coins.
func Send(args []string) error {
if SCon.RBytes == 0 {
return fmt.Errorf("Can't send, spv connection broken")
}
// get all utxos from the database
allUtxos, err := SCon.TS.GetAllUtxos()
if err != nil {
return err
}
var score int64 // score is the sum of all utxo amounts. highest score wins.
// add all the utxos up to get the score
for _, u := range allUtxos {
score += u.Value
}
// score is 0, cannot unlock 'send coins' acheivement
if score == 0 {
return fmt.Errorf("You don't have money. Work hard.")
}
// need args, fail
if len(args) < 2 {
return fmt.Errorf("need args: ssend amount(satoshis) address")
}
amt, err := strconv.ParseInt(args[0], 10, 64)
if err != nil {
return err
}
if amt < 1000 {
return fmt.Errorf("can't send %d, too small", amt)
}
adr, err := btcutil.DecodeAddress(args[1], SCon.TS.Param)
if err != nil {
fmt.Printf("error parsing %s as address\t", args[1])
return err
}
fmt.Printf("send %d to address: %s \n",
amt, adr.String())
err = SendCoins(SCon, adr, amt)
if err != nil {
return err
}
return nil
}
示例11: 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)
}
示例12: getArgs
// getArgs parses command line args and asserts that a private key and an
// address are present and correctly formatted.
func getArgs() requiredArgs {
flag.Parse()
if *toaddress == "" || *privkey == "" || *txid == "" || *vout == -1 || *amount == -1 {
fmt.Println("\nThis program generates a bitcoin trans action that moves coins from an input to an output.\n" +
"You must provide a key, a receiving address, a transaction id (the hash\n" +
"of a tx), the amount to be transferred (in satoshis), and the index into\n" +
"the outputs of that tx that fund your address. Use http://blockchain.info/pushtx\n" +
"to send the raw transaction.\n")
flag.PrintDefaults()
fmt.Println("")
os.Exit(0)
}
pkBytes, err := hex.DecodeString(*privkey)
if err != nil {
log.Fatal(err)
}
// PrivKeyFromBytes returns public key as a separate result, but can ignore it here.
key, _ := btcec.PrivKeyFromBytes(btcec.S256(), pkBytes)
addr, err := btcutil.DecodeAddress(*toaddress, &chaincfg.MainNetParams)
if err != nil {
log.Fatal(err)
}
txid, err := wire.NewShaHashFromStr(*txid)
if err != nil {
log.Fatal(err)
}
args := requiredArgs{
txid: txid,
vout: uint32(*vout),
toAddress: addr,
privKey: key,
amount: int64(*amount),
}
return args
}
示例13: sendOpReturn
func sendOpReturn(addr string, totalAmount float64, msg []byte) {
if len(msg) > MAX_BYTES {
logger.Crit("message oversize")
os.Exit(0)
}
btcAddr, err := btcutil.DecodeAddress(addr, &chaincfg.MainNetParams)
if err != nil {
logger.Crit("can't decode address")
os.Exit(0)
}
logger.Info("finding avaible inputs")
inputs, err := selectInputs(totalAmount + FEE)
if err != nil {
logger.Crit(err.Error())
return
}
change := inputs.total - totalAmount - FEE
rawtx := createTx(inputs, btcAddr, totalAmount, change, msg)
if sendTx {
signedTx, complete, err := client.SignRawTransaction(rawtx)
if err != nil || !complete {
logger.Crit(fmt.Sprintf("could not sign the tx: %s", err.Error()))
os.Exit(0)
} else {
var rawtx bytes.Buffer
signedTx.Serialize(&rawtx)
decodedTx, _ := client.DecodeRawTransaction(rawtx.Bytes())
logger.Info(spew.Sdump(decodedTx))
askForConfirmation("Are you going to send the tx? ")
txHash, err := client.SendRawTransaction(signedTx, false)
if err != nil {
logger.Crit("could not send the tx")
os.Exit(0)
} else {
logger.Info(fmt.Sprintf("tx sent: %s", txHash.String()))
}
}
}
}
示例14: 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
}
示例15: loadConfig
//.........这里部分代码省略.........
"options may not be activated at the same time",
funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// --addrindex and --dropaddrindex do not mix.
if cfg.AddrIndex && cfg.DropAddrIndex {
err := fmt.Errorf("%s: the --addrindex and --dropaddrindex "+
"options may not be activated at the same time",
funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// --addrindex and --droptxindex do not mix.
if cfg.AddrIndex && cfg.DropTxIndex {
err := fmt.Errorf("%s: the --addrindex and --droptxindex "+
"options may not be activated at the same time "+
"because the address index relies on the transaction "+
"index",
funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Check getwork keys are valid and saved parsed versions.
cfg.miningAddrs = make([]btcutil.Address, 0, len(cfg.GetWorkKeys)+
len(cfg.MiningAddrs))
for _, strAddr := range cfg.GetWorkKeys {
addr, err := btcutil.DecodeAddress(strAddr,
activeNetParams.Params)
if err != nil {
str := "%s: getworkkey '%s' failed to decode: %v"
err := fmt.Errorf(str, funcName, strAddr, err)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
if !addr.IsForNet(activeNetParams.Params) {
str := "%s: getworkkey '%s' is on the wrong network"
err := fmt.Errorf(str, funcName, strAddr)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
cfg.miningAddrs = append(cfg.miningAddrs, addr)
}
// Check mining addresses are valid and saved parsed versions.
for _, strAddr := range cfg.MiningAddrs {
addr, err := btcutil.DecodeAddress(strAddr, activeNetParams.Params)
if err != nil {
str := "%s: mining address '%s' failed to decode: %v"
err := fmt.Errorf(str, funcName, strAddr, err)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
if !addr.IsForNet(activeNetParams.Params) {
str := "%s: mining address '%s' is on the wrong network"
err := fmt.Errorf(str, funcName, strAddr)
fmt.Fprintln(os.Stderr, err)