decred.org/dcrwallet/v3@v3.1.0/internal/cfgutil/address.go (about)

     1  // Copyright (c) 2015-2016 The btcsuite developers
     2  // Copyright (c) 2016 The Decred developers
     3  // Use of this source code is governed by an ISC
     4  // license that can be found in the LICENSE file.
     5  
     6  package cfgutil
     7  
     8  import (
     9  	"decred.org/dcrwallet/v3/errors"
    10  	"github.com/decred/dcrd/txscript/v4/stdaddr"
    11  )
    12  
    13  // AddressFlag contains a stdaddr.Address and implements the flags.Marshaler and
    14  // Unmarshaler interfaces so it can be used as a config struct field.
    15  type AddressFlag struct {
    16  	str string
    17  }
    18  
    19  // NewAddressFlag creates an AddressFlag with a default stdaddr.Address.
    20  func NewAddressFlag() *AddressFlag {
    21  	return new(AddressFlag)
    22  }
    23  
    24  // MarshalFlag satisfies the flags.Marshaler interface.
    25  func (a *AddressFlag) MarshalFlag() (string, error) {
    26  	return a.str, nil
    27  }
    28  
    29  // UnmarshalFlag satisfies the flags.Unmarshaler interface.
    30  func (a *AddressFlag) UnmarshalFlag(addr string) error {
    31  	a.str = addr
    32  	return nil
    33  }
    34  
    35  // Address decodes the address flag for the network described by params.
    36  // If the flag is the empty string, this returns a nil address.
    37  func (a *AddressFlag) Address(params stdaddr.AddressParams) (stdaddr.Address, error) {
    38  	if a.str == "" {
    39  		return nil, nil
    40  	}
    41  	return stdaddr.DecodeAddress(a.str, params)
    42  }
    43  
    44  // StakeAddress decodes the address flag for the network described by
    45  // params as a stake address.
    46  // If the flag is the empty string, this returns a nil address.
    47  func (a *AddressFlag) StakeAddress(params stdaddr.AddressParams) (stdaddr.StakeAddress, error) {
    48  	addr, err := a.Address(params)
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  	if addr == nil {
    53  		return nil, nil
    54  	}
    55  	if saddr, ok := addr.(stdaddr.StakeAddress); ok {
    56  		return saddr, nil
    57  	}
    58  	return nil, errors.Errorf("address is not suitable for stake usage")
    59  }