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

Golang btcutil.DecodeAddress函数代码示例

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

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



在下文中一共展示了DecodeAddress函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
}
开发者ID:d4l3k,项目名称:btcinterned,代码行数:26,代码来源:main.go


示例2: CheckAddress

func CheckAddress(address string) bool {
	_, err := btcutil.DecodeAddress(address, &FloParams)
	if err != nil {
		return false
	}
	return true
}
开发者ID:dloa,项目名称:media-protocol,代码行数:7,代码来源:util.go


示例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
}
开发者ID:JoeyWeate,项目名称:Cryptocurrecny,代码行数:36,代码来源:spend.go


示例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
}
开发者ID:jimmysong,项目名称:btcd,代码行数:34,代码来源:example_test.go


示例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
}
开发者ID:skycoin,项目名称:skycoin-exchange,代码行数:62,代码来源:transaction.go


示例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
}
开发者ID:martindale,项目名称:lnd,代码行数:55,代码来源:peer.go


示例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
}
开发者ID:skycoin,项目名称:skycoin-exchange,代码行数:55,代码来源:gateway.go


示例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)
}
开发者ID:D-bank,项目名称:btcwallet,代码行数:14,代码来源:withdrawal_wb_test.go


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


示例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
}
开发者ID:conseweb,项目名称:lnd,代码行数:44,代码来源:shell.go


示例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)
}
开发者ID:D-bank,项目名称:btcwallet,代码行数:19,代码来源:withdrawal_wb_test.go


示例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
}
开发者ID:lgessler,项目名称:cs4501-001-ps1,代码行数:43,代码来源:spend.go


示例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()))
			}
		}
	}
}
开发者ID:libreoscar,项目名称:btcwatch,代码行数:41,代码来源:main.go


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


示例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)
开发者ID:wallclockbuilder,项目名称:btcd,代码行数:67,代码来源:config.go


示例16: Decode

