Exemplo n.º 1
0
func main() {
	fmt.Println("Creating random rpc config for btcd")
	t := template.Must(template.New("rpcOptions").Parse(autoRpcTemplate))

	randRpcOptions := basicRpcOptions{
		Username: randBase64string(*numRandBytes),
		Password: randBase64string(*numRandBytes),
	}

	var autoAuth bytes.Buffer
	if err := t.Execute(&autoAuth, randRpcOptions); err != nil {
		log.Fatalf("unable to generate random auth: %v")
	}

	btcdHomeDir := btcutil.AppDataDir("btcd", false)
	btcctlHomeDir := btcutil.AppDataDir("btcctl", false)
	btcdConfigPath := fmt.Sprintf("%s/btcd.conf", btcdHomeDir)
	btcctlConfigPath := fmt.Sprintf("%s/btcctl.conf", btcctlHomeDir)

	if err := ioutil.WriteFile(btcdConfigPath, autoAuth.Bytes(), 0644); err != nil {
		log.Fatalf("unable to write config for btcd: %v", err)
	}

	if err := ioutil.WriteFile(btcctlConfigPath, autoAuth.Bytes(), 0644); err != nil {
		log.Fatalf("unable to write config for btcctl: %v", err)
	}
	fmt.Println("fin.")
}
Exemplo n.º 2
0
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))
}
Exemplo n.º 3
0
func NewClient() (*btcrpcclient.Client, error) {
	var cerr error
	launchOnce.Do(func() {
		defer launchWG.Done()
		password := randString(40)
		go launchProc("btcd", "--testnet", "-u", RPCUser, "-P", password)
		go launchProc("btcwallet", "-u", RPCUser, "-P", password)

		time.Sleep(2 * time.Second)

		btcdHomeDir := btcutil.AppDataDir("btcd", false)
		certs, err := ioutil.ReadFile(filepath.Join(btcdHomeDir, "rpc.cert"))
		if err != nil {
			cerr = err
			return
		}
		connCfg := &btcrpcclient.ConnConfig{
			Host:         "localhost:18334",
			Endpoint:     "ws",
			User:         RPCUser,
			Pass:         password,
			Certificates: certs,
		}
		_ = connCfg
		client, err = btcrpcclient.New(connCfg, nil) // handlers)
		if err != nil {
			cerr = err
			return
		}
	})
	launchWG.Wait()
	return client, cerr
}
Exemplo n.º 4
0
func main() {
	// Only override the handlers for notifications you care about.
	// Also note most of these handlers will only be called if you register
	// for notifications.  See the documentation of the btcrpcclient
	// NotificationHandlers type for more details about each handler.
	ntfnHandlers := btcrpcclient.NotificationHandlers{
		OnBlockConnected: func(hash *wire.ShaHash, height int32, time time.Time) {
			log.Printf("Block connected: %v (%d) %v", hash, height, time)
		},
		OnBlockDisconnected: func(hash *wire.ShaHash, height int32, time time.Time) {
			log.Printf("Block disconnected: %v (%d) %v", hash, height, time)
		},
	}

	// Connect to local btcd RPC server using websockets.
	btcdHomeDir := btcutil.AppDataDir("btcd", false)
	certs, err := ioutil.ReadFile(filepath.Join(btcdHomeDir, "rpc.cert"))
	if err != nil {
		log.Fatal(err)
	}
	connCfg := &btcrpcclient.ConnConfig{
		Host:         "localhost:8334",
		Endpoint:     "ws",
		User:         "******",
		Pass:         "******",
		Certificates: certs,
	}
	client, err := btcrpcclient.New(connCfg, &ntfnHandlers)
	if err != nil {
		log.Fatal(err)
	}

	// Register for block connect and disconnect notifications.
	if err := client.NotifyBlocks(); err != nil {
		log.Fatal(err)
	}
	log.Println("NotifyBlocks: Registration Complete")

	// Get the current block count.
	blockCount, err := client.GetBlockCount()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Block count: %d", blockCount)

	// For this example gracefully shutdown the client after 10 seconds.
	// Ordinarily when to shutdown the client is highly application
	// specific.
	log.Println("Client shutdown in 10 seconds...")
	time.AfterFunc(time.Second*10, func() {
		log.Println("Client shutting down...")
		client.Shutdown()
		log.Println("Client shutdown complete.")
	})

	// Wait until the client either shuts down gracefully (or the user
	// terminates the process with Ctrl+C).
	client.WaitForShutdown()
}
Exemplo n.º 5
0
Arquivo: btcdconf.go Projeto: mkl-/lnd
func GetBtcdConfig() (cfg config, err error) {
	btcdHomeDir := btcutil.AppDataDir("btcd", false)
	defaultConfigFile := filepath.Join(btcdHomeDir, "btcd.conf")
	cfg = config{
		ConfigFile: defaultConfigFile,
	}
	parser := flags.NewParser(&cfg, flags.Default)
	err = flags.NewIniParser(parser).ParseFile(cfg.ConfigFile)
	return
}
Exemplo n.º 6
0
func main() {
	// Only override the handlers for notifications you care about.
	// Also note most of the handlers will only be called if you register
	// for notifications.  See the documentation of the btcrpcclient
	// NotificationHandlers type for more details about each handler.
	ntfnHandlers := btcrpcclient.NotificationHandlers{
		OnAccountBalance: func(account string, balance btcutil.Amount, confirmed bool) {
			log.Printf("New balance for account %s: %v", account,
				balance)
		},
	}

	// Connect to local btcwallet RPC server using websockets.
	certHomeDir := btcutil.AppDataDir("btcwallet", false)
	certs, err := ioutil.ReadFile(filepath.Join(certHomeDir, "rpc.cert"))
	if err != nil {
		log.Fatal(err)
	}
	connCfg := &btcrpcclient.ConnConfig{
		Host:         "localhost:18332",
		Endpoint:     "ws",
		User:         "******",
		Pass:         "******",
		Certificates: certs,
	}
	client, err := btcrpcclient.New(connCfg, &ntfnHandlers)
	if err != nil {
		log.Fatal(err)
	}

	// Get the list of unspent transaction outputs (utxos) that the
	// connected wallet has at least one private key for.
	unspent, err := client.ListUnspent()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Num unspent outputs (utxos): %d", len(unspent))
	if len(unspent) > 0 {
		log.Printf("First utxo:\n%v", spew.Sdump(unspent[0]))
	}

	// For this example gracefully shutdown the client after 10 seconds.
	// Ordinarily when to shutdown the client is highly application
	// specific.
	log.Println("Client shutdown in 10 seconds...")
	time.AfterFunc(time.Second*10, func() {
		log.Println("Client shutting down...")
		client.Shutdown()
		log.Println("Client shutdown complete.")
	})

	// Wait until the client either shuts down gracefully (or the user
	// terminates the process with Ctrl+C).
	client.WaitForShutdown()
}
Exemplo n.º 7
0
// cleanAndExpandPath expands environement variables and leading ~ in the
// passed path, cleans the result, and returns it.
func cleanAndExpandPath(path string) string {
	// Expand initial ~ to OS specific home directory.
	if strings.HasPrefix(path, "~") {
		appHomeDir := btcutil.AppDataDir("gencerts", false)
		homeDir := filepath.Dir(appHomeDir)
		path = strings.Replace(path, "~", homeDir, 1)
	}

	// NOTE: The os.ExpandEnv doesn't work with Windows-style %VARIABLE%,
	// but they variables can still be expanded via POSIX-style $VARIABLE.
	return filepath.Clean(os.ExpandEnv(path))
}
Exemplo n.º 8
0
	"github.com/btcsuite/btcd/database"
	_ "github.com/btcsuite/btcd/database/ldb"
	"github.com/btcsuite/btcd/wire"
	"github.com/btcsuite/btcutil"
	flags "github.com/btcsuite/go-flags"
)