// Decode...
func (o *OpenChannel) Decode(b io.Reader, addrManager *waddrmgr.Manager) error {
	var scratch [8]byte

	if _, err := b.Read(o.TheirLNID[:]); err != nil {
		return err
	}
	if _, err := b.Read(o.ChanID[:]); err != nil {
		return err
	}

	if _, err := b.Read(scratch[:]); err != nil {
		return err
	}
	o.MinFeePerKb = btcutil.Amount(endian.Uint64(scratch[:]))

	// nonce + serPrivKey + mac
	var encryptedPriv [24 + 32 + 16]byte
	if _, err := b.Read(encryptedPriv[:]); err != nil {
		return err
	}
	decryptedPriv, err := addrManager.Decrypt(waddrmgr.CKTPrivate, encryptedPriv[:])
	if err != nil {
		return err
	}
	o.OurCommitKey, _ = btcec.PrivKeyFromBytes(btcec.S256(), decryptedPriv)

	var serPubKey [33]byte
	if _, err := b.Read(serPubKey[:]); err != nil {
		return err
	}
	o.TheirCommitKey, err = btcec.ParsePubKey(serPubKey[:], btcec.S256())
	if err != nil {
		return err
	}

	if _, err := b.Read(scratch[:]); err != nil {
		return err
	}
	o.Capacity = btcutil.Amount(endian.Uint64(scratch[:]))
	if _, err := b.Read(scratch[:]); err != nil {
		return err
	}
	o.OurBalance = btcutil.Amount(endian.Uint64(scratch[:]))
	if _, err := b.Read(scratch[:]); err != nil {
		return err
	}
	o.TheirBalance = btcutil.Amount(endian.Uint64(scratch[:]))

	o.TheirCommitTx = wire.NewMsgTx()
	if err := o.TheirCommitTx.Deserialize(b); err != nil {
		return err
	}
	o.OurCommitTx = wire.NewMsgTx()
	if err := o.OurCommitTx.Deserialize(b); err != nil {
		return err
	}

	o.FundingTx = wire.NewMsgTx()
	if err := o.FundingTx.Deserialize(b); err != nil {
		return err
	}

	if _, err := b.Read(encryptedPriv[:]); err != nil {
		return err
	}
	decryptedPriv, err = addrManager.Decrypt(waddrmgr.CKTPrivate, encryptedPriv[:])
	if err != nil {
		return err
	}
	o.MultiSigKey, _ = btcec.PrivKeyFromBytes(btcec.S256(), decryptedPriv)

	var redeemScript [71]byte
	if _, err := b.Read(redeemScript[:]); err != nil {
		return err
	}
	o.FundingRedeemScript = redeemScript[:]

	if _, err := b.Read(o.TheirCurrentRevocation[:]); err != nil {
		return err
	}

	var addr [34]byte
	if _, err := b.Read(addr[:]); err != nil {
		return err
	}
	o.OurDeliveryAddress, err = btcutil.DecodeAddress(string(addr[:]), ActiveNetParams)
	if err != nil {
		return err
	}

	if _, err := b.Read(addr[:]); err != nil {
		return err
	}
	o.TheirDeliveryAddress, err = btcutil.DecodeAddress(string(addr[:]), ActiveNetParams)
	if err != nil {
		return err
	}

	if err := binary.Read(b, endian, &o.CsvDelay); err != nil {
//.........这里部分代码省略.........
开发者ID:mkl-,项目名称:lnd,代码行数:101,代码来源:channel.go


示例17: Example_startWithdrawal

// This example demonstrates how to use the Pool.StartWithdrawal method.
func Example_startWithdrawal() {
	// Create the address manager and votingpool DB namespace. See the example
	// for the Create() function for more info on how this is done.
	mgr, vpNamespace, tearDownFunc, err := exampleCreateMgrAndDBNamespace()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer tearDownFunc()

	// Create a pool and a series. See the DepositAddress example for more info
	// on how this is done.
	pool, seriesID, err := exampleCreatePoolAndSeries(mgr, vpNamespace)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Unlock the manager
	if err := mgr.Unlock(privPassphrase); err != nil {
		fmt.Println(err)
		return
	}
	defer mgr.Lock()

	addr, _ := btcutil.DecodeAddress("1MirQ9bwyQcGVJPwKUgapu5ouK2E2Ey4gX", mgr.ChainParams())
	pkScript, _ := txscript.PayToAddrScript(addr)
	requests := []votingpool.OutputRequest{
		votingpool.OutputRequest{
			PkScript:    pkScript,
			Address:     addr,
			Amount:      1e6,
			Server:      "server-id",
			Transaction: 123},
	}
	changeStart, err := pool.ChangeAddress(seriesID, votingpool.Index(0))
	if err != nil {
		fmt.Println(err)
		return
	}
	// This is only needed because we have not used any deposit addresses from
	// the series, and we cannot create a WithdrawalAddress for an unused
	// branch/idx pair.
	if err = pool.EnsureUsedAddr(seriesID, votingpool.Branch(1), votingpool.Index(0)); err != nil {
		fmt.Println(err)
		return
	}
	startAddr, err := pool.WithdrawalAddress(seriesID, votingpool.Branch(1), votingpool.Index(0))
	if err != nil {
		fmt.Println(err)
		return
	}
	lastSeriesID := seriesID
	dustThreshold := btcutil.Amount(1e4)
	currentBlock := int32(19432)
	roundID := uint32(0)
	txstore, tearDownFunc, err := exampleCreateTxStore()
	if err != nil {
		fmt.Println(err)
		return
	}
	_, err = pool.StartWithdrawal(
		roundID, requests, *startAddr, lastSeriesID, *changeStart, txstore, currentBlock,
		dustThreshold)
	if err != nil {
		fmt.Println(err)
	}

	// Output:
	//
}
开发者ID:D-bank,项目名称:btcwallet,代码行数:72,代码来源:example_test.go


示例18: TestLimitAndSkipFetchTxsForAddr

func TestLimitAndSkipFetchTxsForAddr(t *testing.T) {
	testDb, err := setUpTestDb(t, "tstdbtxaddr")
	if err != nil {
		t.Errorf("Failed to open test database %v", err)
		return
	}
	defer testDb.cleanUpFunc()

	// Insert a block with some fake test transactions. The block will have
	// 10 copies of a fake transaction involving same address.
	addrString := "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"
	targetAddr, err := btcutil.DecodeAddress(addrString, &chaincfg.MainNetParams)
	if err != nil {
		t.Fatalf("Unable to decode test address: %v", err)
	}
	outputScript, err := txscript.PayToAddrScript(targetAddr)
	if err != nil {
		t.Fatalf("Unable make test pkScript %v", err)
	}
	fakeTxOut := wire.NewTxOut(10, outputScript)
	var emptyHash wire.ShaHash
	fakeHeader := wire.NewBlockHeader(&emptyHash, &emptyHash, 1, 1)
	msgBlock := wire.NewMsgBlock(fakeHeader)
	for i := 0; i < 10; i++ {
		mtx := wire.NewMsgTx()
		mtx.AddTxOut(fakeTxOut)
		msgBlock.AddTransaction(mtx)
	}

	// Insert the test block into the DB.
	testBlock := btcutil.NewBlock(msgBlock)
	newheight, err := testDb.db.InsertBlock(testBlock)
	if err != nil {
		t.Fatalf("Unable to insert block into db: %v", err)
	}

	// Create and insert an address index for out test addr.
	txLoc, _ := testBlock.TxLoc()
	index := make(database.BlockAddrIndex)
	for i := range testBlock.Transactions() {
		var hash160 [ripemd160.Size]byte
		scriptAddr := targetAddr.ScriptAddress()
		copy(hash160[:], scriptAddr[:])
		index[hash160] = append(index[hash160], &txLoc[i])
	}
	blkSha := testBlock.Sha()
	err = testDb.db.UpdateAddrIndexForBlock(blkSha, newheight, index)
	if err != nil {
		t.Fatalf("UpdateAddrIndexForBlock: failed to index"+
			" addrs for block #%d (%s) "+
			"err %v", newheight, blkSha, err)
		return
	}

	// Try skipping the first 4 results, should get 6 in return.
	txReply, err := testDb.db.FetchTxsForAddr(targetAddr, 4, 100000)
	if err != nil {
		t.Fatalf("Unable to fetch transactions for address: %v", err)
	}
	if len(txReply) != 6 {
		t.Fatalf("Did not correctly skip forward in txs for address reply"+
			" got %v txs, expected %v", len(txReply), 6)
	}

	// Limit the number of results to 3.
	txReply, err = testDb.db.FetchTxsForAddr(targetAddr, 0, 3)
	if err != nil {
		t.Fatalf("Unable to fetch transactions for address: %v", err)
	}
	if len(txReply) != 3 {
		t.Fatalf("Did not correctly limit in txs for address reply"+
			" got %v txs, expected %v", len(txReply), 3)
	}

	// Skip 1, limit 5.
	txReply, err = testDb.db.FetchTxsForAddr(targetAddr, 1, 5)
	if err != nil {
		t.Fatalf("Unable to fetch transactions for address: %v", err)
	}
	if len(txReply) != 5 {
		t.Fatalf("Did not correctly limit in txs for address reply"+
			" got %v txs, expected %v", len(txReply), 5)
	}
}
开发者ID:Cleawing,项目名称:btcd,代码行数:84,代码来源:operational_test.go


示例19: TestAddresses


//.........这里部分代码省略.........
		{
			name: "testnet p2pk hybrid (0x07)",
			addr: "07b0bd634234abbb1ba1e986e884185c61cf43e001f9137f23c2c409273eb16e6" +
				"537a576782eba668a7ef8bd3b3cfb1edb7117ab65129b8a2e681f3c1e0908ef7b",
			encoded: "muUnepk5nPPrxUTuTAhRqrpAQuSWS5fVii",
			valid:   true,
			result: btcutil.TstAddressPubKey(
				[]byte{
					0x07, 0xb0, 0xbd, 0x63, 0x42, 0x34, 0xab, 0xbb, 0x1b, 0xa1,
					0xe9, 0x86, 0xe8, 0x84, 0x18, 0x5c, 0x61, 0xcf, 0x43, 0xe0,
					0x01, 0xf9, 0x13, 0x7f, 0x23, 0xc2, 0xc4, 0x09, 0x27, 0x3e,
					0xb1, 0x6e, 0x65, 0x37, 0xa5, 0x76, 0x78, 0x2e, 0xba, 0x66,
					0x8a, 0x7e, 0xf8, 0xbd, 0x3b, 0x3c, 0xfb, 0x1e, 0xdb, 0x71,
					0x17, 0xab, 0x65, 0x12, 0x9b, 0x8a, 0x2e, 0x68, 0x1f, 0x3c,
					0x1e, 0x09, 0x08, 0xef, 0x7b},
				btcutil.PKFHybrid, chaincfg.TestNet3Params.PubKeyHashAddrID),
			f: func() (btcutil.Address, error) {
				serializedPubKey := []byte{
					0x07, 0xb0, 0xbd, 0x63, 0x42, 0x34, 0xab, 0xbb, 0x1b, 0xa1,
					0xe9, 0x86, 0xe8, 0x84, 0x18, 0x5c, 0x61, 0xcf, 0x43, 0xe0,
					0x01, 0xf9, 0x13, 0x7f, 0x23, 0xc2, 0xc4, 0x09, 0x27, 0x3e,
					0xb1, 0x6e, 0x65, 0x37, 0xa5, 0x76, 0x78, 0x2e, 0xba, 0x66,
					0x8a, 0x7e, 0xf8, 0xbd, 0x3b, 0x3c, 0xfb, 0x1e, 0xdb, 0x71,
					0x17, 0xab, 0x65, 0x12, 0x9b, 0x8a, 0x2e, 0x68, 0x1f, 0x3c,
					0x1e, 0x09, 0x08, 0xef, 0x7b}
				return btcutil.NewAddressPubKey(serializedPubKey, &chaincfg.TestNet3Params)
			},
			net: &chaincfg.TestNet3Params,
		},
	}

	for _, test := range tests {
		// Decode addr and compare error against valid.
		decoded, err := btcutil.DecodeAddress(test.addr, test.net)
		if (err == nil) != test.valid {
			t.Errorf("%v: decoding test failed: %v", test.name, err)
			return
		}

		if err == nil {
			// Ensure the stringer returns the same address as the
			// original.
			if decodedStringer, ok := decoded.(fmt.Stringer); ok {
				if test.addr != decodedStringer.String() {
					t.Errorf("%v: String on decoded value does not match expected value: %v != %v",
						test.name, test.addr, decodedStringer.String())
					return
				}
			}

			// Encode again and compare against the original.
			encoded := decoded.EncodeAddress()
			if test.encoded != encoded {
				t.Errorf("%v: decoding and encoding produced different addressess: %v != %v",
					test.name, test.encoded, encoded)
				return
			}

			// Perform type-specific calculations.
			var saddr []byte
			switch d := decoded.(type) {
			case *btcutil.AddressPubKeyHash:
				saddr = btcutil.TstAddressSAddr(encoded)

			case *btcutil.AddressScriptHash:
				saddr = btcutil.TstAddressSAddr(encoded)
开发者ID:btcsuite,项目名称:btcutil,代码行数:67,代码来源:address_test.go


示例20: deserializeWithdrawal

// deserializeWithdrawal deserializes the given byte slice into a dbWithdrawalRow,
// converts it into an withdrawalInfo and returns it. This function must run
// with the address manager unlocked.
func deserializeWithdrawal(p *Pool, serialized []byte) (*withdrawalInfo, error) {
	var row dbWithdrawalRow
	if err := gob.NewDecoder(bytes.NewReader(serialized)).Decode(&row); err != nil {
		return nil, newError(ErrWithdrawalStorage, "cannot deserialize withdrawal information",
			err)
	}
	wInfo := &withdrawalInfo{
		lastSeriesID:  row.LastSeriesID,
		dustThreshold: row.DustThreshold,
	}
	chainParams := p.Manager().ChainParams()
	wInfo.requests = make([]OutputRequest, len(row.Requests))
	// A map of requests indexed by OutBailmentID; needed to populate
	// WithdrawalStatus.Outputs later on.
	requestsByOID := make(map[OutBailmentID]OutputRequest)
	for i, req := range row.Requests {
		addr, err := btcutil.DecodeAddress(req.Addr, chainParams)
		if err != nil {
			return nil, newError(ErrWithdrawalStorage,
				"cannot deserialize addr for requested output", err)
		}
		pkScript, err := txscript.PayToAddrScript(addr)
		if err != nil {
			return nil, newError(ErrWithdrawalStorage, "invalid addr for requested output", err)
		}
		request := OutputRequest{
			Address:     addr,
			Amount:      req.Amount,
			PkScript:    pkScript,
			Server:      req.Server,
			Transaction: req.Transaction,
		}
		wInfo.requests[i] = request
		requestsByOID[request.outBailmentID()] = request
	}
	startAddr := row.StartAddress
	wAddr, err := p.WithdrawalAddress(startAddr.SeriesID, startAddr.Branch, startAddr.Index)
	if err != nil {
		return nil, newError(ErrWithdrawalStorage, "cannot deserialize startAddress", err)
	}
	wInfo.startAddress = *wAddr

	cAddr, err := p.ChangeAddress(row.ChangeStart.SeriesID, row.ChangeStart.Index)
	if err != nil {
		return nil, newError(ErrWithdrawalStorage, "cannot deserialize changeStart", err)
	}
	wInfo.changeStart = *cAddr

	// TODO: Copy over row.Status.nextInputAddr. Not done because StartWithdrawal
	// does not update that yet.
	nextChangeAddr := row.Status.NextChangeAddr
	cAddr, err = p.ChangeAddress(nextChangeAddr.SeriesID, nextChangeAddr.Index)
	if err != nil {
		return nil, newError(ErrWithdrawalStorage,
			"cannot deserialize nextChangeAddress for withdrawal", err)
	}
	wInfo.status = WithdrawalStatus{
		nextChangeAddr: *cAddr,
		fees:           row.Status.Fees,
		outputs:        make(map[OutBailmentID]*WithdrawalOutput, len(row.Status.Outputs)),
		sigs:           row.Status.Sigs,
		transactions:   make(map[Ntxid]changeAwareTx, len(row.Status.Transactions)),
	}
	for oid, output := range row.Status.Outputs {
		outpoints := make([]OutBailmentOutpoint, len(output.Outpoints))
		for i, outpoint := range output.Outpoints {
			outpoints[i] = OutBailmentOutpoint{
				ntxid:  outpoint.Ntxid,
				index:  outpoint.Index,
				amount: outpoint.Amount,
			}
		}
		wInfo.status.outputs[oid] = &WithdrawalOutput{
			request:   requestsByOID[output.OutBailmentID],
			status:    output.Status,
			outpoints: outpoints,
		}
	}
	for ntxid, tx := range row.Status.Transactions {
		var msgtx wire.MsgTx
		if err := msgtx.Deserialize(bytes.NewBuffer(tx.SerializedMsgTx)); err != nil {
			return nil, newError(ErrWithdrawalStorage, "cannot deserialize transaction", err)
		}
		wInfo.status.transactions[ntxid] = changeAwareTx{
			MsgTx:     &msgtx,
			changeIdx: tx.ChangeIdx,
		}
	}
	return wInfo, nil
}
开发者ID:justusranvier,项目名称:btcwallet,代码行数:93,代码来源:db.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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