const (
	minCandidates        = 1
	maxCandidates        = 20
	defaultNumCandidates = 5
	defaultDbType        = "leveldb"
)

var (
	btcdHomeDir     = btcutil.AppDataDir("btcd", false)
	defaultDataDir  = filepath.Join(btcdHomeDir, "data")
	knownDbTypes    = database.SupportedDBs()
	activeNetParams = &chaincfg.MainNetParams
)

// config defines the configuration options for findcheckpoint.
//
// See loadConfig for details on the configuration load process.
type config struct {
	DataDir        string `short:"b" long:"datadir" description:"Location of the btcd data directory"`
	DbType         string `long:"dbtype" description:"Database backend to use for the Block Chain"`
	TestNet3       bool   `long:"testnet" description:"Use the test network"`
	RegressionTest bool   `long:"regtest" description:"Use the regression test network"`
	SimNet         bool   `long:"simnet" description:"Use the simulation test network"`
	NumCandidates  int    `short:"n" long:"numcandidates" description:"Max num of checkpoint candidates to show {1-20}"`
Exemplo n.º 9
0
	// defaultPubPassphrase is the default public wallet passphrase which is
	// used when the user indicates they do not want additional protection
	// provided by having all public data in the wallet encrypted by a
	// passphrase only known to them.
	defaultPubPassphrase = "public"

	// maxEmptyAccounts is the number of accounts to scan even if they have no
	// transaction history. This is a deviation from BIP044 to make account
	// creation easier by allowing a limited number of empty accounts.
	maxEmptyAccounts = 100

	walletDbName = "wallet.db"
)

var (
	btcdHomeDir        = btcutil.AppDataDir("btcd", false)
	btcwalletHomeDir   = btcutil.AppDataDir("btcwallet", false)
	btcdHomedirCAFile  = filepath.Join(btcdHomeDir, "rpc.cert")
	defaultConfigFile  = filepath.Join(btcwalletHomeDir, defaultConfigFilename)
	defaultDataDir     = btcwalletHomeDir
	defaultRPCKeyFile  = filepath.Join(btcwalletHomeDir, "rpc.key")
	defaultRPCCertFile = filepath.Join(btcwalletHomeDir, "rpc.cert")
	defaultLogDir      = filepath.Join(btcwalletHomeDir, defaultLogDirname)
)

type config struct {
	ShowVersion      bool     `short:"V" long:"version" description:"Display version information and exit"`
	Create           bool     `long:"create" description:"Create the wallet if it does not exist"`
	CreateTemp       bool     `long:"createtemp" description:"Create a temporary simulation wallet (pass=password) in the data directory indicated; must call with --datadir"`
	CAFile           string   `long:"cafile" description:"File containing root certificates to authenticate a TLS connections with btcd"`
	RPCConnect       string   `short:"c" long:"rpcconnect" description:"Hostname/IP and port of btcd RPC server to connect to (default localhost:18334, mainnet: localhost:8334, simnet: localhost:18556)"`
Exemplo n.º 10
0
// See loadConfig for details on the configuration load process.
type config struct {
	ConfigFile  string   `short:"C" long:"configfile" description:"Path to configuration file"`
	Listeners   []string `long:"listen" description:"Add an interface/port to listen on"`
	RPCCert     string   `short:"c" long:"rpccert" description:"RPC server certificate chain for validation"`
	RPCServer   string   `short:"s" long:"rpcserver" description:"IP and port for rpcserver."`
	RPCUser     string   `short:"u" long:"rpcuser" description:"rpc username."`
	RPCPassword string   `short:"P" long:"rpcpass" description:"rpc password."`
}

const (
	defaultConfigFilename = "blocksafari.conf"
)

var (
	btcdHomeDir        = btcutil.AppDataDir("btcd", false)
	bsHomeDir          = btcutil.AppDataDir("blocksafari", false)
	cfg                *config
	defaultConfigFile  = filepath.Join(bsHomeDir, defaultConfigFilename)
	defaultRPCCertFile = filepath.Join(btcdHomeDir, "rpc.cert")

	pem []byte
)

// loadConfig initializes and parses the config using a config file and command
// line options.
//
// The configuration proceeds as follows:
//      1) Start with a default config with sane settings
//      2) Pre-parse the command line to check for an alternative config file
//      3) Load configuration file overwriting defaults with any specified options
Exemplo n.º 11
0
	"github.com/btcsuite/btcd/btcjson"
	"github.com/btcsuite/btcd/chaincfg/chainhash"
	"github.com/btcsuite/btcd/txscript"
	"github.com/btcsuite/btcd/wire"
	"github.com/btcsuite/btcrpcclient"
	"github.com/btcsuite/btcutil"
	"github.com/btcsuite/btcwallet/internal/cfgutil"
	"github.com/btcsuite/btcwallet/netparams"
	"github.com/btcsuite/btcwallet/wallet/txauthor"
	"github.com/btcsuite/btcwallet/wallet/txrules"
	"github.com/btcsuite/golangcrypto/ssh/terminal"
	"github.com/jessevdk/go-flags"
)

var (
	walletDataDirectory = btcutil.AppDataDir("btcwallet", false)
	newlineBytes        = []byte{'\n'}
)

func fatalf(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, format, args...)
	os.Stderr.Write(newlineBytes)
	os.Exit(1)
}

func errContext(err error, context string) error {
	return fmt.Errorf("%s: %v", context, err)
}

// Flags.
var opts = struct {
Exemplo n.º 12
0
	maxBlockSize = flag.Int("maxblocksize", 999000, "Maximum block size in bytes used by the miner")

	// maxSplit defines the maximum number of pieces to divide a utxo into
	maxSplit = flag.Int("maxsplit", 100, "Maximum number of pieces to divide a utxo into")

	// profile
	profile = flag.String("profile", "6060", "Listen address for profiling server")

	// txCurvePath is the path to a CSV file containing the block, utxo count, tx count
	txCurvePath = flag.String("txcurve", "",
		"Path to the CSV File containing block, utxo count, tx count fields")
)

var (
	// AppDataDir is the path to the working directory set using btcutil.AppDataDir
	AppDataDir = btcutil.AppDataDir("btcsim", false)

	// CertFile is the path to the certificate file of a cert-key pair used for RPC connections
	CertFile = filepath.Join(AppDataDir, "rpc.cert")

	// KeyFile is the path to the key file of a cert-key pair used for RPC connections
	KeyFile = filepath.Join(AppDataDir, "rpc.key")
)

func init() {
	flag.Parse()

	// make sure the app data dir exists
	if !fileExists(AppDataDir) {
		if err := os.Mkdir(AppDataDir, 0700); err != nil {
			log.Fatalf("Cannot create app data dir: %v", err)
Exemplo n.º 13
0
	defaultPowHandler = "parallel"

	defaultMsgExpiry        = time.Hour * 60      // 2.5 days
	defaultBroadcastExpiry  = time.Hour * 48      // 2 days
	defaultPubkeyExpiry     = time.Hour * 24 * 14 // 14 days
	defaultGetpubkeyExpiry  = time.Hour * 24 * 14 // 14 days
	defaultUnknownObjExpiry = time.Hour * 24

	defaultLogConsole = true

	defaultGenKeys = -1
)

var (
	defaultDataDir     = btcutil.AppDataDir("bmagent", false)
	bmdDataDir         = btcutil.AppDataDir("bmd", false)
	bmdHomedirCAFile   = filepath.Join(bmdDataDir, "rpc.cert")
	defaultConfigFile  = filepath.Join(defaultDataDir, defaultConfigFilename)
	defaultTLSKeyFile  = filepath.Join(defaultDataDir, "tls.key")
	defaultTLSCertFile = filepath.Join(defaultDataDir, "tls.cert")
	defaultLogDir      = filepath.Join(defaultDataDir, defaultLogDirname)
)

// Config contains the configuration information read from the command line and
// from the config file.
type Config struct {
	ShowVersion bool   `short:"V" long:"version" description:"Display version information and exit"`
	DataDir     string `short:"D" long:"datadir" description:"Directory to store key file and the data store"`
	LogDir      string `long:"logdir" description:"Directory to log output"`
Exemplo n.º 14
0
import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"

	"github.com/btcsuite/btcutil"
	"github.com/btcsuite/btcwallet/walletdb"
	_ "github.com/btcsuite/btcwallet/walletdb/bdb"
	"github.com/jessevdk/go-flags"
)

const defaultNet = "mainnet"

var datadir = btcutil.AppDataDir("btcwallet", false)

// Flags.
var opts = struct {
	Force  bool   `short:"f" description:"Force removal without prompt"`
	DbPath string `long:"db" description:"Path to wallet database"`
}{
	Force:  false,
	DbPath: filepath.Join(datadir, defaultNet, "wallet.db"),
}

func init() {
	_, err := flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}
Exemplo n.º 15
0
)

const (
	defaultCAFilename       = "btcd.cert"
	defaultConfigFilename   = "btcwallet.conf"
	defaultLogLevel         = "info"
	defaultLogDirname       = "logs"
	defaultLogFilename      = "btcwallet.log"
	defaultRPCMaxClients    = 10
	defaultRPCMaxWebsockets = 25

	walletDbName = "wallet.db"
)

var (
	btcdDefaultCAFile  = filepath.Join(btcutil.AppDataDir("btcd", false), "rpc.cert")
	defaultAppDataDir  = btcutil.AppDataDir("btcwallet", false)
	defaultConfigFile  = filepath.Join(defaultAppDataDir, defaultConfigFilename)
	defaultRPCKeyFile  = filepath.Join(defaultAppDataDir, "rpc.key")
	defaultRPCCertFile = filepath.Join(defaultAppDataDir, "rpc.cert")
	defaultLogDir      = filepath.Join(defaultAppDataDir, defaultLogDirname)
)

type config struct {
	// General application behavior
	ConfigFile    *cfgutil.ExplicitString `short:"C" long:"configfile" description:"Path to configuration file"`
	ShowVersion   bool                    `short:"V" long:"version" description:"Display version information and exit"`
	Create        bool                    `long:"create" description:"Create the wallet if it does not exist"`
	CreateTemp    bool                    `long:"createtemp" description:"Create a temporary simulation wallet (pass=password) in the data directory indicated; must call with --datadir"`
	AppDataDir    *cfgutil.ExplicitString `short:"A" long:"appdata" description:"Application data directory for wallet config, databases and logs"`
	TestNet3      bool                    `long:"testnet" description:"Use the test Bitcoin network (version 3) (default mainnet)"`